Skip to content

Commit

Permalink
chore: gas optimisation for the for loop using the unchecked block (#212
Browse files Browse the repository at this point in the history
)

<!--
Please read and fill out this form before submitting your PR.

Please make sure you have reviewed our contributors guide before
submitting your
first PR.
-->

## Overview

Closes #202

## Checklist

<!-- 
Please complete the checklist to ensure that the PR is ready to be
reviewed.

IMPORTANT:
PRs should be left in Draft until the below checklist is completed.
-->

- [ ] New and updated code has appropriate documentation
- [ ] New and updated code has new and/or updated testing
- [ ] Required CI checks are passing
- [ ] Visual proof for any user facing features like CLI or
documentation updates
- [ ] Linked issues closed with keywords
  • Loading branch information
rach-id authored Oct 1, 2023
1 parent 85e8eeb commit 69d0fbc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 20 deletions.
40 changes: 21 additions & 19 deletions src/QuantumGravityBridge.sol
Original file line number Diff line number Diff line change
Expand Up @@ -198,27 +198,29 @@ contract QuantumGravityBridge is IDAOracle, Initializable, UUPSUpgradeable, Owna
uint256 _powerThreshold
) private pure {
uint256 cumulativePower = 0;

for (uint256 i = 0; i < _currentValidators.length; i++) {
// If the signature is nil, then it's not present so continue.
if (isSigNil(_sigs[i])) {
continue;
}

// Check that the current validator has signed off on the hash.
if (!verifySig(_currentValidators[i].addr, _digest, _sigs[i])) {
revert InvalidSignature();
}

// Sum up cumulative power.
cumulativePower += _currentValidators[i].power;

// Break early to avoid wasting gas.
if (cumulativePower >= _powerThreshold) {
break;
// Note: be cautious when updating the code inside the unchecked block.
// Make sure to verify if all the bypassed security checks are respected.
unchecked {
for (uint256 i = 0; i < _currentValidators.length; i++) {
// If the signature is nil, then it's not present so continue.
if (isSigNil(_sigs[i])) {
continue;
}

// Check that the current validator has signed off on the hash.
if (!verifySig(_currentValidators[i].addr, _digest, _sigs[i])) {
revert InvalidSignature();
}

// Sum up cumulative power.
cumulativePower += _currentValidators[i].power;

// Break early to avoid wasting gas.
if (cumulativePower >= _powerThreshold) {
break;
}
}
}

// Check that there was enough power.
if (cumulativePower < _powerThreshold) {
revert InsufficientVotingPower();
Expand Down
Loading

0 comments on commit 69d0fbc

Please sign in to comment.