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

1 stars 0 forks source link

Optimize validateWeights #213

Closed code423n4 closed 2 years ago

code423n4 commented 2 years ago

Handle

pauliax

Vulnerability details

Impact

I assume function validateWeights is very gas-consuming as it iterates against all the tokens again and again and re-assigns dynamic arrays multiple times. I think a good improvement that you may consider would be to ask the _tokens array to be provided in descending order, then a validation would be much cheaper.

Recommended Mitigation Steps

An example solution:

// tokens must be in a descending order
function validateWeights(address[] memory _tokens, uint256[] memory _weights) public pure {
    uint256 length = _tokens.length;
    require(length == _weights.length);
    uint lastIndex = length - 1;
    // check uniqueness of tokens and not token(0)
    for (uint i = 0; i < length; i++) {
        require(_tokens[i] != address(0));
        require(_weights[i] > 0);
        if (i != lastIndex) {
           require(_tokens[i] > _tokens[i + 1], "descending");
        }
    }
}
frank-beard commented 2 years ago

https://github.com/code-423n4/2021-09-defiprotocol-findings/issues/226

GalloDaSballo commented 2 years ago

Duplicate of #160