0

In contracts I often come along hardcoded constant address such as WETH:

address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

I am now curious, whats the difference between this style and the initialization by the constructor, e.g.:

address internal immutable WETH;    
constructor(uint256 _WETH){
     WETH = _WETH;
}

Especially, in terms of security and gas used during deployment and runtime.

Derawi
  • 430
  • 4
  • 12

1 Answers1

1

In terms of gas and security there is not much of a difference in the two approaches. I verified this by writing two simple contracts on remix and using the debugger mode. If you closely look at the screenshots attached for the two approaches you will see the gas limit is almost equal (although the constructor approach has a little higher value but almost equal).

Now talking about why constructors could be used to initialize value, it is used when you want to deploy a contract from another contract or use a deployment script to publish a common code but with different values for some variables (The most common use case of constructors in programming in general - Make different objects of same class but with different configuration, that applies here as well)

First contract (hardcoded value):

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Debugging2 {
    uint256 counter = 200;
}

Second contract (constructor initialization):

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Debugging {
    uint256 counter;
    constructor(uint256 _counter) {
        counter = _counter;
    }
}

Screenshot of first contract (hardcoded value) debugger :

enter image description here


Screenshot of second contract (constructor initialization) debugger :

enter image description here

Shubham Bansal
  • 438
  • 3
  • 8