From 0a1dfd564b35c26f3dbf05d6668bc4c640d65bf2 Mon Sep 17 00:00:00 2001 From: DualFroz Date: Sun, 23 Aug 2026 17:12:00 +0200 Subject: [PATCH] feat(libraries): add bit math and liquidity delta helpers --- src/libraries/BitMath.sol | 83 +++++++++++++++++++++++++++++++++ src/libraries/LiquidityMath.sol | 15 ++++++ 2 files changed, 98 insertions(+) create mode 100644 src/libraries/BitMath.sol create mode 100644 src/libraries/LiquidityMath.sol diff --git a/src/libraries/BitMath.sol b/src/libraries/BitMath.sol new file mode 100644 index 0000000..acf9d2b --- /dev/null +++ b/src/libraries/BitMath.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.36; + +/// @title Most and least significant bit lookups over a 256 bit word. +library BitMath { + function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { + require(x > 0, "BitMath: ZERO"); + unchecked { + if (x >= 0x100000000000000000000000000000000) { + x >>= 128; + r += 128; + } + if (x >= 0x10000000000000000) { + x >>= 64; + r += 64; + } + if (x >= 0x100000000) { + x >>= 32; + r += 32; + } + if (x >= 0x10000) { + x >>= 16; + r += 16; + } + if (x >= 0x100) { + x >>= 8; + r += 8; + } + if (x >= 0x10) { + x >>= 4; + r += 4; + } + if (x >= 0x4) { + x >>= 2; + r += 2; + } + if (x >= 0x2) r += 1; + } + } + + function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { + require(x > 0, "BitMath: ZERO"); + unchecked { + r = 255; + if (x & type(uint128).max > 0) { + r -= 128; + } else { + x >>= 128; + } + if (x & type(uint64).max > 0) { + r -= 64; + } else { + x >>= 64; + } + if (x & type(uint32).max > 0) { + r -= 32; + } else { + x >>= 32; + } + if (x & type(uint16).max > 0) { + r -= 16; + } else { + x >>= 16; + } + if (x & type(uint8).max > 0) { + r -= 8; + } else { + x >>= 8; + } + if (x & 0xf > 0) { + r -= 4; + } else { + x >>= 4; + } + if (x & 0x3 > 0) { + r -= 2; + } else { + x >>= 2; + } + if (x & 0x1 > 0) r -= 1; + } + } +} diff --git a/src/libraries/LiquidityMath.sol b/src/libraries/LiquidityMath.sol new file mode 100644 index 0000000..3897aed --- /dev/null +++ b/src/libraries/LiquidityMath.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.36; + +/// @title Adds a signed delta to an unsigned liquidity amount with overflow guards. +library LiquidityMath { + function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { + unchecked { + if (y < 0) { + require((z = x - uint128(-y)) < x, "LiquidityMath: SUB"); + } else { + require((z = x + uint128(y)) >= x, "LiquidityMath: ADD"); + } + } + } +}