컨트랙트 생성 (Create, Create2)

4e5ung·2023년 4월 7일
0

컨트랙트 생성

컨트랙트 생성에는 Create, Create2 2가지 형태가 있으며, 컨트랙트내에서 컨트랙트를 생성 할 수도 있다.

Create

(0xF0 OPCODE)

sendernonce를 이용하여 RLP 인코딩 후 생성하는 방식으로 nonce 증가함에 따라 생성되는 컨트랙트 주소가 변경 된다.

※ 컨트랙트에도 nonce 값은 존재하며 0이 아닌 1부터 시작한다 (EIP-161)
컨트랙트의 nonce 값은 컨트랙트가 다른 컨트랙트를 생성하는 경우에만 증가한다.

keccak256(rlp([sender, nonce]))[12:]

Create2

(EIP-1014, OxF5 OPCODE)

0xff, address, salt, initcode 를 통해 컨트랙트를 생성하는 방식으로, 같은 값을 사용한다면 동일한 주소로 컨트랙트를 생성 할 수 있다. (일반적으로 동일 주소로 재배포는 불가능하며 selfdesturct를 통해 삭제했을 경우 가능)

keccak256( 0xff ++ address ++ salt ++ keccak256(init_code))[12:]


Create2 사용에는 Solidity 0.6.0 버전 이전과 이후로 나뉘어진다.

Solidity 0.6.0 버전 이전

new 키워드를 사용하여 컨트랙트를 생성할 때 salt 값을 직접 사용하는 것이 불가능해서 creat2 함수를 사용하여 컨트랙트를 생성하는 방법을 사용하였다.

UniswapV2Factory.sol

   bytes memory bytecode = type(UniswapV2Pair).creationCode;
   bytes32 salt = keccak256(abi.encodePacked(token0, token1));
   assembly {
       pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
   }

※ creationCode는 컨트랙트 생성 바이트코드를 나타낸다, assembly 코드를 이용할때 creationCode 이용하여 컨트랙트 생성


Solidity 0.6.0 버전 이후

new 키워드에서 salt 값을 사용하여 컨트랙트를 생성하는 기능이 추가되어, 이를 통해 create2 함수를 사용하지 않고도 예측 가능한 주소에 컨트랙트를 생성할 수 있게 됬었다.

contract D {
    uint public x;
    constructor(uint a) {
        x = a;
    }
}

contract C {
    function createDSalted(bytes32 salt, uint arg) public {
        // This complicated expression just tells you how the address
        // can be pre-computed. It is just there for illustration.
        // You actually only need ``new D{salt: salt}(arg)``.
        address predictedAddress = address(uint160(uint(keccak256(abi.encodePacked(
            bytes1(0xff),
            address(this),
            salt,
            keccak256(abi.encodePacked(
                type(D).creationCode,
                abi.encode(arg)
            ))
        )))));

        D d = new D{salt: salt}(arg);
        require(address(d) == predictedAddress);
    }
}

Ref

https://docs.soliditylang.org/en/v0.8.18/control-structures.html#creating-contracts-via-new
https://velog.io/@bbabi0901/Solidity-Create-Create2
https://medium.com/onther-tech/create2-%EC%B7%A8%EC%95%BD%EC%A0%90-%EB%B6%84%EC%84%9D-d82e913ad28b

0개의 댓글