Solidity

變數未在建構子中設置為 msg.sender

  • October 26, 2018

Solidity 和 web3.js 1.0 有一個奇怪的問題。任何幫助將非常感激。

這是我的 Solidity 程式碼:

pragma solidity ^0.4.16;

contract Test {

   address public contractOwner;

   function TestContract() public {
       contractOwner = msg.sender;
   }

   function foo() constant returns(address) {
       return msg.sender;
   }

}

但是,為 呼叫自動生成的 getter 方法address public contractOwner會產生意想不到的結果。

> var deployed;
undefined
> var contract = new web3.eth.Contract(abi)
undefined
> accounts[0]
'0x78924d231848a2d37781e42A2Fe30737F19b6c5E'
> contract.deploy({data: bytecode}).send({
... from: accounts[0],
... gas: 3000000
... }).then((_deployed) => { deployed = _deployed })
Promise {
 _bitField: 0,
 _fulfillmentHandler0: undefined,
 _rejectionHandler0: undefined,
 _promise0: undefined,
 _receiver0: undefined }
> deployed.setProvider(provider)
true
> deployed.methods.foo().call().then(console.log)
Promise {
 _bitField: 0,
 _fulfillmentHandler0: undefined,
 _rejectionHandler0: undefined,
 _promise0: undefined,
 _receiver0: undefined }
> 0x78924d231848a2d37781e02A2Fe30v37F19b6c5E
> deployed.methods.contractOwner().call().then(console.log)
Promise {
 _bitField: 0,
 _fulfillmentHandler0: undefined,
 _rejectionHandler0: undefined,
 _promise0: undefined,
 _receiver0: undefined }
> 0x0000000000000000000000000000000000000000

如您所見,它foo()執行良好,但contractOwner()返回一個空地址。不應該是0x78924d231848a2d37781e42A2Fe30737F19b6c5E,這是from在部署期間作為屬性傳遞的內容嗎?

Test問題是契約名稱與可能是您的建構子的名稱 .之間的不匹配TestContract

因為TestContract從未執行過,owner從未被賦值,所以它保持其零值 ( address(0))。重命名合約或函式,使其作為建構子工作。

引用自:https://ethereum.stackexchange.com/questions/35709