Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active August 21, 2021 10:43
Show Gist options
  • Save wobsoriano/e2a094c38186b986b83cc8419393e428 to your computer and use it in GitHub Desktop.
Save wobsoriano/e2a094c38186b986b83cc8419393e428 to your computer and use it in GitHub Desktop.
Sending signed transaction with Web3
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