如何使用ethers.js的JsonRpcProvider广播已签名交易?
如何广播已签名的以太坊交易(ethers.js)
请问有什么方法可以将已签名的交易(TX)广播至区块链网络?我在JsonRpcProvider实例中未找到任何含send的方法。以下是我的代码片段:
export async function signAndBroadcast(address, rawTransaction, jrpcUrl, key) { const provider = new ethers.JsonRpcProvider(jrpcUrl) expect( await checkBalance(address, provider)).toBe(true) // Initialize a new Wallet instance const wallet = new ethers.Wallet(key, provider); // Parse the raw transaction const tx = ethers.Transaction.from(rawTransaction); tx.nonce = await provider.getTransactionCount(wallet.address) const { name, chainId } = await provider.getNetwork() tx.chainId = chainId tx.value = ethers.parseUnits('32', 'ether') tx.gasLimit = 1000000 tx.gasPrice = undefined tx.type = 2 // Sign the transaction const signedTransaction = await wallet.signTransaction(tx); console.log("TX signed: " + signedTransaction) // Send the signed transaction const transactionResponse = await provider.sendTransaction(signedTransaction) // no function sendTransaction transactionResponse .then((transactionResponse) => { console.log('Transaction broadcasted, transaction hash:', transactionResponse.hash); }) .catch((error) => { console.error('Error:', error); }).finally(() => { console.log('Finished') }); }
解决方案
问题出在调用的方法名上,JsonRpcProvider并没有sendTransaction方法,广播已签名交易需要使用**broadcastTransaction**方法。
以下是修正后的TypeScript代码:
console.log("Sign TX") // Initialize a new Wallet instance const wallet = new ethers.Wallet(pk, provider); // Parse the raw transaction const tx = ethers.Transaction.from(serializeTx); tx.nonce = await provider.getTransactionCount(wallet.address) const { name, chainId } = await provider.getNetwork() tx.chainId = chainId tx.value = ethers.parseUnits('32', 'ether') tx.gasLimit = 1000000 tx.gasPrice = undefined tx.type = 2 // Sign the transaction const signedTransaction = await wallet.signTransaction(tx); console.log(" >>> TX signed: " + signedTransaction); expect(signedTransaction).not.toBe(""); console.log("Broadcast TX"); const transactionResponse = await provider.broadcastTransaction(signedTransaction); const txHash = transactionResponse.hash console.log("TxHash => ", txHash);
内容的提问来源于stack exchange,提问作者27P
相关产品推荐
相关产品推荐

