合法性:合同称另一份合同和地址不同,为什么?

时间:2017-08-26 18:29:37

标签: ethereum contract solidity

我有一个实例化并调用另一个合同的包装器合同,我的测试用例说所有者(msg.sender)不匹配。为什么呢?

合同A

pragma solidity ^0.4.4;

contract A {

    address public owner;

    function A() {
         owner = msg.sender;
    }

    function createB(string name) {
        return new B(msg.sender, name);
    }
}

合同B

pragma solidity ^0.4.4;

contract B {
    address public owner;
    string public name;

    function B(address _owner, string _name) {
        owner = _owner;
        name = _name;
    }
}

测试用例

pragma solidity ^0.4.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";

contract TestB {
    B testB;
    A testA;

    function beforeEach() {
        A = A(DeployedAddresses.A());
        B = testA.createB("test");
    }

    function testOwnerIsSet() {
        Assert.equal(address(A), address(B), "Owner's address does not match");
    }
}

测试结果

 1) TestB testOwnerIsSet:
     Error: Owner's address does not match
      at /Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214233:17
      at Array.forEach (native)
      at processResult (/Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214231:19)
      at process._tickCallback (internal/process/next_tick.js:109:7)

修改

我已将address public owner添加到contract A。并在owner中公开contract B

现在我的TestB合同看起来像这样:

pragma solidity ^0.4.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";

contract TestB {
    B testB;
    A testA;

    function beforeEach() {
        A = A(DeployedAddresses.A());
        B = testA.createB("test");
    }

    function testOwnerIsSet() {
        address aOwner = A.owner();
        address bOwner = B.owner();
        Assert.equal(aOwner, bOwner, "Owner's address does not match");
    }
}

1 个答案:

答案 0 :(得分:0)

根据你所展示的内容我假设你正在使用松露?说实话,我很惊讶这会编译。

致电时,

B = testA.createB("test");

你是从TestB打来的。 msg.sender将是TestB的地址。

function createB(string name) {
    return new B(msg.sender, name); // msg.sender = TestB instance address
}

This可能有助于实现您的目标。