gpt4 book ai didi

node.js - 合约地址在控制台中返回为未定义

转载 作者:行者123 更新时间:2023-12-02 21:28:53 25 4
gpt4 key购买 nike

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

var accounts_list = web3.eth.accounts;
var code = fs.readFileSync('Voting.sol').toString();
var compiledCode = solc.compile(code);
var abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)
var VotingContract = web3.eth.contract(abiDefinition)
var byteCode = compiledCode.contracts[':Voting'].bytecode
var deployedContract = VotingContract.new(['Itachi','Luffy','Midoriya'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
var deployedContractAddress = deployedContract.address;

var contractInstance = VotingContract.at(deployedContract.address);
// contractInstance.voteForCandidate('Itachi', {from: web3.eth.accounts[0]}) // function to vote for Itachi
// contractInstance.totalVotesFor.call('Itachi').toLocaleString() // function to return Itachi's votes

var deployedAddress = contractInstance.address;

console.log(contractInstance.address);

输出是:未定义

但是当我在 Node 控制台上手动运行每个命令时,情况并非如此。当我尝试 typeofcontractInstance.address 时,它输出为“String”

但我不想每次都手动运行每个命令因此尝试在脚本中运行它

最佳答案

the documentation ,如果您同步部署合约,该函数会立即返回交易哈希,但您需要轮询交易的状态,直到它被挖掘。 (只有这样合约的地址才可用。)

作为替代方案,您可以异步部署合约:

VotingContract.new(['Itachi','Luffy','Midoriya'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}, function (err, deployedContract) {
if (deployedContract.address) {
console.log(`Address: ${deployedContract.address}`);
// use deployedContract here
}
});

关于node.js - 合约地址在控制台中返回为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com