Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas Optimizations #258

Open
code423n4 opened this issue May 8, 2022 · 2 comments
Open

Gas Optimizations #258

code423n4 opened this issue May 8, 2022 · 2 comments
Labels
bug Something isn't working G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

ISSUE LIST

C4-001: Revert String Size Optimization

C4-002 : Adding unchecked directive can save gas

C4-003 : Check if amount > 0 before token transfer can save gas

C4-004 : There is no need to assign default values to variables

C4-005: > 0 can be replaced with != 0 for gas optimization

C4-006 : Free gas savings for using solidity 0.8.10+

C4-007 : ++i is more gas efficient than i++ in loops forwarding

C4-008 : Using operator && used more gas

C4-009 : Non-strict inequalities are cheaper than strict ones

C4-010 : Use Custom Errors instead of Revert Strings to save Gas

C4-001: Revert String Size Optimization

Impact

Shortening revert strings to fit in 32 bytes will decrease deploy time gas and will decrease runtime gas when the revert condition has been met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead for computing memory offset, etc.

Proof of Concept

Revert strings > 32 bytes are here:

  contracts/MerkleDropFactory.sol::90 => require(treeIndex <= numTrees, "Provided merkle index doesn't exist");
  contracts/MerkleDropFactory.sol::92 => require(!withdrawn[destination][treeIndex], "You have already withdrawn your entitled token.");
  contracts/MerkleIdentity.sol::127 => require(verifyMetadata(tree.metadataMerkleRoot, tokenId, uri, metadataProof), "The metadata proof could not be verified");
  contracts/MerkleResistor.sol::171 => require(initialized[destination][treeIndex], "You must initialize your account first.");
  contracts/MerkleVesting.sol::141 => require(initialized[destination][treeIndex], "You must initialize your account first.");
  contracts/VoterID.sol::5 => import "../interfaces/IERC721Receiver.sol";
  contracts/VoterID.sol::37 => // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
  contracts/VoterID.sol::210 => ///  `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
  contracts/VoterID.sol::217 => require(checkOnERC721Received(from, to, tokenId, data), "Identity: transfer to non ERC721Receiver implementer");
  contracts/VoterID.sol::305 => require(owners[tokenId] == from, "Identity: Transfer of token that is not own");
  contracts/VoterID.sol::306 => require(to != address(0), "Identity: transfer to the zero address");

Tools Used

Manual Review

Recommended Mitigation Steps

Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.

C4-002 : Adding unchecked directive can save gas

Impact

For the arithmetic operations that will never over/underflow, using the unchecked directive (Solidity v0.8 has default overflow/underflow checks) can save some gas from the unnecessary internal over/underflow checks.

