Assessment reports>Singularity>Discussion>Gas saving in MerkleTreeOperator

Gas saving in MerkleTreeOperator by reusing merkleRoots

The MerkleTreeOperator contract has a state variable that is a dynamic array of bytes32 containing all previous Merkle roots: bytes32[] public merkleRoots;. This array is not used to check which Merkle roots have already appeared, however; this is done with the merkleRootIsAllowed function, which uses the merkleRootsAllowed mapping instead:

function merkleRootIsAllowed(
    bytes32 _merkleRoot
) external view returns (bool) {
    return merkleRootsAllowed[_merkleRoot];
}

From the merkleRoots array, only the last component is ever used to get the most recent Merkle root. It would thus be possible to make merkleRoots of type bytes32 instead and update it with merkleRoots = leaf; instead of merkleRoots.push(leaf);, replacing the access merkleRoots[merkleRoots.length - 1] with merely merkleRoots. This would save a decent amount of gas, as writing in previously used storage locations is cheaper than writing to previously unused locations (using the array also requires additional reads and writes to access and update the length).

Singularity implemented the suggested changes in

Zellic © 2024Back to top ↑