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



我尝试从web3.js节点库中部署智能合约,我从中获取交易哈希,但是在矿工开采后如何获取合约地址?

终于我得到了答案

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(( 方法等到区块挖矿结束并返回交易地址(此处为合约地址(。如果您不想使用小狐狸钱包对交易进行签名并广播到网络,则此方法适用。

这将返回合约地址...

MyContract是通过迁移创建的build/contracts文件夹中的 .json 文件。

const netId = await web3.eth.net.getId();
const deployedNetwork = MyContract.networks[netId];

const contract = new web3.eth.Contract(
MyContract.abi,
deployedNetwork.address
);

在对象后添加.address

var contact = web3.eth.contract.new(abi,{from: web3.eth.accounts[0], data: bc});
console.log(contract.address); // Prints address

如果您只想通过部署智能合约的交易哈希获取智能合约,则可以使用 web3.eth.getTransactionReceipts 获取交易哈希的收据。如果交易是部署,则收据中填写了联系人地址字段。 看看这个: https://github.com/ChainSafe/web3.js/issues/3515

最新更新