Cedric Martin
Cedric Martin

Reputation: 6014

How to a json-rpc call from Clojure?

I've got a local server running on port 8545 which listen to JSON-RPC requests. I can call it using curl like this:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xf54c19d9ef3873bfd1f7a622d02d86249a328f06", "latest"],"id":1}' http://localhost:8545

What would be the equivalent call from Clojure? Do I need to add some external libraries to the project.clj?

Upvotes: 1

Views: 803

Answers (2)

Hindol
Hindol

Reputation: 2990

I had a similar use case so I created a small Clojure library for making JSON-RPC calls. With this, you can do,

(ns example.core
  (:require [json-rpc.core :as rpc]))

(with-open [channel (rpc/open "http://localhost:8545")]
  (rpc/send! channel "eth_blockNumber" ["latest"]))
  ;; => {:result "0x14eca", :id "6fd9a7a8-c774-4b76-a61e-6802ae64e212"}

, and the boilerplate will be handled for you.

Upvotes: 0

fl00r
fl00r

Reputation: 83680

I think you should try http-kit. Also you will need some library for json (data.json or cheshire)

So add to your project.clj following dependencies:

  • [http-kit "2.1.18"]
  • [org.clojure/data.json "0.2.6"]

And try this

(ns your-ns
  (:require [org.httpkit.client :as http]
            [clojure.data.json :as json]))

(let [url "http://localhost:8545"
      body (json/write-str 
             {:jsonrpc "2.0"
              :method "eth_getBalance"
              :params ["0xf54c19d9ef3873bfd1f7a622d02d86249a328f06" "latest"]
              :id 1})
      options {:body body}
      result @(http/post url options)]
  (prn result))

Upvotes: 2

Related Questions