智能合约与以太坊 / 系统课时
根据 nonce 处理交易顺序
根据 nonce 处理交易顺序
当同一个 Ethereum 账户连续发送多笔交易时,广播先后不等于上链先后。你将通过一个关闭自动出块的本地节点,观察跳号交易为何等待、相同 nonce 的交易为何竞争,以及提高手续费后最终是哪一笔得到确认。
学习目标
- 区分已确认的账户 nonce 与节点待处理交易使用的 nonce。
- 复现 nonce 缺口、重复 nonce 和手续费替换的不同结果。
- 用交易池、交易收据和链上 nonce 排查卡住的交易。
同一发送者必须按 nonce 连续执行
外部账户(EOA)的 nonce 是其已执行交易的计数。新账户通常从 0 开始;假设账户当前链上 nonce 为 0,它的有效交易必须先消耗 0,才能消耗 1 和 2。不同发送账户有各自独立的计数,不能据此推断全网交易顺序。
| 发出的交易 | 节点可能的处理 | 上链条件 |
|---|---|---|
nonce 0 |
进入可执行的 pending 集合 | 费用与其他规则满足要求 |
nonce 2 |
因缺少 0、1 而进入 queued 集合,或被节点拒收 |
前两个 nonce 被消耗 |
第二笔 nonce 0 |
与原交易竞争同一位置,可能被拒或替换 | 仅一个版本最终入链 |
已确认后再发 nonce 0 |
nonce too low 等错误 |
不能再次消耗该 nonce |
这里的 pending 和 queued 是节点交易池的本地分类,并非链上共识状态。即使交易执行时合约回滚,交易被打包后也会消耗发送者的 nonce 并支付已使用的 Gas。

在本地关闭自动出块
准备 Foundry 的 anvil 与 Node.js 18 或更新版本。以下实验只连接 Anvil 默认开发账户,不使用主网私钥,也不会产生真实转账。新开终端启动一个全新的本地链:
anvil --no-mining --port 8545预期结果:Anvil 保持运行并在本地 8545 端口监听 RPC,请将这个终端保持打开。--no-mining 禁止收到交易后自动出块,稍后由 evm_mine 手动出块;端口若被占用,可同时修改命令和脚本中的地址。
发送跳号交易并替换待处理交易
在另一个终端将以下完整示例保存为 nonce-demo.mjs。Node.js 内置的 fetch 直接调用 JSON-RPC,eth_sendTransaction 由本地 Anvil 解锁的测试账户签名;在普通远程节点上不能假定该接口允许任意账户发交易。
const endpoint = "http://127.0.0.1:8545";
let id = 0;
async function rpc(method, params = []) {
const res = await fetch(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params })
});
const data = await res.json();
if (data.error) throw new Error(data.error.message);
return data.result;
}
const [from, to] = await rpc("eth_accounts");
const nonceAt = async (tag) =>
Number(BigInt(await rpc("eth_getTransactionCount", [from, tag])));
if (await nonceAt("latest") !== 0) {
throw new Error("请重启全新的 Anvil 后再运行实验");
}
function tx(nonce, gwei, wei) {
return {
from, to,
nonce: `0x${nonce.toString(16)}`,
gas: "0x5208",
gasPrice: `0x${(BigInt(gwei) * 1000000000n).toString(16)}`,
value: `0x${BigInt(wei).toString(16)}`
};
}
// 先提交 nonce=2,故意留下 0、1 两个缺口。
await rpc("eth_sendTransaction", [tx(2, 2, 1)]);
const pool = await rpc("txpool_status");
console.log("跳号后 queued:", Number(BigInt(pool.queued)));
const oldHash = await rpc("eth_sendTransaction", [tx(0, 2, 1)]);
let underpriced = false;
try {
await rpc("eth_sendTransaction", [tx(0, 2, 2)]);
} catch (error) {
underpriced = /replacement|underpriced/i.test(error.message);
}
console.log("同价替换被拒:", underpriced);
// 用更高 Gas 价格替换 nonce=0,再补齐 nonce=1。
const newHash = await rpc("eth_sendTransaction", [tx(0, 4, 3)]);
await rpc("eth_sendTransaction", [tx(1, 2, 1)]);
console.log("挖矿前 latest:", await nonceAt("latest"));
await rpc("evm_mine");
const oldReceipt = await rpc("eth_getTransactionReceipt", [oldHash]);
const newReceipt = await rpc("eth_getTransactionReceipt", [newHash]);
console.log("旧版 nonce=0 有收据:", oldReceipt !== null);
console.log("新版 nonce=0 有收据:", newReceipt !== null);
console.log("挖矿后 latest:", await nonceAt("latest"));执行命令:
node nonce-demo.mjs预期输出(全新 Anvil、无其他交易干扰时):
跳号后 queued: 1
同价替换被拒: true
挖矿前 latest: 0
旧版 nonce=0 有收据: false
新版 nonce=0 有收据: true
挖矿后 latest: 3latest 在手动出块之前仍为 0,因为广播成功并未改变已确认的账户状态。出块后 nonce 变为 3,意味着三个连续序号已被消耗;旧版 nonce 0 没有入块,只有高费替换版本取得收据。若脚本中途报错,请重启全新 Anvil 再完整重试,避免前次未确认交易影响结果。
在真实应用里分配和修复 nonce
RPC eth_getTransactionCount 使用 latest 查询已上链的下一个 nonce;使用 pending 则尝试计入连接节点知道的可执行待处理交易。后者受节点交易池视图影响,不能当作跨多个 RPC 提供商的全局锁。
服务端同时为一个热钱包发送多笔交易时,应在同一个持久化队列中原子分配递增 nonce,并记录 chainId、发送地址、nonce、交易哈希及状态。若两个进程各自读取 pending=7 后都发送 nonce 7,它们会竞争同一位置,而不是自动得到 7 和 8。
遇到卡单时,先核对交易发送地址与 latest、pending 的计数,再查当前交易哈希的收据;自建 Geth 节点还可用 txpool_contentFrom 查看该账户在 pending 与 queued 中按 nonce 分组的交易。共享 RPC 不一定开放 txpool_ 方法。
替换尚未确认的交易,需要保持相同发送者与 nonce,并提高费用。上面的传统 gasPrice 交易从 2 提到 4 Gwei;对于 EIP-1559 类型交易,通常应同时提高 maxPriorityFeePerGas 和 maxFeePerGas,并确保费用上限足以覆盖当前基础费。Geth 的普通交易池默认替换加价门槛为 10%,但这属于客户端策略,并非 Ethereum 共识规定;提高费用也不能保证交易一定被打包。
若报 nonce too low,先确认该序号是否已经入链;若报 replacement transaction underpriced,检查两项 EIP-1559 费用上限或传统 gasPrice 是否满足当前节点的替换规则;若高 nonce 长时间排队,则先处理最早的缺口,而非持续增加后续交易的手续费。