15,000 USDC
View results
Submission Details
Severity: gas

Caching tokenAddresses length for gas optimisation

Summary

This gas optimization report focuses on reducing the gas cost of the constructor function in the contract. By caching the length of the tokenAddresses array and using the cached value within the loop, gas usage can be reduced, resulting in more efficient contract deployment.

Vulnerability Details

The original constructor function initializes price feeds for various tokens and performs checks on the input arrays. However, it can be further optimized to reduce gas consumption during deployment.

Impact

By optimizing the constructor, we can lower the gas cost of deploying the contract.

Tools Used

Remix IDE: Remix was used to analyze the gas usage of the function in a separate Test contract

Recommendations

Cache the length of tokenAddresses array: In the original constructor, the length of the tokenAddresses array is accessed multiple times during the loop, which consumes unnecessary gas. By caching the length in a local variable, we avoid redundant lookups and save gas.

constructor(address[] memory tokenAddresses, address[] memory priceFeedAddresses, address dscAddress) {
// USD Price Feeds
uint256 tokenAddressLength = tokenAddresses.length;
if (tokenAddressLength != priceFeedAddresses.length) {
revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength();
}
// For example ETH / USD, BTC / USD, MKR / USD, etc
for (uint256 i = 0; i < tokenAddressLength; i++) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
}
i_dsc = DecentralizedStableCoin(dscAddress);
}

By implementing optimization, the gas usage during contract deployment is reduced from 105381 to 104899, resulting in a more efficient and cost-effective Stable Coin contract.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.