Published: 20 Aug 2021 › Updated: 20 Aug 2021
工厂合约模式factory / 学习智能合约#45
从智能合约中创建另一个智能合约,就像一个工厂批量制造出产品一样。工厂模式的想法是拥有一个合约(工厂),该合约将承担创建其他合约的任务。
工厂合约创建子合约有两种方法:new方法和create2方法。
//使用new关键字来创建子合约
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Child{
uint data;
constructor(uint _data){
data = _data;
}
}
contract Factory {
Child[] public children;
function createChild(uint data) public {
Child child = new Child(data);
children.push(child);
}
}
//使用create2方法创建子合约
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Child{
uint data;
constructor(uint _data){
data = _data;
}
}
contract Factory {
Child[] public children;
function createChild(uint data) public {
//给bytecode变量赋值"Child"合约的创建字节码
bytes memory bytecode = type(Child).creationCode;
//constructor
bytes memory bytecode2 = abi.encodePacked(bytecode, abi.encode(data));
//将msg.sender打包后创建哈希
bytes32 salt = keccak256(abi.encodePacked(msg.sender));
//内联汇编
assembly {
//通过create2方法布署合约,并且加盐,返回地址
Child child := create2(0, add(bytecode2, 32), mload(bytecode2), salt)
}
children.push(child);
}
}
Leave 工厂合约模式factory / 学习智能合约#45 to:
Read more #smartcontract posts
Best Posts From lemooljiang
We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From lemooljiang
- Nextjs初体验,和Nuxt的异同
- DeepTutor:AI个性化辅导平台 / ai #57
- ComfyUI:可编程和自动化的PS / ai #56
- 将Neo4j封装进Agent / ai #55
- 闲鱼省钱大法:极限0.5折!
- 对Neo4j批量导入结构化数据 / ai #54
- langchain对neo4j进行交互,写入和查询数据 / ai #53
- 知识图谱和图数据库Neo4j的作用和使用场景 / ai #52
- SpaceX、美股和比特币
- 又是币圈血洗日!
- 链股合流,当币安也开始卖股票啰
- 天涯社区重启,爷青回?
- 诺基亚在AI时代重新杀回来啦
- 《2049:未来10000天的可能》书中的镜像世界为什么不叫元宇宙
- 今天适合吃披萨
- 开通即被封,别再给Claude送人头了!
- 两根内存条引发的“官司”
- AI·Joe V12更新, 更新GPT-5.5和DeepSeek V4 等
- 中医进校园活动反响热烈
- 猪价低伤农,猪价贵伤民