15,000 USDC
View results
Submission Details
Severity: gas

Caching tokenAddress for Gas Optimization

Summary

This gas optimization report analyzes the constructor of the contract, focusing on the caching of the tokenAddresses[i] value during the loop iteration. By introducing this caching mechanism, we aim to reduce gas consumption during contract deployment.

Vulnerability Details

The original constructor loop iterates through the tokenAddresses array and sets the corresponding price feed for each token in the s_priceFeeds mapping. Additionally, it adds each token address to the s_collateralTokens array.

However, in the original code, the contract repeatedly accesses tokenAddresses[i] inside the loop, which can lead to increased gas consumption. Every time the contract accesses an array element, it incurs additional gas costs.

Impact

The impact of repeatedly accessing tokenAddresses[i] within the loop is an increase in gas consumption during contract deployment.

Tools Used

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

Optimisation Details

In the updated code, a caching mechanism is introduced by assigning the tokenAddresses[i] value to a local variable tokenAddress inside the loop. By doing so, the contract avoids repetitive access to the tokenAddresses array, resulting in reduced gas costs during deployment.

Gas Usage for this loop - 124,895 gas

for (uint256 i = 0; i < tokenAddresses.length; i++) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
}

Gas Usage for an updated loop - 123,850 gas

for (uint256 i = 0; i < tokenAddresses.length; i++) {
address tokenAddress = tokenAddresses[i];
s_priceFeeds[tokenAddress] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddress);
}

Recommendations

To optimize gas consumption and improve the contract's efficiency:

Introduce Caching Mechanism: Modify the constructor by introducing a caching mechanism for the tokenAddresses[i] value. By assigning it to a local variable inside the loop, we avoid repetitive access to the array and reduce gas costs.
Modified Constructor:

constructor(address[] memory tokenAddresses, address[] memory priceFeedAddresses, address dscAddress) {
if (tokenAddresses.length != priceFeedAddresses.length) {
revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength();
}
for (uint256 i = 0; i < tokenAddresses.length; i++) {
address tokenAddress = tokenAddresses[i];
s_priceFeeds[tokenAddress] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddress);
}
i_dsc = DecentralizedStableCoin(dscAddress);
}

By implementing this caching mechanism, the contract will have reduced gas consumption during deployment.

Support

FAQs

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