0

I have tried to deploy a SmartContract from web3.js node library, I am getting a transaction hash from it but how would I get the contract address after It's been mined by a miner? here is my code

const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/<Api key>");
const web3 = new Web3(provider);

const account1 = '<acc address>';
web3.eth.defaultAccount = account1;

const privateKey1 = Buffer.from('<private key here>', 'hex');

const myData = "<data here>"

web3.eth.getTransactionCount(account1, (err, txCount) => {
// Build the transaction
  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(4700000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
    data: myData  
  }
    // Sign the transaction
    const tx = new Tx(txObject);
    tx.sign(privateKey1);

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

    // Broadcast the transaction
   web3.eth.sendSignedTransaction(raw, (err, tx) => {
        console.log(tx);
    })
});

2 Answers 2

3

The callback is returning the transaction hash. Instead, I suggest you to use "promise" or ".on" to get the receipt as documented in the package document https://web3js.readthedocs.io/en/1.0/web3-eth.html#sendsignedtransaction

It would look like something like:

// Broadcast the transaction
web3.eth.sendSignedTransaction(raw)
.on('receipt', console.log);

or

// Broadcast the transaction
web3.eth.sendSignedTransaction(raw)
.then(receipt => console.log(receipt);
1

You may want to consider the following alternative for deploying a contract (tested with web3 v1.0.0-beta.34):

async function deploy(contractName, contractArgs) {
    const abi = fs.readFileSync(YOUR_ARTIFACTS_PATH + contractName + ".abi");
    const bin = fs.readFileSync(YOUR_ARTIFACTS_PATH + contractName + ".bin");
    const contract = new web3.eth.Contract(JSON.parse(abi));
    const options = {data: "0x" + bin, arguments: contractArgs};
    const transaction = contract.deploy(options);
    const handle = await send(transaction);
    const args = transaction.encodeABI().slice(options.data.length);
    return new web3.eth.Contract(JSON.parse(abi), handle.contractAddress);
}

async function send(transaction) {
    const options = {
        to   : transaction._parent._address,
        data : transaction.encodeABI(),
        gas  : (await util.web3.eth.getBlock("latest")).gasLimit
    };
    const signedTransaction  = await web3.eth.accounts.signTransaction(options, YOUR_PRIVATE_KEY);
    const transactionReceipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
    return transactionReceipt;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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