# create2创建合约

By [web3zoom](https://paragraph.com/@web3zoom) · 2025-07-22

---

    // SPDX-License-Identifier: GPL-3.0
    
    pragma solidity ^0.8.30;
    
    contract DeployWithCreate2 {
        address public owner;
    
        constructor(address _owner){
            owner = _owner;
        }
    }
    
    contract Create2Factory {
        event Deploy(address addr);
    
        function deploy(uint _salt) external {
            DeployWithCreate2 _contract = new DeployWithCreate2{
                salt: bytes32(_salt)
            }(msg.sender);
            emit Deploy(address(_contract));
        }
    
        function getAddress(bytes memory bytecode, uint _salt) public view returns(address){
            bytes32 hash = keccak256(
                abi.encodePacked(
                    // 新地址 = hash("0xFF",创建者地址, salt, initcode)
                    // address(this): 调用 CREATE2 的当前合约（创建合约）地址。
                    // keccak256(bytecode): 新合约的初始字节码（合约的Creation Code和构造函数的参数）。
                    bytes1(0xff), address(this), _salt, keccak256(bytecode)
                )
            );
            return address(uint160(uint(hash)));
        }
    
        // 获取字节码的方法
        // 将当前合约中的指定方法与EOA账号打包生成字节码
        function getBytecode(address _owner) public  pure returns(bytes memory){
            // 生成的字节码
            bytes memory bytecode = type(DeployWithCreate2).creationCode;
            return abi.encodePacked(bytecode, abi.encode(_owner));
        }
    }
    

通过salt去控制合约方法的字节码，可以提前预知

---

*Originally published on [web3zoom](https://paragraph.com/@web3zoom/create2-2)*
