code-423n4 / 2022-06-canto-v2-findings

0 stars 0 forks source link

Gas Optimizations #129

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

use ++i instead of i++ in for loops

impact

i++ is holding two numbers in memory old one +1 and ++I return just number after +1 means it holds 1 number in memory(for example

What happened in i++: int j = i; i = i + 1; return j; What happened in ++i: i = i + 1; return I;

Mitigation:

just use ++variable instead of variable++

proof of concept:

https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Governance/GovernorAlpha.sol#L181 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Governance/GovernorAlpha.sol#L197 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Governance/GovernorAlpha.sol#L211 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Governance/GovernorBravoDelegate.sol#L66 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Governance/GovernorBravoDelegate.sol#L88 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Stableswap/BaseV1-core.sol#L210 https://github.com/Plex-Engineer/lending-market-v2/blob/ea5840de72eab58bec837bb51986ac73712fcfde/contracts/Stableswap/BaseV1-core.sol#L340

Replace => with > or <= with <.

impact EVM we dont have opcode for >= its means we have > and = when we use the >= we doing > + = and its have more gas than the >

proof pg down Mitigation:

Do this > -1 or > +1 dont forget the increment/decrement the value.

Bool variable should be after the address variable

impact

Solidity contracts have 32 bytes (256 bits) slots used in storage. It means we can minimize the number of slots used within a contract’s storage and therefore reduce deployment gas costs.

And address type of variables has 20 bytes size and bool type variables have 1-byte size to save storage.

Mitigation:

write the bool variable after the address

Use two require instead of one with two parameters

impact

Require statements including conditions with the && operator can be broken down in multiple require statements to save gas.

Mitigation:

write the two require and use it for one parameter

GalloDaSballo commented 2 years ago

Less than 100 gas