2017-07-16 48 views
0

我试图获取部署的HelloWorld协议在节点应用程序中运行。我想运行call()函数来检查它像这样:无法在部署的合同中调用函数

const deployed = helloWorldContract.new({ 
    from: acct1, 
    data: compiled.contracts[':HelloWorld'].bytecode, 
    gas: 151972, 
    gasPrice: 5 
}, (error, contract) => { 
    if(!error){ 
     console.log(contract.displayMessage.call()); 
    } else { 
     console.log(error); 
    } 
}); 

这里是参考合同:

contract HelloWorld { 
    function displayMessage() public constant returns (string){ 
    return "hello from smart contract - {name}"; 
    } 
} 

当我尝试console.log(contract.displayMessage.call())回调,返回:TypeError: Cannot read property 'call' of undefined,但是,当我登录console.log(contract.displayMessage)它返回这个:

{ [Function: bound ] 
    request: [Function: bound ], 
    call: [Function: bound ], 
    sendTransaction: [Function: bound ], 
    estimateGas: [Function: bound ], 
    getData: [Function: bound ], 
    '': [Circular] } 

我在做什么错在这里?我如何在已部署的合同中运行功能call

+0

是不是一个功能,而不是一个属性? – Florian

+0

正确。如果这是一个属性,我不会用'contract.displayMessage.call'访问吗?如果它是一个函数,我不用'contract.displayMessage.call()'来访问它吗?将问题的合同代码添加到清晰度 – joep

+0

我的意思是displayMessage? – Florian

回答

1

我认为你的问题可能是由.new构造函数造成的。我个人不建议使用它,因为它很奇怪。相反,您应该将字节码作为标准事务进行部署。

无论如何,如果你看source code.new你会看到回调实际上是被称为两次。这是完全不标准的,据我所知,没有证件。

发送交易后第一次调用回调,contract对象设置为transactionHash

第二次调用回调时,contract对象应具有address属性集。这是你想要的,因为没有地址属性,你不能调用契约方法。

总之,试试这个

const deployed = helloWorldContract.new({ 
    from: acct1, 
    data: compiled.contracts[':HelloWorld'].bytecode, 
    gas: 151972, 
    gasPrice: 5 
}, (error, contract) => { 
    if (error){ 
     console.error(error); 
    } else { 
     console.log(contract); 
     if (contract.address) { 
     console.log(contract.displayMessage()); 
     } 
    } 
}); 

为了不使用.new方法部署合同,你首先需要生成合同字节码和ABI。您可以使用solc或在线固体编译器或其他任何方式获得它。

然后要部署合同,您使用web3.eth.sendTransaction并将data参数设置为字节码,并使用空的to地址。 sendTransaction会返回你一个transactionHash,你需要等待被开采和确认。最简单的方法是通过轮询 - 一个好的起点可以是我写的这种方法 - https://gist.github.com/gaiazov/17c9fc7fdedf297e82386b74b34c61cd

如果你的合约需要构造函数参数,它们被附加到字节码, data: bytecode + encodedConstructorArguments

+0

非常感谢!你是对的,它被称为两次,我没有线索(因为我甚至没有得到那么多)。 你能提供一个关于如何将字节码作为标准事务部署的建议吗? – joep

+0

我添加了有关如何在不使用“新”方法的情况下部署合同的简短说明。它有点高层次,但我希望它有帮助! – gaiazov