How to send an ERC-20 token transaction with web3

In this tutorial, we are going to see how to send an ERC-20 token to a wallet or a smart contract with web3. It also works with other blockchains like the BSC and BEP-20 tokens.

In this tutorial, we are going to see how to send an ERC-20 token to a wallet or a smart contract with web3. It also works with other blockchains like the BSC and BEP-20 tokens.

First, install the web3 library if you haven't already using the following command:

npm install web3

Then, to interact with a blockchain (Ethereum or BSC or any other) you need to create an instance of Web3 and give it a provider (like window.ethereum for browser wallets, for example).

After that, you need to connect to the user's wallet using any method you want. You can check out our guides if you want to learn how to connect to a wallet.

Now, you need to have the address of the smart contract or wallet that you want to send the tokens to.

The next step is to define the ABI that we will need in order to use the methods available in the smart contract.

Let's say we want to send WETH to a wallet. We go to the etherscan.io page of the token in the Contract > Write Contract section. From there we can see a transfer function. That's what we will use. It takes the destination address and the amount in parameters. From this page, we also copy the token address.

Now, we use this code to transfer tokens to a wallet:

// need a Web3 instance initialized with a provider like window.ethereum for browser wallets, in a variable called web3, to use this code stored
// also need a connected wallet using that instance

const ABI = [{
  constant: false,
  inputs: [{name: "dst", type: "address"}, {name: "wad", type: "uint256"}],
  name: "transfer",
  outputs: [{ name: "", type: "bool" }],
  payable: false,
  stateMutability: "nonpayable",
  type: "function"
}]

const fromAddress = "" // address here
const amount = "0.1"
const contractAddress = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
const destinationAddress = "" // address here

const contract = new web3.eth.Contract(ABI, contractAddress)

const transactionParams = {
  from: fromAddress,
  to: contractAddress,
  value: Web3.utils.toWei(amount),
  data: contract.methods.transfer(destinationAddress, Web3.utils.toWei(amount)).encodeABI()
}

const txHash = await web3.eth.sendTransaction(transactionParams)

It is pretty much like sending Ethereum to an address but the important thing is the data object. It represents the transaction and it contains information about who you are sending the tokens to and the amount.

Also be careful, in the transactionParams object, the property 'to' is not the address that will receive the transaction but the contract address of the token.

The other important thing to keep in mind is that you don't put the amount in the transactionParams object directly under the value property but in the data property.

Thanks for following this tutorial!