I'm using Node to interact with my smart contract. I understand that I need to first sign my transaction before sending it.

In one of the StackExchange answers I see that it can be done using buildTransaction method.

How can I do the same implementation in web3JS?



var Web3 = require('web3')
var Contract = require('web3-eth-contract');
var Tx = require('ethereumjs-tx');
//infura config
const rpcURL = "infura url"
var web3 = new Web3(rpcURL);

const contractCall = () => {
    const account = <address>
    const privateKey = <privateKey>
    const contractAddress = <contractAddress>
    const contractABI = <abi>

    //init contract
    var contract = new Contract(contractABI,contractAddress);

    //vote2 function ABI
    const myData = contract.methods.<define your method here>.encodeABI();

    // transaction count
    const transactionCount = await web3.eth.getTransactionCount(account);

    // Transaction Object
    const txObject = {
        nonce:    web3.utils.toHex(transactionCount),
        to:       contractAddress,
        value:    web3.utils.toHex(web3.utils.toWei('0', 'ether')),
        gasLimit: web3.utils.toHex(2100000),
        gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
        data: myData  

    // sign
    const tx = new Tx.Transaction(txObject, {chain:'goerli', hardfork: 'petersburg'});

    const serializedTx = tx.serialize();
    const raw = '0x' + serializedTx.toString('hex');

    // Broadcast the transaction
    const transaction = await web3.eth.sendSignedTransaction(raw);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.