This commit is contained in:
dexorder
2024-10-17 02:42:28 -04:00
commit 25def69c66
878 changed files with 112489 additions and 0 deletions

View File

@@ -0,0 +1,311 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test, stdError} from "@forge-std/Test.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
contract MathTest is Test {
function testSelect(bool f, uint256 a, uint256 b) public {
assertEq(Math.ternary(f, a, b), f ? a : b);
}
// MIN & MAX
function testMinMax(uint256 a, uint256 b) public {
assertEq(Math.min(a, b), a < b ? a : b);
assertEq(Math.max(a, b), a > b ? a : b);
}
// CEILDIV
function testCeilDiv(uint256 a, uint256 b) public {
vm.assume(b > 0);
uint256 result = Math.ceilDiv(a, b);
if (result == 0) {
assertEq(a, 0);
} else {
uint256 expect = a / b;
if (expect * b < a) {
expect += 1;
}
assertEq(result, expect);
}
}
// SQRT
function testSqrt(uint256 input, uint8 r) public {
Math.Rounding rounding = _asRounding(r);
uint256 result = Math.sqrt(input, rounding);
// square of result is bigger than input
if (_squareBigger(result, input)) {
assertTrue(Math.unsignedRoundsUp(rounding));
assertTrue(_squareSmaller(result - 1, input));
}
// square of result is smaller than input
else if (_squareSmaller(result, input)) {
assertFalse(Math.unsignedRoundsUp(rounding));
assertTrue(_squareBigger(result + 1, input));
}
// input is perfect square
else {
assertEq(result * result, input);
}
}
function _squareBigger(uint256 value, uint256 ref) private pure returns (bool) {
(bool noOverflow, uint256 square) = Math.tryMul(value, value);
return !noOverflow || square > ref;
}
function _squareSmaller(uint256 value, uint256 ref) private pure returns (bool) {
return value * value < ref;
}
// INV
function testInvMod(uint256 value, uint256 p) public {
_testInvMod(value, p, true);
}
function testInvMod2(uint256 seed) public {
uint256 p = 2; // prime
_testInvMod(bound(seed, 1, p - 1), p, false);
}
function testInvMod17(uint256 seed) public {
uint256 p = 17; // prime
_testInvMod(bound(seed, 1, p - 1), p, false);
}
function testInvMod65537(uint256 seed) public {
uint256 p = 65537; // prime
_testInvMod(bound(seed, 1, p - 1), p, false);
}
function testInvModP256(uint256 seed) public {
uint256 p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff; // prime
_testInvMod(bound(seed, 1, p - 1), p, false);
}
function _testInvMod(uint256 value, uint256 p, bool allowZero) private {
uint256 inverse = Math.invMod(value, p);
if (inverse != 0) {
assertEq(mulmod(value, inverse, p), 1);
assertLt(inverse, p);
} else {
assertTrue(allowZero);
}
}
// LOG2
function testLog2(uint256 input, uint8 r) public {
Math.Rounding rounding = _asRounding(r);
uint256 result = Math.log2(input, rounding);
if (input == 0) {
assertEq(result, 0);
} else if (_powerOf2Bigger(result, input)) {
assertTrue(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf2Smaller(result - 1, input));
} else if (_powerOf2Smaller(result, input)) {
assertFalse(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf2Bigger(result + 1, input));
} else {
assertEq(2 ** result, input);
}
}
function _powerOf2Bigger(uint256 value, uint256 ref) private pure returns (bool) {
return value >= 256 || 2 ** value > ref; // 2**256 overflows uint256
}
function _powerOf2Smaller(uint256 value, uint256 ref) private pure returns (bool) {
return 2 ** value < ref;
}
// LOG10
function testLog10(uint256 input, uint8 r) public {
Math.Rounding rounding = _asRounding(r);
uint256 result = Math.log10(input, rounding);
if (input == 0) {
assertEq(result, 0);
} else if (_powerOf10Bigger(result, input)) {
assertTrue(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf10Smaller(result - 1, input));
} else if (_powerOf10Smaller(result, input)) {
assertFalse(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf10Bigger(result + 1, input));
} else {
assertEq(10 ** result, input);
}
}
function _powerOf10Bigger(uint256 value, uint256 ref) private pure returns (bool) {
return value >= 78 || 10 ** value > ref; // 10**78 overflows uint256
}
function _powerOf10Smaller(uint256 value, uint256 ref) private pure returns (bool) {
return 10 ** value < ref;
}
// LOG256
function testLog256(uint256 input, uint8 r) public {
Math.Rounding rounding = _asRounding(r);
uint256 result = Math.log256(input, rounding);
if (input == 0) {
assertEq(result, 0);
} else if (_powerOf256Bigger(result, input)) {
assertTrue(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf256Smaller(result - 1, input));
} else if (_powerOf256Smaller(result, input)) {
assertFalse(Math.unsignedRoundsUp(rounding));
assertTrue(_powerOf256Bigger(result + 1, input));
} else {
assertEq(256 ** result, input);
}
}
function _powerOf256Bigger(uint256 value, uint256 ref) private pure returns (bool) {
return value >= 32 || 256 ** value > ref; // 256**32 overflows uint256
}
function _powerOf256Smaller(uint256 value, uint256 ref) private pure returns (bool) {
return 256 ** value < ref;
}
// MULDIV
function testMulDiv(uint256 x, uint256 y, uint256 d) public {
// Full precision for x * y
(uint256 xyHi, uint256 xyLo) = _mulHighLow(x, y);
// Assume result won't overflow (see {testMulDivDomain})
// This also checks that `d` is positive
vm.assume(xyHi < d);
// Perform muldiv
uint256 q = Math.mulDiv(x, y, d);
// Full precision for q * d
(uint256 qdHi, uint256 qdLo) = _mulHighLow(q, d);
// Add remainder of x * y / d (computed as rem = (x * y % d))
(uint256 qdRemLo, uint256 c) = _addCarry(qdLo, mulmod(x, y, d));
uint256 qdRemHi = qdHi + c;
// Full precision check that x * y = q * d + rem
assertEq(xyHi, qdRemHi);
assertEq(xyLo, qdRemLo);
}
function testMulDivDomain(uint256 x, uint256 y, uint256 d) public {
(uint256 xyHi, ) = _mulHighLow(x, y);
// Violate {testMulDiv} assumption (covers d is 0 and result overflow)
vm.assume(xyHi >= d);
// we are outside the scope of {testMulDiv}, we expect muldiv to revert
vm.expectRevert(d == 0 ? stdError.divisionError : stdError.arithmeticError);
Math.mulDiv(x, y, d);
}
// MOD EXP
function testModExp(uint256 b, uint256 e, uint256 m) public {
if (m == 0) {
vm.expectRevert(stdError.divisionError);
}
uint256 result = Math.modExp(b, e, m);
assertLt(result, m);
assertEq(result, _nativeModExp(b, e, m));
}
function testTryModExp(uint256 b, uint256 e, uint256 m) public {
(bool success, uint256 result) = Math.tryModExp(b, e, m);
assertEq(success, m != 0);
if (success) {
assertLt(result, m);
assertEq(result, _nativeModExp(b, e, m));
} else {
assertEq(result, 0);
}
}
function testModExpMemory(uint256 b, uint256 e, uint256 m) public {
if (m == 0) {
vm.expectRevert(stdError.divisionError);
}
bytes memory result = Math.modExp(abi.encodePacked(b), abi.encodePacked(e), abi.encodePacked(m));
assertEq(result.length, 0x20);
uint256 res = abi.decode(result, (uint256));
assertLt(res, m);
assertEq(res, _nativeModExp(b, e, m));
}
function testTryModExpMemory(uint256 b, uint256 e, uint256 m) public {
(bool success, bytes memory result) = Math.tryModExp(
abi.encodePacked(b),
abi.encodePacked(e),
abi.encodePacked(m)
);
if (success) {
assertEq(result.length, 0x20); // m is a uint256, so abi.encodePacked(m).length is 0x20
uint256 res = abi.decode(result, (uint256));
assertLt(res, m);
assertEq(res, _nativeModExp(b, e, m));
} else {
assertEq(result.length, 0);
}
}
function _nativeModExp(uint256 b, uint256 e, uint256 m) private pure returns (uint256) {
if (m == 1) return 0;
uint256 r = 1;
while (e > 0) {
if (e % 2 > 0) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
e >>= 1;
}
return r;
}
// Helpers
function _asRounding(uint8 r) private pure returns (Math.Rounding) {
vm.assume(r < uint8(type(Math.Rounding).max));
return Math.Rounding(r);
}
function _mulHighLow(uint256 x, uint256 y) private pure returns (uint256 high, uint256 low) {
(uint256 x0, uint256 x1) = (x & type(uint128).max, x >> 128);
(uint256 y0, uint256 y1) = (y & type(uint128).max, y >> 128);
// Karatsuba algorithm
// https://en.wikipedia.org/wiki/Karatsuba_algorithm
uint256 z2 = x1 * y1;
uint256 z1a = x1 * y0;
uint256 z1b = x0 * y1;
uint256 z0 = x0 * y0;
uint256 carry = ((z1a & type(uint128).max) + (z1b & type(uint128).max) + (z0 >> 128)) >> 128;
high = z2 + (z1a >> 128) + (z1b >> 128) + carry;
unchecked {
low = x * y;
}
}
function _addCarry(uint256 x, uint256 y) private pure returns (uint256 res, uint256 carry) {
unchecked {
res = x + y;
}
carry = res < x ? 1 : 0;
}
}