Proof of Concept

  contracts/MerkleLib.sol::22 => for (uint i = 0; i < proof.length; i += 1) {
  contracts/MerkleResistor.sol::40 => uint minEndTime; // minimum length (offset, not absolute) of vesting schedule in seconds
  contracts/MerkleResistor.sol::41 => uint maxEndTime; // maximum length (offset, not absolute) of vesting schedule in seconds
  contracts/MerkleResistor.sol::130 => /// @param vestingTime the actual length of the vesting schedule, chosen by the user
  contracts/MerkleResistor.sol::211 => /// @param vestingTime user chosen length of vesting schedule
  contracts/MerkleResistor.sol::243 => // x axis = length of vesting schedule
  contracts/PermissionlessBasicPoolFactory.sol::112 => require(rewardsWeiPerSecondPerToken.length == rewardTokenAddresses.length, 'Rewards and reward token arrays must be same length');
  contracts/PermissionlessBasicPoolFactory.sol::115 => for (uint i = 0; i < rewardTokenAddresses.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::141 => for (uint i = 0; i < pool.rewardFunding.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::167 => uint[] memory rewardsLocal = new uint[](pool.rewardsWeiPerSecondPerToken.length);
  contracts/PermissionlessBasicPoolFactory.sol::168 => for (uint i = 0; i < pool.rewardsWeiPerSecondPerToken.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::224 => for (uint i = 0; i < rewards.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::249 => for (uint i = 0; i < pool.rewardTokens.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::266 => for (uint i = 0; i < pool.rewardTokens.length; i++) {

Tools Used

None

Recommended Mitigation Steps

Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.

Unchecked{i++};

C4-003 : Check if amount > 0 before token transfer can save gas

Impact

Since _amount can be 0. Checking if (_amount != 0) before the transfer can potentially save an external call and the unnecessary gas cost of a 0 token transfer.

Proof of Concept

  contracts/MerkleDropFactory.sol::77 => require(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), "ERC20 transfer failed");
  contracts/MerkleDropFactory.sol::107 => require(IERC20(tree.tokenAddress).transfer(destination, value), "ERC20 transfer failed");
  contracts/MerkleResistor.sol::121 => require(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), "ERC20 transfer failed");
  contracts/MerkleResistor.sol::204 => require(IERC20(tree.tokenAddress).transfer(destination, currentWithdrawal), 'Token transfer failed');
  contracts/MerkleVesting.sol::89 => require(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), "ERC20 transfer failed");
  contracts/MerkleVesting.sol::173 => IERC20(tree.tokenAddress).transfer(destination, currentWithdrawal);
  contracts/PermissionlessBasicPoolFactory.sol::144 => success = success && IERC20(pool.rewardTokens[i]).transferFrom(msg.sender, address(this), amount);
  contracts/PermissionlessBasicPoolFactory.sol::198 => bool success = IERC20(pool.depositToken).transferFrom(msg.sender, address(this), amount);
  contracts/PermissionlessBasicPoolFactory.sol::230 => success = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, transferAmount);
  contracts/PermissionlessBasicPoolFactory.sol::233 => success = success && IERC20(pool.depositToken).transfer(receipt.owner, receipt.amountDepositedWei);
  contracts/PermissionlessBasicPoolFactory.sol::252 => success = success && IERC20(pool.rewardTokens[i]).transfer(pool.excessBeneficiary, rewards);
  contracts/PermissionlessBasicPoolFactory.sol::269 => success = success && IERC20(pool.rewardTokens[i]).transfer(globalBeneficiary, tax);

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider checking amount != 0.

C4-004 : There is no need to assign default values to variables

Impact - Gas Optimization

When a variable is declared solidity assigns the default value. In case the contract assigns the value again, it costs extra gas.

Example: uint x = 0 costs more gas than uint x without having any different functionality.

Proof of Concept

  contracts/MerkleLib.sol::22 => for (uint i = 0; i < proof.length; i += 1) {
  contracts/MerkleResistor.sol::40 => uint minEndTime; // minimum length (offset, not absolute) of vesting schedule in seconds
  contracts/MerkleResistor.sol::41 => uint maxEndTime; // maximum length (offset, not absolute) of vesting schedule in seconds
  contracts/MerkleResistor.sol::130 => /// @param vestingTime the actual length of the vesting schedule, chosen by the user
  contracts/MerkleResistor.sol::211 => /// @param vestingTime user chosen length of vesting schedule
  contracts/MerkleResistor.sol::243 => // x axis = length of vesting schedule
  contracts/PermissionlessBasicPoolFactory.sol::112 => require(rewardsWeiPerSecondPerToken.length == rewardTokenAddresses.length, 'Rewards and reward token arrays must be same length');
  contracts/PermissionlessBasicPoolFactory.sol::115 => for (uint i = 0; i < rewardTokenAddresses.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::141 => for (uint i = 0; i < pool.rewardFunding.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::167 => uint[] memory rewardsLocal = new uint[](pool.rewardsWeiPerSecondPerToken.length);
  contracts/PermissionlessBasicPoolFactory.sol::168 => for (uint i = 0; i < pool.rewardsWeiPerSecondPerToken.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::224 => for (uint i = 0; i < rewards.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::249 => for (uint i = 0; i < pool.rewardTokens.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::266 => for (uint i = 0; i < pool.rewardTokens.length; i++) {

Tools Used

Code Review

Recommended Mitigation Steps

uint x = 0 costs more gas than uint x without having any different functionality.

C4-005: > 0 can be replaced with != 0 for gas optimization

Impact

!= 0 is a cheaper operation compared to > 0, when dealing with uint. (Before Pragma 0.8.13)

Proof of Concept

  1. Navigate to the following contracts.
  contracts/FixedPricePassThruGate.sol::51 => if (msg.value > 0) {
  contracts/MerkleResistor.sol::156 => startTime,     // start time will usually be in the past, if pctUpFront > 0
  contracts/SpeedBumpPriceGate.sol::77 => if (msg.value > 0) {
  contracts/VoterID.sol::52 => *     => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
  contracts/VoterID.sol::208 => ///  checks if `to` is a smart contract (code size > 0). If so, it calls
  contracts/VoterID.sol::348 => return size > 0;


Tools Used

Code Review

Recommended Mitigation Steps

Use "!=0" instead of ">0" for the gas optimization.

C4-006 : Free gas savings for using solidity 0.8.10+

Impact

Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.

Proof of Concept

All Contracts

Solidity 0.8.10 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Solidity 0.8.13 has some improvements too but not well tested.

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider to upgrade pragma to at least 0.8.10.

C4-007 : ++i is more gas efficient than i++ in loops forwarding

Impact

++i is more gas efficient than i++ in loops forwarding.

Proof of Concept

  1. Navigate to the following contracts.
  contracts/PermissionlessBasicPoolFactory.sol::115 => for (uint i = 0; i < rewardTokenAddresses.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::141 => for (uint i = 0; i < pool.rewardFunding.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::168 => for (uint i = 0; i < pool.rewardsWeiPerSecondPerToken.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::224 => for (uint i = 0; i < rewards.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::249 => for (uint i = 0; i < pool.rewardTokens.length; i++) {
  contracts/PermissionlessBasicPoolFactory.sol::266 => for (uint i = 0; i < pool.rewardTokens.length; i++) {

Tools Used

Code Review

Recommended Mitigation Steps

It is recommend to use unchecked{++i} and change i declaration to uint256.

C4-008 : Using operator && used more gas

Impact

Using double require instead of operator && can save more gas.

Proof of Concept

  1. Navigate to the following contracts.
  contracts/PermissionlessBasicPoolFactory.sol::144 => success = success && IERC20(pool.rewardTokens[i]).transferFrom(msg.sender, address(this), amount);
  contracts/PermissionlessBasicPoolFactory.sol::198 => bool success = IERC20(pool.depositToken).transferFrom(msg.sender, address(this), amount);
  contracts/PermissionlessBasicPoolFactory.sol::230 => success = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, transferAmount);
  contracts/PermissionlessBasicPoolFactory.sol::233 => success = success && IERC20(pool.depositToken).transfer(receipt.owner, receipt.amountDepositedWei);
  contracts/PermissionlessBasicPoolFactory.sol::252 => success = success && IERC20(pool.rewardTokens[i]).transfer(pool.excessBeneficiary, rewards);
  contracts/PermissionlessBasicPoolFactory.sol::269 => success = success && IERC20(pool.rewardTokens[i]).transfer(globalBeneficiary, tax);

Tools Used

Code Review

Recommended Mitigation Steps

Example


using &&:

function check(uint x)public view{
   require(x == 0 && x < 1 );
}
// gas cost 21630

using double require:

   require(x == 0 );
   require( x < 1);
   }
}
// gas cost 21622

C4-009 : Non-strict inequalities are cheaper than strict ones

Impact

Strict inequalities add a check of non equality which costs around 3 gas.

Proof of Concept

  contracts/FixedPricePassThruGate.sol::51 => if (msg.value > 0) {
  contracts/MerkleResistor.sol::156 => startTime,     // start time will usually be in the past, if pctUpFront > 0
  contracts/SpeedBumpPriceGate.sol::77 => if (msg.value > 0) {
  contracts/VoterID.sol::52 => *     => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
  contracts/VoterID.sol::208 => ///  checks if `to` is a smart contract (code size > 0). If so, it calls
  contracts/VoterID.sol::348 => return size > 0;

Tools Used

Code Review

Recommended Mitigation Steps

Use >= or <= instead of > and < when possible.

C4-010 : 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 Custom Errors in Solidity:

Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.

Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).

Instances include:

All require Statements

Tools Used

Code Review

Recommended Mitigation Steps

Recommended to replace revert strings with custom errors.

@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels May 8, 2022
code423n4 added a commit that referenced this issue May 8, 2022
@illuzen
Copy link
Collaborator

illuzen commented May 12, 2022

all duplicates except c4-006

@illuzen illuzen closed this as completed May 12, 2022
@itsmetechjay itsmetechjay reopened this May 12, 2022
@gititGoro
Copy link
Collaborator

C4-008 is not correctly reported: there's no need for a double require. But the principle of avoiding && will be taken into account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working G (Gas Optimization)
Projects
None yet
Development

No branches or pull requests

4 participants