Last active
August 21, 2021 10:43
-
-
Save wobsoriano/e2a094c38186b986b83cc8419393e428 to your computer and use it in GitHub Desktop.
Sending signed transaction with Web3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Common, { Chain } from '@ethereumjs/common' | |
| import { Transaction } from '@ethereumjs/tx' | |
| import Web3 from 'web3' | |
| const web3 = new Web3('https://ropsten.infura.io/v3/blablablabla') | |
| const account1 = 'YOUR_ACCOUNT_1' | |
| const privateKey1 = Buffer.from('YOUR_ACCOUNT_1_PRIVATE_KEY', 'hex') | |
| const account2 = 'YOUR_ACCOUNT_2' | |
| const sendSignedTransaction = async () => { | |
| const txCount = await web3.eth.getTransactionCount(account1) | |
| const { toHex, toWei } = web3.utils | |
| // Build the transaction | |
| const txData = { | |
| nonce: toHex(txCount), | |
| to: account2, | |
| value: toHex(toWei('1', 'ether')), | |
| gasLimit: toHex(21000), | |
| gasPrice: toHex(toWei('10', 'gwei')) | |
| } | |
| const common = new Common.default({ chain: Chain.Ropsten }) | |
| // Sign the transaction | |
| const tx = Transaction.fromTxData(txData, { common }) | |
| const signedTx = tx.sign(privateKey1) | |
| const serializedTx = signedTx.serialize() | |
| const raw = '0x' + serializedTx.toString('hex') | |
| // Broadcast the transaction | |
| const txHash = await web3.eth.sendSignedTransaction(raw); | |
| console.log('txHash: ', txHash) | |
| } | |
| sendSignedTransaction() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment