How to send ERC20 token with Web3.js
2 min readMay 24, 2018
- In this article, Web3.js version
0.20.6
is used. - If you use Web3.js version
1.0.0
, please read How to send ERC20 token with Web3.js@1.0.0 instead.
Prepare ABI to interact with ERC20 Token Smart Contracts
- ABI is an interface which represents what functions/state variables a smart contract has.
- To interact with smart contracts with Web3.js, ABI is needed to call its functions and state variables.
- In general, ABI contains all of functions/state variables which a smart contract has. However, in this article, I’m going to use minimum ABI because only
transfer
is needed.
The minimum ABI to call a transfer function
let minABI = [
// transfer
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"type": "function"
}
];
Example code
In this example, following values are used:
- decimals: 18
- amount to send: 100 tokens
- ERC20 Token address: 0x2A65D41dbC6E8925bD9253abfAdaFab98eA53E34
- Recipient’s address: 0x8Df70546681657D6FFE227aB51662e5b6e831B7A
let tokenAddress = "0x2A65D41dbC6E8925bD9253abfAdaFab98eA53E34";
let toAddress = "0x8Df70546681657D6FFE227aB51662e5b6e831B7A";// Use BigNumber
let decimals = web3.toBigNumber(18);
let amount = web3.toBigNumber(100);let minABI = [
// transfer
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"type": "function"
}
];// Get ERC20 Token contract instance
let contract = web3.eth.contract(minABI).at(tokenAddress);// calculate ERC20 token amount
let value = amount.times(web3.toBigNumber(10).pow(decimals));// call transfer function
contract.transfer(toAddress, value, (error, txHash) => {
// it returns tx hash because sending tx
console.log(txHash);
});
Tx result I sent using the code above
Related article
Working Demo
https://piyolab.github.io/playground/ethereum/sendERC20Token/
Support
If you find this article is helpful, it would be greatly appreciated if you could tip Ether to the address below. Thank you!
0x0089d53F703f7E0843953D48133f74cE247184c2