How to Send ETH and ERC20 Tokens Using web3.js

·

Ethereum transactions primarily fall into two categories: ETH transfers and ERC20 token transfers. The transfer process for both is fundamentally similar but with key differences in transaction initialization.

Understanding Ethereum Transaction Structure

The main difference between ETH and ERC20 transactions occurs during the initialization of the raw transaction object (rawTx{}), particularly in the to and value fields:

Transaction FieldETH TransferERC20 TransferDescription
fromfromAddressfromAddressSender's wallet address
nonceHex converted nonceHex converted nonceTransaction sequence number
gasLimitHex value (e.g., 8000000)Hex value (e.g., 8000000)Maximum gas allowed
gasPriceHex value (e.g., 10 Gwei)Hex value (e.g., 10 Gwei)Gas price per unit
toRecipient addressSmart contract addressDestination differs by token type
valueHex converted amount"0x0"Transfer amount (ETH only)
dataEncoded transfer methodEncoded transfer methodContains token transfer details
chainIdNetwork ID (e.g., 0x04)Network ID (e.g., 0x04)Identifies blockchain network

Checking Token Balances

Checking ETH Balance

function getEthBalance(fromAddress, bookmark) {
  web3.eth.getBalance(fromAddress).then(
    function(wei) {
      balance = web3.utils.fromWei(wei, 'ether');
      console.log(bookmark + balance);
    }
  );
}

Checking ERC20 Token Balance

function getERC20Balance(fromAddress, contractObj, bookmark) {
  contractObj.methods.balanceOf(fromAddress).call().then(
    function(wei) {
      balance = web3.utils.fromWei(wei, 'ether');
      console.log(bookmark + balance);
    }
  );
}

Sending Tokens with web3.js

Project Setup

  1. Create project directory:

    mkdir sendToken
    cd sendToken
    npm init -y
    truffle init
  2. Configure package.json with required dependencies:

    {
      "dependencies": {
        "@openzeppelin/contracts": "^2.5.0",
        "@truffle/hdwallet-provider": "^1.1.1",
        "web3": "^1.3.0"
      }
    }
  3. Install dependencies:

    npm install
  4. Create necessary directories for ABIs and configurations.

Sending ETH Transactions

async function sendEth() {
  const transferAmount = web3.utils.toWei('20', 'milli');
  const nonceCnt = await web3.eth.getTransactionCount(myAddress);
  
  const rawTx = {
    "from": myAddress,
    "nonce": web3.utils.toHex(nonceCnt),
    "to": recipientAddress,
    "value": web3.utils.toHex(transferAmount),
    "chainId": 0x04
  };

  const tx = new Tx(rawTransaction);
  tx.sign(privateKey);
  const serializedTx = tx.serialize();
  
  const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
  console.log(`Transaction receipt: ${JSON.stringify(receipt)}`);
}

👉 Learn more about secure ETH transactions

Sending ERC20 Token Transactions

async function sendERC20() {
  const transferAmount = web3.utils.toWei('20', 'milli');
  const nonceCnt = await web3.eth.getTransactionCount(myAddress);
  
  const rawTx = {
    "from": myAddress,
    "nonce": web3.utils.toHex(nonceCnt),
    "to": contractAddress,
    "value": "0x0",
    "data": contract.methods.transfer(recipientAddress, transferAmount).encodeABI(),
    "chainId": 0x04
  };

  const tx = new Tx(rawTransaction);
  tx.sign(privateKey);
  const serializedTx = tx.serialize();
  
  const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
  console.log(`Transaction receipt: ${JSON.stringify(receipt)}`);
}

Frequently Asked Questions

What's the difference between ETH and ERC20 transactions?

ETH transactions are native currency transfers, while ERC20 transactions interact with smart contracts to transfer token balances between accounts.

How do I choose the right gas price?

Gas prices fluctuate with network congestion. Use tools like ETH Gas Station to determine optimal gas prices.

Why does my ERC20 transaction need contract ABI?

👉 Understanding ABIs and smart contracts The ABI (Application Binary Interface) defines how to interact with the smart contract, including how to call the transfer function.

What's a nonce in Ethereum transactions?

A nonce is a sequential number that ensures each transaction from an address is processed in order and prevents duplicate transactions.

How can I track my transaction status?

Use blockchain explorers like Etherscan by searching your transaction hash or wallet address to monitor transaction progress.

What happens if my transaction fails?

Failed transactions still consume gas. Always verify sufficient ETH balance for gas fees and correct recipient addresses before sending.