Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually create the instance of the contract in truffle

Say I have 2 contracts like this

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;
    }
}

I am trying to write the test cases for these contracts. I can deploy the contract A using the migrations file and will get the instance of it.

But I am not sure about how to get the instance of contract B, after the contract is created using function createB()

Ok I can get the address of the contract B in events after calling function createB(), But not sure about the instance.

For this example, you can say that I can separately test contract B as it doesn't do much. But in the real case, I need to create an instance using the address coming from the event.

Here is the little bit of js code for truffle test file In this I have the address of 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?
         */
    })
})
like image 528
utkarsh tyagi Avatar asked Feb 13 '18 13:02

utkarsh tyagi


1 Answers

You can try to do it like this

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);

    })
})
like image 55
Vitaly Migunov Avatar answered Oct 17 '22 15:10

Vitaly Migunov