首页 > 解决方案 > 从 web3js 调用 Factory 合约的子函数

问题描述

给定一份合同Example和一份工厂合同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);
  }
}

我如何printName在我的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!!
    })

  })
})

标签: ethereumsolidityweb3jstruffle

解决方案


调用this.exampleFactory.examples(0)返回子合约的地址,web3.js 不知道 ABI。需要导入孩子的ABI,用地址实例化一个对象

artifacts.require("Example" )

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

推荐阅读