code-423n4 / 2021-09-defiprotocol-findings

1 stars 0 forks source link

Gas: Improve `validateWeights` uniqueness check #226

Closed code423n4 closed 2 years ago

code423n4 commented 2 years ago

Handle

cmichel

Vulnerability details

The Basket.validateWeights function checks the uniqueness of the tokens by iterating over all tokens for each token. This runs in O(_tokens.length^2) and is very inefficient as the number of tokens increases.

Recommended Mitigation Steps

Sort the tokens off-chain and provide them already in a sorted (ascending) way. Then the validateWeights function only needs to verify that the tokens are indeed strictly sorted which runs in linear time:

for (uint i = 0; i < length; i++) {
    require(_tokens[i] != address(0));
    require(_weights[i] > 0);

    // check sorted to ensure uniqueness
    if (i > 0) {
        require(_tokens[i] > _tokens[i - 1]);
    }
}
GalloDaSballo commented 2 years ago

Agree with the findings, but want to point that the suggested improvement requires full trust of the input, which may not be a good idea

GalloDaSballo commented 2 years ago

Duplicate of #160