从 web3js 调用工厂合同子项中的函数

Calling function in child of Factory contract from web3js

给定合同 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);
  }
}

如何在 truffle test 中调用 printName?:

//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!!
    })

  })
})

调用 this.exampleFactory.examples(0) returns child 合约的地址,web3.js 不知道 ABI。 您需要导入 child 的 ABI 并使用地址

实例化一个 object
artifacts.require("Example" )

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