15,000 USDC
View results
Submission Details
Severity: gas
Valid

don't use push

Details

In DSCEngine's constructor you are pushing tokenAddresses array items one by one in the s_collateralTokens array but pushing them one by one into storage cost too much gas, you should set s_collateralTokens to tokenAddresses array in one go.

here is a simple example to see how much gas each one will use

If I pass [1,2,3] array to this function execution cost will be 80255 gas

function setNum1(uint[] memory _num) public {
for(uint i; i < _num.length;i++){
number++;
numArr.push(_num[i]);
}
}

And if I pass [1,2,3] array to this function execution cost will be 35251 gas

function setNum2(uint[] memory _num) public {
for(uint i; i < _num.length;i++){
number++;
}
numArr = _num;
}

So it means you gonna save about 45000 gas for creation of this contract, Your code should look like this:

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

Support

FAQs

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