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

如何用Node.js(如Web3.js)通过交易ID获取以太坊原始交易

获取以太坊原始交易的Node.js实现

核心思路

当eth_getRawTransaction返回空时,可通过获取交易的完整字段后手动进行RLP编码生成原始交易——以太坊原始交易本质就是按固定顺序排列的交易字段的RLP编码结果。

具体步骤

  1. 获取交易完整字段
    通过eth_getTransactionByHash RPC调用获取目标交易的所有关键字段:nonce、gasPrice、gasLimit、to、value、data、v、r、s。

  2. RLP编码生成原始交易
    严格按照[nonce, gasPrice, gasLimit, to, value, data, v, r, s]的顺序对字段进行RLP编码,即可得到原始交易数据。

Node.js代码示例

使用ethers.js库实现(无需额外安装RLP工具,ethers内置RLP编码功能):

const { ethers } = require("ethers");

async function generateRawTransaction(txHash, providerUrl) {
  const provider = new ethers.JsonRpcProvider(providerUrl);
  const tx = await provider.getTransaction(txHash);

  // 处理合约创建交易的空to字段,替换为零地址
  const toAddress = tx.to ? tx.to : ethers.ZeroAddress;

  // 按固定顺序准备编码字段
  const txFields = [
    tx.nonce,
    tx.gasPrice,
    tx.gasLimit,
    toAddress,
    tx.value,
    tx.data,
    tx.v,
    tx.r,
    tx.s
  ];

  // 执行RLP编码
  const rawTransaction = ethers.RLP.encode(txFields);
  return rawTransaction;
}

// 使用示例
const targetTxHash = "0xafef64d0d03db9f13c6c3f8aec5902167ea680bd0ffa0268d89a426d624b2ae1";
// 替换为你的全节点服务URL(如Infura、Alchemy或本地Geth节点)
const nodeUrl = "https://mainnet.infura.io/v3/your-api-key";

generateRawTransaction(targetTxHash, nodeUrl)
  .then(rawTx => console.log("生成的原始交易:", rawTx))
  .catch(error => console.error("执行错误:", error));

注意事项

  • 必须使用全节点服务(如Infura、Alchemy)或本地全节点,轻节点可能无法返回完整的交易签名字段(v、r、s)。
  • 生成的原始交易可通过ethers.RLP.decode()解码验证,确认字段与原交易一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:01:20