Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State Variables that can be changed to immutable #48

Open
code423n4 opened this issue Sep 8, 2021 · 2 comments
Open

State Variables that can be changed to immutable #48

code423n4 opened this issue Sep 8, 2021 · 2 comments

Comments

@code423n4
Copy link
Contributor

Handle

hrkrshnn

Vulnerability details

State Variables that can be changed to immutable

Solidity 0.6.5
introduced immutable as a major feature. It allows setting
contract-level variables at construction time which gets stored in code
rather than storage.

Consider the following generic example:

contract C {
    /// The owner is set during contruction time, and never changed afterwards.
    address public owner = msg.sender;
}

In the above example, each call to the function owner() reads from
storage, using a sload. After
EIP-2929, this costs 2100 gas
cold or 100 gas warm. However, the following snippet is more gas
efficient:

contract C {
    /// The owner is set during contruction time, and never changed afterwards.
    address public immutable owner = msg.sender;
}

In the above example, each storage read of the owner state variable is
replaced by the instruction push32 value, where value is set during
contract construction time. Unlike the last example, this costs only 3
gas.

Examples

  1. https://github.com/althea-net/cosmos-gravity-bridge/blob/92d0e12cea813305e6472851beeb80bd2eaf858d/solidity/contracts/Gravity.sol#L59
  2. https://github.com/althea-net/cosmos-gravity-bridge/blob/92d0e12cea813305e6472851beeb80bd2eaf858d/solidity/contracts/Gravity.sol#L60
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Sep 8, 2021
code423n4 added a commit that referenced this issue Sep 8, 2021
@jkilpatr
Copy link
Collaborator

jkilpatr commented Sep 10, 2021

This is a good improvement that will have some nice gas savings considering how often we access these variables. Which should probably be hardcoded rather than constructor arguments anyways.

also mentioned (not directly though) in #44

@loudoguno
Copy link

reopening as per judges assessment as "primary issue" on findings sheet

@loudoguno loudoguno reopened this Oct 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants