<!-- canonical: https://0xsimao.com/findings/metazero-ii-variables-cached-memory-gas -->

# Variables should be cached to memory to save gas

Low/Info · Three Sigma · Omnichain RWA tokenisation · 6th April, 2024

Finding 3S-MZ-N01 of the MetaZero Staking security review.

- Protocol: https://metazero.gg/
- Report: /reports/metazero-ii
- Codebase: https://github.com/0xsimao/stakingContract/tree/dffac73e838a9fbd12bed18e41b9799177bcde7f
- Source: https://cdn.sanity.io/files/qoqld077/production/3e07b0c2806b62578b8031e88c59bc5dbd38de1b.pdf

---

### Description

Storage reads are expensive and should be avoided. This is usually done by caching storage
variables in memory ones.

### Recommendation

Replace all storage rewards that happen more than once per function (or even better, per
flow) for memory caching.
Example:

```solidity
function rewardPerToken() public view returns (uint256) {
    uint256 totalStakedAccruingRewardsCached = totalStakedAccruingRewards;
    if (totalStakedAccruingRewardsCached == 0) {
        return rewardPerTokenStored;
    }
    return rewardPerTokenStored + (
```

(lastApplicableTime() - lastUpdateTime) * rewardRate * 1e18 /
totalStakedAccruingRewardsCached

```solidity
);
}
```

### Status

Acknowledged

---

Related findings:

- [Storage variables should be cached whenever possible to save gas](https://0xsimao.com/findings/glacier-storage-cached-whenever-gas): Glacier
- [Storage variables can be cached to save gas](https://0xsimao.com/findings/mitosis-storage-variables-cached-gas): Mitosis
- [Storage variables can be cached to save gas](https://0xsimao.com/findings/orange-storage-variables-cached-gas): Orange Bridge
- [pool-v2-private: cache list length in memory and uncheck i_ to save gas.](https://0xsimao.com/findings/maple-finance-iii-private-cache-uncheck-gas): Maple Finance
