From 0b46d9c103a7e22c85b5f080ad6a00f9c8e94162 Mon Sep 17 00:00:00 2001 From: Chris Wawer Date: Sun, 23 Jun 2024 21:50:55 +0200 Subject: [PATCH] Allow to call JSON RPC with custom block number (#268) --- lib/eth/client.rb | 6 +++++- spec/eth/client_spec.rb | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/eth/client.rb b/lib/eth/client.rb index ecd9dff6..7b203b5b 100644 --- a/lib/eth/client.rb +++ b/lib/eth/client.rb @@ -34,6 +34,9 @@ class Client # The default transaction max fee per gas in Wei, defaults to {Tx::DEFAULT_GAS_PRICE}. attr_accessor :max_fee_per_gas + # The block number used for archive calls. + attr_accessor :block_number + # A custom error type if a contract interaction fails. class ContractExecutionError < StandardError; end @@ -469,7 +472,8 @@ def encode_constructor_params(contract, args) # Prepares parameters and sends the command to the client. def send_command(command, args) - args << "latest" if ["eth_getBalance", "eth_call"].include? command + @block_number ||= "latest" + args << block_number if ["eth_getBalance", "eth_call"].include? command payload = { jsonrpc: "2.0", method: command, diff --git a/spec/eth/client_spec.rb b/spec/eth/client_spec.rb index 46439e07..c9a6a2c5 100644 --- a/spec/eth/client_spec.rb +++ b/spec/eth/client_spec.rb @@ -220,6 +220,35 @@ expect(geth_http.call(erc20_contract, "balanceOf", address)).to be_nil end + it "allows to call client with custom block numberreturn nil if raw result is 0x" do + block_number = 123 + + geth_http.block_number = block_number + + expected_payload = { + jsonrpc: "2.0", + method: "eth_call", + params: [{ + data: "0x70a08231000000000000000000000000d496b23d61f88a8c7758fca7560dcfac7b3b01f9", + to: "0xD496b23D61F88A8C7758fca7560dCFac7b3b01F9" + }, "0x#{block_number.to_s(16)}"], + id: 1 + }.to_json + + mock_response = { + jsonrpc: "2.0", + id: 1, + result: "0x0000000000000000000000000000000000000000000000000000000000000000" + } + + expect_any_instance_of(Eth::Client::Http) + .to receive(:send_request) + .with(expected_payload) + .and_return(mock_response.to_json) + + geth_http.call(erc20_contract, "balanceOf", address) + end + it "called function name not defined" do expect { geth_http.call(contract, "ge")