Web3.js – How to Build and Sign a Transaction to Deploy a Contract

private-keytransactionsweb3js

I am trying to generate a transaction to deploy a smart contract on the chain and to sign it with web3js.

My problem is that I have no idea how to build the transaction object needed for the signTransaction function.

I first tried to create an object using the contract.deploy() function (without sending), but the transaction object needs a gas property, that the deploy() function does not create.

How do I create a transaction object that deploy a contract and how do I sign it with a private key?

Best Answer

Got it working with the following method: First, get the contract instance without specifying an address (according to documentation, it is optional):

let abi = JSON.parse(fs.readFileSync(tokenAbi).toString());
        let contractInstance = new web3g.eth.Contract(abi);

Then deploy the contract WITHOUT sending it and use the encodeABI function:

let deploy = newContract.deploy({
              data: bytecode,
              arguments: [my args here
}).encodeABI();

Build a transaction object using the deploy object and other properties as follow:

 let gas = parseInt(4000000).toString(16);
 let gasPrice = parseInt(4000000000).toString(16);
    let transactionObject = {
                     gas: gas,
                     gasPrice: gasPrice,
                     data: deploy,
                     from: req.body.sender_address
                                                };

Note: If you don't encode to hex, geth will return you an error saying it cannot parse from whatever to some Golang type

Then you ca nsign and send the signed transaction

     web3g.eth.accounts.signTransaction(transactionObject, req.body.private_key, function (error, signedTx) {
                         if (error) {
                         //do stuff
                } else {  
                      web3g.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('confirmation', function (number) {//dostuff});
Related Topic