Gas Optimizations #34
Labels
bug
Something isn't working
G (Gas Optimization)
resolved
Finding has been patched by sponsor (sponsor pls link to PR containing fix)
sponsor confirmed
Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
Gas Report
Table of Contents:
> 0
is less efficient than!= 0
for unsigned integers (with proof)Foreword
@audit
tagsFile: CollateralizedDebt.sol
modifier onlyConvenience()
Inline a modifier that's only used once
As
onlyConvenience()
is only used once in this contract (infunction mint()
), it should get inlined to save gas:File: TimeswapPair.sol
function mint()
Use memory variables for calculation
The code can be optimized from this:
to this:
function burn()
> 0
is less efficient than!= 0
for unsigned integers (with proof)!= 0
costs less gas compared to> 0
for unsigned integers inrequire
statements with the optimizer enabled (6 gas)Proof: While it may seem that
> 0
is cheaper than!=
, this is only true without the optimizer enabled and outside a require statement. If you enable the optimizer at 10k AND you're in arequire
statement, this will save gas. You can see this tweet for more proofs: https://twitter.com/gzeon/status/1485428085885640706I suggest changing
> 0
with!= 0
here:Also, please enable the Optimizer.
function lend()
Use memory variables for calculation
Just like in
function mint()
( Use memory variables for calculation ), the code can be optimized here by caching the new values forpool.state.x
,pool.state.y
andpool.state.z
:The same way, the final code will look like this (with the difference that
yDecrease
andzDecreased
are used here):function borrow()
Use memory variables for calculation
Just like in
function mint()
( Use memory variables for calculation ) andfunction lend()
, the code can be optimized here by caching the new values forpool.state.x
,pool.state.y
andpool.state.z
:The same way, the final code will look like this (with the difference that
xDecrease
is used here):function pay()
An array's length should be cached to save gas in for-loops
Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.
Caching the array length in the stack saves around 3 gas per iteration.
Here, I suggest storing the array's length in a variable before the for-loop, and use it instead:
General recommendation
Use Custom Errors instead of Revert Strings to save Gas
Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met)
Source: https://blog.soliditylang.org/2021/04/21/custom-errors/:
Custom errors are defined using the
error
statement, which can be used inside and outside of contracts (including interfaces and libraries).Instances include:
I suggest replacing revert strings with custom errors.
The text was updated successfully, but these errors were encountered: