[Ethereum] INIT_CODE_HASH and how is it calculated / used in DeFi smart contracts

defi

I am forking the Sushiswap Exchange code for educational purposes, and I have come across a variable in the code called INIT_CODE_HASH. I am struggling to understand exactly how this variable works, and how it is used in the various DeFi platforms.

My limited understanding is that INIT_CODE_HASH is used to verify which function of a contract a caller is calling, by using the hash of the init code (Not really sure what the init code is). For some reason I don't quite understand, this is both for security and efficiency purposes.

My Question:

What is INIT_CODE_HASH, and how is it calculated / used?

Best Answer

INIT_CODE_HASH is a hash of the initcode of a contract. The initcode is the code that creates the bytecode that is stored on-chain. You can read more about the types of bytecode here.

Most dapps, including Sushiswap, use this variable to create a new contract with create2. When a dapp wants to create a contract with a known address, they will use the create2 opcode, which uses the hashed initcode as a parameter. The EIP for it is here.

You can see that Sushiswap uses it in this getCreate2Address address:

[tokens[1].address]: getCreate2Address(
            FACTORY_ADDRESS,
            keccak256(['bytes'], [pack(['address', 'address'], [tokens[0].address, tokens[1].address])]),
            INIT_CODE_HASH
          )
Related Topic