区块确认对确保以太坊中的交易最终性至关重要。本指南解释了确认的工作原理以及如何在应用程序中实施它们。
// 检查确认数量
const getConfirmations = async (txHash) => {
const tx = await web3.eth.getTransaction(txHash);
const currentBlock = await web3.eth.getBlockNumber();
return tx.blockNumber ? currentBlock - tx.blockNumber : 0;
};
// 等待特定数量的确认
const waitForConfirmations = async (txHash, confirmations = 6) => {
while ((await getConfirmations(txHash)) < confirmations) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
return true;
};