Skip to content

Commit

Permalink
Fixed a bug with "pow" (#216)
Browse files Browse the repository at this point in the history
  • Loading branch information
jalextowle authored May 2, 2023
1 parent d5816ab commit 9e960c5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
11 changes: 10 additions & 1 deletion contracts/src/libraries/FixedPointMath.sol
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,19 @@ library FixedPointMath {
/// @param y Fixed point number in 1e18 format.
/// @return The result of x^y.
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
// If the exponent is 0, return 1.
if (y == 0) {
return ONE_18;
}

// If the base is 0, return 0.
if (x == 0) {
return 0;
}

// Using properties of logarithms we calculate x^y:
// -> ln(x^y) = y * ln(x)
// -> e^(y * ln(x)) = x^y

int256 y_int256 = int256(y); // solhint-disable-line var-name-mixedcase

// Compute y*ln(x)
Expand Down
23 changes: 21 additions & 2 deletions test/units/libraries/FixedPointMath.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,29 @@ contract FixedPointMathTest is Test {
function test_pow() public {
// NOTE: Coverage only works if I initialize the fixture in the test function
MockFixedPointMath mockFixedPointMath = new MockFixedPointMath();
uint256 x = 300000000000000000000000;
uint256 y = 977464155968402951;

uint256 x = 0;
uint256 y = 0;
uint256 result = mockFixedPointMath.pow(x, y);
uint256 expected = LogExpMath.pow(x, y);
assertEq(result, expected);

x = 300000000000000000000000;
y = 0;
result = mockFixedPointMath.pow(x, y);
expected = LogExpMath.pow(x, y);
assertEq(result, expected);

x = 0;
y = 977464155968402951;
result = mockFixedPointMath.pow(x, y);
expected = LogExpMath.pow(x, y);
assertEq(result, expected);

x = 300000000000000000000000;
y = 977464155968402951;
result = mockFixedPointMath.pow(x, y);
expected = LogExpMath.pow(x, y);
assertApproxEqAbs(result, expected, 1e5 wei);

x = 180000000000000000000000;
Expand Down

0 comments on commit 9e960c5

Please sign in to comment.