[Ethereum] how to get contract address after its been mined with web3.js

go-ethereumjavascriptweb3js

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);
    })
});

Best Answer

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);
Related Topic