簡體   English   中英

使用web3.js部署時如何獲取智能合約地址

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

我試圖從 web3.js 節點庫中部署一個 SmartContract,我從中獲取了一個交易哈希,但是在它被礦工開采后如何獲取合約地址?

終於我得到了答案

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() 方法等待區塊挖掘結束並返回交易地址(這里是合約地址)。 如果您不想使用元掩碼對交易進行簽名並廣播到網絡,則此方法適用。

在對象后添加.address

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

這將返回合同地址...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM