Last active
January 3, 2018 05:49
-
-
Save nickbclifford/56efe3ebee672db64471b987ab725747 to your computer and use it in GitHub Desktop.
Reference implementation for https://codegolf.meta.stackexchange.com/a/14496/65298
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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