Rely on strict increasing order in checkpoints lookups #4544
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Implements what is mentioned in :
#4540 (comment)
I'm very interested in why the library relies on non-strictly increasing order everywhere, like here:
openzeppelin-contracts/contracts/utils/structs/Checkpoints.sol
Line 164 in b2e7bab
Based on the descriptions of the functions, it looks like they were created with the expectation that there may be elements with the same keys:
openzeppelin-contracts/contracts/utils/structs/Checkpoints.sol
Line 151 in b2e7bab
At the same time, the insertion implementation does not allow adding multiple elements with the same key. This, of course, can be done manually by forcibly adding an element to the array. But you can also add an incorrect element (with a decreasing key) in such way. So it doesn't look like there should be multiple elements with the same key in an array in normal use of the library.
If the array is strictly ordered, then it is strange that the search does not handle the case when it hits the desired key (the case of equality). In the worst case, if the array is N long and the target is exactly in the middle, the current implementation will do something like
log2(n) - 1
excessive reads of cold storage slots (~2100 gas each).So with simple example like (keys)
[2, 3, 5, 7, 11, 12, 13, 14]
i tried two implementations oflowerLookup
: current and with separate handling of equality. Gas estimations forlowerLookup(11)
(including 21000 “base fee”):current version: 31712
modified version: 26762
I'm interested if there's a reason not to make such changes.
PR Checklist
npx changeset add
)