Skip to content

Instantly share code, notes, and snippets.

@nickbclifford
Last active January 3, 2018 05:49
Show Gist options
  • Save nickbclifford/56efe3ebee672db64471b987ab725747 to your computer and use it in GitHub Desktop.
Save nickbclifford/56efe3ebee672db64471b987ab725747 to your computer and use it in GitHub Desktop.
require "big"
require "http/client"
require "json"
def send_contract_call(to address, data)
JSON.parse(HTTP::Client.post("localhost:8545", body: {
"jsonrpc" => "2.0",
"method" => "eth_call",
"params" => [{
"to" => address,
"data" => data
}, "latest"],
"id" => 1
}.to_json).body)["result"]
end
BALANCE_METHOD_ID = "0x70a08231" # First 4 bytes of Keccak256("balanceOf(address)")
DECIMALS_METHOD_ID = "0x313ce567" # First 4 bytes of Keccak256("decimals()")
token = ARGV[0]
wallet = ARGV[1][2..-1] # Remove "0x" from beginning
balance = BigInt.new(send_contract_call(
to: token,
data: BALANCE_METHOD_ID + wallet.rjust(64, '0') # Pad wallet address to 32 bytes before appending
).as_s[2..-1], 16)
decimals = send_contract_call(
to: token,
data: DECIMALS_METHOD_ID
).as_s[2..-1].to_i(16)
puts BigDecimal.new(balance, decimals) # Really just `balance / (10 ** decimals)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment