Verified contractPartialGPL-2.0-or-later
BinPoolManager
Address0xa61093c554d58ee0b0108ad71cdc57c396f04313
- Balance
0 ETH
- Transactions
3
- Compiler
solc 0.8.26
- Same code
1 more contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 25,666 runs
- EVM version
- cancun
- Via IR
- yes
- License
- GPL-2.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,354,474
- Creation transaction
- 0xc53340f711…bab59caa0b
47 files
- src/pool-bin/BinPoolManager.solmain12.16 KB
- src/Extsload.sol1.8 KB
- src/Owner.sol596 B
- src/ProtocolFees.sol4.06 KB
- src/base/Ownable.sol2.18 KB
- src/base/Pausable.sol2.1 KB
- src/interfaces/IERC20Minimal.sol3.03 KB
- src/interfaces/IExtsload.sol593 B
- src/interfaces/IHooks.sol151 B
- src/interfaces/IPoolManager.sol1.77 KB
- src/interfaces/IProtocolFeeController.sol836 B
- src/interfaces/IProtocolFees.sol3.08 KB
- src/interfaces/IVault.sol7.01 KB
- src/interfaces/IVaultToken.sol2.92 KB
- src/libraries/CustomRevert.sol2.36 KB
- src/libraries/Hooks.sol5.24 KB
- src/libraries/LPFeeLibrary.sol3.82 KB
- src/libraries/ParseBytes.sol1.28 KB
- src/libraries/ProtocolFeeLibrary.sol2.92 KB
- src/libraries/SafeCast.sol2.09 KB
- src/libraries/VaultAppDeltaSettlement.sol1.01 KB
- src/libraries/math/Encoded.sol3.98 KB
- src/libraries/math/ParametersHelper.sol982 B
- src/libraries/math/UnsafeMath.sol1.24 KB
- src/pool-bin/interfaces/IBinHooks.sol8.85 KB
- src/pool-bin/interfaces/IBinPoolManager.sol10.95 KB
- src/pool-bin/libraries/BinHelper.sol14.15 KB
- src/pool-bin/libraries/BinHooks.sol9.8 KB
- src/pool-bin/libraries/BinPool.sol22.74 KB
- src/pool-bin/libraries/BinPoolParametersHelper.sol1.41 KB
- src/pool-bin/libraries/BinPosition.sol2.33 KB
- src/pool-bin/libraries/Constants.sol672 B
- src/pool-bin/libraries/FeeHelper.sol2.52 KB
- src/pool-bin/libraries/PriceHelper.sol2.96 KB
- src/pool-bin/libraries/math/BitMath.sol4.01 KB
- src/pool-bin/libraries/math/LiquidityConfigurations.sol3.53 KB
- src/pool-bin/libraries/math/PackedUint128Math.sol8.95 KB
- src/pool-bin/libraries/math/SafeCast.sol9.54 KB
- src/pool-bin/libraries/math/TreeMath.sol7.58 KB
- src/pool-bin/libraries/math/Uint128x128Math.sol7.75 KB
- src/pool-bin/libraries/math/Uint256x256Math.sol10.57 KB
- src/pool-bin/types/BinSlot0.sol3.14 KB
- src/types/BalanceDelta.sol2.36 KB
- src/types/BeforeSwapDelta.sol1.68 KB
- src/types/Currency.sol5.29 KB
- src/types/PoolId.sol468 B
- src/types/PoolKey.sol1.02 KB
src/pool-bin/BinPoolManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity 0.8.26;
import {ProtocolFees} from "../ProtocolFees.sol";
import {Hooks} from "../libraries/Hooks.sol";
import {BinPool} from "./libraries/BinPool.sol";
import {BinPoolParametersHelper} from "./libraries/BinPoolParametersHelper.sol";
import {ParametersHelper} from "../libraries/math/ParametersHelper.sol";
import {Currency, CurrencyLibrary} from "../types/Currency.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {IBinPoolManager} from "./interfaces/IBinPoolManager.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {IVault} from "../interfaces/IVault.sol";
import {BinPosition} from "./libraries/BinPosition.sol";
import {LPFeeLibrary} from "../libraries/LPFeeLibrary.sol";
import {PackedUint128Math} from "./libraries/math/PackedUint128Math.sol";
import {Extsload} from "../Extsload.sol";
import {BinHooks} from "./libraries/BinHooks.sol";
import {PriceHelper} from "./libraries/PriceHelper.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
import {BinSlot0} from "./types/BinSlot0.sol";
import {VaultAppDeltaSettlement} from "../libraries/VaultAppDeltaSettlement.sol";
/// @notice Holds the state for all bin pools
contract BinPoolManager is IBinPoolManager, ProtocolFees, Extsload {
using BinPool for *;
using BinPosition for mapping(bytes32 => BinPosition.Info);
using BinPoolParametersHelper for bytes32;
using LPFeeLibrary for uint24;
using PackedUint128Math for bytes32;
using Hooks for bytes32;
using VaultAppDeltaSettlement for IVault;
/// @inheritdoc IBinPoolManager
uint16 public constant override MIN_BIN_STEP = 1;
/// @inheritdoc IBinPoolManager
uint16 public override maxBinStep = 100;
/// @inheritdoc IBinPoolManager
uint256 public override minBinShareForDonate = 2 ** 128;
mapping(PoolId id => BinPool.State poolState) public pools;
mapping(PoolId id => PoolKey poolKey) public poolIdToPoolKey;
constructor(IVault vault) ProtocolFees(vault) {}
/// @notice pool manager specified in the pool key must match current contract
modifier poolManagerMatch(address poolManager) {
if (address(this) != poolManager) revert PoolManagerMismatch();
_;
}
/// @inheritdoc IBinPoolManager
function getSlot0(PoolId id) external view override returns (uint24 activeId, uint24 protocolFee, uint24 lpFee) {
BinSlot0 slot0 = pools[id].slot0;
return (slot0.activeId(), slot0.protocolFee(), slot0.lpFee());
}
/// @inheritdoc IBinPoolManager
function getBin(PoolId id, uint24 binId)
external
view
override
returns (uint128 binReserveX, uint128 binReserveY, uint256 binLiquidity, uint256 totalShares)
{
PoolKey memory key = poolIdToPoolKey[id];
(binReserveX, binReserveY, binLiquidity, totalShares) = pools[id].getBin(key.parameters.getBinStep(), binId);
}
/// @inheritdoc IBinPoolManager
function getPosition(PoolId id, address owner, uint24 binId, bytes32 salt)
external
view
override
returns (BinPosition.Info memory position)
{
return pools[id].positions.get(owner, binId, salt);
}
/// @inheritdoc IBinPoolManager
function getNextNonEmptyBin(PoolId id, bool swapForY, uint24 binId)
external
view
override
returns (uint24 nextId)
{
nextId = pools[id].getNextNonEmptyBin(swapForY, binId);
}
/// @inheritdoc IBinPoolManager
function initialize(PoolKey memory key, uint24 activeId)
external
override
poolManagerMatch(address(key.poolManager))
{
uint16 binStep = key.parameters.getBinStep();
if (binStep < MIN_BIN_STEP) revert BinStepTooSmall(binStep);
if (binStep > maxBinStep) revert BinStepTooLarge(binStep);
if (key.currency0 >= key.currency1) {
revert CurrenciesInitializedOutOfOrder(Currency.unwrap(key.currency0), Currency.unwrap(key.currency1));
}
// safety check, making sure that the price can be calculated
PriceHelper.getPriceFromId(activeId, binStep);
ParametersHelper.checkUnusedBitsAllZero(
key.parameters, BinPoolParametersHelper.OFFSET_MOST_SIGNIFICANT_UNUSED_BITS
);
Hooks.validateHookConfig(key);
BinHooks.validatePermissionsConflict(key);
/// @notice init value for dynamic lp fee is 0, but hook can still set it in afterInitialize
uint24 lpFee = key.fee.getInitialLPFee();
lpFee.validate(LPFeeLibrary.TEN_PERCENT_FEE);
BinHooks.beforeInitialize(key, activeId);
PoolId id = key.toId();
uint24 protocolFee = _fetchProtocolFee(key);
pools[id].initialize(activeId, protocolFee, lpFee);
poolIdToPoolKey[id] = key;
/// @notice Make sure the first event is noted, so that later events from afterHook won't get mixed up with this one
emit Initialize(id, key.currency0, key.currency1, key.hooks, key.fee, key.parameters, activeId);
BinHooks.afterInitialize(key, activeId);
}
/// @inheritdoc IBinPoolManager
function swap(PoolKey memory key, bool swapForY, int128 amountSpecified, bytes calldata hookData)
external
override
whenNotPaused
returns (BalanceDelta delta)
{
if (amountSpecified == 0) revert AmountSpecifiedIsZero();
PoolId id = key.toId();
BinPool.State storage pool = pools[id];
pool.checkPoolInitialized();
(int128 amountToSwap, BeforeSwapDelta beforeSwapDelta, uint24 lpFeeOverride) =
BinHooks.beforeSwap(key, swapForY, amountSpecified, hookData);
/// @dev fix stack too deep
{
BinPool.SwapState memory state;
(delta, state) = pool.swap(
BinPool.SwapParams({
swapForY: swapForY,
binStep: key.parameters.getBinStep(),
lpFeeOverride: lpFeeOverride,
amountSpecified: amountToSwap
})
);
unchecked {
if (state.feeAmountToProtocol > 0) {
protocolFeesAccrued[key.currency0] += state.feeAmountToProtocol.decodeX();
protocolFeesAccrued[key.currency1] += state.feeAmountToProtocol.decodeY();
}
}
/// @notice Make sure the first event is noted, so that later events from afterHook won't get mixed up with this one
emit Swap(
id, msg.sender, delta.amount0(), delta.amount1(), state.activeId, state.swapFee, state.protocolFee
);
}
BalanceDelta hookDelta;
(delta, hookDelta) = BinHooks.afterSwap(key, swapForY, amountSpecified, delta, hookData, beforeSwapDelta);
vault.accountAppDeltaWithHookDelta(key, delta, hookDelta);
}
/// @inheritdoc IBinPoolManager
function mint(PoolKey memory key, IBinPoolManager.MintParams calldata params, bytes calldata hookData)
external
override
whenNotPaused
returns (BalanceDelta delta, BinPool.MintArrays memory mintArray)
{
PoolId id = key.toId();
BinPool.State storage pool = pools[id];
pool.checkPoolInitialized();
(uint24 lpFeeOverride) = BinHooks.beforeMint(key, params, hookData);
bytes32 feeAmountToProtocol;
bytes32 compositionFeeAmount;
(delta, feeAmountToProtocol, mintArray, compositionFeeAmount) = pool.mint(
BinPool.MintParams({
to: msg.sender,
liquidityConfigs: params.liquidityConfigs,
amountIn: params.amountIn,
binStep: key.parameters.getBinStep(),
lpFeeOverride: lpFeeOverride,
salt: params.salt
})
);
unchecked {
if (feeAmountToProtocol > 0) {
protocolFeesAccrued[key.currency0] += feeAmountToProtocol.decodeX();
protocolFeesAccrued[key.currency1] += feeAmountToProtocol.decodeY();
}
}
/// @notice Make sure the first event is noted, so that later events from afterHook won't get mixed up with this one
emit Mint(
id, msg.sender, mintArray.ids, params.salt, mintArray.amounts, compositionFeeAmount, feeAmountToProtocol
);
BalanceDelta hookDelta;
(delta, hookDelta) = BinHooks.afterMint(key, params, delta, hookData);
vault.accountAppDeltaWithHookDelta(key, delta, hookDelta);
}
/// @inheritdoc IBinPoolManager
function burn(PoolKey memory key, IBinPoolManager.BurnParams memory params, bytes calldata hookData)
external
override
returns (BalanceDelta delta)
{
PoolId id = key.toId();
BinPool.State storage pool = pools[id];
pool.checkPoolInitialized();
BinHooks.beforeBurn(key, params, hookData);
uint256[] memory binIds;
bytes32[] memory amountRemoved;
(delta, binIds, amountRemoved) = pool.burn(
BinPool.BurnParams({
from: msg.sender,
ids: params.ids,
amountsToBurn: params.amountsToBurn,
salt: params.salt
})
);
/// @notice Make sure the first event is noted, so that later events from afterHook won't get mixed up with this one
emit Burn(id, msg.sender, binIds, params.salt, amountRemoved);
BalanceDelta hookDelta;
(delta, hookDelta) = BinHooks.afterBurn(key, params, delta, hookData);
vault.accountAppDeltaWithHookDelta(key, delta, hookDelta);
}
function donate(PoolKey memory key, uint128 amount0, uint128 amount1, bytes calldata hookData)
external
override
whenNotPaused
returns (BalanceDelta delta, uint24 binId)
{
PoolId id = key.toId();
BinPool.State storage pool = pools[id];
pool.checkPoolInitialized();
BinHooks.beforeDonate(key, amount0, amount1, hookData);
/// @dev Share is 1:1 liquidity when liquidity is first added to bin
uint256 currentBinShare = pool.shareOfBin[pool.slot0.activeId()];
if (currentBinShare < minBinShareForDonate) {
revert InsufficientBinShareForDonate(currentBinShare);
}
(delta, binId) = pool.donate(key.parameters.getBinStep(), amount0, amount1);
vault.accountAppBalanceDelta(key.currency0, key.currency1, delta, msg.sender);
/// @notice Make sure the first event is noted, so that later events from afterHook won't get mixed up with this one
emit Donate(id, msg.sender, delta.amount0(), delta.amount1(), binId);
BinHooks.afterDonate(key, amount0, amount1, hookData);
}
/// @inheritdoc IBinPoolManager
function setMaxBinStep(uint16 newMaxBinStep) external override onlyOwner {
if (newMaxBinStep <= MIN_BIN_STEP) revert MaxBinStepTooSmall(newMaxBinStep);
maxBinStep = newMaxBinStep;
emit SetMaxBinStep(newMaxBinStep);
}
/// @inheritdoc IBinPoolManager
function setMinBinSharesForDonate(uint256 minBinShare) external override onlyOwner {
minBinShareForDonate = minBinShare;
emit SetMinBinSharesForDonate(minBinShare);
}
/// @inheritdoc IPoolManager
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external override {
if (!key.fee.isDynamicLPFee() || msg.sender != address(key.hooks)) revert UnauthorizedDynamicLPFeeUpdate();
newDynamicLPFee.validate(LPFeeLibrary.TEN_PERCENT_FEE);
PoolId id = key.toId();
pools[id].setLPFee(newDynamicLPFee);
emit DynamicLPFeeUpdated(id, newDynamicLPFee);
}
function _setProtocolFee(PoolId id, uint24 newProtocolFee) internal override {
pools[id].setProtocolFee(newProtocolFee);
}
}
src/Extsload.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice This code is adapted from
// https://github.com/RageTrade/core/blob/main/contracts/utils/Extsload.sol
import {IExtsload} from "./interfaces/IExtsload.sol";
/// @notice Allows the inheriting contract make it's state accessable to other contracts
/// https://ethereum-magicians.org/t/extsload-opcode-proposal/2410/11
abstract contract Extsload is IExtsload {
/// @inheritdoc IExtsload
function extsload(bytes32 slot) external view returns (bytes32) {
assembly ("memory-safe") {
mstore(0, sload(slot))
return(0, 0x20)
}
}
/// @inheritdoc IExtsload
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory) {
assembly ("memory-safe") {
let memptr := mload(0x40)
let start := memptr
// for abi encoding the response - the array will be found at 0x20
mstore(memptr, 0x20)
// next we store the length of the return array
mstore(add(memptr, 0x20), slots.length)
// update memptr to the first location to hold an array entry
memptr := add(memptr, 0x40)
// A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas.
let end := add(memptr, shl(5, slots.length))
let calldataptr := slots.offset
for {} 1 {} {
mstore(memptr, sload(calldataload(calldataptr)))
memptr := add(memptr, 0x20)
calldataptr := add(calldataptr, 0x20)
if iszero(lt(memptr, end)) { break }
}
return(start, sub(end, start))
}
}
}
src/Owner.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Ownable} from "./base/Ownable.sol";
import {Pausable} from "./base/Pausable.sol";
/// @notice Allow owner to pause in case of emergency
/// @dev This contract is inherited by ProtocolFees and part of both CL/BinPoolManager
abstract contract Owner is Ownable, Pausable {
constructor() Ownable(msg.sender) {}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
src/ProtocolFees.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Owner} from "./Owner.sol";
import {Currency} from "./types/Currency.sol";
import {IProtocolFeeController} from "./interfaces/IProtocolFeeController.sol";
import {IProtocolFees} from "./interfaces/IProtocolFees.sol";
import {ProtocolFeeLibrary} from "./libraries/ProtocolFeeLibrary.sol";
import {PoolKey} from "./types/PoolKey.sol";
import {PoolId} from "./types/PoolId.sol";
import {IVault} from "./interfaces/IVault.sol";
import {CustomRevert} from "./libraries/CustomRevert.sol";
abstract contract ProtocolFees is IProtocolFees, Owner {
using ProtocolFeeLibrary for uint24;
/// @inheritdoc IProtocolFees
mapping(Currency currency => uint256 amount) public protocolFeesAccrued;
/// @inheritdoc IProtocolFees
IProtocolFeeController public protocolFeeController;
/// @inheritdoc IProtocolFees
IVault public immutable vault;
constructor(IVault _vault) {
vault = _vault;
}
function _setProtocolFee(PoolId id, uint24 newProtocolFee) internal virtual;
/// @inheritdoc IProtocolFees
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external virtual {
if (msg.sender != address(protocolFeeController)) revert InvalidCaller();
if (!newProtocolFee.validate()) revert ProtocolFeeTooLarge(newProtocolFee);
PoolId id = key.toId();
_setProtocolFee(id, newProtocolFee);
emit ProtocolFeeUpdated(id, newProtocolFee);
}
/// @notice Fetch the protocol fee for a given pool
/// @dev Revert if call to protocolFeeController fails or if return value is not 32 bytes
/// However if the call to protocolFeeController succeed, it can still revert if the return value is too large
/// @return protocolFee The protocol fee for the pool
function _fetchProtocolFee(PoolKey memory key) internal view returns (uint24 protocolFee) {
if (address(protocolFeeController) != address(0)) {
address targetProtocolFeeController = address(protocolFeeController);
bytes memory data = abi.encodeCall(IProtocolFeeController.protocolFeeForPool, (key));
bool success;
uint256 returnData;
assembly ("memory-safe") {
// only load the first 32 bytes of the return data to prevent gas griefing
success := staticcall(gas(), targetProtocolFeeController, add(data, 0x20), mload(data), 0, 32)
// load the return data
returnData := mload(0)
// success if return data size is also 32 bytes
success := and(success, eq(returndatasize(), 32))
}
// revert if call fails or return size is not 32 bytes
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
targetProtocolFeeController, bytes4(data), ProtocolFeeCannotBeFetched.selector
);
}
if (returnData == uint24(returnData) && uint24(returnData).validate()) {
protocolFee = uint24(returnData);
} else {
// revert if return value overflow a uint24 or greater than max protocol fee
revert ProtocolFeeTooLarge(uint24(returnData));
}
}
}
function setProtocolFeeController(IProtocolFeeController controller) external onlyOwner {
protocolFeeController = controller;
emit ProtocolFeeControllerUpdated(address(controller));
}
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
override
returns (uint256 amountCollected)
{
if (msg.sender != address(protocolFeeController)) revert InvalidCaller();
amountCollected = (amount == 0) ? protocolFeesAccrued[currency] : amount;
protocolFeesAccrued[currency] -= amountCollected;
vault.collectFee(currency, amountCollected, recipient);
}
}
src/base/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Copy from openZeppelin contracts(v5.0.0) (access/Ownable.sol), and remove unnecessary functions.
* Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != msg.sender) {
revert();
}
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert();
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
src/base/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Referenced from openZeppelin contracts(v5.0.0) (utils/Pausable.sol), removed unnecessary functions and gas optimization.
* Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable {
uint256 private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool res) {
assembly ("memory-safe") {
res := sload(_paused.slot)
}
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = 1;
emit Paused(msg.sender);
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual {
_paused = 0;
emit Unpaused(msg.sender);
}
}
src/interfaces/IERC20Minimal.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for SquadSwapV4
/// @notice Contains a subset of the full ERC20 interface that is used in SquadSwapV4
interface IERC20Minimal {
/// @notice Returns the balance of a token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
src/interfaces/IExtsload.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
src/interfaces/IHooks.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IHooks {
function getHooksRegistrationBitmap() external view returns (uint16);
}
src/interfaces/IPoolManager.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IHooks} from "./IHooks.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {PoolId} from "../types/PoolId.sol";
import {Currency} from "../types/Currency.sol";
interface IPoolManager {
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesInitializedOutOfOrder(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool is not a dynamic fee pool.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Emitted when lp fee is updated
/// @dev The event is emitted even if the updated fee value is the same as previous one
event DynamicLPFeeUpdated(PoolId indexed id, uint24 dynamicLPFee);
/// @notice Updates lp fee for a dyanmic fee pool
/// @dev Some of the use case could be:
/// 1) when hook#beforeSwap() is called and hook call this function to update the lp fee
/// 2) For BinPool only, when hook#beforeMint() is called and hook call this function to update the lp fee
/// 3) other use case where the hook might want to on an ad-hoc basis increase/reduce lp fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
/// @notice Return PoolKey for a given PoolId
function poolIdToPoolKey(PoolId id)
external
view
returns (
Currency currency0,
Currency currency1,
IHooks hooks,
IPoolManager poolManager,
uint24 fee,
bytes32 parameters
);
}
src/interfaces/IProtocolFeeController.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
interface IProtocolFeeController {
/// @notice Get the protocol fee for a pool given the conditions of this contract
/// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool
/// to determine the protocol fee, hence the entire key is needed.
/// @return protocolFee The pool's protocol fee, expressed in hundredths of a bip. The upper 12 bits are for 1->0
/// and the lower 12 are for 0->1. The maximum is 4000 - meaning the maximum protocol fee is 0.4%.
/// the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24 protocolFee);
}
src/interfaces/IProtocolFees.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {IProtocolFeeController} from "./IProtocolFeeController.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IVault} from "./IVault.sol";
interface IProtocolFees {
/// @notice Thrown when the protocol fee exceeds the upper limit.
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when calls to protocolFeeController fails or return size is not 32 bytes
error ProtocolFeeCannotBeFetched();
/// @notice Thrown when user not authorized to set or collect protocol fee
error InvalidCaller();
/// @notice Emitted when protocol fee is updated
/// @dev The event is emitted even if the updated protocolFee is the same as previous protocolFee
/// @param id The pool id for which the protocol fee is updated
/// @param protocolFee The new protocol fee value
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Emitted when protocol fee controller is updated
/// @param protocolFeeController The new protocol fee controller
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the given currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Returns the current protocol fee controller address
/// @return IProtocolFeeController The currency protocol fee controller
function protocolFeeController() external view returns (IProtocolFeeController);
/// @notice Sets the protocol's swap fee for the given pool
/// @param key The pool key for which to set the protocol fee
/// @param newProtocolFee The new protocol fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Update the protocol fee controller, called by the owner
/// @param controller The new protocol fee controller to be set
function setProtocolFeeController(IProtocolFeeController controller) external;
/// @notice Collects the protocol fee accrued in the given currency, called by the owner or the protocol fee controller
/// @dev This will revert if vault is locked
/// @param recipient The address to which the protocol fees should be sent
/// @param currency The currency in which to collect the protocol fees
/// @param amount The amount of protocol fees to collect
/// @return amountCollected The amount of protocol fees actually collected
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the vault where the protocol fees are safely stored
/// @return IVault The address of the vault
function vault() external view returns (IVault);
}
src/interfaces/IVault.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IVaultToken} from "./IVaultToken.sol";
interface IVault is IVaultToken {
event AppRegistered(address indexed app);
/// @notice Thrown when a app is not registered
error AppUnregistered();
/// @notice Thrown when a currency is not netted out after a lock
error CurrencyNotSettled();
/// @notice Thrown when an app's transient reserve deficit is not fully repaid by the end of a lock
error AppCurrencyNotFullyRepaid();
/// @notice Thrown when there is already a locker
/// @param locker The address of the current locker
error LockerAlreadySet(address locker);
/// @notice Thrown when passing in msg.value for non-native currency
error SettleNonNativeCurrencyWithValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Thrown when there is no locker
error NoLocker();
/// @notice Thrown when collectFee is attempted on a token that is synced.
error FeeCurrencySynced();
function isAppRegistered(address app) external returns (bool);
/// @notice Returns the reserves for a a given pool type and currency
function reservesOfApp(address app, Currency currency) external view returns (uint256);
/// @notice register an app so that it can perform accounting base on vault
function registerApp(address app) external;
/// @notice Returns the locker who is locking the vault
function getLocker() external view returns (address locker);
/// @notice Returns the reserve and its amount that is currently being stored in trnasient storage
function getVaultReserve() external view returns (Currency, uint256);
/// @notice Returns lock data
function getUnsettledDeltasCount() external view returns (uint256 count);
/// @notice Get the current delta for a locker in the given currency
/// @param currency The currency for which to lookup the delta
function currencyDelta(address settler, Currency currency) external view returns (int256);
/// @notice Returns the number of app/currency pairs with an outstanding transient reserve deficit
function getAppDeficitCount() external view returns (uint256 count);
/// @notice Returns an app's outstanding transient reserve deficit for a currency
function appCurrencyDeficit(address app, Currency currency) external view returns (uint256);
/// @notice All operations go through this function
/// @param data Any data to pass to the callback, via `ILockCallback(msg.sender).lockCallback(data)`
/// @return The data returned by the call to `ILockCallback(msg.sender).lockCallback(data)`
function lock(bytes calldata data) external returns (bytes memory);
/// @notice Called by registered app to account for a change in the pool balance,
/// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate,
/// include the case where hookDelta is involved
/// @param currency0 The PoolKey currency0 to update
/// @param currency1 The PoolKey currency1 to update
/// @param delta The change in the pool's balance
/// @param settler The address whose delta will be updated
/// @param hookDelta The change in the pool's balance from hook
/// @param hook The address whose hookDelta will be updated
function accountAppBalanceDelta(
Currency currency0,
Currency currency1,
BalanceDelta delta,
address settler,
BalanceDelta hookDelta,
address hook
) external;
/// @notice Called by registered app to account for a change in the pool balance,
/// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate
/// @param currency0 The PoolKey currency0 to update
/// @param currency1 The PoolKey currency1 to update
/// @param delta The change in the pool's balance
/// @param settler The address whose delta will be updated
function accountAppBalanceDelta(Currency currency0, Currency currency1, BalanceDelta delta, address settler)
external;
/// @notice This works as a general accounting mechanism for non-dex app
/// @param currency The currency to update
/// @param delta The change in the balance
/// @param settler The address whose delta will be updated
function accountAppBalanceDelta(Currency currency, int128 delta, address settler) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
function take(Currency currency, address to, uint256 amount) external;
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency token0) external;
/// @notice Called by the user to pay what is owed
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retreivable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by app to collect any fee related
/// @dev no restriction on caller, underflow happen if caller collect more than the reserve
function collectFee(Currency currency, uint256 amount, address recipient) external;
/// @notice Called by the user to store surplus tokens in the vault
function mint(address to, Currency currency, uint256 amount) external;
/// @notice Called by the user to use surplus tokens for payment settlement
function burn(address from, Currency currency, uint256 amount) external;
}
src/interfaces/IVaultToken.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
interface IVaultToken {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, Currency indexed currency, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, Currency indexed currency, uint256 amount);
/// @notice get the amount of owner's surplus token in vault
/// @param owner The address you want to query the balance of
/// @param currency The currency you want to query the balance of
/// @return balance The balance of the specified address
function balanceOf(address owner, Currency currency) external view returns (uint256 balance);
/// @notice get the amount that owner has authorized for spender to use
/// @param owner The address of the owner
/// @param spender The address who is allowed to spend the owner's token
/// @param currency The currency the spender is allowed to spend
/// @return amount The amount of token the spender is allowed to spend
function allowance(address owner, address spender, Currency currency) external view returns (uint256 amount);
/// @notice approve spender for using user's token
/// @param spender The address msg.sender is approving to spend the his token
/// @param currency The currency the spender is allowed to spend
/// @param amount The amount of token the spender is allowed to spend
/// @return bool Whether the approval was successful or not
function approve(address spender, Currency currency, uint256 amount) external returns (bool);
/// @notice transfer msg.sender's token to someone else
/// @param to The address to transfer the token to
/// @param currency The currency to transfer
/// @param amount The amount of token to transfer
/// @return bool Whether the transfer was successful or not
function transfer(address to, Currency currency, uint256 amount) external returns (bool);
/// @notice transfer from address's token on behalf of him
/// @param from The address to transfer the token from
/// @param to The address to transfer the token to
/// @param currency The currency to transfer
/// @param amount The amount of token to transfer
/// @return bool Whether the transfer was successful or not
function transferFrom(address from, address to, Currency currency, uint256 amount) external returns (bool);
}
src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src/libraries/Hooks.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {Encoded} from "./math/Encoded.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {ParametersHelper} from "./math/ParametersHelper.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/**
* @title Hooks library
* @notice It provides some general helper functions that are used by the poolManager when verifying hook permissions, interacting with hooks, etc.
*/
library Hooks {
using Encoded for bytes32;
using ParametersHelper for bytes32;
using LPFeeLibrary for uint24;
using ParseBytes for bytes;
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice Hook permissions contain conflict
/// 1. enabled beforeSwapReturnsDelta, but lacking beforeSwap call
/// 2. enabled afterSwapReturnsDelta, but lacking afterSwap call
/// 3. enabled addLiquidityReturnsDelta/mintReturnsDelta, but lacking addLiquidity/mint call
/// 4. enabled removeLiquidityReturnsDelta/burnReturnsDelta, but lacking removeLiquidityburn call
error HookPermissionsValidationError();
/// @notice Hook config validation failed
/// 1. either registration bitmap mismatch
/// 2. or fee related config misconfigured
error HookConfigValidationError();
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Hook delta exceeds swap amount
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in pool initialization to ensure
/// the hook contract's hooks registration bitmap match the configration in the pool key
function validateHookConfig(PoolKey memory poolKey) internal view {
uint16 bitmapInParameters = poolKey.parameters.getHooksRegistrationBitmap();
if (address(poolKey.hooks) == address(0)) {
/// @notice If the hooks address is 0, then the bitmap must be 0,
/// in the same time, the dynamic fee should be disabled as well
if (bitmapInParameters == 0 && !poolKey.fee.isDynamicLPFee()) {
return;
}
revert HookConfigValidationError();
}
if (poolKey.hooks.getHooksRegistrationBitmap() != bitmapInParameters) {
revert HookConfigValidationError();
}
}
/// @return true if parameter has offset enabled
function hasOffsetEnabled(bytes32 parameters, uint8 offset) internal pure returns (bool) {
return parameters.decodeBool(offset);
}
/// @notice checks if hook should be called -- based on 2 factors:
/// 1. whether pool.parameters has the callback offset registered
/// 2. whether msg.sender is the hook itself
function shouldCall(bytes32 parameters, uint8 offset, IHooks hook) internal view returns (bool) {
return hasOffsetEnabled(parameters, offset) && address(hook) != msg.sender;
}
/// @notice performs a hook call using the given calldata on the given hook that doesnt return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
revert InvalidHookResponse();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return delta The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn)
internal
returns (int256 delta)
{
bytes memory result = callHook(self, data);
// If this hook wasnt meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) revert InvalidHookResponse();
return result.parseReturnDelta();
}
}
src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Library for handling lp fee setting from `PoolKey.fee`
/// It can be either static or dynamic, and upper 4 bits are used to store the flag:
/// 1. if the flag is set, then the fee is dynamic, it can be set and updated by hook
/// 2. otherwise if the flag is not set, then the fee is static, and the lower 20 bits are used to store the fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
/// @notice Thrown when the static/dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant OVERRIDE_MASK = 0xBFFFFF;
/// @notice a dynamic fee pool must have exactly same value for fee field
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice the fee is represented in hundredths of a bip
/// max fee varies between different pool types i.e. it's 100% for cl pool and 10% for bin pool
uint24 public constant ONE_HUNDRED_PERCENT_FEE = 1_000_000;
uint24 public constant TEN_PERCENT_FEE = 100_000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicLPFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
/// @param maxFee The maximum fee allowed for the pool
function validate(uint24 self, uint24 maxFee) internal pure {
if (self > maxFee) revert LPFeeTooLarge(self);
}
/// @notice gets the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the original value
function getInitialLPFee(uint24 self) internal pure returns (uint24 initialFee) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicLPFee()) return 0;
initialFee = self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @param maxFee The maximum fee allowed for the pool
/// @return fee The fee without the override flag set (if valid)
function removeOverrideAndValidate(uint24 self, uint24 maxFee) internal pure returns (uint24) {
uint24 fee = self.removeOverrideFlag();
fee.validate(maxFee);
return fee;
}
}
src/libraries/ParseBytes.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
src/libraries/ProtocolFeeLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import "./math/UnsafeMath.sol";
library ProtocolFeeLibrary {
/// @dev Increasing these values could lead to overflow in Pool.swap
/// @notice Max protocol fee is 0.4% (4000 pips)
uint16 public constant MAX_PROTOCOL_FEE = 4000;
/// @notice Thresholds used for optimized bounds checks on protocol fees
uint24 internal constant FEE_0_THRESHOLD = 4001;
uint24 internal constant FEE_1_THRESHOLD = 4001 << 12;
/// @notice the protocol fee is represented in hundredths of a bip
uint256 internal constant PIPS_DENOMINATOR = 1_000_000;
/// @notice Get the fee taken when swap token0 for token1
/// @param self The composite protocol fee to get the single direction fee from
/// @return The fee taken when swapping token0 for token1
function getZeroForOneFee(uint24 self) internal pure returns (uint16) {
return uint16(self & 0xfff);
}
/// @notice Get the fee taken when swap token1 for token0
/// @param self The composite protocol fee to get the single direction fee from
/// @return The fee taken when swapping token1 for token0
function getOneForZeroFee(uint24 self) internal pure returns (uint16) {
return uint16(self >> 12);
}
/// @notice Validate that the protocol fee is within bounds
/// @param self The composite protocol fee to validate
/// @return valid True if the fee is within bounds
function validate(uint24 self) internal pure returns (bool valid) {
// Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE
assembly ("memory-safe") {
let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD)
let isOneForZeroFeeOk := lt(and(self, 0xfff000), FEE_1_THRESHOLD)
valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk)
}
}
/// @notice The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining
// Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 (rounded up)
/// Also note the swap fee is capped at 1_000_000 (100%) for cl pool and 100_000 (10%) for bin pool
/// @param self The single direction protocol fee to calculate the swap fee from
/// @param lpFee The LP fee to calculate the swap fee from
/// @return swapFee The composite swap fee
function calculateSwapFee(uint16 self, uint24 lpFee) internal pure returns (uint24 swapFee) {
// protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)
assembly ("memory-safe") {
self := and(self, 0xfff)
lpFee := and(lpFee, 0xffffff)
let numerator := mul(self, lpFee)
swapFee := sub(add(self, lpFee), div(numerator, PIPS_DENOMINATOR))
}
}
}
src/libraries/SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
error SafeCastOverflow();
function _revertOverflow() private pure {
assembly ("memory-safe") {
// Store the function selector of `SafeCastOverflow()`.
mstore(0x00, 0x93dafdf1)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) _revertOverflow();
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) _revertOverflow();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) _revertOverflow();
}
/// @notice Cast a int256 to a uint256, revert on overflow
/// @param x The int256 to be casted
/// @return y The casted integer, now type uint256
function toUint256(int256 x) internal pure returns (uint256 y) {
if (x < 0) _revertOverflow();
y = uint256(x);
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) _revertOverflow();
return int128(int256(x));
}
}
src/libraries/VaultAppDeltaSettlement.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {BalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IVault} from "../interfaces/IVault.sol";
/// @notice Library for handling AppDeltaSettlement for the apps (eg. CL, Bin etc..)
library VaultAppDeltaSettlement {
/// @notice helper method to call `vault.accountAppBalanceDelta`
function accountAppDeltaWithHookDelta(IVault vault, PoolKey memory key, BalanceDelta delta, BalanceDelta hookDelta)
internal
{
if (hookDelta == BalanceDeltaLibrary.ZERO_DELTA) {
/// @dev default case when no hook return delta is set
vault.accountAppBalanceDelta(key.currency0, key.currency1, delta, msg.sender);
} else {
vault.accountAppBalanceDelta(key.currency0, key.currency1, delta, msg.sender, hookDelta, address(key.hooks));
}
}
}
src/libraries/math/Encoded.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/**
* @notice Helper contract used for decoding bytes32
*/
library Encoded {
uint256 internal constant MASK_UINT1 = 0x1;
uint256 internal constant MASK_UINT16 = 0xffff;
uint256 internal constant MASK_UINT24 = 0xffffff;
uint256 internal constant MASK_UINT64 = 0xffffffffffffffff;
/**
* @notice Internal function to set a value in an encoded bytes32 using a mask and offset
* @dev This function can overflow
* @param encoded The previous encoded value
* @param value The value to encode
* @param mask The mask
* @param offset The offset
* @return newEncoded The new encoded value
*/
function set(bytes32 encoded, uint256 value, uint256 mask, uint256 offset)
internal
pure
returns (bytes32 newEncoded)
{
assembly ("memory-safe") {
newEncoded := and(encoded, not(shl(offset, mask)))
newEncoded := or(newEncoded, shl(offset, and(value, mask)))
}
}
/**
* @notice Internal function to set a bool in an encoded bytes32 using an offset
* @dev This function can overflow
* @param encoded The previous encoded value
* @param boolean The bool to encode
* @param offset The offset
* @return newEncoded The new encoded value
*/
function setBool(bytes32 encoded, bool boolean, uint256 offset) internal pure returns (bytes32 newEncoded) {
return set(encoded, boolean ? 1 : 0, MASK_UINT1, offset);
}
/**
* @notice Internal function to decode a bytes32 sample using a mask and offset
* @dev This function can overflow
* @param encoded The encoded value
* @param mask The mask
* @param offset The offset
* @return value The decoded value
*/
function decode(bytes32 encoded, uint256 mask, uint256 offset) internal pure returns (uint256 value) {
assembly ("memory-safe") {
value := and(shr(offset, encoded), mask)
}
}
/**
* @notice Internal function to decode a bytes32 sample into a bool using an offset
* @dev This function can overflow
* @param encoded The encoded value
* @param offset The offset
* @return boolean The decoded value as a bool
*/
function decodeBool(bytes32 encoded, uint256 offset) internal pure returns (bool boolean) {
assembly ("memory-safe") {
boolean := and(shr(offset, encoded), MASK_UINT1)
}
}
/**
* @notice Internal function to decode a bytes32 sample into a uint16 using an offset
* @dev This function can overflow
* @param encoded The encoded value
* @param offset The offset
* @return value The decoded value
*/
function decodeUint16(bytes32 encoded, uint256 offset) internal pure returns (uint16 value) {
assembly ("memory-safe") {
value := and(shr(offset, encoded), MASK_UINT16)
}
}
/**
* @notice Internal function to decode a bytes32 sample into a uint24 using an offset
* @dev This function can overflow
* @param encoded The encoded value
* @param offset The offset
* @return value The decoded value
*/
function decodeUint24(bytes32 encoded, uint256 offset) internal pure returns (uint24 value) {
assembly ("memory-safe") {
value := and(shr(offset, encoded), MASK_UINT24)
}
}
/**
* @notice Internal function to decode a bytes32 sample into a uint64 using an offset
* @dev This function can overflow
* @param encoded The encoded value
* @param offset The offset
* @return value The decoded value
*/
function decodeUint64(bytes32 encoded, uint256 offset) internal pure returns (uint64 value) {
assembly ("memory-safe") {
value := and(shr(offset, encoded), MASK_UINT64)
}
}
}
src/libraries/math/ParametersHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Encoded} from "./Encoded.sol";
library ParametersHelper {
using Encoded for bytes32;
error UnusedBitsNonZero();
uint256 internal constant OFFSET_HOOK = 0;
/**
* @dev Get the hooks registration bitmap from the encoded parameters
* @param params The encoded parameters, as follows:
* [0 - 16[: bitmap for hooks registration (16 bits)
* [16 - 256[: other parameters
* @return bitmap The bitmap
*/
function getHooksRegistrationBitmap(bytes32 params) internal pure returns (uint16 bitmap) {
bitmap = params.decodeUint16(OFFSET_HOOK);
}
function checkUnusedBitsAllZero(bytes32 params, uint256 mostSignificantUnUsedBitOffset) internal pure {
if ((uint256(params) >> (mostSignificantUnUsedBitOffset)) != 0) {
revert UnusedBitsNonZero();
}
}
}
src/libraries/math/UnsafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}
src/pool-bin/interfaces/IBinHooks.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../../types/PoolKey.sol";
import {BalanceDelta} from "../../types/BalanceDelta.sol";
import {IBinPoolManager} from "./IBinPoolManager.sol";
import {IHooks} from "../../interfaces/IHooks.sol";
import {BeforeSwapDelta} from "../../types/BeforeSwapDelta.sol";
uint8 constant HOOKS_BEFORE_INITIALIZE_OFFSET = 0;
uint8 constant HOOKS_AFTER_INITIALIZE_OFFSET = 1;
uint8 constant HOOKS_BEFORE_MINT_OFFSET = 2;
uint8 constant HOOKS_AFTER_MINT_OFFSET = 3;
uint8 constant HOOKS_BEFORE_BURN_OFFSET = 4;
uint8 constant HOOKS_AFTER_BURN_OFFSET = 5;
uint8 constant HOOKS_BEFORE_SWAP_OFFSET = 6;
uint8 constant HOOKS_AFTER_SWAP_OFFSET = 7;
uint8 constant HOOKS_BEFORE_DONATE_OFFSET = 8;
uint8 constant HOOKS_AFTER_DONATE_OFFSET = 9;
uint8 constant HOOKS_BEFORE_SWAP_RETURNS_DELTA_OFFSET = 10;
uint8 constant HOOKS_AFTER_SWAP_RETURNS_DELTA_OFFSET = 11;
uint8 constant HOOKS_AFTER_MINT_RETURNS_DELTA_OFFSET = 12;
uint8 constant HOOKS_AFTER_BURN_RETURNS_DELTA_OFFSET = 13;
/// @notice The PoolManager contract decides whether to invoke specific hook by inspecting the first 16
/// bits of bytes32 PoolKey.parameters. For example a 1 bit in the first bit will cause the beforeInitialize
/// hook to be invoked.
/// @dev Should only be callable by the PoolManager.
interface IBinHooks is IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param activeId The binId of the pool, when the value is 2 ** 23, token price is 1:1
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint24 activeId) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param activeId The binId of the pool, when the value is 2 ** 23, token price is 1:1
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint24 activeId) external returns (bytes4);
/// @notice The hook called before adding liquidity
/// @param sender The initial msg.sender for the modify position call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return uint24 Optionally override the lp fee, only used if four conditions are met:
/// 1) Liquidity added to active bin in different ratio from current bin (causing an internal swap)
/// 2) the Pool has a dynamic fee,
/// 3) the value's override flag is set to 1 i.e. vaule & OVERRIDE_FEE_FLAG = 0x400000 != 0
/// 4) the value is less than or equal to the maximum fee (100_000) - 10%
function beforeMint(
address sender,
PoolKey calldata key,
IBinPoolManager.MintParams calldata params,
bytes calldata hookData
) external returns (bytes4, uint24);
/// @notice The hook called after adding liquidity
/// @param sender The initial msg.sender for the modify position call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The amount owed to the locker (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1.
function afterMint(
address sender,
PoolKey calldata key,
IBinPoolManager.MintParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before removing liquidity
/// @param sender The initial msg.sender for the modify position call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeBurn(
address sender,
PoolKey calldata key,
IBinPoolManager.BurnParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after removing liquidity
/// @param sender The initial msg.sender for the modify position call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The amount owed to the locker (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the liquidty provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1.
function afterBurn(
address sender,
PoolKey calldata key,
IBinPoolManager.BurnParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param swapForY If true, indicate swap X for Y or if false, swap Y for X
/// @param amountSpecified Amount of tokenX or tokenY, negative imply exactInput, positive imply exactOutput
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies.
/// @return uint24 Optionally override the lp fee, only used if three conditions are met:
/// 1) the Pool has a dynamic fee,
/// 2) the value's override flag is set to 1 i.e. vaule & OVERRIDE_FEE_FLAG = 0x400000 != 0
/// 3) the value is less than or equal to the maximum fee (100_000) - 10%
function beforeSwap(
address sender,
PoolKey calldata key,
bool swapForY,
int128 amountSpecified,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param swapForY If true, indicate swap X for Y or if false, swap Y for X
/// @param amountSpecified Amount of tokenX or tokenY, negative imply exactInput, positive imply exactOutput
/// @param delta The amount owed to the locker or owed to the pool
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency
function afterSwap(
address sender,
PoolKey calldata key,
bool swapForY,
int128 amountSpecified,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
src/pool-bin/interfaces/IBinPoolManager.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../../types/Currency.sol";
import {IProtocolFees} from "../../interfaces/IProtocolFees.sol";
import {PoolId} from "../../types/PoolId.sol";
import {PoolKey} from "../../types/PoolKey.sol";
import {BalanceDelta} from "../../types/BalanceDelta.sol";
import {IPoolManager} from "../../interfaces/IPoolManager.sol";
import {IExtsload} from "../../interfaces/IExtsload.sol";
import {IHooks} from "../../interfaces/IHooks.sol";
import {BinPosition, BinPool} from "../libraries/BinPool.sol";
interface IBinPoolManager is IProtocolFees, IPoolManager, IExtsload {
/// @notice PoolManagerMismatch is thrown when pool manager specified in the pool key does not match current contract
error PoolManagerMismatch();
/// @notice Pool binStep cannot be lesser than 1. Otherwise there will be no price jump between bin
error BinStepTooSmall(uint16 binStep);
/// @notice Pool binstep cannot be greater than the limit set at maxBinStep
error BinStepTooLarge(uint16 binStep);
/// @notice Error thrown when owner set max bin step too small
error MaxBinStepTooSmall(uint16 maxBinStep);
/// @notice Error thrown when bin has insufficient shares to accept donation
error InsufficientBinShareForDonate(uint256 shares);
/// @notice Error thrown when amount specified is 0 in swap
error AmountSpecifiedIsZero();
/// @notice Returns the constant representing the max bin step
/// @return maxBinStep a value of 100 would represent a 1% price jump between bin (limit can be raised by owner)
function maxBinStep() external view returns (uint16);
/// @notice Returns the constant representing the min bin step
/// @dev 1 would represent a 0.01% price jump between bin
function MIN_BIN_STEP() external view returns (uint16);
/// @notice min share in bin before donate is allowed in current bin
function minBinShareForDonate() external view returns (uint256);
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param fee The lp fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param parameters Includes hooks callback bitmap and binStep
/// @param activeId The id of active bin on initialization
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
IHooks hooks,
uint24 fee,
bytes32 parameters,
uint24 activeId
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param activeId The activeId of the pool after the swap
/// @param fee The fee collected upon every swap in the pool (including protocol fee and LP fee), denominated in hundredths of a bip
/// @param protocolFee Single direction protocol fee from the swap, also denominated in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint24 activeId,
uint24 fee,
uint16 protocolFee
);
/// @notice Emitted when liquidity is added
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param ids List of binId with liquidity added
/// @param salt The salt to distinguish different mint from the same owner
/// @param amounts List of amount added to each bin
/// @param compositionFeeAmount fee occurred
/// @param feeAmountToProtocol Protocol fee from the swap: token0 and token1 amount
event Mint(
PoolId indexed id,
address indexed sender,
uint256[] ids,
bytes32 salt,
bytes32[] amounts,
bytes32 compositionFeeAmount,
bytes32 feeAmountToProtocol
);
/// @notice Emitted when liquidity is removed
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param ids List of binId with liquidity removed
/// @param salt The salt to specify the position to burn if multiple positions are available
/// @param amounts List of amount removed from each bin
event Burn(PoolId indexed id, address indexed sender, uint256[] ids, bytes32 salt, bytes32[] amounts);
/// @notice Emitted when donate happen
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param binId The donated bin id
event Donate(PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint24 binId);
/// @notice Emitted when min share for donate is updated
event SetMinBinSharesForDonate(uint256 minLiquidity);
/// @notice Emitted when bin step is updated
event SetMaxBinStep(uint16 maxBinStep);
struct MintParams {
bytes32[] liquidityConfigs;
/// @dev amountIn intended
bytes32 amountIn;
/// the salt to distinguish different mint from the same owner
bytes32 salt;
}
struct BurnParams {
/// @notice id of the bin from which to withdraw
uint256[] ids;
/// @notice amount of share to burn for each bin
uint256[] amountsToBurn;
/// the salt to specify the position to burn if multiple positions are available
bytes32 salt;
}
/// @notice Get the current value in slot0 of the given pool
function getSlot0(PoolId id) external view returns (uint24 activeId, uint24 protocolFee, uint24 lpFee);
/// @notice Returns the reserves of a bin
/// @param id The id of the bin
/// @return binReserveX The reserve of token X in the bin
/// @return binReserveY The reserve of token Y in the bin
/// @return binLiquidity The total liquidity in the bin
/// @return totalShares The total shares minted in the bin
function getBin(PoolId id, uint24 binId)
external
view
returns (uint128 binReserveX, uint128 binReserveY, uint256 binLiquidity, uint256 totalShares);
/// @notice Returns the positon of owner at a binId
/// @param id The id of PoolKey
/// @param owner Address of the owner
/// @param binId The id of the bin
/// @param salt The salt to distinguish different positions for the same owner
function getPosition(PoolId id, address owner, uint24 binId, bytes32 salt)
external
view
returns (BinPosition.Info memory position);
/// @notice Returns the next non-empty bin
/// @dev The next non-empty bin is the bin with a higher (if swapForY is true) or lower (if swapForY is false)
/// id that has a non-zero reserve of token X or Y.
/// @param swapForY Whether the swap is for token Y (true) or token X (false)
/// @param id The id of the bin
/// @return nextId The id of the next non-empty bin
function getNextNonEmptyBin(PoolId id, bool swapForY, uint24 binId) external view returns (uint24 nextId);
/// @notice Initialize a new pool
function initialize(PoolKey memory key, uint24 activeId) external;
/// @notice Add liquidity to a pool
/// @dev For the first liquidity added to a bin, the share minted would be slightly lessser (1e3 lesser) to prevent
/// share inflation attack.
/// @return delta BalanceDelta, will be negative indicating how much total amt0 and amt1 liquidity added
/// @return mintArray Liquidity added in which ids, how much amt0, amt1 and how much liquidity added
function mint(PoolKey memory key, IBinPoolManager.MintParams calldata params, bytes calldata hookData)
external
returns (BalanceDelta delta, BinPool.MintArrays memory mintArray);
/// @notice Remove liquidity from a pool
/// @return delta BalanceDelta, will be positive indicating how much total amt0 and amt1 liquidity removed
function burn(PoolKey memory key, IBinPoolManager.BurnParams memory params, bytes calldata hookData)
external
returns (BalanceDelta delta);
/// @notice Peform a swap to a pool
/// @param key The pool key
/// @param swapForY If true, swap token X for Y, if false, swap token Y for X
/// @param amountSpecified If negative, imply exactInput, if positive, imply exactOutput.
function swap(PoolKey memory key, bool swapForY, int128 amountSpecified, bytes calldata hookData)
external
returns (BalanceDelta delta);
/// @notice Donate the given currency amounts to the active bin liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @param key The pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData Any data to pass to the callback
/// @return delta Negative amt means the caller owes the vault, while positive amt means the vault owes the caller
/// @return binId The donated bin id, which is the current active bin id. if no-op happen, binId will be 0
function donate(PoolKey memory key, uint128 amount0, uint128 amount1, bytes calldata hookData)
external
returns (BalanceDelta delta, uint24 binId);
/// @notice Set max bin step for BinPool
/// @dev To be realistic, its highly unlikely a pool type with > 100 bin step is required. (>1% price jump per bin)
function setMaxBinStep(uint16 maxBinStep) external;
/// @notice Set min shares in bin before donate is allowed in current bin
/// @dev Bin share is 1:1 liquidity when liquidity is first added. And liquidity: price * x + y << 128, where price is a 128.128 number. A
/// min share amount required in the bin for donate prevents share inflation attack.
/// Min share should always be greater than 0, there should be a validation on BinPoolManagerOwner to prevent setting min share to 0
function setMinBinSharesForDonate(uint256 minShare) external;
}
src/pool-bin/libraries/BinHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {PackedUint128Math} from "./math/PackedUint128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
import {BinPoolParametersHelper} from "./BinPoolParametersHelper.sol";
import {FeeHelper} from "./FeeHelper.sol";
import {PriceHelper} from "./PriceHelper.sol";
import {ProtocolFeeLibrary} from "../../libraries/ProtocolFeeLibrary.sol";
/// @notice This library contains functions to help interaction with bins.
library BinHelper {
using PackedUint128Math for bytes32;
using PackedUint128Math for uint128;
using Uint256x256Math for uint256;
using PriceHelper for uint24;
using SafeCast for uint256;
using BinPoolParametersHelper for bytes32;
using FeeHelper for uint128;
using ProtocolFeeLibrary for uint24;
using ProtocolFeeLibrary for uint16;
error BinHelper__CompositionFactorFlawed(uint24 id);
error BinHelper__LiquidityOverflow();
/// @dev Returns the amount of tokens that will be received when burning the given amount of liquidity
/// @param binReserves The reserves of the bin
/// @param amountToBurn The amount of liquidity to burn
/// @param totalSupply The total supply of the liquidity book
/// @return amountsOut The encoded amount of tokens that will be received
function getAmountOutOfBin(bytes32 binReserves, uint256 amountToBurn, uint256 totalSupply)
internal
pure
returns (bytes32 amountsOut)
{
(uint128 binReserveX, uint128 binReserveY) = binReserves.decode();
uint128 amountXOutFromBin;
uint128 amountYOutFromBin;
if (binReserveX > 0) {
amountXOutFromBin = (amountToBurn.mulDivRoundDown(binReserveX, totalSupply)).safe128();
}
if (binReserveY > 0) {
amountYOutFromBin = (amountToBurn.mulDivRoundDown(binReserveY, totalSupply)).safe128();
}
amountsOut = amountXOutFromBin.encode(amountYOutFromBin);
}
/// @dev Returns the share and the effective amounts in when adding liquidity
/// @param binReserves The reserves of the bin
/// @param amountsIn The amounts of tokens to add
/// @param price The price of the bin
/// @param totalSupply The total supply of the liquidity book
/// @return shares The share of the liquidity book that the user will receive
/// @return effectiveAmountsIn The encoded effective amounts of tokens that the user will add.
/// This is the amount of tokens that the user will actually add to the liquidity book,
/// and will always be less than or equal to the amountsIn.
function getSharesAndEffectiveAmountsIn(bytes32 binReserves, bytes32 amountsIn, uint256 price, uint256 totalSupply)
internal
pure
returns (uint256 shares, bytes32 effectiveAmountsIn)
{
(uint256 x, uint256 y) = amountsIn.decode();
uint256 userLiquidity = getLiquidity(x, y, price);
if (totalSupply == 0 || userLiquidity == 0) return (userLiquidity, amountsIn);
// current bin liquidity
uint256 binLiquidity = getLiquidity(binReserves, price);
if (binLiquidity == 0) return (userLiquidity, amountsIn);
shares = userLiquidity.mulDivRoundDown(totalSupply, binLiquidity);
uint256 effectiveLiquidity = shares.mulDivRoundUp(binLiquidity, totalSupply);
if (userLiquidity > effectiveLiquidity) {
uint256 deltaLiquidity = userLiquidity - effectiveLiquidity;
// The other way might be more efficient, but as y is the quote asset, it is more valuable
if (deltaLiquidity >= Constants.SCALE) {
uint256 deltaY = deltaLiquidity >> Constants.SCALE_OFFSET;
deltaY = deltaY > y ? y : deltaY;
unchecked {
y -= deltaY;
}
deltaLiquidity -= deltaY << Constants.SCALE_OFFSET;
}
if (deltaLiquidity >= price) {
uint256 deltaX = deltaLiquidity / price;
deltaX = deltaX > x ? x : deltaX;
unchecked {
x -= deltaX;
}
}
amountsIn = uint128(x).encode(uint128(y));
}
return (shares, amountsIn);
}
/// @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
/// @param amounts The amounts of tokens
/// @param price The price of the bin
/// @return liquidity The amount of liquidity
function getLiquidity(bytes32 amounts, uint256 price) internal pure returns (uint256 liquidity) {
(uint256 x, uint256 y) = amounts.decode();
return getLiquidity(x, y, price);
}
/// @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
/// @param x The amount of the token X
/// @param y The amount of the token Y
/// @param price The price of the bin
/// @return liquidity The amount of liquidity
function getLiquidity(uint256 x, uint256 y, uint256 price) internal pure returns (uint256 liquidity) {
if (x > 0) {
// equivalent to
// liquidity = price * x;
// if (liquidity / x != price) revert BinHelper__LiquidityOverflow();
assembly ("memory-safe") {
liquidity := mul(price, x)
if iszero(eq(div(liquidity, x), price)) {
mstore(0x00, 0x63f1e01f) // selector BinHelper__LiquidityOverflow
revert(0x1c, 0x04)
}
}
}
if (y > 0) {
// equivalent to
// y <<= Constants.SCALE_OFFSET;
// liquidity += y;
// if (liquidity < y) revert BinHelper__LiquidityOverflow();
uint8 offset = Constants.SCALE_OFFSET;
assembly ("memory-safe") {
y := shl(offset, y)
liquidity := add(liquidity, y)
// Check for overflow: if liquidity < y, revert with error
if lt(liquidity, y) {
mstore(0x00, 0x63f1e01f) // selector BinHelper__LiquidityOverflow
revert(0x1c, 0x04)
}
}
}
return liquidity;
}
/// @dev Verify that the amounts are correct and that the composition factor is not flawed
/// @param amounts The amounts of tokens
/// @param activeId The id of the active bin
/// @param id The id of the bin
function verifyAmounts(bytes32 amounts, uint24 activeId, uint24 id) internal pure {
if ((id < activeId && (amounts << 128) > 0) || (id > activeId && uint256(amounts) > type(uint128).max)) {
revert BinHelper__CompositionFactorFlawed(id);
}
}
/// @dev Returns the composition fees when adding liquidity to the active bin with a different
/// composition factor than the bin's one, as it does an implicit swap
/// @param binReserves The reserves of the bin
/// @param protocolFee 100 = 0.01%, 1000 = 0.1%
/// @param lpFee 100 = 0.01%, 1000 = 0.1%
/// @param amountsIn The amounts of tokens to add
/// @param totalSupply The total supply of the liquidity book
/// @param shares The share of the liquidity book that the user will receive
/// @return feesAmount The encoded fees that will be charged (including protocol and LP fee)
/// @return feeAmountToProtocol The encoded protocol fee that will be charged
function getCompositionFeesAmount(
bytes32 binReserves,
uint24 protocolFee, // fee: 100 = 0.01%
uint24 lpFee,
bytes32 amountsIn,
uint256 totalSupply,
uint256 shares
) internal pure returns (bytes32 feesAmount, bytes32 feeAmountToProtocol) {
if (shares == 0) return (0, 0);
(uint128 amountX, uint128 amountY) = amountsIn.decode();
(uint128 receivedAmountX, uint128 receivedAmountY) =
getAmountOutOfBin(binReserves.add(amountsIn), shares, totalSupply + shares).decode();
// if received more X than given X, then swap some Y for X
if (receivedAmountX > amountX) {
protocolFee = protocolFee.getOneForZeroFee();
uint24 swapFee = uint16(protocolFee).calculateSwapFee(lpFee);
uint128 amtSwapped = amountY - receivedAmountY;
feesAmount = amtSwapped.getCompositionFee(swapFee).encodeSecond();
feeAmountToProtocol = amtSwapped.getCompositionFee(protocolFee).encodeSecond();
} else if (receivedAmountY > amountY) {
protocolFee = protocolFee.getZeroForOneFee();
uint24 swapFee = uint16(protocolFee).calculateSwapFee(lpFee);
uint128 amtSwapped = amountX - receivedAmountX;
feesAmount = amtSwapped.getCompositionFee(swapFee).encodeFirst();
feeAmountToProtocol = amtSwapped.getCompositionFee(protocolFee).encodeFirst();
}
}
/// @dev Returns whether the bin is empty (true) or not (false)
/// @param binReserves The reserves of the bin
/// @param isX Whether the reserve to check is the X reserve (true) or the Y reserve (false)
/// @return Whether the bin is empty (true) or not (false)
function isEmpty(bytes32 binReserves, bool isX) internal pure returns (bool) {
return isX ? binReserves.decodeX() == 0 : binReserves.decodeY() == 0;
}
/// @dev Returns the amounts of tokens that will be added and removed from the bin during a exactOut swap
/// along with the fees that will be charged
/// @param binReserves The reserves of the bin
/// @param fee 100 = 0.01%, 1_000 = 0.1%
/// @param binStep The step of the bin
/// @param swapForY Whether the swap is for Y (true) or for X (false)
/// @param activeId The id of the active bin
/// @param amountsOutLeft The amounts of tokens out left
/// @return amountsInWithFees The encoded amounts of tokens that will be added to the bin, including fees
/// @return amountsOutOfBin The encoded amounts of tokens that will be removed from the bin
/// @return totalFees The encoded fees that will be charged
function getAmountsIn(
bytes32 binReserves,
uint24 fee,
uint16 binStep,
bool swapForY,
uint24 activeId,
bytes32 amountsOutLeft
) internal pure returns (bytes32 amountsInWithFees, bytes32 amountsOutOfBin, bytes32 totalFees) {
uint256 price = activeId.getPriceFromId(binStep);
uint128 binReserveOut = binReserves.decode(!swapForY);
uint128 amountOutLeft128 = amountsOutLeft.decode(!swapForY);
// amountOutOfBin = if bin reserve has > amountOut, then amountOutOfBin = amountOut
uint128 amountOutOfBin = binReserveOut > amountOutLeft128 ? amountOutLeft128 : binReserveOut;
uint128 amountInWithoutFee = swapForY
? uint256(amountOutOfBin).shiftDivRoundUp(Constants.SCALE_OFFSET, price).safe128()
: uint256(amountOutOfBin).mulShiftRoundUp(price, Constants.SCALE_OFFSET).safe128();
uint128 feeAmount = amountInWithoutFee.getFeeAmount(fee);
uint128 amountIn = amountInWithoutFee + feeAmount;
(amountsInWithFees, amountsOutOfBin, totalFees) = swapForY
? (amountIn.encodeFirst(), amountOutOfBin.encodeSecond(), feeAmount.encodeFirst())
: (amountIn.encodeSecond(), amountOutOfBin.encodeFirst(), feeAmount.encodeSecond());
}
/// @dev Returns the amounts of tokens that will be added and removed from the bin during a exactIn swap
/// along with the fees that will be charged
/// @param binReserves The reserves of the bin
/// @param fee 100 = 0.01%, 1_000 = 0.1%
/// @param binStep The step of the bin
/// @param swapForY Whether the swap is for Y (true) or for X (false)
/// @param activeId The id of the active bin
/// @param amountsInLeft The amounts of tokens left to swap
/// @return amountsInWithFees The encoded amounts of tokens that will be added to the bin, including fees
/// @return amountsOutOfBin The encoded amounts of tokens that will be removed from the bin
/// @return totalFees The encoded fees that will be charged
function getAmountsOut(
bytes32 binReserves,
uint24 fee,
uint16 binStep,
bool swapForY, // swap `swapForY` and `activeId` to avoid stack too deep
uint24 activeId,
bytes32 amountsInLeft
) internal pure returns (bytes32 amountsInWithFees, bytes32 amountsOutOfBin, bytes32 totalFees) {
uint256 price = activeId.getPriceFromId(binStep);
uint128 binReserveOut = binReserves.decode(!swapForY);
uint128 maxAmountIn = swapForY
? uint256(binReserveOut).shiftDivRoundUp(Constants.SCALE_OFFSET, price).safe128()
: uint256(binReserveOut).mulShiftRoundUp(price, Constants.SCALE_OFFSET).safe128();
uint128 maxFee = maxAmountIn.getFeeAmount(fee);
maxAmountIn += maxFee;
uint128 amountIn128 = amountsInLeft.decode(swapForY);
uint128 fee128;
uint128 amountOut128;
if (amountIn128 >= maxAmountIn) {
fee128 = maxFee;
amountIn128 = maxAmountIn;
amountOut128 = binReserveOut;
} else {
fee128 = amountIn128.getFeeAmountFrom(fee);
uint256 amountIn = amountIn128 - fee128;
amountOut128 = swapForY
? uint256(amountIn).mulShiftRoundDown(price, Constants.SCALE_OFFSET).safe128()
: uint256(amountIn).shiftDivRoundDown(Constants.SCALE_OFFSET, price).safe128();
if (amountOut128 > binReserveOut) amountOut128 = binReserveOut;
}
(amountsInWithFees, amountsOutOfBin, totalFees) = swapForY
? (amountIn128.encodeFirst(), amountOut128.encodeSecond(), fee128.encodeFirst())
: (amountIn128.encodeSecond(), amountOut128.encodeFirst(), fee128.encodeSecond());
}
}
src/pool-bin/libraries/BinHooks.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import "../interfaces/IBinHooks.sol";
import {PoolKey} from "../../types/PoolKey.sol";
import {IBinPoolManager} from "../interfaces/IBinPoolManager.sol";
import {Hooks} from "../../libraries/Hooks.sol";
import {BalanceDelta, BalanceDeltaLibrary, toBalanceDelta} from "../../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../../types/BeforeSwapDelta.sol";
import {LPFeeLibrary} from "../../libraries/LPFeeLibrary.sol";
import {ParseBytes} from "../../libraries/ParseBytes.sol";
import {SafeCast} from "../../libraries/SafeCast.sol";
import {Hooks} from "../../libraries/Hooks.sol";
library BinHooks {
using Hooks for bytes32;
using SafeCast for int256;
using LPFeeLibrary for uint24;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
/// @notice Validate hook permission, eg. if before_swap_return_delta is set, before_swap_delta must be set
function validatePermissionsConflict(PoolKey memory key) internal pure {
if (
key.parameters.hasOffsetEnabled(HOOKS_BEFORE_SWAP_RETURNS_DELTA_OFFSET)
&& !key.parameters.hasOffsetEnabled(HOOKS_BEFORE_SWAP_OFFSET)
) {
revert Hooks.HookPermissionsValidationError();
}
if (
key.parameters.hasOffsetEnabled(HOOKS_AFTER_SWAP_RETURNS_DELTA_OFFSET)
&& !key.parameters.hasOffsetEnabled(HOOKS_AFTER_SWAP_OFFSET)
) {
revert Hooks.HookPermissionsValidationError();
}
if (
key.parameters.hasOffsetEnabled(HOOKS_AFTER_MINT_RETURNS_DELTA_OFFSET)
&& !key.parameters.hasOffsetEnabled(HOOKS_AFTER_MINT_OFFSET)
) {
revert Hooks.HookPermissionsValidationError();
}
if (
key.parameters.hasOffsetEnabled(HOOKS_AFTER_BURN_RETURNS_DELTA_OFFSET)
&& !key.parameters.hasOffsetEnabled(HOOKS_AFTER_BURN_OFFSET)
) {
revert Hooks.HookPermissionsValidationError();
}
}
function beforeInitialize(PoolKey memory key, uint24 activeId) internal {
IBinHooks hooks = IBinHooks(address(key.hooks));
if (key.parameters.shouldCall(HOOKS_BEFORE_INITIALIZE_OFFSET, hooks)) {
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.beforeInitialize, (msg.sender, key, activeId)));
}
}
function afterInitialize(PoolKey memory key, uint24 activeId) internal {
IBinHooks hooks = IBinHooks(address(key.hooks));
if (key.parameters.shouldCall(HOOKS_AFTER_INITIALIZE_OFFSET, hooks)) {
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.afterInitialize, (msg.sender, key, activeId)));
}
}
function beforeMint(PoolKey memory key, IBinPoolManager.MintParams calldata params, bytes calldata hookData)
internal
returns (uint24 lpFeeOverride)
{
IBinHooks hooks = IBinHooks(address(key.hooks));
if (!key.parameters.shouldCall(HOOKS_BEFORE_MINT_OFFSET, hooks)) {
return lpFeeOverride;
}
bytes memory result =
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.beforeMint, (msg.sender, key, params, hookData)));
// A length of 64 bytes is required to return a bytes4, and an LP fee
if (result.length != 64) revert Hooks.InvalidHookResponse();
if (key.fee.isDynamicLPFee()) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, uint24));
assembly {
lpFeeOverride := mload(add(result, 0x40))
}
}
}
function afterMint(
PoolKey memory key,
IBinPoolManager.MintParams memory params,
BalanceDelta delta,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
IBinHooks hooks = IBinHooks(address(key.hooks));
callerDelta = delta;
if (key.parameters.shouldCall(HOOKS_AFTER_MINT_OFFSET, hooks)) {
hookDelta = BalanceDelta.wrap(
Hooks.callHookWithReturnDelta(
hooks,
abi.encodeCall(IBinHooks.afterMint, (msg.sender, key, params, delta, hookData)),
key.parameters.hasOffsetEnabled(HOOKS_AFTER_MINT_RETURNS_DELTA_OFFSET)
)
);
callerDelta = callerDelta - hookDelta;
}
}
function beforeBurn(PoolKey memory key, IBinPoolManager.BurnParams memory params, bytes calldata hookData)
internal
{
IBinHooks hooks = IBinHooks(address(key.hooks));
if (key.parameters.shouldCall(HOOKS_BEFORE_BURN_OFFSET, hooks)) {
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.beforeBurn, (msg.sender, key, params, hookData)));
}
}
function afterBurn(
PoolKey memory key,
IBinPoolManager.BurnParams memory params,
BalanceDelta delta,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
IBinHooks hooks = IBinHooks(address(key.hooks));
callerDelta = delta;
if (key.parameters.shouldCall(HOOKS_AFTER_BURN_OFFSET, hooks)) {
hookDelta = BalanceDelta.wrap(
Hooks.callHookWithReturnDelta(
hooks,
abi.encodeCall(IBinHooks.afterBurn, (msg.sender, key, params, delta, hookData)),
key.parameters.hasOffsetEnabled(HOOKS_AFTER_BURN_RETURNS_DELTA_OFFSET)
)
);
callerDelta = callerDelta - hookDelta;
}
}
function beforeSwap(PoolKey memory key, bool swapForY, int128 amountSpecified, bytes calldata hookData)
internal
returns (int128 amountToSwap, BeforeSwapDelta beforeSwapDelta, uint24 lpFeeOverride)
{
IBinHooks hooks = IBinHooks(address(key.hooks));
amountToSwap = amountSpecified;
/// @notice If the hook is not registered, return the original amount to swap
if (!key.parameters.shouldCall(HOOKS_BEFORE_SWAP_OFFSET, hooks)) {
return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
}
bytes memory result = Hooks.callHook(
hooks, abi.encodeCall(IBinHooks.beforeSwap, (msg.sender, key, swapForY, amountSpecified, hookData))
);
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) revert Hooks.InvalidHookResponse();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicLPFee()) {
lpFeeOverride = result.parseFee();
}
// Update the swap amount according to the hook's return
if (key.parameters.hasOffsetEnabled(HOOKS_BEFORE_SWAP_RETURNS_DELTA_OFFSET)) {
// any return in unspecified is passed to the afterSwap hook for handling
beforeSwapDelta = BeforeSwapDelta.wrap(result.parseReturnDelta());
int128 hookDeltaSpecified = beforeSwapDelta.getSpecifiedDelta();
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) revert Hooks.HookDeltaExceedsSwapAmount();
}
}
}
function afterSwap(
PoolKey memory key,
bool swapForY,
int128 amountSpecified,
BalanceDelta delta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapDelta
) internal returns (BalanceDelta, BalanceDelta) {
IBinHooks hooks = IBinHooks(address(key.hooks));
int128 hookDeltaSpecified = beforeSwapDelta.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapDelta.getUnspecifiedDelta();
if (key.parameters.shouldCall(HOOKS_AFTER_SWAP_OFFSET, hooks)) {
hookDeltaUnspecified += Hooks.callHookWithReturnDelta(
hooks,
abi.encodeCall(IBinHooks.afterSwap, (msg.sender, key, swapForY, amountSpecified, delta, hookData)),
key.parameters.hasOffsetEnabled(HOOKS_AFTER_SWAP_RETURNS_DELTA_OFFSET)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (amountSpecified < 0 == swapForY)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
delta = delta - hookDelta;
}
return (delta, hookDelta);
}
function beforeDonate(PoolKey memory key, uint128 amount0, uint128 amount1, bytes calldata hookData) internal {
IBinHooks hooks = IBinHooks(address(key.hooks));
if (key.parameters.shouldCall(HOOKS_BEFORE_DONATE_OFFSET, hooks)) {
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function afterDonate(PoolKey memory key, uint128 amount0, uint128 amount1, bytes calldata hookData) internal {
IBinHooks hooks = IBinHooks(address(key.hooks));
if (key.parameters.shouldCall(HOOKS_AFTER_DONATE_OFFSET, hooks)) {
Hooks.callHook(hooks, abi.encodeCall(IBinHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
}
src/pool-bin/libraries/BinPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {BalanceDelta, toBalanceDelta} from "../../types/BalanceDelta.sol";
import {BinSlot0} from "../types/BinSlot0.sol";
import {LiquidityConfigurations} from "./math/LiquidityConfigurations.sol";
import {PackedUint128Math} from "./math/PackedUint128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {TreeMath} from "./math/TreeMath.sol";
import {PriceHelper} from "./PriceHelper.sol";
import {BinHelper} from "./BinHelper.sol";
import {BinPosition} from "./BinPosition.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
import {FeeHelper} from "./FeeHelper.sol";
import {ProtocolFeeLibrary} from "../../libraries/ProtocolFeeLibrary.sol";
import {LPFeeLibrary} from "../../libraries/LPFeeLibrary.sol";
/// @notice a library with all actions that can be performed on bin pool
library BinPool {
using BinHelper for bytes32;
using LiquidityConfigurations for bytes32;
using PackedUint128Math for bytes32;
using PackedUint128Math for uint128;
using PriceHelper for uint24;
using Uint256x256Math for uint256;
using BinPosition for mapping(bytes32 => BinPosition.Info);
using BinPosition for BinPosition.Info;
using TreeMath for bytes32;
using SafeCast for uint256;
using SafeCast for uint128;
using FeeHelper for uint128;
using BinPool for State;
using ProtocolFeeLibrary for uint24;
using ProtocolFeeLibrary for uint16;
using LPFeeLibrary for uint24;
error PoolNotInitialized();
error PoolAlreadyInitialized();
error PoolInvalidParameter();
error BinPool__EmptyLiquidityConfigs();
error BinPool__ZeroShares(uint24 id);
error BinPool__InvalidBurnInput();
error BinPool__BurnZeroAmount(uint24 id);
error BinPool__ZeroAmountsOut(uint24 id);
error BinPool__OutOfLiquidity();
error BinPool__NoLiquidityToReceiveFees();
/// @dev if swap exactIn, x for y, unspecifiedToken = token y. if swap x for exact out y, unspecified token is x
error BinPool__InsufficientAmountUnSpecified();
error BinPool__MaxLiquidityPerBinExceeded();
/// @dev The state of a pool
struct State {
BinSlot0 slot0;
/// @notice binId ==> (reserve of token x and y in the bin)
mapping(uint256 binId => bytes32 reserve) reserveOfBin;
/// @notice binId ==> (total share minted)
mapping(uint256 binId => uint256 share) shareOfBin;
/// @notice (user, binId, salt) => shares of user in a binId
mapping(bytes32 positionHash => BinPosition.Info info) positions;
/// @dev todo: cannot nest a struct with mapping, error: recursive type is not allowed for public state variables.
/// TreeMath.TreeUint24 _tree;
/// the 3 attributes below come from TreeMath
bytes32 level0;
mapping(bytes32 => bytes32) level1;
mapping(bytes32 => bytes32) level2;
}
/// @dev when a bin has supply for the first time, 1e3 share will be locked up
/// this is to prevent share inflation attack on BinPool type
uint256 constant MINIMUM_SHARE = 1e3;
function initialize(State storage self, uint24 activeId, uint24 protocolFee, uint24 lpFee) internal {
/// An initialized pool will not have activeId: 0
if (self.slot0.activeId() != 0) revert PoolAlreadyInitialized();
self.slot0 = BinSlot0.wrap(bytes32(0)).setActiveId(activeId).setProtocolFee(protocolFee).setLpFee(lpFee);
}
function setProtocolFee(State storage self, uint24 protocolFee) internal {
self.checkPoolInitialized();
self.slot0 = self.slot0.setProtocolFee(protocolFee);
}
/// @notice Only dynamic fee pools may update the swap fee.
function setLPFee(State storage self, uint24 lpFee) internal {
self.checkPoolInitialized();
self.slot0 = self.slot0.setLpFee(lpFee);
}
struct SwapParams {
bool swapForY;
uint16 binStep;
uint24 lpFeeOverride;
int128 amountSpecified; // negative for exactInput, positive for exactOutput
}
struct SwapState {
// current activeId
uint24 activeId;
// the protocol fee for the swap (single direction)
uint16 protocolFee;
// the swapFee (the total percentage charged within a swap, including the protocol fee and the LP fee)
uint24 swapFee;
// how much protocol fee has been charged
bytes32 feeAmountToProtocol;
}
function swap(State storage self, SwapParams memory params)
internal
returns (BalanceDelta result, SwapState memory swapState)
{
BinSlot0 slot0Cache = self.slot0;
swapState.activeId = slot0Cache.activeId();
bool swapForY = params.swapForY;
swapState.protocolFee =
swapForY ? slot0Cache.protocolFee().getZeroForOneFee() : slot0Cache.protocolFee().getOneForZeroFee();
bool exactInput = params.amountSpecified < 0;
{
uint24 lpFee = params.lpFeeOverride.isOverride()
? params.lpFeeOverride.removeOverrideAndValidate(LPFeeLibrary.TEN_PERCENT_FEE)
: slot0Cache.lpFee();
/// @dev swap fee includes protocolFee (charged first) and lpFee
swapState.swapFee = swapState.protocolFee == 0 ? lpFee : swapState.protocolFee.calculateSwapFee(lpFee);
}
/// @notice early return if hook has updated amountSpecified to 0
if (params.amountSpecified == 0) return (result, swapState);
uint128 amount;
unchecked {
amount = params.amountSpecified > 0 ? uint128(params.amountSpecified) : uint128(-params.amountSpecified);
}
/// @dev Amount of token left. In exactIn, refer to how much input left. In exactOut, refer to how much output left
bytes32 amountsLeft = (swapForY == exactInput) ? amount.encodeFirst() : amount.encodeSecond();
/// @dev Amount of token on the other side. In exactIn, refer to how much token out. In exactOut, refer to how much token in
bytes32 amountsUnspecified;
while (true) {
bytes32 binReserves = self.reserveOfBin[swapState.activeId];
if (!binReserves.isEmpty(!swapForY)) {
bytes32 amountsInWithFees;
bytes32 amountsOutOfBin;
bytes32 totalFee;
if (exactInput) {
(amountsInWithFees, amountsOutOfBin, totalFee) = binReserves.getAmountsOut(
swapState.swapFee, params.binStep, swapForY, swapState.activeId, amountsLeft
);
amountsLeft = amountsLeft.sub(amountsInWithFees);
amountsUnspecified = amountsUnspecified.add(amountsOutOfBin);
} else {
(amountsInWithFees, amountsOutOfBin, totalFee) = binReserves.getAmountsIn(
swapState.swapFee, params.binStep, swapForY, swapState.activeId, amountsLeft
);
amountsLeft = amountsLeft.sub(amountsOutOfBin);
amountsUnspecified = amountsUnspecified.add(amountsInWithFees);
}
if (amountsInWithFees > 0) {
/// @dev calc protocol fee for current bin, totalFee * protocolFee / (protocolFee + lpFee)
bytes32 pFee = totalFee.getProtocolFeeAmt(slot0Cache.protocolFee(), swapState.swapFee);
if (pFee != 0) {
swapState.feeAmountToProtocol = swapState.feeAmountToProtocol.add(pFee);
amountsInWithFees = amountsInWithFees.sub(pFee);
}
self.reserveOfBin[swapState.activeId] = binReserves.add(amountsInWithFees).sub(amountsOutOfBin);
if (
self.reserveOfBin[swapState.activeId].getLiquidity(
swapState.activeId.getPriceFromId(params.binStep)
) > Constants.MAX_LIQUIDITY_PER_BIN
) {
revert BinPool__MaxLiquidityPerBinExceeded();
}
}
}
if (amountsLeft == 0) {
break;
} else {
uint24 nextId = getNextNonEmptyBin(self, swapForY, swapState.activeId);
// Equivalent to: if (nextId == 0 || nextId == type(uint24).max) revert BinPool__OutOfLiquidity();
assembly ("memory-safe") {
if or(iszero(nextId), eq(nextId, 0xffffff)) {
mstore(0x00, 0x96aa65ad) // Selector BinPool__OutOfLiquidity()
revert(0x1c, 0x04)
}
}
swapState.activeId = nextId;
}
}
if (amountsUnspecified == 0) revert BinPool__InsufficientAmountUnSpecified();
self.slot0 = self.slot0.setActiveId(swapState.activeId);
unchecked {
// uncheckeck as negating positive int128 is safe
if (exactInput) {
if (swapForY) {
result = toBalanceDelta(-amount.safeInt128(), amountsUnspecified.decodeY().safeInt128());
} else {
result = toBalanceDelta(amountsUnspecified.decodeX().safeInt128(), -(amount.safeInt128()));
}
} else {
if (swapForY) {
result = toBalanceDelta(-amountsUnspecified.decodeX().safeInt128(), amount.safeInt128());
} else {
result = toBalanceDelta(amount.safeInt128(), -(amountsUnspecified.decodeY().safeInt128()));
}
}
}
}
struct MintParams {
address to; // nft minted to
bytes32[] liquidityConfigs;
bytes32 amountIn;
uint16 binStep;
uint24 lpFeeOverride;
bytes32 salt;
}
struct MintArrays {
uint256[] ids;
bytes32[] amounts;
uint256[] liquidityMinted;
}
/// @return result the delta of the token balance of the pool (inclusive of fees)
/// @return feeAmountToProtocol total protocol fee amount
/// @return arrays the ids, amounts and liquidity minted for each bin
/// @return compositionFeeAmount composition fee for adding different ratio to active bin
function mint(State storage self, MintParams memory params)
internal
returns (
BalanceDelta result,
bytes32 feeAmountToProtocol,
MintArrays memory arrays,
bytes32 compositionFeeAmount
)
{
if (params.liquidityConfigs.length == 0) revert BinPool__EmptyLiquidityConfigs();
arrays = MintArrays({
ids: new uint256[](params.liquidityConfigs.length),
amounts: new bytes32[](params.liquidityConfigs.length),
liquidityMinted: new uint256[](params.liquidityConfigs.length)
});
(bytes32 amountsLeft, bytes32 feeAmt, bytes32 compoFeeAmt) = _mintBins(self, params, arrays);
feeAmountToProtocol = feeAmt;
compositionFeeAmount = compoFeeAmt;
(uint128 x1, uint128 x2) = params.amountIn.sub(amountsLeft).decode();
// set balanceDelta to negative (so user must settle()) from the vault
result = toBalanceDelta(-(x1.safeInt128()), -(x2.safeInt128()));
}
/// @notice Returns the reserves of a bin
/// @param binStep The binStep of the bin
/// @param id The id of the bin
/// @return binReserveX The reserve of token X in the bin
/// @return binReserveY The reserve of token Y in the bin
/// @return binLiquidity The liquidity in the bin
/// @return binShare The shares in the bin
function getBin(State storage self, uint16 binStep, uint24 id)
internal
view
returns (uint128 binReserveX, uint128 binReserveY, uint256 binLiquidity, uint256 binShare)
{
bytes32 binReserves = self.reserveOfBin[id];
(binReserveX, binReserveY) = binReserves.decode();
binLiquidity = binReserves.getLiquidity(id.getPriceFromId(binStep));
binShare = self.shareOfBin[id];
}
/// @dev Returns next non-empty bin
/// @param swapForY Whether the swap is for Y
/// @param id The id of the bin
/// @return The id of the next non-empty bin
function getNextNonEmptyBin(State storage self, bool swapForY, uint24 id) internal view returns (uint24) {
return swapForY
? TreeMath.findFirstRight(self.level0, self.level1, self.level2, id)
: TreeMath.findFirstLeft(self.level0, self.level1, self.level2, id);
}
struct BurnParams {
address from;
uint256[] ids;
uint256[] amountsToBurn;
bytes32 salt;
}
/// @notice Burn user's share and withdraw tokens form the pool.
/// @return result the delta of the token balance of the pool
function burn(State storage self, BurnParams memory params)
internal
returns (BalanceDelta result, uint256[] memory ids, bytes32[] memory amounts)
{
ids = params.ids;
uint256 idsLength = ids.length;
uint256[] memory amountsToBurn = params.amountsToBurn;
if (idsLength == 0 || idsLength != amountsToBurn.length) revert BinPool__InvalidBurnInput();
bytes32 amountsOut;
amounts = new bytes32[](idsLength);
for (uint256 i; i < idsLength;) {
uint24 id = ids[i].safe24();
uint256 amountToBurn = amountsToBurn[i];
if (amountToBurn == 0) revert BinPool__BurnZeroAmount(id);
bytes32 binReserves = self.reserveOfBin[id];
uint256 supply = self.shareOfBin[id];
_subShare(self, params.from, id, params.salt, amountToBurn);
bytes32 amountsOutFromBin = binReserves.getAmountOutOfBin(amountToBurn, supply);
if (amountsOutFromBin == 0) revert BinPool__ZeroAmountsOut(id);
binReserves = binReserves.sub(amountsOutFromBin);
/// @dev _removeBinIdToTree if supply is MINIMUM_SHARE after burning as min share is too low liquidity for trade anyway
if (supply - amountToBurn == MINIMUM_SHARE) _removeBinIdToTree(self, id);
self.reserveOfBin[id] = binReserves;
amounts[i] = amountsOutFromBin;
amountsOut = amountsOut.add(amountsOutFromBin);
unchecked {
++i;
}
}
result = toBalanceDelta(amountsOut.decodeX().safeInt128(), amountsOut.decodeY().safeInt128());
}
function donate(State storage self, uint16 binStep, uint128 amount0, uint128 amount1)
internal
returns (BalanceDelta result, uint24 activeId)
{
activeId = self.slot0.activeId();
bytes32 amountIn = amount0.encode(amount1);
bytes32 binReserves = self.reserveOfBin[activeId];
if (binReserves == 0) revert BinPool__NoLiquidityToReceiveFees();
/// @dev overflow check on total reserves and the resulting liquidity
uint256 price = activeId.getPriceFromId(binStep);
bytes32 newReserves = binReserves.add(amountIn);
if (newReserves.getLiquidity(price) > Constants.MAX_LIQUIDITY_PER_BIN) {
revert BinPool__MaxLiquidityPerBinExceeded();
}
self.reserveOfBin[activeId] = newReserves;
result = toBalanceDelta(-(amount0.safeInt128()), -(amount1.safeInt128()));
}
/// @dev Helper function to mint liquidity in each bin in the liquidity configurations
/// @param params MintParams (to, liquidityConfig, amountIn, binStep and fee)
/// @param arrays MintArrays (ids[] , amounts[], liquidityMinted[])
/// @return amountsLeft amountLeft after deducting all the input (inclusive of fee) from amountIn
/// @return feeAmountToProtocol total protocol fee for minting
/// @return compositionFeeAmount composition fee for adding different ratio to active bin
function _mintBins(State storage self, MintParams memory params, MintArrays memory arrays)
private
returns (bytes32 amountsLeft, bytes32 feeAmountToProtocol, bytes32 compositionFeeAmount)
{
amountsLeft = params.amountIn;
uint24 id;
uint256 shares;
bytes32 amountsIn;
bytes32 amountsInToBin;
bytes32 binFeeAmt;
bytes32 binCompositionFee;
uint256 liquidityConfigsLength = params.liquidityConfigs.length;
for (uint256 i; i < liquidityConfigsLength;) {
// fix stack too deep
{
bytes32 maxAmountsInToBin;
(maxAmountsInToBin, id) = params.liquidityConfigs[i].getAmountsAndId(params.amountIn);
(shares, amountsIn, amountsInToBin, binFeeAmt, binCompositionFee) =
_updateBin(self, params, id, maxAmountsInToBin);
}
amountsLeft = amountsLeft.sub(amountsIn);
feeAmountToProtocol = feeAmountToProtocol.add(binFeeAmt);
shares = _addShare(self, params.to, id, params.salt, shares);
arrays.ids[i] = id;
arrays.amounts[i] = amountsInToBin;
arrays.liquidityMinted[i] = shares;
compositionFeeAmount = compositionFeeAmount.add(binCompositionFee);
unchecked {
++i;
}
}
}
/// @dev Helper function to update a bin during minting
/// @param id The id of the bin
/// @param maxAmountsInToBin The maximum amounts in to the bin
/// @return shares The amount of shares minted
/// @return amountsIn The amounts in
/// @return amountsInToBin The amounts in to the bin
/// @return feeAmountToProtocol The amounts of fee for protocol
/// @return compositionFeeAmount The total amount of composition fee
function _updateBin(State storage self, MintParams memory params, uint24 id, bytes32 maxAmountsInToBin)
internal
returns (
uint256 shares,
bytes32 amountsIn,
bytes32 amountsInToBin,
bytes32 feeAmountToProtocol,
bytes32 compositionFeeAmount
)
{
BinSlot0 slot0Cache = self.slot0;
uint24 activeId = slot0Cache.activeId();
bytes32 binReserves = self.reserveOfBin[id];
uint256 price = id.getPriceFromId(params.binStep);
uint256 supply = self.shareOfBin[id];
(shares, amountsIn) = binReserves.getSharesAndEffectiveAmountsIn(maxAmountsInToBin, price, supply);
amountsInToBin = amountsIn;
if (id == activeId) {
// Fees happens when user try to add liquidity in active bin but with different ratio of (x, y)
/// eg. current bin is 40/60 (a,b) but user tries to add liquidity with 50/50 ratio
uint24 lpFee = params.lpFeeOverride.isOverride()
? params.lpFeeOverride.removeOverrideAndValidate(LPFeeLibrary.TEN_PERCENT_FEE)
: slot0Cache.lpFee();
bytes32 feesAmount;
(feesAmount, feeAmountToProtocol) =
binReserves.getCompositionFeesAmount(slot0Cache.protocolFee(), lpFee, amountsIn, supply, shares);
compositionFeeAmount = feesAmount;
if (feesAmount != 0) {
{
uint256 userLiquidity = amountsIn.sub(feesAmount).getLiquidity(price);
/// @dev Ensure fee accrued only to existing lp, before calculating new share for minter
uint256 binLiquidity = binReserves.add(feesAmount.sub(feeAmountToProtocol)).getLiquidity(price);
shares = userLiquidity.mulDivRoundDown(supply, binLiquidity);
}
if (feeAmountToProtocol != 0) {
amountsInToBin = amountsInToBin.sub(feeAmountToProtocol);
}
}
} else {
amountsIn.verifyAmounts(activeId, id);
}
if (shares == 0 || amountsInToBin == 0) revert BinPool__ZeroShares(id);
/// @dev if supply was originally MINIMUM_SHARE (people added and remove liquidity before) or 0 (new bin), add binId to tree
if (supply <= MINIMUM_SHARE) _addBinIdToTree(self, id);
bytes32 newReserves = binReserves.add(amountsInToBin);
if (newReserves.getLiquidity(price) > Constants.MAX_LIQUIDITY_PER_BIN) {
revert BinPool__MaxLiquidityPerBinExceeded();
}
self.reserveOfBin[id] = newReserves;
}
/// @notice Subtract share from user's position and update total share supply of bin
function _subShare(State storage self, address owner, uint24 binId, bytes32 salt, uint256 shares) internal {
self.positions.get(owner, binId, salt).subShare(shares);
self.shareOfBin[binId] -= shares;
}
/// @notice Add share to user's position and update total share supply of bin
/// @dev if bin is empty, deduct MINIMUM_SHARE from shares
/// @return userShareAdded The amount of share added to user's position
function _addShare(State storage self, address owner, uint24 binId, bytes32 salt, uint256 shares)
internal
returns (uint256 userShareAdded)
{
userShareAdded = shares;
if (self.shareOfBin[binId] == 0) {
/// @dev Only for first liquidity provider for the bin, deduct MINIMUM_SHARE, expected to underflow
/// if shares < MINIMUM_SHARE for first mint
userShareAdded = shares - MINIMUM_SHARE;
/// @dev Reject a first mint that locks the minimum but leaves the minter with no share, otherwise
/// the bin ends up with reserves and a tree entry that no position owns (see burn-side threshold)
if (userShareAdded == 0) revert BinPool__ZeroShares(binId);
}
self.positions.get(owner, binId, salt).addShare(userShareAdded);
self.shareOfBin[binId] += shares;
}
/// @notice Enable bin id for a pool
function _addBinIdToTree(State storage self, uint24 binId) internal {
(, self.level0) = TreeMath.add(self.level0, self.level1, self.level2, binId);
}
/// @notice remove bin id for a pool
function _removeBinIdToTree(State storage self, uint24 binId) internal {
(, self.level0) = TreeMath.remove(self.level0, self.level1, self.level2, binId);
}
function checkPoolInitialized(State storage self) internal view {
if (self.slot0.activeId() == 0) {
// revert PoolNotInitialized();
assembly ("memory-safe") {
mstore(0x00, 0x486aa307)
revert(0x1c, 0x04)
}
}
}
}
src/pool-bin/libraries/BinPoolParametersHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Encoded} from "../../libraries/math/Encoded.sol";
/// @title Bin Pool Pair Parameter Helper Library
/// @dev This library contains functions to get and set parameters of a pair
/// The parameters are stored in a single bytes32 variable in the following format:
/// [0 - 16[: reserve for hooks
/// [16 - 31[: binStep (16 bits)
/// [32 - 256[: unused
library BinPoolParametersHelper {
using Encoded for bytes32;
uint256 internal constant OFFSET_BIN_STEP = 16;
uint256 internal constant OFFSET_MOST_SIGNIFICANT_UNUSED_BITS = 32;
/// @dev Get binstep from the encoded pair parameters
/// @param params The encoded pair parameters, as follows:
/// [0 - 15[: bitmap for hooks registration
/// [16 - 31[: binSteps (16 bits)
/// [32 - 256[: unused
/// @return binStep The binStep
function getBinStep(bytes32 params) internal pure returns (uint16 binStep) {
binStep = params.decodeUint16(OFFSET_BIN_STEP);
}
/**
* @dev Helper method to set bin step in the encoded pair parameter
* @return The new encoded pair parameter
*/
function setBinStep(bytes32 params, uint16 binStep) internal pure returns (bytes32) {
return params.set(binStep, Encoded.MASK_UINT16, OFFSET_BIN_STEP);
}
}
src/pool-bin/libraries/BinPosition.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @title BinPosition
/// @notice Positions represent an owner address' share for a bin
library BinPosition {
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct Info {
// the amount of share owned by this position
uint256 share;
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param binId The bin id where the position's liquidity is added
/// @param salt A unique value to differentiate between multiple positions in the same binId, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, uint24 binId, bytes32 salt) internal pure returns (bytes32 key) {
// dev same as `positionKey = keccak256(abi.encodePacked(binId, owner, salt))`
// make salt, binId, owner to be tightly packed in memory
assembly ("memory-safe") {
mstore(0x0, or(shl(160, binId), and(owner, 0xffffffffffffffffffffffffffffffffffffffff))) // binId at [0x09,0x0c), owner at [0x0c, 0x20)
mstore(0x20, salt) // salt at [0x20, 0x40)
key := keccak256(0x09, 0x37)
}
}
/// @notice Returns the Info struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param binId The bin id where the position's liquidity is added
/// @param salt The salt to distinguish different positions for the same owner
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => Info) storage self, address owner, uint24 binId, bytes32 salt)
internal
view
returns (BinPosition.Info storage position)
{
bytes32 key = calculatePositionKey(owner, binId, salt);
position = self[key];
}
function addShare(Info storage self, uint256 share) internal {
self.share += share;
}
function subShare(Info storage self, uint256 share) internal {
self.share -= share;
}
}
src/pool-bin/libraries/Constants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Set of constants for BinPool
library Constants {
uint8 internal constant SCALE_OFFSET = 128;
uint256 internal constant SCALE = 1 << SCALE_OFFSET;
uint256 internal constant PRECISION = 1e18;
uint256 internal constant SQUARED_PRECISION = PRECISION * PRECISION;
uint256 internal constant BASIS_POINT_MAX = 10_000;
// (2^256 - 1) / (2 * log(2**128) / log(1.0001))
uint256 internal constant MAX_LIQUIDITY_PER_BIN =
65251743116719673010965625540244653191619923014385985379600384103134737;
}
src/pool-bin/libraries/FeeHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Constants} from "./Constants.sol";
/// @notice Helper to calculate fees for BinPool
library FeeHelper {
/// @dev Calculates the fee amount from the amount with fees, rounding up
/// @param amountWithFees The amount with fees
/// @param feeBips feeBips - 100 = 0.01%, 1_000 = 0.1%, 100_000 = 10% (max)
/// @return feeAmount The fee amount
function getFeeAmountFrom(uint128 amountWithFees, uint24 feeBips) internal pure returns (uint128) {
unchecked {
uint128 totalFee = uint128(feeBips) * 1e12;
// Can't overflow, max(result) = (type(uint128).max * 0.1e18 + 1e18 - 1) / 1e18 < 2^128
return uint128((uint256(amountWithFees) * totalFee + Constants.PRECISION - 1) / Constants.PRECISION);
}
}
/// @dev Calculates the fee amount that will be charged, rounding up
/// @param amount The amount
/// @param feeBips feeBips - 100 = 0.01%, 1_000 = 0.1%, 100_000 = 10% (max)
/// @return feeAmount The fee amount
function getFeeAmount(uint128 amount, uint24 feeBips) internal pure returns (uint128) {
unchecked {
uint128 totalFee = uint128(feeBips) * 1e12;
uint256 denominator = Constants.PRECISION - totalFee;
// Can't overflow, max(result) = (type(uint128).max * 0.1e18 + (1e18 - 1)) / 0.9e18 < 2^128
return uint128((uint256(amount) * totalFee + denominator - 1) / denominator);
}
}
/// @notice Calculates the composition fee amount from the amount with fees, rounding down
/// @dev Composition fee is higher than swapFee to ensure user do not does an implicit swap through mint to take advantage of lower fees
/// @param amountWithFees The amount with fees
/// @param feeBips The total fee, 100 = 0.01%, 10_000 = 1%, 100_000 = 10% (max)
/// @return The amount with fees
function getCompositionFee(uint128 amountWithFees, uint24 feeBips) internal pure returns (uint128) {
unchecked {
uint128 totalFee = uint128(feeBips) * 1e12;
uint256 denominator = Constants.SQUARED_PRECISION; // 1e36
// Can't overflow, max(result) = type(uint128).max * 0.1e18 * 1.1e18 / 1e36 <= 2^128 * 0.11e36 / 1e36 < 2^128
return
uint128((uint256(amountWithFees) * totalFee * (uint256(totalFee) + Constants.PRECISION)) / denominator);
}
}
}
src/pool-bin/libraries/PriceHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Uint128x128Math} from "./math/Uint128x128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
/// @notice This library contains functions to calculate prices
library PriceHelper {
using Uint128x128Math for uint256;
using Uint256x256Math for uint256;
using SafeCast for uint256;
int256 private constant REAL_ID_SHIFT = 1 << 23;
/// @dev Calculates the price from the id and the bin step
/// @param id The id
/// @param binStep The bin step
/// @return price The price as a 128.128-binary fixed-point number
function getPriceFromId(uint24 id, uint16 binStep) internal pure returns (uint256 price) {
uint256 base = getBase(binStep);
int256 exponent = getExponent(id);
price = base.pow(exponent);
}
/// @dev Calculates the id from the price and the bin step
/// @param price The price as a 128.128-binary fixed-point number
/// @param binStep The bin step
/// @return id The id
function getIdFromPrice(uint256 price, uint16 binStep) internal pure returns (uint24 id) {
uint256 base = getBase(binStep);
int256 realId = price.log2() / base.log2();
unchecked {
id = uint256(REAL_ID_SHIFT + realId).safe24();
}
}
/// @dev Calculates the base from the bin step, which is `1 + binStep / BASIS_POINT_MAX`
/// @param binStep The bin step
/// @return base The base
function getBase(uint16 binStep) internal pure returns (uint256) {
unchecked {
return Constants.SCALE + (uint256(binStep) << Constants.SCALE_OFFSET) / Constants.BASIS_POINT_MAX;
}
}
/// @dev Calculates the exponent from the id, which is `id - REAL_ID_SHIFT`
/// @param id The id
/// @return exponent The exponent
function getExponent(uint24 id) internal pure returns (int256) {
unchecked {
return int256(uint256(id)) - REAL_ID_SHIFT;
}
}
/// @dev Converts a price with 18 decimals to a 128.128-binary fixed-point number
/// @param price The price with 18 decimals
/// @return price128x128 The 128.128-binary fixed-point number
function convertDecimalPriceTo128x128(uint256 price) internal pure returns (uint256) {
return price.shiftDivRoundDown(Constants.SCALE_OFFSET, Constants.PRECISION);
}
/// @dev Converts a 128.128-binary fixed-point number to a price with 18 decimals
/// @param price128x128 The 128.128-binary fixed-point number
/// @return price The price with 18 decimals
function convert128x128PriceToDecimal(uint256 price128x128) internal pure returns (uint256) {
return price128x128.mulShiftRoundDown(Constants.PRECISION, Constants.SCALE_OFFSET);
}
}
src/pool-bin/libraries/math/BitMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Helper contract used for bit calculations
library BitMath {
/// @dev Returns the index of the closest bit on the right of x that is non null
/// @param x The value as a uint256
/// @param bit The index of the bit to start searching at
/// @return id The index of the closest non null bit on the right of x. If there is no closest bit, it returns max(uint256)
function closestBitRight(uint256 x, uint8 bit) internal pure returns (uint256 id) {
unchecked {
uint256 shift = 255 - bit;
x <<= shift;
// can't overflow as it's non-zero and we shifted it by `_shift`
return (x == 0) ? type(uint256).max : mostSignificantBit(x) - shift;
}
}
/// @dev Returns the index of the closest bit on the left of x that is non null
/// @param x The value as a uint256
/// @param bit The index of the bit to start searching at
/// @return id The index of the closest non null bit on the left of x.If there is no closest bit, it returns max(uint256)
function closestBitLeft(uint256 x, uint8 bit) internal pure returns (uint256 id) {
unchecked {
x >>= bit;
return (x == 0) ? type(uint256).max : leastSignificantBit(x) + bit;
}
}
/// @dev Returns the index of the most significant bit of x. This function returns 0 if x is 0
/// @param x The value as a uint256
/// @return msb The index of the most significant bit of x
function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
assembly ("memory-safe") {
if gt(x, 0xffffffffffffffffffffffffffffffff) {
x := shr(128, x)
msb := 128
}
if gt(x, 0xffffffffffffffff) {
x := shr(64, x)
msb := add(msb, 64)
}
if gt(x, 0xffffffff) {
x := shr(32, x)
msb := add(msb, 32)
}
if gt(x, 0xffff) {
x := shr(16, x)
msb := add(msb, 16)
}
if gt(x, 0xff) {
x := shr(8, x)
msb := add(msb, 8)
}
if gt(x, 0xf) {
x := shr(4, x)
msb := add(msb, 4)
}
if gt(x, 0x3) {
x := shr(2, x)
msb := add(msb, 2)
}
if gt(x, 0x1) { msb := add(msb, 1) }
}
}
/// @dev Returns the index of the least significant bit of x. This function returns 255 if x is 0
/// @param x The value as a uint256
/// @return lsb The index of the least significant bit of x
function leastSignificantBit(uint256 x) internal pure returns (uint8 lsb) {
assembly ("memory-safe") {
let sx := shl(128, x)
if iszero(iszero(sx)) {
lsb := 128
x := sx
}
sx := shl(64, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 64)
}
sx := shl(32, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 32)
}
sx := shl(16, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 16)
}
sx := shl(8, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 8)
}
sx := shl(4, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 4)
}
sx := shl(2, x)
if iszero(iszero(sx)) {
x := sx
lsb := add(lsb, 2)
}
if iszero(iszero(shl(1, x))) { lsb := add(lsb, 1) }
lsb := sub(255, lsb)
}
}
}
src/pool-bin/libraries/math/LiquidityConfigurations.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {PackedUint128Math} from "./PackedUint128Math.sol";
import {Encoded} from "../../../libraries/math/Encoded.sol";
/// @notice This library contains functions to encode and decode the config of a pool and interact with the encoded bytes32.
library LiquidityConfigurations {
using PackedUint128Math for bytes32;
using PackedUint128Math for uint128;
using Encoded for bytes32;
error LiquidityConfigurations__InvalidConfig();
uint256 private constant OFFSET_ID = 0;
uint256 private constant OFFSET_DISTRIBUTION_Y = 24;
uint256 private constant OFFSET_DISTRIBUTION_X = 88;
uint256 private constant PRECISION = 1e18;
/// @dev Encode the distributionX, distributionY and id into a single bytes32
/// @param distributionX The distribution of the first token
/// @param distributionY The distribution of the second token
/// @param id The id of the pool
/// @return config The encoded config as follows:
/// [0 - 24[: id
/// [24 - 88[: distributionY
/// [88 - 152[: distributionX
/// [152 - 256[: empty
function encodeParams(uint64 distributionX, uint64 distributionY, uint24 id)
internal
pure
returns (bytes32 config)
{
config = config.set(distributionX, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_X);
config = config.set(distributionY, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_Y);
config = config.set(id, Encoded.MASK_UINT24, OFFSET_ID);
}
/// @dev Decode the distributionX, distributionY and id from a single bytes32
/// @param config The encoded config as follows:
/// [0 - 24[: id
/// [24 - 88[: distributionY
/// [88 - 152[: distributionX
/// [152 - 256[: empty
/// @return distributionX The distribution of the first token
/// @return distributionY The distribution of the second token
/// @return id The id of the bin to add the liquidity to
function decodeParams(bytes32 config)
internal
pure
returns (uint64 distributionX, uint64 distributionY, uint24 id)
{
distributionX = config.decodeUint64(OFFSET_DISTRIBUTION_X);
distributionY = config.decodeUint64(OFFSET_DISTRIBUTION_Y);
id = config.decodeUint24(OFFSET_ID);
if (uint256(config) > type(uint152).max || distributionX > PRECISION || distributionY > PRECISION) {
revert LiquidityConfigurations__InvalidConfig();
}
}
/// @dev Get the amounts and id from a config and amountsIn
/// @param config The encoded config as follows:
/// [0 - 24[: id
/// [24 - 88[: distributionY
/// [88 - 152[: distributionX
/// [152 - 256[: empty
/// @param amountsIn The amounts to distribute as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @return amounts The distributed amounts as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @return id The id of the bin to add the liquidity to
function getAmountsAndId(bytes32 config, bytes32 amountsIn) internal pure returns (bytes32, uint24) {
(uint64 distributionX, uint64 distributionY, uint24 id) = decodeParams(config);
(uint128 x1, uint128 x2) = amountsIn.decode();
assembly ("memory-safe") {
x1 := div(mul(x1, distributionX), PRECISION)
x2 := div(mul(x2, distributionY), PRECISION)
}
return (x1.encode(x2), id);
}
}
src/pool-bin/libraries/math/PackedUint128Math.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Constants} from "../Constants.sol";
import {ProtocolFeeLibrary} from "../../../libraries/ProtocolFeeLibrary.sol";
import {SafeCast} from "./SafeCast.sol";
/// @notice This library contains functions to encode and decode two uint128 into a single bytes32
/// and interact with the encoded bytes32.
library PackedUint128Math {
using ProtocolFeeLibrary for uint24;
using SafeCast for uint256;
error PackedUint128Math__AddOverflow();
error PackedUint128Math__SubUnderflow();
uint256 private constant OFFSET = 128;
uint256 private constant MASK_128 = 0xffffffffffffffffffffffffffffffff;
uint256 private constant MASK_128_PLUS_ONE = MASK_128 + 1;
/// @dev Encodes two uint128 into a single bytes32
/// @param x1 The first uint128
/// @param x2 The second uint128
/// @return z The encoded bytes32 as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
function encode(uint128 x1, uint128 x2) internal pure returns (bytes32 z) {
assembly ("memory-safe") {
z := or(and(x1, MASK_128), shl(OFFSET, x2))
}
}
/// @dev Encodes a uint128 into a single bytes32 as the first uint128
/// @param x1 The uint128
/// @return z The encoded bytes32 as follows:
/// [0 - 128[: x1
/// [128 - 256[: empty
function encodeFirst(uint128 x1) internal pure returns (bytes32 z) {
assembly ("memory-safe") {
z := and(x1, MASK_128)
}
}
/// @dev Encodes a uint128 into a single bytes32 as the second uint128
/// @param x2 The uint128
// @return z The encoded bytes32 as follows:
/// [0 - 128[: empty
/// [128 - 256[: x2
function encodeSecond(uint128 x2) internal pure returns (bytes32 z) {
assembly ("memory-safe") {
z := shl(OFFSET, x2)
}
}
/// @dev Encodes a uint128 into a single bytes32 as the first or second uint128
/// @param x The uint128
/// @param first Whether to encode as the first or second uint128
/// @return z The encoded bytes32 as follows:
/// if first:
/// [0 - 128[: x
/// [128 - 256[: empty
/// else:
/// [0 - 128[: empty
/// [128 - 256[: x
function encode(uint128 x, bool first) internal pure returns (bytes32 z) {
return first ? encodeFirst(x) : encodeSecond(x);
}
/// @dev Decodes a bytes32 into two uint128
/// @param z The encoded bytes32 as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @return x1 The first uint128
/// @return x2 The second uint128
function decode(bytes32 z) internal pure returns (uint128 x1, uint128 x2) {
assembly ("memory-safe") {
x1 := and(z, MASK_128)
x2 := shr(OFFSET, z)
}
}
/// @dev Decodes a bytes32 into a uint128 as the first uint128
/// @param z The encoded bytes32 as follows:
/// [0 - 128[: x
/// [128 - 256[: any
/// @return x The first uint128
function decodeX(bytes32 z) internal pure returns (uint128 x) {
assembly ("memory-safe") {
x := and(z, MASK_128)
}
}
/// @dev Decodes a bytes32 into a uint128 as the second uint128
/// @param z The encoded bytes32 as follows:
/// [0 - 128[: any
/// [128 - 256[: y
/// @return y The second uint128
function decodeY(bytes32 z) internal pure returns (uint128 y) {
assembly ("memory-safe") {
y := shr(OFFSET, z)
}
}
/// @dev Decodes a bytes32 into a uint128 as the first or second uint128
/// @param z The encoded bytes32 as follows:
/// if first:
/// [0 - 128[: x1
/// [128 - 256[: empty
/// else:
/// [0 - 128[: empty
/// [128 - 256[: x2
/// @param first Whether to decode as the first or second uint128
/// @return x The decoded uint128
function decode(bytes32 z, bool first) internal pure returns (uint128 x) {
return first ? decodeX(z) : decodeY(z);
}
/// @dev Adds two encoded bytes32, reverting on overflow on any of the uint128
/// @param x The first bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y The second bytes32 encoded as follows:
/// [0 - 128[: y1
/// [128 - 256[: y2
/// @return z The sum of x and y encoded as follows:
/// [0 - 128[: x1 + y1
/// [128 - 256[: x2 + y2
function add(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
assembly ("memory-safe") {
z := add(x, y)
}
if (z < x || uint128(uint256(z)) < uint128(uint256(x))) {
revert PackedUint128Math__AddOverflow();
}
}
/// @dev Adds an encoded bytes32 and two uint128, reverting on overflow on any of the uint128
/// @param x The bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y1 The first uint128
/// @param y2 The second uint128
/// @return z The sum of x and y encoded as follows:
/// [0 - 128[: x1 + y1
/// [128 - 256[: x2 + y2
function add(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
return add(x, encode(y1, y2));
}
/// @dev Subtracts two encoded bytes32, reverting on underflow on any of the uint128
/// @param x The first bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y The second bytes32 encoded as follows:
/// [0 - 128[: y1
/// [128 - 256[: y2
/// @return z The difference of x and y encoded as follows:
/// [0 - 128[: x1 - y1
/// [128 - 256[: x2 - y2
function sub(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
assembly ("memory-safe") {
z := sub(x, y)
}
if (z > x || uint128(uint256(z)) > uint128(uint256(x))) {
revert PackedUint128Math__SubUnderflow();
}
}
/// @dev Subtracts an encoded bytes32 and two uint128, reverting on underflow on any of the uint128
/// @param x The bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y1 The first uint128
/// @param y2 The second uint128
/// @return z The difference of x and y encoded as follows:
/// [0 - 128[: x1 - y1
/// [128 - 256[: x2 - y2
function sub(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
return sub(x, encode(y1, y2));
}
/// @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
/// @param x The first bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y The second bytes32 encoded as follows:
/// [0 - 128[: y1
/// [128 - 256[: y2
/// @return x1 < y1 || x2 < y2
function lt(bytes32 x, bytes32 y) internal pure returns (bool) {
(uint128 x1, uint128 x2) = decode(x);
(uint128 y1, uint128 y2) = decode(y);
return x1 < y1 || x2 < y2;
}
/// @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
/// @param x The first bytes32 encoded as follows:
/// [0 - 128[: x1
/// [128 - 256[: x2
/// @param y The second bytes32 encoded as follows:
/// [0 - 128[: y1
/// [128 - 256[: y2
/// @return x1 < y1 || x2 < y2
function gt(bytes32 x, bytes32 y) internal pure returns (bool) {
(uint128 x1, uint128 x2) = decode(x);
(uint128 y1, uint128 y2) = decode(y);
return x1 > y1 || x2 > y2;
}
/// @dev given amount and protocolFee, calculate and return external protocol fee amt
/// @param amount encoded bytes with (x, y)
/// @param protocolFee Protocol fee from the swap, also denominated in hundredths of a bip
/// @param swapFee The fee collected upon every swap in the pool (including protocol fee and LP fee), denominated in hundredths of a bip
function getProtocolFeeAmt(bytes32 amount, uint24 protocolFee, uint24 swapFee) internal pure returns (bytes32 z) {
if (protocolFee == 0 || swapFee == 0) return 0;
(uint128 amountX, uint128 amountY) = decode(amount);
uint16 fee0 = protocolFee.getZeroForOneFee();
uint16 fee1 = protocolFee.getOneForZeroFee();
uint128 feeForX;
uint128 feeForY;
unchecked {
if (fee0 == 0) {
feeForX = 0;
} else if (fee0 == swapFee) {
feeForX = amountX;
} else {
feeForX = (uint256(amountX) * fee0 / swapFee).safe128();
}
if (fee1 == 0) {
feeForY = 0;
} else if (fee1 == swapFee) {
feeForY = amountY;
} else {
feeForY = (uint256(amountY) * fee1 / swapFee).safe128();
}
}
return encode(feeForX, feeForY);
}
}
src/pool-bin/libraries/math/SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice This library contains functions to safely cast uint256 to different uint types.
library SafeCast {
error SafeCastOverflow();
function _revertOverflow() private pure {
assembly ("memory-safe") {
// Store the function selector of `SafeCastOverflow()`.
mstore(0x00, 0x93dafdf1)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
/// @dev Returns x on uint248 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint248
function safe248(uint256 x) internal pure returns (uint248 y) {
if ((y = uint248(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint240 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint240
function safe240(uint256 x) internal pure returns (uint240 y) {
if ((y = uint240(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint232 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint232
function safe232(uint256 x) internal pure returns (uint232 y) {
if ((y = uint232(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint224 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint224
function safe224(uint256 x) internal pure returns (uint224 y) {
if ((y = uint224(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint216 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint216
function safe216(uint256 x) internal pure returns (uint216 y) {
if ((y = uint216(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint208 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint208
function safe208(uint256 x) internal pure returns (uint208 y) {
if ((y = uint208(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint200 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint200
function safe200(uint256 x) internal pure returns (uint200 y) {
if ((y = uint200(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint192 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint192
function safe192(uint256 x) internal pure returns (uint192 y) {
if ((y = uint192(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint184 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint184
function safe184(uint256 x) internal pure returns (uint184 y) {
if ((y = uint184(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint176 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint176
function safe176(uint256 x) internal pure returns (uint176 y) {
if ((y = uint176(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint168 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint168
function safe168(uint256 x) internal pure returns (uint168 y) {
if ((y = uint168(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint160 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint160
function safe160(uint256 x) internal pure returns (uint160 y) {
if ((y = uint160(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint152 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint152
function safe152(uint256 x) internal pure returns (uint152 y) {
if ((y = uint152(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint144 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint144
function safe144(uint256 x) internal pure returns (uint144 y) {
if ((y = uint144(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint136 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint136
function safe136(uint256 x) internal pure returns (uint136 y) {
if ((y = uint136(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint128 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint128
function safe128(uint256 x) internal pure returns (uint128 y) {
if ((y = uint128(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint120 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint120
function safe120(uint256 x) internal pure returns (uint120 y) {
if ((y = uint120(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint112 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint112
function safe112(uint256 x) internal pure returns (uint112 y) {
if ((y = uint112(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint104 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint104
function safe104(uint256 x) internal pure returns (uint104 y) {
if ((y = uint104(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint96 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint96
function safe96(uint256 x) internal pure returns (uint96 y) {
if ((y = uint96(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint88 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint88
function safe88(uint256 x) internal pure returns (uint88 y) {
if ((y = uint88(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint80 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint80
function safe80(uint256 x) internal pure returns (uint80 y) {
if ((y = uint80(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint72 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint72
function safe72(uint256 x) internal pure returns (uint72 y) {
if ((y = uint72(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint64 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint64
function safe64(uint256 x) internal pure returns (uint64 y) {
if ((y = uint64(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint56 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint56
function safe56(uint256 x) internal pure returns (uint56 y) {
if ((y = uint56(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint48 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint48
function safe48(uint256 x) internal pure returns (uint48 y) {
if ((y = uint48(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint40 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint40
function safe40(uint256 x) internal pure returns (uint40 y) {
if ((y = uint40(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint32 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint32
function safe32(uint256 x) internal pure returns (uint32 y) {
if ((y = uint32(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint24 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint24
function safe24(uint256 x) internal pure returns (uint24 y) {
if ((y = uint24(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint16 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint16
function safe16(uint256 x) internal pure returns (uint16 y) {
if ((y = uint16(x)) != x) _revertOverflow();
}
/// @dev Returns x on uint8 and check that it does not overflow
/// @param x The value as an uint256
/// @return y The value as an uint8
function safe8(uint256 x) internal pure returns (uint8 y) {
if ((y = uint8(x)) != x) _revertOverflow();
}
/// @dev Return x on int128 and check that it does not overflow
/// @param x The value as uint128
/// @return y The value as int128
function safeInt128(uint128 x) internal pure returns (int128 y) {
if (x > uint128(type(int128).max)) _revertOverflow();
y = int128(x);
}
}
src/pool-bin/libraries/math/TreeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
/// @notice This library contains functions to interact with a tree of TreeUint24.
library TreeMath {
using BitMath for uint256;
/// @dev Returns true if the tree contains the id
function contains(mapping(bytes32 => bytes32) storage level2, uint24 id) internal view returns (bool) {
bytes32 leaf2 = bytes32(uint256(id) >> 8);
return level2[leaf2] & bytes32(1 << (id & type(uint8).max)) != 0;
}
/// @dev Adds the id to the tree and returns true if the id was not already in the tree
/// It will also propagate the change to the parent levels.
/// @return True if the id was not already in the tree
function add(
bytes32 level0,
mapping(bytes32 => bytes32) storage level1,
mapping(bytes32 => bytes32) storage level2,
uint24 id
) internal returns (bool, bytes32) {
bytes32 key2 = bytes32(uint256(id) >> 8);
bytes32 leaves = level2[key2];
bytes32 newLeaves = leaves | bytes32(1 << (id & type(uint8).max));
if (leaves != newLeaves) {
level2[key2] = newLeaves;
if (leaves == 0) {
bytes32 key1 = key2 >> 8;
leaves = level1[key1];
level1[key1] = leaves | bytes32(1 << (uint256(key2) & type(uint8).max));
if (leaves == 0) level0 |= bytes32(1 << (uint256(key1) & type(uint8).max));
}
return (true, level0);
}
return (false, level0);
}
/// @dev Removes the id from the tree and returns true if the id was in the tree.
/// It will also propagate the change to the parent levels.
/// @param id The id
/// @return True if the id was in the tree
function remove(
bytes32 level0,
mapping(bytes32 => bytes32) storage level1,
mapping(bytes32 => bytes32) storage level2,
uint24 id
) internal returns (bool, bytes32) {
bytes32 key2 = bytes32(uint256(id) >> 8);
bytes32 leaves = level2[key2];
bytes32 newLeaves = leaves & ~bytes32(1 << (id & type(uint8).max));
if (leaves != newLeaves) {
level2[key2] = newLeaves;
if (newLeaves == 0) {
bytes32 key1 = key2 >> 8;
newLeaves = level1[key1] & ~bytes32(1 << (uint256(key2) & type(uint8).max));
level1[key1] = newLeaves;
if (newLeaves == 0) level0 &= ~bytes32(1 << (uint256(key1) & type(uint8).max));
}
return (true, level0);
}
return (false, level0);
}
/// @dev Returns the first id in the tree that is lower than or equal to the given id.
/// It will return type(uint24).max if there is no such id.
/// @return The first id in the tree that is lower than or equal to the given id
function findFirstRight(
bytes32 level0,
mapping(bytes32 => bytes32) storage level1,
mapping(bytes32 => bytes32) storage level2,
uint24 id
) internal view returns (uint24) {
bytes32 leaves;
bytes32 key2 = bytes32(uint256(id) >> 8);
uint8 bit = uint8(id & type(uint8).max);
if (bit != 0) {
leaves = level2[key2];
uint256 closestBit = _closestBitRight(leaves, bit);
if (closestBit != type(uint256).max) return uint24((uint256(key2) << 8) | closestBit);
}
bytes32 key1 = key2 >> 8;
bit = uint8(uint256(key2) & type(uint8).max);
if (bit != 0) {
leaves = level1[key1];
uint256 closestBit = _closestBitRight(leaves, bit);
if (closestBit != type(uint256).max) {
key2 = bytes32((uint256(key1) << 8) | closestBit);
leaves = level2[key2];
return uint24((uint256(key2) << 8) | uint256(leaves).mostSignificantBit());
}
}
bit = uint8(uint256(key1) & type(uint8).max);
if (bit != 0) {
leaves = level0;
uint256 closestBit = _closestBitRight(leaves, bit);
if (closestBit != type(uint256).max) {
key1 = bytes32(closestBit);
leaves = level1[key1];
key2 = bytes32((uint256(key1) << 8) | uint256(leaves).mostSignificantBit());
leaves = level2[key2];
return uint24((uint256(key2) << 8) | uint256(leaves).mostSignificantBit());
}
}
return type(uint24).max;
}
/// @dev Returns the first id in the tree that is higher than or equal to the given id.
/// It will return 0 if there is no such id.
/// @return The first id in the tree that is higher than or equal to the given id
function findFirstLeft(
bytes32 level0,
mapping(bytes32 => bytes32) storage level1,
mapping(bytes32 => bytes32) storage level2,
uint24 id
) internal view returns (uint24) {
bytes32 leaves;
bytes32 key2 = bytes32(uint256(id) >> 8);
uint8 bit = uint8(id & type(uint8).max);
if (bit != type(uint8).max) {
leaves = level2[key2];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) return uint24((uint256(key2) << 8) | closestBit);
}
bytes32 key1 = key2 >> 8;
bit = uint8(uint256(key2) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = level1[key1];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key2 = bytes32((uint256(key1) << 8) | closestBit);
leaves = level2[key2];
return uint24((uint256(key2) << 8) | uint256(leaves).leastSignificantBit());
}
}
bit = uint8(uint256(key1) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = level0;
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key1 = bytes32(closestBit);
leaves = level1[key1];
key2 = bytes32((uint256(key1) << 8) | uint256(leaves).leastSignificantBit());
leaves = level2[key2];
return uint24((uint256(key2) << 8) | uint256(leaves).leastSignificantBit());
}
}
return 0;
}
/// @dev Returns the first bit in the given leaves that is strictly lower than the given bit.
/// It will return type(uint256).max if there is no such bit.
/// @param leaves The leaves
/// @param bit The bit
/// @return The first bit in the given leaves that is strictly lower than the given bit
function _closestBitRight(bytes32 leaves, uint8 bit) private pure returns (uint256) {
unchecked {
return uint256(leaves).closestBitRight(bit - 1);
}
}
/// @dev Returns the first bit in the given leaves that is strictly higher than the given bit.
/// It will return type(uint256).max if there is no such bit.
/// @param leaves The leaves
/// @param bit The bit
/// @return The first bit in the given leaves that is strictly higher than the given bit
function _closestBitLeft(bytes32 leaves, uint8 bit) private pure returns (uint256) {
unchecked {
return uint256(leaves).closestBitLeft(bit + 1);
}
}
}
src/pool-bin/libraries/math/Uint128x128Math.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Constants} from "../Constants.sol";
import {BitMath} from "./BitMath.sol";
/// @notice Helper contract used for power and log calculations
library Uint128x128Math {
using BitMath for uint256;
error Uint128x128Math__LogUnderflow();
error Uint128x128Math__PowUnderflow(uint256 x, int256 y);
uint256 internal constant LOG_SCALE_OFFSET = 127;
uint256 internal constant LOG_SCALE = 1 << LOG_SCALE_OFFSET;
uint256 internal constant LOG_SCALE_SQUARED = LOG_SCALE * LOG_SCALE;
/// @notice Calculates the binary logarithm of x.
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
/// Requirements:
/// - x must be greater than zero.
/// Caveats:
/// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation
/// Also because x is converted to an unsigned 129.127-binary fixed-point number during the operation to optimize the multiplication
/// @param x The unsigned 128.128-binary fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a signed 128.128-binary fixed-point number.
function log2(uint256 x) internal pure returns (int256 result) {
// Convert x to a unsigned 129.127-binary fixed-point number to optimize the multiplication.
// If we use an offset of 128 bits, y would need 129 bits and y**2 would would overflow and we would have to
// use mulDiv, by reducing x to 129.127-binary fixed-point number we assert that y will use 128 bits, and we
// can use the regular multiplication
if (x == 1) return -128;
if (x == 0) revert Uint128x128Math__LogUnderflow();
x >>= 1;
unchecked {
// This works because log2(x) = -log2(1/x).
int256 sign;
if (x >= LOG_SCALE) {
sign = 1;
} else {
sign = -1;
// Do the fixed-point inversion inline to save gas
x = LOG_SCALE_SQUARED / x;
}
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = (x >> LOG_SCALE_OFFSET).mostSignificantBit();
// The integer part of the logarithm as a signed 129.127-binary fixed-point number. The operation can't overflow
// because n is maximum 255, LOG_SCALE_OFFSET is 127 bits and sign is either 1 or -1.
result = int256(n) << LOG_SCALE_OFFSET;
// This is y = x * 2^(-n).
uint256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y != LOG_SCALE) {
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (int256 delta = int256(1 << (LOG_SCALE_OFFSET - 1)); delta > 0; delta >>= 1) {
y = (y * y) >> LOG_SCALE_OFFSET;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 1 << (LOG_SCALE_OFFSET + 1)) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
}
// Convert x back to unsigned 128.128-binary fixed-point number
result = (result * sign) << 1;
}
}
/// @notice Returns the value of x^y. It calculates `1 / x^abs(y)` if x is bigger than 2^128.
/// At the end of the operations, we invert the result if needed.
/// @param x The unsigned 128.128-binary fixed-point number for which to calculate the power
/// @param y A relative number without any decimals, needs to be between ]2^21; 2^21[
function pow(uint256 x, int256 y) internal pure returns (uint256 result) {
bool invert;
uint256 absY;
if (y == 0) return Constants.SCALE;
assembly ("memory-safe") {
absY := y
if slt(absY, 0) {
absY := sub(0, absY)
invert := iszero(invert)
}
}
if (absY < 0x100000) {
result = Constants.SCALE;
assembly ("memory-safe") {
let squared := x
if gt(x, 0xffffffffffffffffffffffffffffffff) {
squared := div(not(0), squared)
invert := iszero(invert)
}
if and(absY, 0x1) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x2) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x4) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x8) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x10) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x20) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x40) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x80) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x100) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x200) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x400) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x800) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x1000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x2000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x4000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x8000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x10000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x20000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x40000) { result := shr(128, mul(result, squared)) }
squared := shr(128, mul(squared, squared))
if and(absY, 0x80000) { result := shr(128, mul(result, squared)) }
}
}
// revert if y is too big or if x^y underflowed
if (result == 0) revert Uint128x128Math__PowUnderflow(x, y);
return invert ? type(uint256).max / result : result;
}
}
src/pool-bin/libraries/math/Uint256x256Math.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Helper contract used for full precision calculations
library Uint256x256Math {
error Uint256x256Math__MulShiftOverflow();
error Uint256x256Math__MulDivOverflow();
/// @notice Calculates floor(x*y/denominator) with full precision
/// The result will be rounded down
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The denominator cannot be zero
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @param denominator The divisor as an uint256
/// @return result The result as an uint256
function mulDivRoundDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
(uint256 prod0, uint256 prod1) = _getMulProds(x, y);
return _getEndOfDivRoundDown(x, y, denominator, prod0, prod1);
}
/// @notice Calculates ceil(x*y/denominator) with full precision
/// The result will be rounded up
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The denominator cannot be zero
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @param denominator The divisor as an uint256
/// @return result The result as an uint256
function mulDivRoundUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
result = mulDivRoundDown(x, y, denominator);
if (mulmod(x, y, denominator) != 0) result += 1;
}
/// @notice Calculates floor(x * y / 2**offset) with full precision
/// The result will be rounded down
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The offset needs to be strictly lower than 256
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @param offset The offset as an uint256, can't be greater than 256
/// @return result The result as an uint256
function mulShiftRoundDown(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
(uint256 prod0, uint256 prod1) = _getMulProds(x, y);
if (prod0 != 0) result = prod0 >> offset;
if (prod1 != 0) {
// Make sure the result is less than 2^256.
if (prod1 >= 1 << offset) revert Uint256x256Math__MulShiftOverflow();
unchecked {
result += prod1 << (256 - offset);
}
}
}
/// @notice Calculates floor(x * y / 2**offset) with full precision
/// The result will be rounded down
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The offset needs to be strictly lower than 256
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @param offset The offset as an uint256, can't be greater than 256
/// @return result The result as an uint256
function mulShiftRoundUp(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
result = mulShiftRoundDown(x, y, offset);
if (mulmod(x, y, 1 << offset) != 0) result += 1;
}
/// @notice Calculates floor(x << offset / y) with full precision
/// The result will be rounded down
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The offset needs to be strictly lower than 256
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param offset The number of bit to shift x as an uint256
/// @param denominator The divisor as an uint256
/// @return result The result as an uint256
function shiftDivRoundDown(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
prod0 = x << offset; // Least significant 256 bits of the product
unchecked {
prod1 = x >> (256 - offset); // Most significant 256 bits of the product
}
return _getEndOfDivRoundDown(x, 1 << offset, denominator, prod0, prod1);
}
/// @notice Calculates ceil(x << offset / y) with full precision
/// The result will be rounded up
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
/// Requirements:
/// - The offset needs to be strictly lower than 256
/// - The result must fit within uint256
/// Caveats:
/// - This function does not work with fixed-point numbers
/// @param x The multiplicand as an uint256
/// @param offset The number of bit to shift x as an uint256
/// @param denominator The divisor as an uint256
/// @return result The result as an uint256
function shiftDivRoundUp(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
result = shiftDivRoundDown(x, offset, denominator);
if (mulmod(x, 1 << offset, denominator) != 0) result += 1;
}
/// @notice Helper function to return the result of `x * y` as 2 uint256
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @return prod0 The least significant 256 bits of the product
/// @return prod1 The most significant 256 bits of the product
function _getMulProds(uint256 x, uint256 y) private pure returns (uint256 prod0, uint256 prod1) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
}
/// @notice Helper function to return the result of `x * y / denominator` with full precision
/// @param x The multiplicand as an uint256
/// @param y The multiplier as an uint256
/// @param denominator The divisor as an uint256
/// @param prod0 The least significant 256 bits of the product
/// @param prod1 The most significant 256 bits of the product
/// @return result The result as an uint256
function _getEndOfDivRoundDown(uint256 x, uint256 y, uint256 denominator, uint256 prod0, uint256 prod1)
private
pure
returns (uint256 result)
{
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
} else {
// Make sure the result is less than 2^256. Also prevents denominator == 0
if (prod1 >= denominator) revert Uint256x256Math__MulDivOverflow();
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1
// See https://cs.stackexchange.com/q/138556/92363
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function
uint256 lpotdod = denominator & (~denominator + 1);
assembly ("memory-safe") {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0
prod0 |= prod1 * lpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
}
}
}
}
src/pool-bin/types/BinSlot0.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev BinSlot0 is a packed version of solidity structure.
* Using the packaged version saves gas by not storing the structure fields in memory slots.
*
* Layout:
* 184 bits empty | 24 bits lpFee | 12 bits protocolFee 1->0 | 12 bits protocolFee 0->1 | 24 bits activeId
*
* Fields in the direction from the least significant bit:
*
* The current activeId
* uint24 activeId;
*
* Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1
* the maximum is 1000 - meaning the maximum protocol fee is 0.1%
* the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
* uint24 protocolFee;
*
* The current LP fee of the pool. If the pool is dynamic, this does not include the dynamic fee flag.
* uint24 lpFee;
*/
type BinSlot0 is bytes32;
using BinSlot0Library for BinSlot0 global;
/// @notice Library for getting and setting values in the Slot0 type
library BinSlot0Library {
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint8 internal constant PROTOCOL_FEE_OFFSET = 24;
uint8 internal constant LP_FEE_OFFSET = 48;
////////////////////////////////////////////////////////////////////////////////////////
// #### GETTERS ####
////////////////////////////////////////////////////////////////////////////////////////
function activeId(BinSlot0 _packed) internal pure returns (uint24 _activeId) {
assembly ("memory-safe") {
_activeId := and(MASK_24_BITS, _packed)
}
}
function protocolFee(BinSlot0 _packed) internal pure returns (uint24 _protocolFee) {
assembly ("memory-safe") {
_protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed))
}
}
function lpFee(BinSlot0 _packed) internal pure returns (uint24 _lpFee) {
assembly ("memory-safe") {
_lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed))
}
}
////////////////////////////////////////////////////////////////////////////////////////
// #### SETTERS ####
////////////////////////////////////////////////////////////////////////////////////////
function setActiveId(BinSlot0 _packed, uint24 _activeId) internal pure returns (BinSlot0 _result) {
assembly ("memory-safe") {
_result := or(and(not(MASK_24_BITS), _packed), and(MASK_24_BITS, _activeId))
}
}
function setProtocolFee(BinSlot0 _packed, uint24 _protocolFee) internal pure returns (BinSlot0 _result) {
assembly ("memory-safe") {
_result :=
or(
and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed),
shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee))
)
}
}
function setLpFee(BinSlot0 _packed, uint24 _lpFee) internal pure returns (BinSlot0 _result) {
assembly ("memory-safe") {
_result :=
or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee)))
}
}
}
src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice Constant for a BalanceDelta of zero value
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
src/types/BeforeSwapDelta.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice Constant for a BeforeSwapDelta of zero value
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// @notice extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// @param delta The BeforeSwapDelta returned by beforeSwap
/// @return deltaSpecified The delta in specified tokens
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// @notice extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// @param delta The BeforeSwapDelta returned by beforeSwap
/// @return deltaUnspecified The delta in unspecified tokens
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
src/types/Currency.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
using CurrencyLibrary for Currency;
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant NATIVE = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isNative()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isNative()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isNative()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isNative(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(NATIVE);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
src/types/PoolId.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xc0 represents the total size of the poolKey struct (6 slots of 32 bytes)
poolId := keccak256(poolKey, 0xc0)
}
}
}
src/types/PoolKey.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The hooks of the pool, won't have a general interface because hooks interface vary on pool type
IHooks hooks;
/// @notice The pool manager of the pool
IPoolManager poolManager;
/// @notice The pool lp fee, capped at 1_000_000. If the pool has a dynamic fee then it must be exactly equal to 0x800000
uint24 fee;
/// @notice Hooks callback and pool specific parameters, i.e. tickSpacing for CL, binStep for bin
bytes32 parameters;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 25666,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-gas-snapshot/=lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"solmate/=lib/solmate/",
"squadswap-create3-factory/=lib/pancake-create3-factory/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"pancake-create3-factory/=lib/pancake-create3-factory/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.