Go-Ethereum

使用 web3.js 探勘合約地址後如何獲取合約地址

  • June 7, 2019

我試圖從 web3.js 節點庫部署一個 SmartContract,我從中獲得了一個交易雜湊,但是在它被礦工開採後我將如何獲得契約地址?這是我的程式碼

const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/<Api key>");
const web3 = new Web3(provider);

const account1 = '<acc address>';
web3.eth.defaultAccount = account1;

const privateKey1 = Buffer.from('<private key here>', 'hex');

const myData = "<data here>"

web3.eth.getTransactionCount(account1, (err, txCount) => {
// Build the transaction
 const txObject = {
   nonce:    web3.utils.toHex(txCount),
   gasLimit: web3.utils.toHex(4700000),
   gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
   data: myData  
 }
   // 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, tx) => {
       console.log(tx);
   })
});

回調正在返回事務雜湊。相反,我建議您使用“promise”或“.on”來獲取包裹文件中記錄的收據https://web3js.readthedocs.io/en/1.0/web3-eth.html#sendsignedtransaction

它看起來像:

// Broadcast the transaction
web3.eth.sendSignedTransaction(raw)
.on('receipt', console.log);

或者

// Broadcast the transaction
web3.eth.sendSignedTransaction(raw)
.then(receipt => console.log(receipt);

您可能需要考慮以下替代方案來部署合約(使用 web3 v1.0.0-beta.34 測試):

async function deploy(contractName, contractArgs) {
   const abi = fs.readFileSync(YOUR_ARTIFACTS_PATH + contractName + ".abi");
   const bin = fs.readFileSync(YOUR_ARTIFACTS_PATH + contractName + ".bin");
   const contract = new web3.eth.Contract(JSON.parse(abi));
   const options = {data: "0x" + bin, arguments: contractArgs};
   const transaction = contract.deploy(options);
   const handle = await send(transaction);
   const args = transaction.encodeABI().slice(options.data.length);
   return new web3.eth.Contract(JSON.parse(abi), handle.contractAddress);
}

async function send(transaction) {
   const options = {
       to   : transaction._parent._address,
       data : transaction.encodeABI(),
       gas  : (await util.web3.eth.getBlock("latest")).gasLimit
   };
   const signedTransaction  = await web3.eth.accounts.signTransaction(options, YOUR_PRIVATE_KEY);
   const transactionReceipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
   return transactionReceipt;
}

引用自:https://ethereum.stackexchange.com/questions/71578