SignedMath.test.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. const { min, max } = require('../../helpers/math');
  5. async function testCommutative(fn, lhs, rhs, expected, ...extra) {
  6. expect(await fn(lhs, rhs, ...extra)).to.deep.equal(expected);
  7. expect(await fn(rhs, lhs, ...extra)).to.deep.equal(expected);
  8. }
  9. async function fixture() {
  10. const mock = await ethers.deployContract('$SignedMath');
  11. return { mock };
  12. }
  13. describe('SignedMath', function () {
  14. beforeEach(async function () {
  15. Object.assign(this, await loadFixture(fixture));
  16. });
  17. describe('max', function () {
  18. it('is correctly detected in both position', async function () {
  19. await testCommutative(this.mock.$max, -1234n, 5678n, max(-1234n, 5678n));
  20. });
  21. });
  22. describe('min', function () {
  23. it('is correctly detected in both position', async function () {
  24. await testCommutative(this.mock.$min, -1234n, 5678n, min(-1234n, 5678n));
  25. });
  26. });
  27. describe('average', function () {
  28. it('is correctly calculated with various input', async function () {
  29. for (const x of [ethers.MinInt256, -57417n, -42304n, -4n, -3n, 0n, 3n, 4n, 42304n, 57417n, ethers.MaxInt256]) {
  30. for (const y of [ethers.MinInt256, -57417n, -42304n, -5n, -2n, 0n, 2n, 5n, 42304n, 57417n, ethers.MaxInt256]) {
  31. expect(await this.mock.$average(x, y)).to.equal((x + y) / 2n);
  32. }
  33. }
  34. });
  35. });
  36. describe('abs', function () {
  37. const abs = x => (x < 0n ? -x : x);
  38. for (const n of [ethers.MinInt256, ethers.MinInt256 + 1n, -1n, 0n, 1n, ethers.MaxInt256 - 1n, ethers.MaxInt256]) {
  39. it(`correctly computes the absolute value of ${n}`, async function () {
  40. expect(await this.mock.$abs(n)).to.equal(abs(n));
  41. });
  42. }
  43. });
  44. });