From 96a122f79d80a5b481461b85082616c485fdf8cd Mon Sep 17 00:00:00 2001 From: Hiroshi <108636367+0xhiroshi@users.noreply.github.com> Date: Thu, 19 Oct 2023 14:07:59 +0100 Subject: [PATCH] feat: UnsafeMathUint256 (#100) * feat: UnsafeMathUint256 * chore: Trailing whitespace --- contracts/libraries/UnsafeMathUint256.sol | 28 +++++++++++++++ test/foundry/UnsafeMathUint256.t.sol | 42 +++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 contracts/libraries/UnsafeMathUint256.sol create mode 100644 test/foundry/UnsafeMathUint256.t.sol diff --git a/contracts/libraries/UnsafeMathUint256.sol b/contracts/libraries/UnsafeMathUint256.sol new file mode 100644 index 0000000..1b68062 --- /dev/null +++ b/contracts/libraries/UnsafeMathUint256.sol @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.17; + +library UnsafeMathUint256 { + function unsafeAdd(uint256 a, uint256 b) internal pure returns (uint256) { + unchecked { + return a + b; + } + } + + function unsafeSubtract(uint256 a, uint256 b) internal pure returns (uint256) { + unchecked { + return a - b; + } + } + + function unsafeMultiply(uint256 a, uint256 b) internal pure returns (uint256) { + unchecked { + return a * b; + } + } + + function unsafeDivide(uint256 a, uint256 b) internal pure returns (uint256) { + unchecked { + return a / b; + } + } +} diff --git a/test/foundry/UnsafeMathUint256.t.sol b/test/foundry/UnsafeMathUint256.t.sol new file mode 100644 index 0000000..751bf95 --- /dev/null +++ b/test/foundry/UnsafeMathUint256.t.sol @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.17; + +import {UnsafeMathUint256} from "../../contracts/libraries/UnsafeMathUint256.sol"; +import {TestHelpers} from "./utils/TestHelpers.sol"; + +contract UnsafeMathUint256Test is TestHelpers { + using UnsafeMathUint256 for uint256; + + function testFuzz_unsafeAdd(uint256 number) public { + vm.assume(number < type(uint256).max); + assertEq(number.unsafeAdd(1), number + 1); + } + + function test_unsafeAdd_NumberIsUint256Max() public { + assertEq(type(uint256).max.unsafeAdd(1), 0); + } + + function testFuzz_unsafeSubtract(uint256 number) public { + vm.assume(number > 0); + assertEq(number.unsafeSubtract(1), number - 1); + } + + function test_unsafeSubtract_NumberIs0() public { + assertEq(uint256(0).unsafeSubtract(1), type(uint256).max); + } + + function testFuzz_unsafeMultiply(uint256 a, uint256 b) public { + vm.assume(a <= type(uint128).max && b <= type(uint128).max); + assertEq(a.unsafeMultiply(b), a * b); + } + + function test_unsafeMultiply_NumbersAreGreaterThanUint128() public { + uint256 number = uint256(type(uint128).max) + 1; + assertEq(number.unsafeMultiply(number), 0); + } + + function testFuzz_unsafeDivide(uint256 a, uint256 b) public { + vm.assume(b != 0); + assertEq(a.unsafeDivide(b), a / b); + } +}