You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Web3获取交易哈希以调用getTransactionReceipt()方法

获取交易哈希并使用getTransactionReceipt打印交易信息

1. 调用合约函数时直接获取交易哈希

当你通过Truffle的合约实例调用需要发送交易的合约函数(非view/pure类型),send()方法会返回一个交易响应对象,其中的transactionHash字段就是你需要的哈希值。

示例代码:

// 假设已通过Truffle初始化合约实例 myContract
async function callContractMethod() {
  // 调用合约的交易型函数(比如转账、修改状态的方法)
  const txResponse = await myContract.methods.yourContractFunction(/* 传入函数参数 */).send({
    from: '你的钱包地址'
  });
  
  // 提取交易哈希
  const txHash = txResponse.transactionHash;
  console.log('交易哈希:', txHash);
}

注意:如果调用的是view或pure类型的只读函数,不会产生链上交易,自然也没有交易哈希。这类函数用call()方法调用,只会返回函数执行结果,不会生成交易记录。

2. 用交易哈希获取并打印交易收据

拿到交易哈希后,直接调用Web3的getTransactionReceipt()方法即可获取交易完成后的详细收据信息。为了确保交易已被打包上链,建议先等待交易确认。

示例代码:

async function fetchAndLogTxReceipt(txHash) {
  // 等待交易被区块链确认(可选但推荐,避免收据未生成)
  await web3.eth.waitForTransactionReceipt(txHash);
  
  // 获取交易收据
  const txReceipt = await web3.eth.getTransactionReceipt(txHash);
  
  // 打印完整收据或关键信息
  console.log('交易收据详情:', txReceipt);
  console.log('交易状态:', txReceipt.status ? '成功' : '失败');
  console.log('消耗Gas:', txReceipt.gasUsed);
  console.log('所在区块号:', txReceipt.blockNumber);
}

3. 完整整合示例

把调用合约和获取收据的逻辑整合,实现交易完成后自动打印信息:

async function executeTxWithLog() {
  try {
    // 1. 调用合约函数并获取交易哈希
    const txResponse = await myContract.methods.yourContractFunction(/* 参数 */).send({
      from: '你的钱包地址'
    });
    const txHash = txResponse.transactionHash;
    console.log('交易已发送,哈希:', txHash);

    // 2. 等待交易确认并获取收据
    const txReceipt = await web3.eth.waitForTransactionReceipt(txHash);
    
    // 3. 打印交易结果
    console.log('交易执行完成:');
    console.log('- 状态:', txReceipt.status ? '成功' : '失败');
    console.log('- 区块号:', txReceipt.blockNumber);
    console.log('- 实际消耗Gas:', txReceipt.gasUsed);
  } catch (err) {
    console.error('交易失败:', err.message);
  }
}

// 执行函数
executeTxWithLog();

关键注意事项

  • 只有修改链上状态的合约操作(调用非view/pure函数)才会生成交易哈希,只读操作无交易记录。
  • waitForTransactionReceipt()方法会自动等待交易被打包上链,返回确认后的收据,比直接调用getTransactionReceipt()更可靠。
  • 如果交易失败(比如Gas不足、合约逻辑报错),收据的status字段会是0,可以据此判断交易结果。

内容的提问来源于stack exchange,提问作者P00

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:20:40