how display balance of token through Ethereum RPC?
$id = 0;
$data = array();
$data['jsonrpc'] = '2.0';
$data['id'] = $id++;
$data['method'] = 'eth_call';
$data['params'] = [['from' => '0x0...', 'to' => '0x0...', 'data' => 'contract byte code here 0x0...'], 'latest'];
$ch = curl_init();
...
Return:
{"jsonrpc":"2.0","id":0,"result":"0x"}
What to do next? Call contract method balanceOf? How to do that?
When calling a Solidity contract function, in general,
data
should be the following, encoded as a hex string:The function signature for an ERC20 token's
balanceOf
isbalanceOf(address)
. The keccak-256 hash is70a08231b98ef4ca268c9cc3f6b4590e4bfec28280db06bb5d45e689f2a360be
, so the first four bytes are70a08231
.The function only takes a single parameter: the address of the account whose balance you're trying to look up. To ABI-encode it, simply left-pad it with zeros until it's 32 bytes long. Since addresses are 20 bytes, this means adding 12 bytes of zeros (or 24 characters in hex).
So the full
data
field should be"0x70a08231" + "000000000000000000000000" + address
.For token transaction you need to use
eth_sendTransaction
.To get token balance with
eth_call
you needto
anddata
parameter.to
is contract address, here we need to generate thedata
parameter. As the doc eth_call says,Take this EOS token transaction as a example.
Contract address:
0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0
Token Holder address:
0x0b88516a6d22bf8e0d3657effbd41577c5fd4cb7
You can see the contract code here.
Function Selector
Take the first four bytes
70a08231
Argument Encoding
Padding the 20 bytes token address to 32 bytes with
0
to token holder address:Then concat the function selector and encoded parameter, we get
data
parameter:0x70a082310000000000000000000000000b88516a6d22bf8e0d3657effbd41577c5fd4cb7
Make the request with:
here is the curl result (You may get different answer here, as there may be some transaction with this address done after my polling the request)
You can change convert hex format balance to decimal
Check the result,
May I recommend a proper ERC20 library for PHP that I have developed myself.
https://www.furqansiddiqui.com/libraries/erc20-php/
https://github.com/furqansiddiqui/erc20-php
sample code to retrieve balance: