patternjavascriptTip
Sending an ERC-20 transfer transaction and waiting for confirmation
Viewed 0 times
ethers.js v6.x
ERC-20 transfertx.waittransaction receiptconfirmationparseUnitssigner
Error Messages
Problem
Sending a token transfer requires a signer, and you need to handle the async lifecycle: broadcast, pending, confirmed.
Solution
Attach the contract to a signer, call transfer(), then call wait() on the returned transaction response to block until mined.
const tokenWithSigner = token.connect(signer);
const tx = await tokenWithSigner.transfer(recipient, amount);
const receipt = await tx.wait();
console.log('Confirmed in block', receipt.blockNumber);Why
Ethereum transactions are asynchronous — the broadcast and mining are separate events. tx.wait() subscribes to the transaction receipt event.
Gotchas
- tx.wait() can resolve with null if the transaction was replaced (speed-up/cancel); always check receipt !== null
- amount must be in raw token units (use parseUnits to convert from human-readable)
- Always set a gas limit or estimate gas to avoid out-of-gas failures
Code Snippets
Send ERC-20 transfer and await confirmation
import { Contract, parseUnits } from 'ethers';
async function sendTokens(tokenAddress, signer, recipient, humanAmount, decimals) {
const ERC20_ABI = ['function transfer(address to, uint256 amount) returns (bool)'];
const token = new Contract(tokenAddress, ERC20_ABI, signer);
const amount = parseUnits(humanAmount, decimals);
const tx = await token.transfer(recipient, amount);
console.log('Tx hash:', tx.hash);
const receipt = await tx.wait();
if (!receipt) throw new Error('Transaction replaced or dropped');
return receipt;
}Context
Implementing a token send feature in a dApp
Revisions (0)
No revisions yet.