Skip to content

Commit

Permalink
Merge pull request #128 from bancorprotocol/add-test-function-exp2
Browse files Browse the repository at this point in the history
Add tests for function `MathEx.exp2`
  • Loading branch information
barakman authored Jan 29, 2024
2 parents 637a895 + fd4d9f8 commit cfb582f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
6 changes: 5 additions & 1 deletion contracts/helpers/TestMathEx.sol
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.19;

import { MathEx } from "../utility/MathEx.sol";
import { MathEx, Fraction } from "../utility/MathEx.sol";

contract TestMathEx {
function mulDivF(uint256 x, uint256 y, uint256 z) external pure returns (uint256) {
Expand All @@ -15,4 +15,8 @@ contract TestMathEx {
function minFactor(uint256 x, uint256 y) external pure returns (uint256) {
return MathEx.minFactor(x, y);
}

function exp2(Fraction memory f) external pure returns (Fraction memory) {
return MathEx.exp2(f);
}
}
29 changes: 29 additions & 0 deletions test/utility/MathEx.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import Contracts, { TestMathEx } from '../../components/Contracts';
import { expect } from 'chai';
import { BigNumber } from 'ethers';
import { EXP2_INPUT_TOO_HIGH } from '../../utils/Constants';
import { Fraction } from '../../utils/Types';
import { Relation } from '../matchers';
import Decimal from 'decimal.js';

const MAX_UINT256 = BigNumber.from(2).pow(256).sub(1);

Expand Down Expand Up @@ -51,6 +55,25 @@ describe('MathEx', () => {
}
};

const testExp2 = (f: Fraction, maxRelativeError: Decimal) => {
it(`exp2(${f.n} / ${f.d})`, async () => {
const fVal = new Decimal(f.n).div(f.d);
if (fVal.lt(EXP2_INPUT_TOO_HIGH)) {
const actual = await mathContract.exp2(f);
const expected = new Decimal(2).pow(fVal);
await expect(actual).to.almostEqual(
{ n: expected, d: 1 },
{
maxRelativeError,
relation: Relation.LesserOrEqual
}
);
} else {
await expect(mathContract.exp2(f)).to.revertedWithError('Overflow');
}
});
};

describe('quick tests', () => {
for (const px of [128, 192, 256]) {
for (const py of [128, 192, 256]) {
Expand All @@ -76,6 +99,12 @@ describe('MathEx', () => {
}
}
}

for (let d = 1000; d < 1000000000; d *= 10) {
for (let n = EXP2_INPUT_TOO_HIGH.mul(d).sub(10); n.lte(EXP2_INPUT_TOO_HIGH.mul(d).sub(1)); n = n.add(1)) {
testExp2({ n: n.floor().toNumber(), d }, new Decimal('0.000000000000000000000000000000000002'));
}
}
});

describe('@stress tests', () => {
Expand Down

0 comments on commit cfb582f

Please sign in to comment.