Search code examples
ethereumsolidityweb3jstruffle

Calling function in child of Factory contract from web3js


Given a contract Example and a factory contract ExampleFactory:

//Example.sol

contract ExampleFactory {
  Example [] public examples;

 function newExample(bytes32 _name) {
   Example example = new Example(_name);
   examples.push(example);
 }
}

contract Example {

  bytes32 public name;
  bool printed;
  event Print(bytes32);

  constructor(bytes32 _name) {
    name = _name;
  }

  function printName() public {
    printed = true;
    emit Print(name);
  }
}

How do I call printName within my truffle test?:

//Example.test.sol

artifacts.require("ExampleFactory");

contract("Example", function () {

  beforeEach(async function() {
    this.exampleFactory = await ExampleFactory.new()
    await ExampleFactory.newExample(web3.utils.utf8ToHex("hello"))
  })

  describe("printName()", function () {

    it("PRINTS!", async function() {
     const example = await this.exampleFactory.examples(0);
     await example.printName() // example.printName is not a function!!
    })

  })
})

Solution

  • Calling this.exampleFactory.examples(0) returns the address of the child contract, which web3.js doesn't know the ABI. You need to import the child's ABI and instantiate an object with the address

    artifacts.require("Example" )
    
    Const example = await Example.at(await this.exampleFactory.examples(0))