lemooljiang avatar

工厂合约模式factory / 学习智能合约#45

lemooljiang

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:

Written by

Designer , Poet , Technology enthusiasts

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