Web3js – How to Sign a Send Method in Web3 1.0

signatureweb3js

I have the following function and don't want to manually sign the transaction every time it's called, how would I go about setting up a way of signing this transaction with an object. I've seen sendRawTransaction and account.signTransaction but can't figure out a way to implement these in my issue.

this.contractObject = this.contractObject = {from: this.account, gas:300000};

this.contract.methods.createCountry(arg1, 1rg2, arg3).send(this.contractObject, (err, res) => {
                if (err) {
                    throw err;
                } else {
                    console.log(res);
                }
            })

The following function gets added in a batch, I don't know if this will matter.

Best Answer

First, you need to generate your transaction, here is an example:

   let tx_builder = contractInstance.methods.myMethod(arg1, arg2, ...);
let encoded_tx = tx_builder.encodeABI();
let transactionObject = {
    gas: amountOfGas,
    data: encoded_tx,
    from: from_address,
    to: contract_address
};

Then you can sign the transaction, using the address and the private key of this specific address. When it is signed, you can send it to the node:

        web3g.eth.accounts.signTransaction(transactionObject, private_key, function (error, signedTx) {
        if (error) {
        console.log(error);
        // handle error
    } else {
web3g.eth.sendSignedTransaction(signedTx.rawTransaction)
        .on('receipt', function (receipt) {
            //do something
     });
    }

Edit: After signing it, you don't have to send it. You can add it to the batch request.

Related Topic