View File

@@ -0,0 +1,562 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { PANIC_CODES } = require('@nomicfoundation/hardhat-chai-matchers/panic');
const { Rounding } = require('../../helpers/enums');
const { min, max, modExp } = require('../../helpers/math');
const { generators } = require('../../helpers/random');
const { product, range } = require('../../helpers/iterate');
const RoundingDown = [Rounding.Floor, Rounding.Trunc];
const RoundingUp = [Rounding.Ceil, Rounding.Expand];
const bytes = (value, width = undefined) => ethers.Typed.bytes(ethers.toBeHex(value, width));
const uint256 = value => ethers.Typed.uint256(value);
bytes.zero = '0x';
uint256.zero = 0n;
async function testCommutative(fn, lhs, rhs, expected, ...extra) {
expect(await fn(lhs, rhs, ...extra)).to.deep.equal(expected);
expect(await fn(rhs, lhs, ...extra)).to.deep.equal(expected);
}
async function fixture() {
const mock = await ethers.deployContract('$Math');
// disambiguation, we use the version with explicit rounding
mock.$mulDiv = mock['$mulDiv(uint256,uint256,uint256,uint8)'];
mock.$sqrt = mock['$sqrt(uint256,uint8)'];
mock.$log2 = mock['$log2(uint256,uint8)'];
mock.$log10 = mock['$log10(uint256,uint8)'];
mock.$log256 = mock['$log256(uint256,uint8)'];
return { mock };
}
describe('Math', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
describe('tryAdd', function () {
it('adds correctly', async function () {
const a = 5678n;
const b = 1234n;
await testCommutative(this.mock.$tryAdd, a, b, [true, a + b]);
});
it('reverts on addition overflow', async function () {
const a = ethers.MaxUint256;
const b = 1n;
await testCommutative(this.mock.$tryAdd, a, b, [false, 0n]);
});
});
describe('trySub', function () {
it('subtracts correctly', async function () {
const a = 5678n;
const b = 1234n;
expect(await this.mock.$trySub(a, b)).to.deep.equal([true, a - b]);
});
it('reverts if subtraction result would be negative', async function () {
const a = 1234n;
const b = 5678n;
expect(await this.mock.$trySub(a, b)).to.deep.equal([false, 0n]);
});
});
describe('tryMul', function () {
it('multiplies correctly', async function () {
const a = 1234n;
const b = 5678n;
await testCommutative(this.mock.$tryMul, a, b, [true, a * b]);
});
it('multiplies by zero correctly', async function () {
const a = 0n;
const b = 5678n;
await testCommutative(this.mock.$tryMul, a, b, [true, a * b]);
});
it('reverts on multiplication overflow', async function () {
const a = ethers.MaxUint256;
const b = 2n;
await testCommutative(this.mock.$tryMul, a, b, [false, 0n]);
});
});
describe('tryDiv', function () {
it('divides correctly', async function () {
const a = 5678n;
const b = 5678n;
expect(await this.mock.$tryDiv(a, b)).to.deep.equal([true, a / b]);
});
it('divides zero correctly', async function () {
const a = 0n;
const b = 5678n;
expect(await this.mock.$tryDiv(a, b)).to.deep.equal([true, a / b]);
});
it('returns complete number result on non-even division', async function () {
const a = 7000n;
const b = 5678n;
expect(await this.mock.$tryDiv(a, b)).to.deep.equal([true, a / b]);
});
it('reverts on division by zero', async function () {
const a = 5678n;
const b = 0n;
expect(await this.mock.$tryDiv(a, b)).to.deep.equal([false, 0n]);
});
});
describe('tryMod', function () {
describe('modulos correctly', function () {
it('when the dividend is smaller than the divisor', async function () {
const a = 284n;
const b = 5678n;
expect(await this.mock.$tryMod(a, b)).to.deep.equal([true, a % b]);
});
it('when the dividend is equal to the divisor', async function () {
const a = 5678n;
const b = 5678n;
expect(await this.mock.$tryMod(a, b)).to.deep.equal([true, a % b]);
});
it('when the dividend is larger than the divisor', async function () {
const a = 7000n;
const b = 5678n;
expect(await this.mock.$tryMod(a, b)).to.deep.equal([true, a % b]);
});
it('when the dividend is a multiple of the divisor', async function () {
const a = 17034n; // 17034 == 5678 * 3
const b = 5678n;
expect(await this.mock.$tryMod(a, b)).to.deep.equal([true, a % b]);
});
});
it('reverts with a 0 divisor', async function () {
const a = 5678n;
const b = 0n;
expect(await this.mock.$tryMod(a, b)).to.deep.equal([false, 0n]);
});
});
describe('max', function () {
it('is correctly detected in both position', async function () {
await testCommutative(this.mock.$max, 1234n, 5678n, max(1234n, 5678n));
});
});
describe('min', function () {
it('is correctly detected in both position', async function () {
await testCommutative(this.mock.$min, 1234n, 5678n, min(1234n, 5678n));
});
});
describe('average', function () {
it('is correctly calculated with two odd numbers', async function () {
const a = 57417n;
const b = 95431n;
expect(await this.mock.$average(a, b)).to.equal((a + b) / 2n);
});
it('is correctly calculated with two even numbers', async function () {
const a = 42304n;
const b = 84346n;
expect(await this.mock.$average(a, b)).to.equal((a + b) / 2n);
});
it('is correctly calculated with one even and one odd number', async function () {
const a = 57417n;
const b = 84346n;
expect(await this.mock.$average(a, b)).to.equal((a + b) / 2n);
});
it('is correctly calculated with two max uint256 numbers', async function () {
const a = ethers.MaxUint256;
expect(await this.mock.$average(a, a)).to.equal(a);
});
});
describe('ceilDiv', function () {
it('reverts on zero division', async function () {
const a = 2n;
const b = 0n;
// It's unspecified because it's a low level 0 division error
await expect(this.mock.$ceilDiv(a, b)).to.be.revertedWithPanic(PANIC_CODES.DIVISION_BY_ZERO);
});
it('does not round up a zero result', async function () {
const a = 0n;
const b = 2n;
const r = 0n;
expect(await this.mock.$ceilDiv(a, b)).to.equal(r);
});
it('does not round up on exact division', async function () {
const a = 10n;
const b = 5n;
const r = 2n;
expect(await this.mock.$ceilDiv(a, b)).to.equal(r);
});
it('rounds up on division with remainders', async function () {
const a = 42n;
const b = 13n;
const r = 4n;
expect(await this.mock.$ceilDiv(a, b)).to.equal(r);
});
it('does not overflow', async function () {
const a = ethers.MaxUint256;
const b = 2n;
const r = 1n << 255n;
expect(await this.mock.$ceilDiv(a, b)).to.equal(r);
});
it('correctly computes max uint256 divided by 1', async function () {
const a = ethers.MaxUint256;
const b = 1n;
const r = ethers.MaxUint256;
expect(await this.mock.$ceilDiv(a, b)).to.equal(r);
});
});
describe('mulDiv', function () {
it('divide by 0', async function () {
const a = 1n;
const b = 1n;
const c = 0n;
await expect(this.mock.$mulDiv(a, b, c, Rounding.Floor)).to.be.revertedWithPanic(PANIC_CODES.DIVISION_BY_ZERO);
});
it('reverts with result higher than 2 ^ 256', async function () {
const a = 5n;
const b = ethers.MaxUint256;
const c = 2n;
await expect(this.mock.$mulDiv(a, b, c, Rounding.Floor)).to.be.revertedWithPanic(
PANIC_CODES.ARITHMETIC_UNDER_OR_OVERFLOW,
);
});
describe('does round down', function () {
it('small values', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$mulDiv(3n, 4n, 5n, rounding)).to.equal(2n);
expect(await this.mock.$mulDiv(3n, 5n, 5n, rounding)).to.equal(3n);
}
});
it('large values', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$mulDiv(42n, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding)).to.equal(41n);
expect(await this.mock.$mulDiv(17n, ethers.MaxUint256, ethers.MaxUint256, rounding)).to.equal(17n);
expect(
await this.mock.$mulDiv(ethers.MaxUint256 - 1n, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding),
).to.equal(ethers.MaxUint256 - 2n);
expect(
await this.mock.$mulDiv(ethers.MaxUint256, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding),
).to.equal(ethers.MaxUint256 - 1n);
expect(await this.mock.$mulDiv(ethers.MaxUint256, ethers.MaxUint256, ethers.MaxUint256, rounding)).to.equal(
ethers.MaxUint256,
);
}
});
});
describe('does round up', function () {
it('small values', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$mulDiv(3n, 4n, 5n, rounding)).to.equal(3n);
expect(await this.mock.$mulDiv(3n, 5n, 5n, rounding)).to.equal(3n);
}
});
it('large values', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$mulDiv(42n, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding)).to.equal(42n);
expect(await this.mock.$mulDiv(17n, ethers.MaxUint256, ethers.MaxUint256, rounding)).to.equal(17n);
expect(
await this.mock.$mulDiv(ethers.MaxUint256 - 1n, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding),
).to.equal(ethers.MaxUint256 - 1n);
expect(
await this.mock.$mulDiv(ethers.MaxUint256, ethers.MaxUint256 - 1n, ethers.MaxUint256, rounding),
).to.equal(ethers.MaxUint256 - 1n);
expect(await this.mock.$mulDiv(ethers.MaxUint256, ethers.MaxUint256, ethers.MaxUint256, rounding)).to.equal(
ethers.MaxUint256,
);
}
});
});
});
describe('invMod', function () {
for (const factors of [
[0n],
[1n],
[2n],
[17n],
[65537n],
[0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn],
[3n, 5n],
[3n, 7n],
[47n, 53n],
]) {
const p = factors.reduce((acc, f) => acc * f, 1n);
describe(`using p=${p} which is ${p > 1 && factors.length > 1 ? 'not ' : ''}a prime`, function () {
it('trying to inverse 0 returns 0', async function () {
expect(await this.mock.$invMod(0, p)).to.equal(0n);
expect(await this.mock.$invMod(p, p)).to.equal(0n); // p is 0 mod p
});
if (p != 0) {
for (const value of Array.from({ length: 16 }, generators.uint256)) {
const isInversible = factors.every(f => value % f);
it(`trying to inverse ${value}`, async function () {
const result = await this.mock.$invMod(value, p);
if (isInversible) {
expect((value * result) % p).to.equal(1n);
} else {
expect(result).to.equal(0n);
}
});
}
}
});
}
});
describe('modExp', function () {
for (const [name, type] of Object.entries({ uint256, bytes })) {
describe(`with ${name} inputs`, function () {
it('is correctly calculating modulus', async function () {
const b = 3n;
const e = 200n;
const m = 50n;
expect(await this.mock.$modExp(type(b), type(e), type(m))).to.equal(type(b ** e % m).value);
});
it('is correctly reverting when modulus is zero', async function () {
const b = 3n;
const e = 200n;
const m = 0n;
await expect(this.mock.$modExp(type(b), type(e), type(m))).to.be.revertedWithPanic(
PANIC_CODES.DIVISION_BY_ZERO,
);
});
});
}
describe('with large bytes inputs', function () {
for (const [[b, log2b], [e, log2e], [m, log2m]] of product(
range(320, 512, 64).map(e => [2n ** BigInt(e) + 1n, e]),
range(320, 512, 64).map(e => [2n ** BigInt(e) + 1n, e]),
range(320, 512, 64).map(e => [2n ** BigInt(e) + 1n, e]),
)) {
it(`calculates b ** e % m (b=2**${log2b}+1) (e=2**${log2e}+1) (m=2**${log2m}+1)`, async function () {
const mLength = ethers.dataLength(ethers.toBeHex(m));
expect(await this.mock.$modExp(bytes(b), bytes(e), bytes(m))).to.equal(bytes(modExp(b, e, m), mLength).value);
});
}
});
});
describe('tryModExp', function () {
for (const [name, type] of Object.entries({ uint256, bytes })) {
describe(`with ${name} inputs`, function () {
it('is correctly calculating modulus', async function () {
const b = 3n;
const e = 200n;
const m = 50n;
expect(await this.mock.$tryModExp(type(b), type(e), type(m))).to.deep.equal([true, type(b ** e % m).value]);
});
it('is correctly reverting when modulus is zero', async function () {
const b = 3n;
const e = 200n;
const m = 0n;
expect(await this.mock.$tryModExp(type(b), type(e), type(m))).to.deep.equal([false, type.zero]);
});
});
}
describe('with large bytes inputs', function () {
for (const [[b, log2b], [e, log2e], [m, log2m]] of product(
range(320, 513, 64).map(e => [2n ** BigInt(e) + 1n, e]),
range(320, 513, 64).map(e => [2n ** BigInt(e) + 1n, e]),
range(320, 513, 64).map(e => [2n ** BigInt(e) + 1n, e]),
)) {
it(`calculates b ** e % m (b=2**${log2b}+1) (e=2**${log2e}+1) (m=2**${log2m}+1)`, async function () {
const mLength = ethers.dataLength(ethers.toBeHex(m));
expect(await this.mock.$tryModExp(bytes(b), bytes(e), bytes(m))).to.deep.equal([
true,
bytes(modExp(b, e, m), mLength).value,
]);
});
}
});
});
describe('sqrt', function () {
it('rounds down', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$sqrt(0n, rounding)).to.equal(0n);
expect(await this.mock.$sqrt(1n, rounding)).to.equal(1n);
expect(await this.mock.$sqrt(2n, rounding)).to.equal(1n);
expect(await this.mock.$sqrt(3n, rounding)).to.equal(1n);
expect(await this.mock.$sqrt(4n, rounding)).to.equal(2n);
expect(await this.mock.$sqrt(144n, rounding)).to.equal(12n);
expect(await this.mock.$sqrt(999999n, rounding)).to.equal(999n);
expect(await this.mock.$sqrt(1000000n, rounding)).to.equal(1000n);
expect(await this.mock.$sqrt(1000001n, rounding)).to.equal(1000n);
expect(await this.mock.$sqrt(1002000n, rounding)).to.equal(1000n);
expect(await this.mock.$sqrt(1002001n, rounding)).to.equal(1001n);
expect(await this.mock.$sqrt(ethers.MaxUint256, rounding)).to.equal(340282366920938463463374607431768211455n);
}
});
it('rounds up', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$sqrt(0n, rounding)).to.equal(0n);
expect(await this.mock.$sqrt(1n, rounding)).to.equal(1n);
expect(await this.mock.$sqrt(2n, rounding)).to.equal(2n);
expect(await this.mock.$sqrt(3n, rounding)).to.equal(2n);
expect(await this.mock.$sqrt(4n, rounding)).to.equal(2n);
expect(await this.mock.$sqrt(144n, rounding)).to.equal(12n);
expect(await this.mock.$sqrt(999999n, rounding)).to.equal(1000n);
expect(await this.mock.$sqrt(1000000n, rounding)).to.equal(1000n);
expect(await this.mock.$sqrt(1000001n, rounding)).to.equal(1001n);
expect(await this.mock.$sqrt(1002000n, rounding)).to.equal(1001n);
expect(await this.mock.$sqrt(1002001n, rounding)).to.equal(1001n);
expect(await this.mock.$sqrt(ethers.MaxUint256, rounding)).to.equal(340282366920938463463374607431768211456n);
}
});
});
describe('log', function () {
describe('log2', function () {
it('rounds down', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$log2(0n, rounding)).to.equal(0n);
expect(await this.mock.$log2(1n, rounding)).to.equal(0n);
expect(await this.mock.$log2(2n, rounding)).to.equal(1n);
expect(await this.mock.$log2(3n, rounding)).to.equal(1n);
expect(await this.mock.$log2(4n, rounding)).to.equal(2n);
expect(await this.mock.$log2(5n, rounding)).to.equal(2n);
expect(await this.mock.$log2(6n, rounding)).to.equal(2n);
expect(await this.mock.$log2(7n, rounding)).to.equal(2n);
expect(await this.mock.$log2(8n, rounding)).to.equal(3n);
expect(await this.mock.$log2(9n, rounding)).to.equal(3n);
expect(await this.mock.$log2(ethers.MaxUint256, rounding)).to.equal(255n);
}
});
it('rounds up', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$log2(0n, rounding)).to.equal(0n);
expect(await this.mock.$log2(1n, rounding)).to.equal(0n);
expect(await this.mock.$log2(2n, rounding)).to.equal(1n);
expect(await this.mock.$log2(3n, rounding)).to.equal(2n);
expect(await this.mock.$log2(4n, rounding)).to.equal(2n);
expect(await this.mock.$log2(5n, rounding)).to.equal(3n);
expect(await this.mock.$log2(6n, rounding)).to.equal(3n);
expect(await this.mock.$log2(7n, rounding)).to.equal(3n);
expect(await this.mock.$log2(8n, rounding)).to.equal(3n);
expect(await this.mock.$log2(9n, rounding)).to.equal(4n);
expect(await this.mock.$log2(ethers.MaxUint256, rounding)).to.equal(256n);
}
});
});
describe('log10', function () {
it('rounds down', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$log10(0n, rounding)).to.equal(0n);
expect(await this.mock.$log10(1n, rounding)).to.equal(0n);
expect(await this.mock.$log10(2n, rounding)).to.equal(0n);
expect(await this.mock.$log10(9n, rounding)).to.equal(0n);
expect(await this.mock.$log10(10n, rounding)).to.equal(1n);
expect(await this.mock.$log10(11n, rounding)).to.equal(1n);
expect(await this.mock.$log10(99n, rounding)).to.equal(1n);
expect(await this.mock.$log10(100n, rounding)).to.equal(2n);
expect(await this.mock.$log10(101n, rounding)).to.equal(2n);
expect(await this.mock.$log10(999n, rounding)).to.equal(2n);
expect(await this.mock.$log10(1000n, rounding)).to.equal(3n);
expect(await this.mock.$log10(1001n, rounding)).to.equal(3n);
expect(await this.mock.$log10(ethers.MaxUint256, rounding)).to.equal(77n);
}
});
it('rounds up', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$log10(0n, rounding)).to.equal(0n);
expect(await this.mock.$log10(1n, rounding)).to.equal(0n);
expect(await this.mock.$log10(2n, rounding)).to.equal(1n);
expect(await this.mock.$log10(9n, rounding)).to.equal(1n);
expect(await this.mock.$log10(10n, rounding)).to.equal(1n);
expect(await this.mock.$log10(11n, rounding)).to.equal(2n);
expect(await this.mock.$log10(99n, rounding)).to.equal(2n);
expect(await this.mock.$log10(100n, rounding)).to.equal(2n);
expect(await this.mock.$log10(101n, rounding)).to.equal(3n);
expect(await this.mock.$log10(999n, rounding)).to.equal(3n);
expect(await this.mock.$log10(1000n, rounding)).to.equal(3n);
expect(await this.mock.$log10(1001n, rounding)).to.equal(4n);
expect(await this.mock.$log10(ethers.MaxUint256, rounding)).to.equal(78n);
}
});
});
describe('log256', function () {
it('rounds down', async function () {
for (const rounding of RoundingDown) {
expect(await this.mock.$log256(0n, rounding)).to.equal(0n);
expect(await this.mock.$log256(1n, rounding)).to.equal(0n);
expect(await this.mock.$log256(2n, rounding)).to.equal(0n);
expect(await this.mock.$log256(255n, rounding)).to.equal(0n);
expect(await this.mock.$log256(256n, rounding)).to.equal(1n);
expect(await this.mock.$log256(257n, rounding)).to.equal(1n);
expect(await this.mock.$log256(65535n, rounding)).to.equal(1n);
expect(await this.mock.$log256(65536n, rounding)).to.equal(2n);
expect(await this.mock.$log256(65537n, rounding)).to.equal(2n);
expect(await this.mock.$log256(ethers.MaxUint256, rounding)).to.equal(31n);
}
});
it('rounds up', async function () {
for (const rounding of RoundingUp) {
expect(await this.mock.$log256(0n, rounding)).to.equal(0n);
expect(await this.mock.$log256(1n, rounding)).to.equal(0n);
expect(await this.mock.$log256(2n, rounding)).to.equal(1n);
expect(await this.mock.$log256(255n, rounding)).to.equal(1n);
expect(await this.mock.$log256(256n, rounding)).to.equal(1n);
expect(await this.mock.$log256(257n, rounding)).to.equal(2n);
expect(await this.mock.$log256(65535n, rounding)).to.equal(2n);
expect(await this.mock.$log256(65536n, rounding)).to.equal(2n);
expect(await this.mock.$log256(65537n, rounding)).to.equal(3n);
expect(await this.mock.$log256(ethers.MaxUint256, rounding)).to.equal(32n);
}
});
});
});
});

