合同地址在控制台中以未定义的形式返回

时间:2018-06-09 06:13:18

标签: node.js ethereum web3

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时,它输出为“字符串”

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

1 个答案:

答案 0 :(得分:2)

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