使用Infura Ropsten节点调用eth_sendTransaction报错不存在如何解决
报错核心原因及解决方法
1. 直接报错原因:Infura 节点不支持eth_sendTransaction接口
eth_sendTransaction方法需要节点持有发起地址的私钥,在节点侧完成交易签名后再广播,Infura 作为公共节点不会存储任何用户私钥,因此默认禁用了该接口,你必须改用eth_sendRawTransaction,在本地完成交易签名后再将序列化后的原始交易发送给 Infura 广播。
2. 现有代码逻辑错误:当前代码是 ETH 转账逻辑,无法实现 ERC20 代币转账
ERC20 代币转账本质是调用代币合约的transfer方法,你当前的交易配置里to字段填了收款地址、value字段填了转账金额,这是标准 ETH 转账的写法,完全不符合 ERC20 转账规则。正确的交易配置应为:
to字段填 ERC20 代币的合约地址value字段填 0data字段拼接transfer方法的 ABI 编码,包含收款地址和转账金额两个参数
修复后的参考代码
const Web3 = require('web3'); const web3 = new Web3('替换为你的Infura Ropsten节点地址'); const Tx = require('ethereumjs-tx').Transaction; // 需提前安装ethereumjs-tx依赖 // ERC20合约ABI,仅保留transfer方法的定义即可 const erc20Abi = [ { "constant": false, "inputs": [ {"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"} ], "name": "transfer", "outputs": [{"name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]; const fromAddress = "替换为你的发起转账地址"; // 私钥去掉0x前缀后转Buffer,注意私钥绝对不要泄露,仅本地测试使用 const privateKey = Buffer.from('替换为你的发起地址私钥,去掉0x前缀', 'hex'); const tokenContractAddress = "替换为ERC20代币的合约地址"; const toAddress = "替换为收款地址"; // 若你的ERC20代币小数位不是18,需自行调整金额计算逻辑,不要直接用toWei const transferAmount = web3.utils.toWei('50', 'ether'); // 初始化代币合约实例 const tokenContract = new web3.eth.Contract(erc20Abi, tokenContractAddress); // 编码transfer方法的调用参数,作为交易的data字段 const data = tokenContract.methods.transfer(toAddress, transferAmount).encodeABI(); // 获取发起地址的当前nonce web3.eth.getTransactionCount(fromAddress, (err, nonce) => { const txParams = { nonce: web3.utils.toHex(nonce), gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')), gasLimit: web3.utils.toHex(100000), // ERC20转账一般消耗6-8万gas,留足够余量 to: tokenContractAddress, value: web3.utils.toHex(0), // 转ERC20不需要附带ETH,value填0 data: data, chainId: 3 // Ropsten测试网的chainId为3 }; // 本地用私钥签名交易 const tx = new Tx(txParams, {chain: 'ropsten'}); tx.sign(privateKey); const serializedTx = tx.serialize(); const rawTx = '0x' + serializedTx.toString('hex'); // 发送签名后的原始交易到Infura web3.eth.sendSignedTransaction(rawTx, (err, txHash) => { if (err) { console.log("Transaction error", err); } else { console.log("交易哈希:", txHash); alert(txHash); } }); });
注意事项
- 上述代码仅适合本地/后端测试使用,前端场景不要硬编码私钥,对接MetaMask等钱包调用钱包内置的签名接口即可,不需要自行处理私钥。
- 转账前确认你的发起地址持有对应数量的ERC20代币,同时留有足够的ETH支付gas费。
内容的提问来源于stack exchange,提问作者Muhammad Noman
相关产品推荐
相关产品推荐

