Web3.js: How to Send ERC-20 Tokens
This tutorial makes use of Web3.js v1.x.x. Not all functionality might work with Web3.js v4.
In this quick guide we’ll be looking at how to send an ERC-20 token with web3.js. We’ll use as a reference this example that sends value from one address to another and look at what actually changes if we want to send an ERC-20 token instead of ETH.
But before that let’s get some test ERC-20 tokens - we’ll be using Goerli as a testnet and get some LINK tokens from this faucet https://faucets.chain.link/
Good, so I’m hoping that the faucet transaction went through and we all have some test tokens to play with. Let’s start with pointing out the essential difference between sending ETH and a different token: the transaction will not send any value but instead it will call the token contract Transfer function with the relevant parameters (to_address, amount).
How does this changes the referenced code ? Well, firstly we need to create a contract instance and use the token contract ABI which is going to be loaded from a file.
var fs = require("fs");
var jsonFile = "ct_abi.json";
var parsed = JSON.parse(fs.readFileSync(jsonFile));
var abi = parsed.abi;
const tokenAddress = "0x326C977E6efc84E512bB9C30f76E30c160eD06FB";
const contract = new web3.eth.Contract(abi, tokenAddress, {
from: signer.address,
});