Sending a parcel through a courier has an order to it. You fill in a form (destination, contents, the most you'll pay for shipping), sign it, and hand it in at the counter. The parcel waits in the warehouse (the mempool) until the next truck (a block) takes it, and you get a receipt that says delivered or refused. You pay for shipping even when the parcel is refused. A parcel still in the warehouse can have its form replaced; a parcel that has left can't be pulled back.
Sending a transaction works the same way. You ask the network to change state: redeeming PTS, moving ETH, calling a function that writes. Because it changes state, a transaction must be signed by the account's owner and must pay gas.
The five steps of a transaction
- Build: fill in its fields (the table below).
- Sign: a wallet signs it with the private key. In a browser that's the user's wallet; on our local chain, the Hardhat node holds the test accounts.
- Send: the signed transaction goes to a node and waits in the mempool.
- Mined: a validator puts it in a block.
- Receipt: the outcome can be read: success or revert, gas used, logs.
This is Dinda's transaction redeeming 100 PTS ($5 off), built by viem 2.57.4 on the same local chain as the previous lesson (blocks 1 to 5):
| Field | Value | Meaning |
|---|---|---|
from |
Dinda 0x7099...79C8 |
who signs |
to |
RakaPoints 0x5FbD...0aa3 |
the contract being called |
value |
0 | no ETH is sent |
data |
0xdb006a75...056bc75e2d63100000 |
redeem(100 PTS) as calldata |
nonce |
0 | Dinda's transaction counter; this is her first |
gas |
33,946 | the gas limit, from eth_estimateGas |
maxPriorityFeePerGas |
1,000,000,000 wei (1 gwei) | the tip for the validator |
maxFeePerGas |
1,617,957,277 wei | the highest price per gas she'll pay |
chainId |
31337 | so the signature isn't valid on another chain |
type |
2 (EIP-1559) | the base fee + tip format |
The nonce is each account's own queue number, starting at 0. A node only processes nonce 1 after nonce 0 is done, and each nonce can be used only once. That's what stops the same transaction from being replayed.
Building, sending and waiting with viem
import { createPublicClient, createWalletClient, http, parseAbi, parseUnits, encodeFunctionData } from 'viem'
import { hardhat } from 'viem/chains'
const abi = parseAbi([
'function redeem(uint256 amount)',
'event Redeemed(address indexed customer, uint256 amount)',
'error NotEnoughPoints(uint256 balance, uint256 needed)',
])
const publicClient = createPublicClient({ chain: hardhat, transport: http() })
const dinda = createWalletClient({ account: DINDA, chain: hardhat, transport: http() })
const request = await dinda.prepareTransactionRequest({
to: PTS,
data: encodeFunctionData({ abi, functionName: 'redeem', args: [parseUnits('100', 18)] }),
})
console.log(request.nonce, request.gas, request.maxFeePerGas, request.maxPriorityFeePerGas)
const hash = await dinda.sendTransaction(request)
const receipt = await publicClient.waitForTransactionReceipt({ hash })
console.log(receipt.status, receipt.blockNumber, receipt.gasUsed, receipt.effectiveGasPrice)
0 33946n 1617957277n 1000000000n
success 6n 33946n 1450674241n
prepareTransactionRequestfills in the nonce (eth_getTransactionCount), the gas (eth_estimateGas) and the fees. viem works outmaxFeePerGas= the last block's base fee × 1.2 + the tip: 514,964,398 × 1.2 + 1,000,000,000 = 1,617,957,277 wei, rounded down.sendTransactionsendseth_sendTransaction; the node signs for its test account and returns the hash straight away. The hash is only a ticket, not proof of success.waitForTransactionReceiptwaits until the transaction is in a block. ethers v6 is the same idea:const tx = await points.connect(dinda).redeem(amount), thenconst receipt = await tx.wait(), andreceipt.statusis1.
What gets signed is all of those fields. The result is 147 bytes, starting with 0x02 (the EIP-1559 type), and the transaction hash = keccak256 of those bytes (cut short):
0x02f890827a6980843b9aca00846070119d82849a945fbdb2315678afecb367f032d93f642f64180aa380a4db006a75...c001a01ebab370...a058e301e9...
Receipt: status 1 or 0
Dinda, redeem(100) |
Yoga, redeem(200) with a 100,000 gas limit |
|
|---|---|---|
status |
success (1) |
reverted (0) |
| block | 6 | 7 |
gasUsed |
33,946 | 24,263 |
effectiveGasPrice |
1,450,674,241 wei | 1,394,403,705 wei |
| cost | 0.000049244587784986 ETH | 0.000033832417094415 ETH |
logs |
Redeemed(Dinda, 100 PTS) |
empty |
| PTS afterwards | 60 | still 115 |
effectiveGasPrice = that block's base fee + the tip: block 6 has a base fee of 450,674,241, plus a 1 gwei tip. Yoga's transaction reverted, so all its changes were undone and it left no log. But the EVM's work up to the revert is still paid for: 24,263 gas, not 0 and not 100,000. The rest of the gas limit is refunded; the whole limit is lost only when the gas runs out midway (out of gas). Yoga's nonce is used up too: his next transaction takes nonce 1.
Reverts with a custom error
Before sending, simulate. simulateContract runs the transaction through eth_call, so a revert shows up with no signature and no gas:
await publicClient.simulateContract({ account: YOGA, address: PTS, abi, functionName: 'redeem', args: [parseUnits('200', 18)] })
The contract function "redeem" reverted.
Error: NotEnoughPoints(uint256 balance, uint256 needed)
(115000000000000000000, 200000000000000000000)
The node really only returns bytes of revert data. viem can read them because error NotEnoughPoints is in the abi:
0x9badc4e6 selector NotEnoughPoints(uint256,uint256)
0000000000000000000000000000000000000000000000063bf212b431ec0000 115 × 10^18, Yoga's balance
00000000000000000000000000000000000000000000000ad78ebc5ac6200000 200 × 10^18, the amount asked for
An error selector is worked out exactly like a function selector. In ethers v6, an error from sending can arrive as execution reverted (unknown custom error); turn it into a name and arguments with points.interface.parseError(error.data).
Waiting for confirmations
Once it's in block 6, Dinda's transaction has 1 confirmation. Every new block on top adds one. After block 7 is mined, waitForTransactionReceipt({ hash, confirmations: 2 }) returns (in ethers: tx.wait(2)). The more confirmations, the smaller the chance its block gets replaced. For things that really matter, wait until its block is finalized (the previous lesson).
A stuck transaction and how to replace it
Yoga tries again for 100 PTS, but sets maxFeePerGas to 0.1 gwei (100,000,000 wei), below block 7's base fee (394,403,705 wei). The mempool accepts it, but it can't get into a block: block 8 is mined without it. While it isn't in a block, a transaction can be replaced: send a new one with the same nonce and a higher fee. The Hardhat node refuses a raise that's too small:
Replacement transaction underpriced. A gasPrice/maxFeePerGas of at least 110000000 is necessary to replace the existing transaction with nonce 1.
With maxFeePerGas at 2 gwei and a 1 gwei tip, the replacement lands in block 9 (status success, 33,946 gas), Yoga has 15 PTS left, and the old hash is gone: Transaction with hash "0x5250727da7169bd826b23c2f8abd09a34d6bfa89536394709c0683b3a6cca8d1" could not be found. viem tells you through onReplaced in waitForTransactionReceipt, with reason: 'repriced'. To cancel, replace it with a 0 ETH transaction to your own address with the same nonce. But once a transaction is in a block, nothing can be cancelled any more: a blockchain has no undo button.
⚠️ Habits that leave a transaction stuck or waste gas
- Taking the hash as success. The hash is only a ticket. Wait for the receipt, then check
status. - Sending without simulating. A revert you could have caught for free with
simulateContractorestimateGasbecomes a revert you pay for. - Managing the nonce yourself. A skipped nonce makes every later transaction wait. Let the wallet or library fill it; set a nonce by hand only to replace a stuck transaction.
- A fee that's too low. If
maxFeePerGasis under the base fee, the transaction sits in the mempool. Replace it with the same nonce and a higher fee.
TL;DR: A transaction goes through build, sign, send, mined, receipt. Its fields: to, value, data, nonce (the per-account order), the gas limit, maxFeePerGas and maxPriorityFeePerGas (EIP-1559), chainId, then the signature from the private key. viem: prepareTransactionRequest, sendTransaction, waitForTransactionReceipt; ethers: tx.wait(). A hash isn't proof: check receipt.status (1 success, 0 revert). A revert undoes the changes but the gas used is still paid (Yoga: 24,263 gas). Simulate first: NotEnoughPoints(115, 200) is read from the revert data 0x9badc4e6.... Confirmations grow with each block. A stuck transaction is replaced with the same nonce and a higher fee; one that's already in a block can't be cancelled.
⚡ The nonce: each account's queue number
Meaning: The nonce starts at 0. A node only processes nonce 1 after nonce 0 is done, and each nonce can be used only once. That's what stops the same transaction from being replayed.
⚡ A hash is only a ticket
Write:
const hash = await dinda.sendTransaction(request)
const receipt = await publicClient.waitForTransactionReceipt({ hash })
Meaning: After sending a transaction, wait until it's in a block, then check receipt.status: 1 is success, 0 is a revert. In ethers, that's tx.wait().
⚡ A revert still pays for gas
Guess first: Yoga redeems 200 PTS with a 100,000 gas limit, but his balance is only 115. How much gas does he pay for?
24,263 gas, not 0 and not 100,000. The changes are undone, but the EVM's work up to the revert is still paid for, and the rest of the gas limit is refunded.
Meaning: Simulate first with simulateContract, so a revert shows up for free, with no signature.
⚡ A stuck transaction is replaced, not cancelled
Meaning: While it isn't in a block, send a new one with the same nonce and a higher fee. Once a transaction is in a block, nothing can cancel it.