Ethereum Transaction Guide: Using Web3 and Infura for ETH and ERC-20 Token Transfers

·

Ethereum has revolutionized the blockchain space by enabling developers to build decentralized applications (DApps) and issue custom digital assets through smart contracts. One of the most common tasks in Ethereum development is transferring Ether (ETH) or ERC-20 tokens programmatically. This guide walks you through the core concepts, transaction mechanics, and practical implementation using Web3.js and Infura, ideal for developers building automated transfer systems.

Whether you're creating a wallet service, automating payouts, or integrating crypto payments into your app, understanding how gas, private keys, and transaction parameters work is essential.

Understanding Ethereum Account Structure

Every Ethereum account consists of three key components:

The private key is a 64-character hexadecimal string that grants full control over an account. While secure, it's difficult to memorize or manually record. To improve usability, the mnemonic phrase—a sequence of 12 or 24 common English words—is used as a human-readable representation of the same cryptographic seed. These words are derived from a standardized dictionary and can regenerate the private key using deterministic algorithms like BIP39 and BIP44.

The mnemonic and private key are cryptographically linked—either can generate the other. Never expose either to untrusted environments.

Your public address, starting with 0x, is where others send funds. It’s safe to share but always verify before transactions.

How Ethereum Transactions Work

Ethereum operates on a decentralized network powered by the Ethereum Virtual Machine (EVM), which executes smart contracts across all participating nodes. Unlike Bitcoin’s limited scripting, the EVM is Turing-complete, allowing complex logic execution.

When you initiate a transaction—whether sending ETH or interacting with a smart contract—it triggers a series of operations in the EVM. Each operation consumes computational resources measured in gas.

What Is Gas?

Think of gas as fuel for your Ethereum transaction:

👉 Discover how blockchain transactions work under the hood

Transactions with higher gasPrice get prioritized by miners or validators, leading to faster confirmation. If gasUsed exceeds gasLimit, the transaction fails and gas is still charged. If it succeeds, only gasUsed * gasPrice is deducted.

Gas Units & Conversion

1 Gwei = 1,000,000,000 Wei  
1 Ether = 1,000,000,000 Gwei  
Transaction Fee = gasUsed × gasPrice

For example, a transaction using 21,000 gas at 13 Gwei costs:

21,000 × 13 = 273,000 Gwei = 0.000273 ETH

You can verify this on Etherscan by checking any transaction’s "Transaction Fee" field.

ERC-20 Tokens: The Standard for Custom Cryptocurrencies

Many projects issue their own tokens on Ethereum using the ERC-20 standard, which defines a set of rules for fungible tokens. Examples include USDT, UNI, and LINK.

While ETH is native to Ethereum and pays for transaction fees, ERC-20 tokens represent value within specific applications. Transferring them requires calling the transfer() function on their respective smart contract.

A crucial detail: token amounts must be adjusted for decimals—the number of digits after the decimal point defined at token creation. For instance, USDT has 6 decimals, so transferring $1 means sending 1 * 10^6 = 1,000,000 units.

Core Tools: Web3.js and Infura

To interact with Ethereum without running a full node, developers use:

These tools let you query balances, estimate gas, and broadcast signed transactions—all from your application backend.

👉 Start testing Ethereum integrations securely today

Installing Required Dependencies

npm install bip39 eth-json-rpc-infura ethereumjs-wallet [email protected]
Use compatible versions to avoid breaking changes in older beta releases.

Implementing ETH and Token Transfers

Step 1: Connect to Ethereum via Infura

Create provider.js:

const createInfuraProvider = require('eth-json-rpc-infura/src/createProvider');
const provider = { send: createInfuraProvider('your-infura-project-id').sendAsync };
module.exports = provider;

Initialize Web3 in client.js:

const Web3 = require('web3');
const Transaction = require('ethereumjs-tx').Transaction;
const provider = require('./provider');
const contractABI = require('./erc20-abi.json');
const web3 = new Web3(provider);

Step 2: Derive Wallet from Mnemonic

const bip39 = require('bip39');
const hdkey = require('ethereumjs-wallet/hdkey');

