使用web3.js部署时如何获取智能合约地址

Abh*_*kar 4 node.js ethereum smartcontracts web3js

我试图从 web3.js 节点库中部署一个 SmartContract,我从中获得了一个交易哈希,但是在它被矿工开采后我如何获得合约地址?

Abh*_*kar 8

终于我得到了答案

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

})
Run Code Online (Sandbox Code Playgroud)

.on() 方法等待区块挖掘结束并返回交易地址(这里是合约地址)。如果您不想使用元掩码对交易进行签名并广播到网络,则此方法适用。