2017-07-16 18 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