ethereum - 从 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!!
})
})
})
解决方案
调用this.exampleFactory.examples(0)
返回子合约的地址,web3.js 不知道 ABI。需要导入孩子的ABI,用地址实例化一个对象
artifacts.require("Example" )
Const example = await Example.at(await this.exampleFactory.examples(0))
推荐阅读
- git - 构建错误:指定的路径、文件名或两者都太长
- flutter - 更改子项的属性不会触发 Flutter Getx 上的 UI 更改
- google-analytics - 在 Measurement Protocol 上查看 ID - Google Analytics
- docker - 无法在 docker 映像上运行本地集合
- javascript - GTM“在模板中发现无效的 HTML、CSS 或 JavaScript”
- python - 如何使用分隔符拆分文件?
- python - 如何使用函数对熊猫数据框进行布尔索引
- r - 删除 Markdown 输出中的换行符
- azure-devops - Azure devops 构建管道
- graphql - Apollo GraphQL - 处理 onConnect 和 OnDisconnect 事件