Interact with ERC-20 tokens
ERC-20 is a simple token standard and the most common contract type on Ethereum.
You can:
Send ERC-20 transactions using
eth_sendRawTransaction
.Observe event logs of processed ERC-20 transactions using
eth_getLogs
.Follow this tutorial to retrieve the balance of ERC-20 tokens.
Follow this tutorial to track ERC-20 token transfers.
ERC-20 token functions and events
An ERC-20 token must implement the following functions:
totalSupply()
Returns the total token supply.balanceOf(owner)
Returns the account balance of another account with addressowner
.allowance(owner, spender)
Returns the amount whichspender
is still allowed to withdraw fromowner
.transfer(to, value)
Transfersvalue
amount of tokens to addressto.
approve(spender, value)
Allowsspender
to withdraw from your account multiple times, up to thevalue
amount.transferFrom(from, to, value)
Transfersvalue
amount of tokens from addressfrom
to addressto
.
At certain times, an ERC-20 token also must emit the following events:
Transfer(from, to, value)
Must trigger when tokens are transferred, including zero value transfers.Approval(owner, spender, value)
Must trigger on any successful call toapprove(spender, value)
.
View EIP-20 for more details about how these functions work and when to emit these events.
Send transactions
Use eth_sendRawTransaction
to send ERC-20 token transactions. This JSON-RPC method expects a data
field format that requires normalization of the Transfer
function to a short function selector.
To do this, set the parameters for the function and run it through Ethereum’s sha3 keccak hash:
To use cast you must first install Foundry.
The above examples produce the following function selector:
Next, the transaction data
field should be constructed as follows:
Start with the function selector:
0xa9059cbb
Append the recipient's address (padded to 32 bytes)
Append the token amount (padded to 32 bytes)
For example:
Where:
0xa9059cbb
: Function selector000000000000000000000001234567890123456789012345678901234567890
: Recipient address (padded)0000000000000000000000000000000000000000000000000de0b6b3a7640000
: Token amount (padded, in this example, 1 token with 18 decimals)
With the data
field value, you can now create a transaction object with the following fields:
to
: The ERC-20 token contract addressvalue
: 0 (since we're not sending ETH)data
: The prepared data string from abovegasPrice
: Current gas price (in wei)gasLimit
: Estimated gas limit for the transactionnonce
: The sender's current transaction count
Finally, you can use your private key to sign the transaction object. This step to do that depend on the library you're using (e.g. Ethers.js, Web3.js).
Now, you can send your signed transaction using eth_sendRawTransaction
:
Observe logs of processed transactions
Last updated
Was this helpful?