Module: Mpp::Methods::Tempo::Rpc

Defined in:
lib/mpp/methods/tempo/rpc.rb

Constant Summary collapse

DEFAULT_TIMEOUT =
30

Class Method Summary collapse

Class Method Details

.call(rpc_url, method, params, client: nil) ⇒ Object

Make a JSON-RPC call.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mpp/methods/tempo/rpc.rb', line 17

def call(rpc_url, method, params, client: nil)
  payload = {"jsonrpc" => "2.0", "method" => method, "params" => params, "id" => 1}

  uri = URI.parse(rpc_url)
  http = client || Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https" unless client
  http.read_timeout = DEFAULT_TIMEOUT unless client

  request = Net::HTTP::Post.new(uri)
  request["Content-Type"] = "application/json"
  request.body = JSON.generate(payload)

  response = http.request(request)
  result = JSON.parse(response.body)

  Kernel.raise "RPC error: #{result["error"]}" if result.key?("error")

  result["result"]
end

.estimate_gas(rpc_url, from_addr, to, data, client: nil) ⇒ Object

Estimate gas for a call.



48
49
50
51
52
53
54
55
56
# File 'lib/mpp/methods/tempo/rpc.rb', line 48

def estimate_gas(rpc_url, from_addr, to, data, client: nil)
  result = call(
    rpc_url,
    "eth_estimateGas",
    [{"from" => from_addr, "to" => to, "data" => data}, "latest"],
    client: client
  )
  result.to_i(16)
end

.get_tx_params(rpc_url, sender, client: nil) ⇒ Object

Fetch chain_id, nonce, and gas_price.



38
39
40
41
42
43
44
45
# File 'lib/mpp/methods/tempo/rpc.rb', line 38

def get_tx_params(rpc_url, sender, client: nil)
  # In Ruby, we make these calls sequentially (or use threads)
  chain_id_hex = call(rpc_url, "eth_chainId", [], client: client)
  nonce_hex = call(rpc_url, "eth_getTransactionCount", [sender, "pending"], client: client)
  gas_hex = call(rpc_url, "eth_gasPrice", [], client: client)

  [chain_id_hex.to_i(16), nonce_hex.to_i(16), gas_hex.to_i(16)]
end