View File

@@ -0,0 +1,159 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { range } = require('../../helpers/iterate');
async function fixture() {
const mock = await ethers.deployContract('$SafeCast');
return { mock };
}
describe('SafeCast', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
for (const bits of range(8, 256, 8).map(ethers.toBigInt)) {
const maxValue = 2n ** bits - 1n;
describe(`toUint${bits}`, () => {
it('downcasts 0', async function () {
expect(await this.mock[`$toUint${bits}`](0n)).is.equal(0n);
});
it('downcasts 1', async function () {
expect(await this.mock[`$toUint${bits}`](1n)).is.equal(1n);
});
it(`downcasts 2^${bits} - 1 (${maxValue})`, async function () {
expect(await this.mock[`$toUint${bits}`](maxValue)).is.equal(maxValue);
});
it(`reverts when downcasting 2^${bits} (${maxValue + 1n})`, async function () {
await expect(this.mock[`$toUint${bits}`](maxValue + 1n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedUintDowncast')
.withArgs(bits, maxValue + 1n);
});
it(`reverts when downcasting 2^${bits} + 1 (${maxValue + 2n})`, async function () {
await expect(this.mock[`$toUint${bits}`](maxValue + 2n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedUintDowncast')
.withArgs(bits, maxValue + 2n);
});
});
}
describe('toUint256', () => {
it('casts 0', async function () {
expect(await this.mock.$toUint256(0n)).is.equal(0n);
});
it('casts 1', async function () {
expect(await this.mock.$toUint256(1n)).is.equal(1n);
});
it(`casts INT256_MAX (${ethers.MaxInt256})`, async function () {
expect(await this.mock.$toUint256(ethers.MaxInt256)).is.equal(ethers.MaxInt256);
});
it('reverts when casting -1', async function () {
await expect(this.mock.$toUint256(-1n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntToUint')
.withArgs(-1n);
});
it(`reverts when casting INT256_MIN (${ethers.MinInt256})`, async function () {
await expect(this.mock.$toUint256(ethers.MinInt256))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntToUint')
.withArgs(ethers.MinInt256);
});
});
for (const bits of range(8, 256, 8).map(ethers.toBigInt)) {
const minValue = -(2n ** (bits - 1n));
const maxValue = 2n ** (bits - 1n) - 1n;
describe(`toInt${bits}`, () => {
it('downcasts 0', async function () {
expect(await this.mock[`$toInt${bits}`](0n)).is.equal(0n);
});
it('downcasts 1', async function () {
expect(await this.mock[`$toInt${bits}`](1n)).is.equal(1n);
});
it('downcasts -1', async function () {
expect(await this.mock[`$toInt${bits}`](-1n)).is.equal(-1n);
});
it(`downcasts -2^${bits - 1n} (${minValue})`, async function () {
expect(await this.mock[`$toInt${bits}`](minValue)).is.equal(minValue);
});
it(`downcasts 2^${bits - 1n} - 1 (${maxValue})`, async function () {
expect(await this.mock[`$toInt${bits}`](maxValue)).is.equal(maxValue);
});
it(`reverts when downcasting -2^${bits - 1n} - 1 (${minValue - 1n})`, async function () {
await expect(this.mock[`$toInt${bits}`](minValue - 1n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntDowncast')
.withArgs(bits, minValue - 1n);
});
it(`reverts when downcasting -2^${bits - 1n} - 2 (${minValue - 2n})`, async function () {
await expect(this.mock[`$toInt${bits}`](minValue - 2n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntDowncast')
.withArgs(bits, minValue - 2n);
});
it(`reverts when downcasting 2^${bits - 1n} (${maxValue + 1n})`, async function () {
await expect(this.mock[`$toInt${bits}`](maxValue + 1n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntDowncast')
.withArgs(bits, maxValue + 1n);
});
it(`reverts when downcasting 2^${bits - 1n} + 1 (${maxValue + 2n})`, async function () {
await expect(this.mock[`$toInt${bits}`](maxValue + 2n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedIntDowncast')
.withArgs(bits, maxValue + 2n);
});
});
}
describe('toInt256', () => {
it('casts 0', async function () {
expect(await this.mock.$toInt256(0)).is.equal(0n);
});
it('casts 1', async function () {
expect(await this.mock.$toInt256(1)).is.equal(1n);
});
it(`casts INT256_MAX (${ethers.MaxInt256})`, async function () {
expect(await this.mock.$toInt256(ethers.MaxInt256)).is.equal(ethers.MaxInt256);
});
it(`reverts when casting INT256_MAX + 1 (${ethers.MaxInt256 + 1n})`, async function () {
await expect(this.mock.$toInt256(ethers.MaxInt256 + 1n))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedUintToInt')
.withArgs(ethers.MaxInt256 + 1n);
});
it(`reverts when casting UINT256_MAX (${ethers.MaxUint256})`, async function () {
await expect(this.mock.$toInt256(ethers.MaxUint256))
.to.be.revertedWithCustomError(this.mock, 'SafeCastOverflowedUintToInt')
.withArgs(ethers.MaxUint256);
});
});
describe('toUint (bool)', function () {
it('toUint(false) should be 0', async function () {
expect(await this.mock.$toUint(false)).to.equal(0n);
});
it('toUint(true) should be 1', async function () {
expect(await this.mock.$toUint(true)).to.equal(1n);
});
});
});

View File

@@ -0,0 +1,80 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test} from "@forge-std/Test.sol";
import {Math} from "../../../contracts/utils/math/Math.sol";
import {SignedMath} from "../../../contracts/utils/math/SignedMath.sol";
contract SignedMathTest is Test {
function testSelect(bool f, int256 a, int256 b) public {
assertEq(SignedMath.ternary(f, a, b), f ? a : b);
}
// MIN & MAX
function testMinMax(int256 a, int256 b) public {
assertEq(SignedMath.min(a, b), a < b ? a : b);
assertEq(SignedMath.max(a, b), a > b ? a : b);
}
// MIN
function testMin(int256 a, int256 b) public {
int256 result = SignedMath.min(a, b);
assertLe(result, a);
assertLe(result, b);
assertTrue(result == a || result == b);
}
// MAX
function testMax(int256 a, int256 b) public {
int256 result = SignedMath.max(a, b);
assertGe(result, a);
assertGe(result, b);
assertTrue(result == a || result == b);
}
// AVERAGE
// 1. simple test, not full int256 range
function testAverage1(int256 a, int256 b) public {
a = bound(a, type(int256).min / 2, type(int256).max / 2);
b = bound(b, type(int256).min / 2, type(int256).max / 2);
int256 result = SignedMath.average(a, b);
assertEq(result, (a + b) / 2);
}
// 2. more complex test, full int256 range
function testAverage2(int256 a, int256 b) public {
(int256 result, int256 min, int256 max) = (
SignedMath.average(a, b),
SignedMath.min(a, b),
SignedMath.max(a, b)
);
// average must be between `a` and `b`
assertGe(result, min);
assertLe(result, max);
unchecked {
// must be unchecked in order to support `a = type(int256).min, b = type(int256).max`
uint256 deltaLower = uint256(result - min);
uint256 deltaUpper = uint256(max - result);
uint256 remainder = uint256((a & 1) ^ (b & 1));
assertEq(remainder, Math.max(deltaLower, deltaUpper) - Math.min(deltaLower, deltaUpper));
}
}
// ABS
function testAbs(int256 a) public {
uint256 result = SignedMath.abs(a);
unchecked {
// must be unchecked in order to support `n = type(int256).min`
assertEq(result, a < 0 ? uint256(-a) : uint256(a));
}
}
}

View File

@@ -0,0 +1,53 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { min, max } = require('../../helpers/math');
async function testCommutative(fn, lhs, rhs, expected, ...extra) {
expect(await fn(lhs, rhs, ...extra)).to.deep.equal(expected);
expect(await fn(rhs, lhs, ...extra)).to.deep.equal(expected);
}
async function fixture() {
const mock = await ethers.deployContract('$SignedMath');
return { mock };
}
describe('SignedMath', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
describe('max', function () {
it('is correctly detected in both position', async function () {
await testCommutative(this.mock.$max, -1234n, 5678n, max(-1234n, 5678n));
});
});
describe('min', function () {
it('is correctly detected in both position', async function () {
await testCommutative(this.mock.$min, -1234n, 5678n, min(-1234n, 5678n));
});
});
describe('average', function () {
it('is correctly calculated with various input', async function () {
for (const x of [ethers.MinInt256, -57417n, -42304n, -4n, -3n, 0n, 3n, 4n, 42304n, 57417n, ethers.MaxInt256]) {
for (const y of [ethers.MinInt256, -57417n, -42304n, -5n, -2n, 0n, 2n, 5n, 42304n, 57417n, ethers.MaxInt256]) {
expect(await this.mock.$average(x, y)).to.equal((x + y) / 2n);
}
}
});
});
describe('abs', function () {
const abs = x => (x < 0n ? -x : x);
for (const n of [ethers.MinInt256, ethers.MinInt256 + 1n, -1n, 0n, 1n, ethers.MaxInt256 - 1n, ethers.MaxInt256]) {
it(`correctly computes the absolute value of ${n}`, async function () {
expect(await this.mock.$abs(n)).to.equal(abs(n));
});
}
});
});