【问题标题】:How to manually create the instance of the contract in truffle如何在松露中手动创建合约实例
【发布时间】:2018-07-23 22:07:41
【问题描述】:

假设我有 2 份这样的合同

A.sol
import './B.sol';
contract A {
    event BCreated(address addressOfB);
    function createB(){
        B b = new B();   
        BCreated(b);
    }
}


B.sol
contract B {    
    uint8 value = 5;
    function getValue() constant returns(uint8){
        return value;
    }
}

我正在尝试为这些合同编写测试用例。 我可以使用迁移文件部署合约 A 并将 获取它的实例。

但是我不确定如何获取合约 B 的实例, 使用函数 createB() 创建合约后

好的,调用createB()函数后,我可以在events中获取合约B的地址, 但不确定实例。

对于这个例子,你可以说我可以单独测试合约 B,因为它做的不多。 但在实际情况下,我需要使用来自事件的地址创建一个实例。

这里是 truffle 测试文件的一小段 js 代码 在这我有B的地址

var A = artifacts.require("./A.sol");
contract('A', (accounts) => {
    it("Value should be 5", async () => {
        let instanceOfA = await A.deployed()
        let resultTx = await instanceOfA.createB({ from: accounts[0] });
        console.log("Address of B: " + resultTx.logs[0].args.addressOfB);
        /**
         * How do I create the instance of B now?
         */
    })
})

【问题讨论】:

    标签: ethereum solidity truffle


    【解决方案1】:

    你可以试试这样

    var A = artifacts.require("./A.sol");
    var B = artifacts.require("./B.sol");
    contract('A', (accounts) => {
        it("Value should be 5", async () => {
            let instanceOfA = await A.deployed()
            let resultTx = await instanceOfA.createB({ from: accounts[0] });
            console.log("Address of B: " + resultTx.logs[0].args.addressOfB);
    
            let instanceOfB = await B.at(resultTx.logs[0].args.addressOfB);
    
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2019-06-13
      • 2022-08-09
      • 1970-01-01
      • 2018-02-13
      相关资源
      最近更新 更多