Search code examples
node.jsethereumsmartcontractsweb3js

How to get Smart Contract address when it is deployed with web3.js


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?


Solution

  • finally i got the answer

    var Tx=require('ethereumjs-tx')
    const Web3=require('web3')
    const web3 = new Web3('https://rinkeby.infura.io/xxxxxxxxxxxxxxxxxx')
    
    const account1='0xf2b6xxxxxxxxxxxxxxxxxxx83e9d52d934e5c'
    const privateKey1=Buffer.from('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx','hex')    
    
    
    web3.eth.getTransactionCount(account1,(err,txCount)=>{
    //smart contract data
    const data = 'your data here'
    
    //create transaction object
    const txObject={
    nonce:web3.utils.toHex(txCount),
    gasLimit:web3.utils.toHex(1000000),
    gasPrice:web3.utils.toHex(web3.utils.toWei('10','gwei')),
    data: data
    }
    
    //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,txHash)=>{
    console.log('err : ',err,'txHash : ',txHash)
    //use this hash to find smartcontract on etherscan
    }).on('receipt', console.log,);
    
    })
    

    .on() method wait till the end of block mining and returns the address of transaction(here contract address). This method is applicable if you don't want to use metamask to sign your transaction and broadcast to the network.