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

时间:2018-10-10 11:05:12

标签: node.js ethereum smartcontracts web3js

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

3 个答案:

答案 0 :(得分:2)

最终我得到了答案

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()方法等到区块挖掘结束并返回交易地址(此处为合同地址)。如果您不想使用元掩码来签署交易并广播到网络,则此方法适用。

答案 1 :(得分:0)

在对象之后添加.address

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

答案 2 :(得分:0)

这将返回合约地址...

MyContractbuild/contracts 文件夹中由迁移创建的 .json 文件。

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


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