Audit Common Issues #1
In this series of articles, we will cover the most common issues we encountered when doing an audit.
Gas Optimization problems
Variables
Always remove unused variables.
Use external
Storing the input parameters in memory costs gas. All public functions’ paramerters are copied to the memory automatically. If a function is only called externally (only from the outside of contract), it should be explicitly marked as external. When the function is declared as external the parameters are not stored in memory but are read from call data directly. This can save gas when the function input parameters are huge.
Inefficient initialization of variables
An uninitialized variable is automatically set with its default value (e.g., a uint256 variable, when not initialized, it is assumed to have the default value 0). When declaring a variable, explicitly setting it with its default value is useless and wastes gas.
Inefficient use of internal functions
Within a smart contract, calls to internal functions are cheaper than calls to public functions. A call to a public function implies that all the parameters are copied into memory and passed to that function. Conversely, a call to an internal function does not entail copying such parameters into memory again.. For this reason, the use of internal functions is preferable whenever possible, especially when the parameters are big.
Inefficient use of memory arrays
Whenever a developer has to make some internal computation in a solidity function with the help of an array, it may be good to avoid using storage, by employing memory arrays. If the size of the array is exactly known, fixed-size memory arrays can be used to save gas
Unbounded loops (the WORST)
In general, loops should be avoided. If avoiding loops is not possible, it could be beneficial to try to avoid unbounded loops, i.e., loops where the upper limit of iterations is not defined
Inefficient use of functions
In Solidity, it could be preferable using fewer larger functions, rather than implementing multiple functions, each performing a single small task. Indeed, multiple smaller functions cost more gas and require more bytecode.
And many more….
Twitter: https://twitter.com/solid_group_1
Telegram group: https://t.me/solidgroup
Contact for an audit: https://t.me/solid_1