function generateWalletFromMnemonic(mnemonic, index = 0) {
  const seed = bip39.mnemonicToSeedSync(mnemonic);
  const hdWallet = hdkey.fromMasterSeed(seed);
  const path = `m/44'/60'/0'/0/${index}`;
  const wallet = hdWallet.derivePath(path).getWallet();
  return {
    address: '0x' + wallet.getAddress().toString('hex'),
    privateKey: wallet.getPrivateKey().toString('hex')
  };
}

Step 3: Send Ether (ETH)

const { address, privateKey } = generateWalletFromMnemonic('your mnemonic here');
const toAddress = '0xRecipientAddress';
const amount = web3.utils.toHex(web3.utils.toWei('0.1', 'ether'));

web3.eth.getTransactionCount(address)
  .then(nonce => {
    const txParams = {
      nonce: web3.utils.toHex(nonce),
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      gasLimit: web3.utils.toHex(21000),
      to: toAddress,
      value: amount
    };

    const tx = new Transaction(txParams, { chain: 'mainnet' });
    tx.sign(Buffer.from(privateKey, 'hex'));

    web3.eth.sendSignedTransaction('0x' + tx.serialize().toString('hex'))
      .on('transactionHash', console.log);
  });

Step 4: Transfer ERC-20 Tokens

const contractAddress = '0xTokenContractAddress';
const contract = new web3.eth.Contract(contractABI, contractAddress);

contract.methods.transfer(toAddress, amountWithDecimals).encodeABI()
  .then(data => {
    // Build tx with contract address as `to` and encoded `data`
    const txParams = {
      nonce: web3.utils.toHex(nonce),
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      gasLimit: web3.utils.toHex(65000),
      to: contractAddress,
      value: '0x0',
      data: data
    };
    // Sign and send...
  });

Estimating Gas and Transaction Costs

Accurate cost estimation improves user experience and prevents failed transactions.

Use these methods:

  1. web3.eth.estimateGas(): Simulates transaction execution.
  2. Third-party APIs:

Example using EthGasStation:

{
  "fastest": 200,
  "fast": 100,
  "safeLow": 30
}

Values are in tenths of Gwei → safeLow = 3 Gwei.

Convert to Wei and multiply by estimated gas:

const gasPriceGwei = 3;
const estimatedGas = await web3.eth.estimateGas({ to: recipient });
const feeInEther = (estimatedGas * gasPriceGwei) / 1e9;

For token transfers:

const estimatedGas = await contract.methods.transfer(to, amount).estimateGas({ from: myAddress });
Ensure sufficient balance before estimation—otherwise you’ll receive error -32000.

Fetching Real-Time ETH Exchange Rates

Use Infura’s ticker API:

GET https://api.infura.io/v1/ticker/ethusd

Response includes bid (buy price) and ask (sell price). Use bid for outgoing payment calculations.

Frequently Asked Questions (FAQ)

Q: Can I recover my private key from a mnemonic phrase?
A: Yes. Using BIP39 standards, your mnemonic generates a seed that derives your private key deterministically.

Q: Why do my transactions get stuck?
A: Low gasPrice causes delays. Monitor pending transactions and rebroadcast with higher gas if needed.

Q: What happens if I exceed the gas limit?
A: The transaction fails and consumed gas isn’t refunded. Always test on testnets first.

Q: Do I need ETH to transfer ERC-20 tokens?
A: Yes. ETH pays for gas—even when moving tokens.

Q: How do I prevent replay attacks?
A: Always use the correct chain ID when signing transactions (e.g., 1 for mainnet).

Q: Can I automate multiple transfers efficiently?
A: Yes. Queue transactions with incrementing nonces or use batch contracts.

Final Notes

Automating Ethereum transactions opens doors to scalable DeFi integrations, payroll systems, and decentralized exchanges. Always:

👉 Explore advanced blockchain automation techniques now

With Web3.js and Infura, you can build robust, scalable solutions that interact seamlessly with the Ethereum ecosystem.


Core Keywords: Ethereum, ERC-20 token transfer, Web3.js, Infura API, gas fee calculation, private key management, smart contract interaction