Skip to content

Commit

Permalink
Merge pull request #384 from Chomtana/optimize-getfraction
Browse files Browse the repository at this point in the history
Optimize gas for _getFraction in AmountDeriver
  • Loading branch information
0age authored Jun 8, 2022
2 parents 15f83f8 + 5a8575d commit 7b3d591
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
13 changes: 6 additions & 7 deletions contracts/lib/AmountDeriver.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
AmountDerivationErrors
} from "../interfaces/AmountDerivationErrors.sol";

import "./ConsiderationConstants.sol";

/**
* @title AmountDeriver
* @author 0age
Expand Down Expand Up @@ -98,16 +100,13 @@ contract AmountDeriver is AmountDerivationErrors {

// Ensure fraction can be applied to the value with no remainder. Note
// that the denominator cannot be zero.
bool exact;
assembly {
// Ensure new value contains no remainder via mulmod operator.
// Credit to @hrkrshnn + @axic for proposing this optimal solution.
exact := iszero(mulmod(value, numerator, denominator))
}

// Ensure that division gave a final result with no remainder.
if (!exact) {
revert InexactFraction();
if mulmod(value, numerator, denominator) {
mstore(0, InexactFraction_error_signature)
revert(0, InexactFraction_error_len)
}
}

// Multiply the numerator by the value and ensure no overflow occurs.
Expand Down
7 changes: 7 additions & 0 deletions contracts/lib/ConsiderationConstants.sol
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,10 @@ uint256 constant Conduit_transferItem_from_ptr = 0x40;
uint256 constant Conduit_transferItem_to_ptr = 0x60;
uint256 constant Conduit_transferItem_identifier_ptr = 0x80;
uint256 constant Conduit_transferItem_amount_ptr = 0xa0;

// Declare constant for errors related to amount derivation.
// error InexactFraction() @ AmountDerivationErrors.sol
uint256 constant InexactFraction_error_signature = (
0xc63cf08900000000000000000000000000000000000000000000000000000000
);
uint256 constant InexactFraction_error_len = 0x20;

0 comments on commit 7b3d591

Please sign in to comment.