After the previous transfer of eth, this time we will continue to see how to transfer ERC20 tokens.
Install dependencies and initialize web3#
I won't go into detail here. If you don't know how to initialize web3, you can refer to one of my previous articles.
Initialize the contract object Contract#
Last time we created a start
method. This time we will create a startContract
method inside it, and replace the code below with the execution of the startContract
method.
const startContract = async () => {
let currentAddress = '0xe208D2fB37df02061B78848B83F02b4AD33540e4'
let toAddress = '0x3EcAa09DD6B8828607bba4B1d7055Ea1143f8B94'
// This time we still choose uni on the goerli test chain for the token
const uniContractAddress = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984' // uni erc20 token contract address
const uniswapAbi = [] // uni's abi information, you can find it yourself, or you can check my web3 learning notes for specific search methods
const uniToken = new web3.eth.Contract(uniswapAbi, uniContractAddress)
}
startContract()
This way we have the contract object Contract
.
Initialize parameters#
Let's prepare some parameters needed for the transaction.
const privateKey = Buffer.from('Your wallet private key', 'hex')
// Before setting the amount, we need to get the precision of the token currency. Here the decimals value is 18, which means 18 digits.
const decimals = await uniToken.methods.decimals().call()
// amount = transfer amount * decimals, here we transfer 1 uni token
const amount = web3.utils.toHex(1 * Math.pow(10, decimals))
const count = await web3.eth.getTransactionCount(currentAddress)
const txParams = {
from: currentAddress,
to: uniContractAddress,
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
gasLimit: web3.utils.toHex(210000),
value: web3.utils.toHex(0),
data: uniToken.methods.transfer(toAddress, amount).encodeABI(),
nonce: web3.utils.toHex(count)
}
const tx = new EthereumTx(txParams, {
chain: 'goerli'
})
tx.sign(privateKey)
Now we have the required parameters and have signed the key.
The above ethereumjs-tx signature scheme uses ethereumjs-common
by default, which has:
mainnet
ropsten
rinkeby
kovan
goerli
(final configuration sincev1.1.0
)
You can directly sign for these chains. For other chains, you need to requireethereumjs-common
yourself.
const Common = require('ethereumjs-common').default
const blockchain = Common.forCustomChain(
'mainnet', {
name: 'Fantom Opera',
networkId: 250,
chainId: 250
},
'petersburg'
)
const tx = new EthereumTx(txParams, {
common: blockchain
})
tx.sign(privateKey)
Send transaction#
web3.eth.sendSignedTransaction('0x' + tx.serialize().toString('hex'))
.on('transactionHash', console.log)
.catch(err => {
console.log({err});
})
This way we have already sent the token.