Web3 by Example: Transferring ETH

The simplest transaction is transferring ETH from one account to another. We can use wallet to send transactions.

Set your private key, see generating new wallets section to learn how to generate one.

Create a wallet from the privateKey, and pass the provider. So we can send transactions using this wallet later.

Construct a transaction object. to is the address of the recipient. value is the amount of ETH to send. The unit is wei(1 ETH = 10^18 wei). We use ethers.utils.parseEther to convert to wei.

sendTransaction will populate all fields in a transaction, signs it and sends it to the network.

We can use .wait to wait for the transaction to be mined. This will return transaction recipient. If status is 1, it means the transaction was successfully mined.

transfer-eth.js

const ethers = require("ethers");
(async () => {
const provider = new ethers.providers.AlchemyProvider("goerli");
const privateKey = "your-private-key";
const wallet = new ethers.Wallet(privateKey, provider);
const tx = {
to: "0xddB51f100672Cb252C67D516eb79931bf27cE3E6",
value: ethers.utils.parseEther("0.1"),
};
const res = await wallet.sendTransaction(tx);
console.log(res);
})();

output

➜ node transfer-eth.js
{
type: 2,
chainId: 5,
nonce: 127,
maxPriorityFeePerGas: BigNumber { _hex: '0x9502f900', _isBigNumber: true },
maxFeePerGas: BigNumber { _hex: '0x9502f912', _isBigNumber: true },
gasPrice: null,
gasLimit: BigNumber { _hex: '0x5208', _isBigNumber: true },
to: '0xddB51f100672Cb252C67D516eb79931bf27cE3E6',
value: BigNumber { _hex: '0x016345785d8a0000', _isBigNumber: true },
data: '0x',
accessList: [],
hash: '0x11a4f81841dae0e5bb1b948d3ea8ca1e81d9481a56d5053f47c415f9c4a1d356',
v: 0,
r: '0x11034c123f6a9634a59d86c9c2167361d243a98d7f9c587ce916961bade99878',
s: '0x4cb00d84b992a1f0644571fe521c82969900a970860900da4ce3122e4d714254',
from: '0x67CF3bF40b2b3b3D68F6c361AEf81F8AEb2dB637',
confirmations: 0,
wait: [Function (anonymous)]
}

Next example: Transferring Tokens (ERC-20)