code-423n4 / 2022-03-paladin-findings

0 stars 0 forks source link

Gas Optimizations #13

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Paladin Contest

March 31, 2022

@securerodd #

Gas Optimizations

1. Use of Unchecked Directive and Caching of Calculated Value Saves 355 Gas

This finding applies to the following five functions:

increaseLockDuration(uint256 duration)

increaseLock(uint256 amount)

stakeAndIncreaseLock(uint256 amount, uint256 duration)

_kick(address user, address kicker

_unlock(address user)

Each function implemented almost the exact same logic to check that a lock exists and then to get the current lock. The logic (taken from increaseLockDuration(uint256 duration)) can be seen below:

require(userLocks[msg.sender].length != 0, "hPAL: No Lock");
// Find the current Lock
uint256 currentUserLockIndex = userLocks[msg.sender].length - 1;

Significant gas can be saved by first caching the length of userlocks[msg.sender] into a local variable, then checking that it is not 0, and using the unchecked directive to decrement it by 1. The suggested replacement logic is seen below:

uint256 currentUserLockIndex = userLocks[msg.sender].length;
require(currentUserLockIndex != 0, "hPAL: No Lock");
// Find the current Lock
unchecked {--currentUserLockIndex;}

Through testing on Remix, this saved 71 gas on increaseLockDuration(uint256 duration). This same logic could be ported over to all 5 functions for ~355 gas savings.

Kogaroshi commented 2 years ago

QA & gas optimizations changes are done in the PR: https://github.com/PaladinFinance/Paladin-Tokenomics/pull/6 (some changes/tips were implemented, others are noted but won't be applied)