【问题标题】:Contract address returning as undefined in console合约地址在控制台中返回未定义
【发布时间】:2018-06-09 06:13:18
【问题描述】:
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);

输出是:undefined

但是当我在节点控制台上手动运行每个命令时,情况并非如此。 当我尝试typeof contractInstance.address 它输出为“字符串”

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

【问题讨论】:

  • 我相信VotingContract.new 会返回Promise,而您必须等到该承诺得到解决才能获得地址。
  • 怎么做我尝试将除控制台部分之外的所有代码放在一个函数中。然后用promise调用print..还是不行
  • 其实你用的是什么版本的web3.js?
  • web3 版本:^0.20.1
  • 当我在控制台中执行它时它工作正常..但是当我将它作为脚本运行时它显示未定义..所以版本可能不是问题它可能需要对 Promises 做一些事情

标签: node.js ethereum web3


【解决方案1】:

根据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
    }
});

【讨论】:

  • 它醒了,谢谢!!
猜你喜欢
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多