#100daysofcode 6 兼RailsからJSON-RPCでEthereumにつなぐ
ethereum.rbを使えばよいんじゃないかって気もするけど、RubyもRailsも勘で書いている人に向けて
簡単に手順
①JSON-RPCのAPI一覧を参考に、Ethereumを操作したい内容をcurlで書く
JSON RPC · ethereum/wiki Wiki · GitHub
お試し用に
curl -H 'Content-Type:application/json' -X POST http://localhost:7545 --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":,"id":1}'
②curlコマンドをRuby用に変換してくれる便利サイトに張り付ける
curl-to-ruby: Convert curl commands to ruby's net/http
すると
require 'net/http' require 'uri' require 'json' uri = URI.parse("http://localhost:7545") request = Net::HTTP::Post.new(uri) request.content_type = "application/json" request.body = JSON.dump({ "jsonrpc" => "2.0", "method" => "web3_clientVersion", "id" => 1 }) req_options = { use_ssl: uri.scheme == "https", } response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| http.request(request) end
のように変換してくれるので、
取得したJSONをresultに取得して、必要な部分をsourceに格納する。
begin # responseの値に応じて処理を分ける case response # 成功した場合 when Net::HTTPSuccess # responseのbody要素をJSON形式で解釈し、hashに変換 @result = JSON.parse(response.body) # 表示用の変数に結果を格納 @source = @result["result"] end end
をcontrollerに追加してあげて、
後はviewに
<p> source: <%= @source %> </p>
とでも書いてあげれば
source: EthereumJS TestRPC/v2.1.5/ethereum-js
のような表示が出るはず。