Verified contractPartialGPL-2.0-or-later
BinPositionManager
Address0x97c4e1880213415f1918afcdee4a56ec92d08773
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1,000,000 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,348,560
- Creation transaction
- 0x3874f88602…3c22947c83
65 files
- src/pool-bin/BinPositionManager.solmain18.95 KB
- ../squadswap-v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- ../squadswap-v4-core/src/interfaces/IERC20Minimal.sol3.03 KB
- ../squadswap-v4-core/src/interfaces/IExtsload.sol593 B
- ../squadswap-v4-core/src/interfaces/IHooks.sol151 B
- ../squadswap-v4-core/src/interfaces/ILockCallback.sol465 B
- ../squadswap-v4-core/src/interfaces/IPoolManager.sol1.77 KB
- ../squadswap-v4-core/src/interfaces/IProtocolFeeController.sol836 B
- ../squadswap-v4-core/src/interfaces/IProtocolFees.sol3.08 KB
- ../squadswap-v4-core/src/interfaces/IVault.sol7.01 KB
- ../squadswap-v4-core/src/interfaces/IVaultToken.sol2.92 KB
- ../squadswap-v4-core/src/libraries/CustomRevert.sol2.36 KB
- ../squadswap-v4-core/src/libraries/LPFeeLibrary.sol3.82 KB
- ../squadswap-v4-core/src/libraries/ProtocolFeeLibrary.sol2.92 KB
- ../squadswap-v4-core/src/libraries/SafeCast.sol2.09 KB
- ../squadswap-v4-core/src/libraries/math/Encoded.sol3.98 KB
- ../squadswap-v4-core/src/libraries/math/UnsafeMath.sol1.24 KB
- ../squadswap-v4-core/src/pool-bin/interfaces/IBinPoolManager.sol10.95 KB
- ../squadswap-v4-core/src/pool-bin/libraries/BinHelper.sol14.15 KB
- ../squadswap-v4-core/src/pool-bin/libraries/BinPool.sol22.74 KB
- ../squadswap-v4-core/src/pool-bin/libraries/BinPoolParametersHelper.sol1.41 KB
- ../squadswap-v4-core/src/pool-bin/libraries/BinPosition.sol2.33 KB
- ../squadswap-v4-core/src/pool-bin/libraries/Constants.sol672 B
- ../squadswap-v4-core/src/pool-bin/libraries/FeeHelper.sol2.52 KB
- ../squadswap-v4-core/src/pool-bin/libraries/PriceHelper.sol2.96 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/BitMath.sol4.01 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/LiquidityConfigurations.sol3.53 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/PackedUint128Math.sol8.95 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/SafeCast.sol9.54 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/TreeMath.sol7.58 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/Uint128x128Math.sol7.75 KB
- ../squadswap-v4-core/src/pool-bin/libraries/math/Uint256x256Math.sol10.57 KB
- ../squadswap-v4-core/src/pool-bin/types/BinSlot0.sol3.14 KB
- ../squadswap-v4-core/src/types/BalanceDelta.sol2.36 KB
- ../squadswap-v4-core/src/types/Currency.sol5.29 KB
- ../squadswap-v4-core/src/types/PoolId.sol468 B
- ../squadswap-v4-core/src/types/PoolKey.sol1.02 KB
- lib/permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- lib/permit2/src/interfaces/IEIP712.sol145 B
- src/base/BaseActionsRouter.sol3.58 KB
- src/base/DeltaResolver.sol5.75 KB
- src/base/ImmutableState.sol576 B
- src/base/Multicall.sol966 B
- src/base/NativeWrapper.sol1.22 KB
- src/base/Permit2Forwarder.sol2.15 KB
- src/base/ReentrancyLock.sol978 B
- src/base/SafeCallback.sol1.38 KB
- src/interfaces/IImmutableState.sol351 B
- src/interfaces/IMulticall.sol803 B
- src/interfaces/IPositionManager.sol1.61 KB
- src/interfaces/ISquadSwapV4Router.sol1.08 KB
- src/interfaces/external/IWETH9.sol409 B
- src/libraries/ActionConstants.sol1.12 KB
- src/libraries/Actions.sol2.7 KB
- src/libraries/CalldataDecoder.sol9.96 KB
- src/libraries/PathKey.sol1.59 KB
- src/libraries/SafeCast.sol1.31 KB
- src/libraries/SlippageCheck.sol3.75 KB
- src/pool-bin/BinFungibleToken.sol4.82 KB
- src/pool-bin/interfaces/IBinFungibleToken.sol2.68 KB
- src/pool-bin/interfaces/IBinPositionManager.sol4.59 KB
- src/pool-bin/interfaces/IBinRouterBase.sol1.04 KB
- src/pool-bin/libraries/BinCalldataDecoder.sol5.51 KB
- src/pool-bin/libraries/BinTokenLibrary.sol468 B
- src/pool-cl/interfaces/ICLRouterBase.sol1.29 KB
src/pool-bin/BinPositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity 0.8.26;
import {IVault} from "squadswap-v4-core/src/interfaces/IVault.sol";
import {BalanceDelta} from "squadswap-v4-core/src/types/BalanceDelta.sol";
import {
Currency,
CurrencyLibrary
} from "squadswap-v4-core/src/types/Currency.sol";
import {
IBinPoolManager
} from "squadswap-v4-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {BinPool} from "squadswap-v4-core/src/pool-bin/libraries/BinPool.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {PoolId} from "squadswap-v4-core/src/types/PoolId.sol";
import {
LiquidityConfigurations
} from "squadswap-v4-core/src/pool-bin/libraries/math/LiquidityConfigurations.sol";
import {
BinPoolParametersHelper
} from "squadswap-v4-core/src/pool-bin/libraries/BinPoolParametersHelper.sol";
import {
PackedUint128Math
} from "squadswap-v4-core/src/pool-bin/libraries/math/PackedUint128Math.sol";
import {
IAllowanceTransfer
} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {SafeCastTemp} from "../libraries/SafeCast.sol";
import {BaseActionsRouter} from "../base/BaseActionsRouter.sol";
import {ReentrancyLock} from "../base/ReentrancyLock.sol";
import {DeltaResolver} from "../base/DeltaResolver.sol";
import {Permit2Forwarder} from "../base/Permit2Forwarder.sol";
import {IPositionManager} from "../interfaces/IPositionManager.sol";
import {IBinPositionManager} from "./interfaces/IBinPositionManager.sol";
import {CalldataDecoder} from "../libraries/CalldataDecoder.sol";
import {Actions} from "../libraries/Actions.sol";
import {BinCalldataDecoder} from "./libraries/BinCalldataDecoder.sol";
import {BinFungibleToken} from "./BinFungibleToken.sol";
import {BinTokenLibrary} from "./libraries/BinTokenLibrary.sol";
import {Multicall} from "../base/Multicall.sol";
import {SlippageCheck} from "../libraries/SlippageCheck.sol";
import {NativeWrapper} from "../base/NativeWrapper.sol";
import {IWETH9} from "../interfaces/external/IWETH9.sol";
/// @title BinPositionManager
/// @notice Contract for modifying liquidity for SS squadswap Bin pools
contract BinPositionManager is
IBinPositionManager,
BinFungibleToken,
DeltaResolver,
ReentrancyLock,
BaseActionsRouter,
Permit2Forwarder,
Multicall,
NativeWrapper
{
using CalldataDecoder for bytes;
using PackedUint128Math for uint128;
using PackedUint128Math for bytes32;
using BinCalldataDecoder for bytes;
using BinTokenLibrary for PoolId;
using BinPoolParametersHelper for bytes32;
using SlippageCheck for BalanceDelta;
using SafeCastTemp for uint256;
IBinPoolManager public immutable override binPoolManager;
struct TokenPosition {
PoolId poolId;
uint24 binId;
}
/// @dev tokenId => TokenPosition
mapping(uint256 => TokenPosition) private _positions;
/// @dev poolId => poolKey
mapping(bytes32 => PoolKey) private _poolIdToPoolKey;
constructor(
IVault _vault,
IBinPoolManager _binPoolManager,
IAllowanceTransfer _permit2,
IWETH9 _weth9
)
BaseActionsRouter(_vault)
Permit2Forwarder(_permit2)
NativeWrapper(_weth9)
{
binPoolManager = _binPoolManager;
}
/// @notice Reverts if the deadline has passed
/// @param deadline The timestamp at which the call is no longer valid, passed in by the caller
modifier checkDeadline(uint256 deadline) {
if (block.timestamp > deadline) revert DeadlinePassed(deadline);
_;
}
/// @notice Enforces that the vault is unlocked.
modifier onlyIfVaultUnlocked() override {
if (vault.getLocker() != address(0)) revert VaultMustBeUnlocked();
_;
}
/// @inheritdoc IBinPositionManager
function positions(
uint256 tokenId
) external view returns (PoolKey memory, uint24) {
TokenPosition memory position = _positions[tokenId];
if (PoolId.unwrap(position.poolId) == 0) revert InvalidTokenID();
PoolKey memory poolKey = _poolIdToPoolKey[
PoolId.unwrap(position.poolId)
];
return (poolKey, position.binId);
}
/// @inheritdoc IPositionManager
function modifyLiquidities(
bytes calldata payload,
uint256 deadline
) external payable override isNotLocked checkDeadline(deadline) {
_executeActions(payload);
}
/// @inheritdoc IPositionManager
function modifyLiquiditiesWithoutLock(
bytes calldata actions,
bytes[] calldata params
) external payable override isNotLocked {
_executeActionsWithoutLock(actions, params);
}
/// @inheritdoc IBinPositionManager
function initializePool(
PoolKey memory key,
uint24 activeId
) external payable {
/// @dev if the pool revert due to other error (currencyOutOfOrder etc..), then the follow-up action to the pool will still revert accordingly
try binPoolManager.initialize(key, activeId) {} catch {}
}
function msgSender() public view override returns (address) {
return _getLocker();
}
function _handleAction(
uint256 action,
bytes calldata params
) internal virtual override {
if (action > Actions.BURN_6909) {
if (action == Actions.BIN_ADD_LIQUIDITY) {
IBinPositionManager.BinAddLiquidityParams
calldata liquidityParams = params
.decodeBinAddLiquidityParams();
_addLiquidity(
liquidityParams.poolKey,
liquidityParams.amount0.encode(liquidityParams.amount1),
liquidityParams.amount0Max.encode(
liquidityParams.amount1Max
),
liquidityParams.activeIdDesired,
liquidityParams.idSlippage,
liquidityParams.deltaIds,
liquidityParams.distributionX,
liquidityParams.distributionY,
liquidityParams.minLiquidities,
_mapRecipient(liquidityParams.to),
liquidityParams.hookData
);
return;
} else if (action == Actions.BIN_ADD_LIQUIDITY_FROM_DELTAS) {
IBinPositionManager.BinAddLiquidityFromDeltasParams
calldata liquidityParams = params
.decodeBinAddLiquidityFromDeltasParams();
_addLiquidity(
liquidityParams.poolKey,
_getFullCredit(liquidityParams.poolKey.currency0)
.toUint128()
.encode(
_getFullCredit(
liquidityParams.poolKey.currency1
)
.toUint128()
),
liquidityParams.amount0Max.encode(
liquidityParams.amount1Max
),
liquidityParams.activeIdDesired,
liquidityParams.idSlippage,
liquidityParams.deltaIds,
liquidityParams.distributionX,
liquidityParams.distributionY,
liquidityParams.minLiquidities,
_mapRecipient(liquidityParams.to),
liquidityParams.hookData
);
return;
} else if (action == Actions.BIN_REMOVE_LIQUIDITY) {
IBinPositionManager.BinRemoveLiquidityParams
calldata liquidityParams = params
.decodeBinRemoveLiquidityParams();
_removeLiquidity(liquidityParams);
return;
}
} else {
if (action == Actions.SETTLE_PAIR) {
(Currency currency0, Currency currency1) = params
.decodeCurrencyPair();
_settlePair(currency0, currency1);
return;
} else if (action == Actions.TAKE_PAIR) {
(
Currency currency0,
Currency currency1,
address recipient
) = params.decodeCurrencyPairAndAddress();
_takePair(currency0, currency1, _mapRecipient(recipient));
return;
} else if (action == Actions.SETTLE) {
(Currency currency, uint256 amount, bool payerIsUser) = params
.decodeCurrencyUint256AndBool();
_settle(
currency,
_mapPayer(payerIsUser),
_mapSettleAmount(amount, currency)
);
return;
} else if (action == Actions.TAKE) {
(Currency currency, address recipient, uint256 amount) = params
.decodeCurrencyAddressAndUint256();
_take(
currency,
_mapRecipient(recipient),
_mapTakeAmount(amount, currency)
);
return;
} else if (action == Actions.CLOSE_CURRENCY) {
Currency currency = params.decodeCurrency();
_close(currency);
return;
} else if (action == Actions.CLEAR_OR_TAKE) {
(Currency currency, uint256 amountMax) = params
.decodeCurrencyAndUint256();
_clearOrTake(currency, amountMax);
return;
} else if (action == Actions.SWEEP) {
(Currency currency, address to) = params
.decodeCurrencyAndAddress();
_sweep(currency, _mapRecipient(to));
return;
} else if (action == Actions.WRAP) {
uint256 amount = params.decodeUint256();
_wrap(
_mapWrapUnwrapAmount(
CurrencyLibrary.NATIVE,
amount,
Currency.wrap(address(WETH9))
)
);
return;
} else if (action == Actions.UNWRAP) {
uint256 amount = params.decodeUint256();
_unwrap(
_mapWrapUnwrapAmount(
Currency.wrap(address(WETH9)),
amount,
CurrencyLibrary.NATIVE
)
);
return;
}
}
revert UnsupportedAction(action);
}
/// @dev Store poolKey in mapping for lookup
function cachePoolKey(
PoolKey memory poolKey
) internal returns (PoolId poolId) {
poolId = poolKey.toId();
if (
_poolIdToPoolKey[PoolId.unwrap(poolId)].parameters.getBinStep() == 0
) {
_poolIdToPoolKey[PoolId.unwrap(poolId)] = poolKey;
}
}
/// @param amountIn packed (amount0, amount1) to add, see PackedUint128Math
/// @param amountsMax packed (amount0Max, amount1Max) slippage cap on token input, see PackedUint128Math
function _addLiquidity(
PoolKey calldata poolKey,
bytes32 amountIn,
bytes32 amountsMax,
uint256 activeIdDesired,
uint256 idSlippage,
int256[] calldata deltaIds,
uint256[] calldata distributionX,
uint256[] calldata distributionY,
uint256[] calldata minLiquidities,
address to,
bytes calldata hookData
) internal {
uint256 deltaLen = deltaIds.length;
uint256 lenX = distributionX.length;
uint256 lenY = distributionY.length;
uint256 lenMin = minLiquidities.length;
assembly ("memory-safe") {
/// @dev revert if deltaLen != lenX || deltaLen != lenY || deltaLen != lenMin
if iszero(
and(
and(eq(deltaLen, lenX), eq(deltaLen, lenY)),
eq(deltaLen, lenMin)
)
) {
mstore(0, 0xaaad13f7) // selector InputLengthMismatch
revert(0x1c, 0x04)
}
}
if (
activeIdDesired > type(uint24).max || idSlippage > type(uint24).max
) {
revert AddLiquidityInputActiveIdMismatch();
}
/// @dev Checks if the activeId is within slippage before calling mint. If user mint to activeId and there
// was a swap in hook.beforeMint() which changes the activeId, user txn will fail
(uint24 activeId, , ) = binPoolManager.getSlot0(poolKey.toId());
if (activeIdDesired + idSlippage < activeId) {
revert IdSlippageCaught(activeIdDesired, idSlippage, activeId);
}
if (activeIdDesired - idSlippage > activeId) {
revert IdSlippageCaught(activeIdDesired, idSlippage, activeId);
}
bytes32[] memory liquidityConfigs = new bytes32[](deltaLen);
for (uint256 i; i < liquidityConfigs.length; i++) {
int256 _id = int256(uint256(activeId)) + deltaIds[i];
if (_id < 0 || uint256(_id) > type(uint24).max)
revert IdOverflows(_id);
liquidityConfigs[i] = LiquidityConfigurations.encodeParams(
uint64(distributionX[i]),
uint64(distributionY[i]),
uint24(uint256(_id))
);
}
(
BalanceDelta delta,
BinPool.MintArrays memory mintArray
) = binPoolManager.mint(
poolKey,
IBinPoolManager.MintParams({
liquidityConfigs: liquidityConfigs,
amountIn: amountIn,
salt: bytes32(0)
}),
hookData
);
/// Slippage checks, similar to CL type. However, this is different from TJ. In SS squadswap,
/// as hooks can impact delta (take extra token), user need to be protected with amountMax instead
(uint128 amount0Max, uint128 amount1Max) = amountsMax.decode();
delta.validateMaxIn(amount0Max, amount1Max);
// mint
PoolId poolId = cachePoolKey(poolKey);
uint256[] memory tokenIds = new uint256[](mintArray.ids.length);
for (uint256 i; i < mintArray.ids.length; i++) {
if (mintArray.liquidityMinted[i] < minLiquidities[i]) {
revert LiquiditySlippageCaught(
uint24(mintArray.ids[i]),
minLiquidities[i],
mintArray.liquidityMinted[i]
);
}
uint256 tokenId = poolId.toTokenId(mintArray.ids[i]);
_mint(to, tokenId, mintArray.liquidityMinted[i]);
if (_positions[tokenId].binId == 0) {
_positions[tokenId] = TokenPosition({
poolId: poolId,
binId: uint24(mintArray.ids[i])
});
}
tokenIds[i] = tokenId;
}
emit TransferBatch(
msgSender(),
address(0),
to,
tokenIds,
mintArray.liquidityMinted
);
}
function _removeLiquidity(
IBinPositionManager.BinRemoveLiquidityParams calldata params
) internal checkApproval(params.from, msgSender()) {
if (params.ids.length != params.amounts.length)
revert InputLengthMismatch();
BalanceDelta delta = binPoolManager.burn(
params.poolKey,
IBinPoolManager.BurnParams({
ids: params.ids,
amountsToBurn: params.amounts,
salt: bytes32(0)
}),
params.hookData
);
// Slippage checks, similar to CL type, if delta is negative, it will revert.
delta.validateMinOut(params.amount0Min, params.amount1Min);
PoolId poolId = params.poolKey.toId();
uint256[] memory tokenIds = new uint256[](params.ids.length);
for (uint256 i; i < params.ids.length; i++) {
uint256 tokenId = poolId.toTokenId(params.ids[i]);
_burn(params.from, tokenId, params.amounts[i]);
tokenIds[i] = tokenId;
}
emit TransferBatch(
msgSender(),
params.from,
address(0),
tokenIds,
params.amounts
);
}
function _settlePair(Currency currency0, Currency currency1) internal {
// the locker is the payer when settling
address caller = msgSender();
_settle(currency0, caller, _getFullDebt(currency0));
_settle(currency1, caller, _getFullDebt(currency1));
}
function _takePair(
Currency currency0,
Currency currency1,
address recipient
) internal {
_take(currency0, recipient, _getFullCredit(currency0));
_take(currency1, recipient, _getFullCredit(currency1));
}
function _close(Currency currency) internal {
// this address has applied all deltas on behalf of the user/owner
// it is safe to close this entire delta because of slippage checks throughout the batched calls.
int256 currencyDelta = vault.currencyDelta(address(this), currency);
// the locker is the payer or receiver
address caller = msgSender();
if (currencyDelta < 0) {
_settle(currency, caller, uint256(-currencyDelta));
} else {
_take(currency, caller, uint256(currencyDelta));
}
}
/// @dev integrators may elect to forfeit positive deltas with clear
/// if the forfeit amount exceeds the user-specified max, the amount is taken instead
function _clearOrTake(Currency currency, uint256 amountMax) internal {
uint256 delta = _getFullCredit(currency);
// forfeit the delta if its less than or equal to the user-specified limit
if (delta <= amountMax) {
vault.clear(currency, delta);
} else {
_take(currency, msgSender(), delta);
}
}
/// @notice Sweeps the entire contract balance of specified currency to the recipient
function _sweep(Currency currency, address to) internal {
uint256 balance = currency.balanceOfSelf();
if (balance > 0) currency.transfer(to, balance);
}
function _pay(
Currency currency,
address payer,
uint256 amount
) internal override(DeltaResolver) {
if (payer == address(this)) {
currency.transfer(address(vault), amount);
} else {
permit2.transferFrom(
payer,
address(vault),
uint160(amount),
Currency.unwrap(currency)
);
}
}
}
../squadswap-v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
../squadswap-v4-core/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);
}
../squadswap-v4-core/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);
}
../squadswap-v4-core/src/interfaces/IHooks.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IHooks {
function getHooksRegistrationBitmap() external view returns (uint16);
}
../squadswap-v4-core/src/interfaces/ILockCallback.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address locks the vault
interface ILockCallback {
/// @notice Called by the pool manager on `msg.sender` when a lock is acquired
/// @param data The data that was passed to the call to lock
/// @return Any data that you want to be returned from the lock call
function lockAcquired(bytes calldata data) external returns (bytes memory);
}
../squadswap-v4-core/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
);
}
../squadswap-v4-core/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);
}
../squadswap-v4-core/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);
}
../squadswap-v4-core/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;
}
../squadswap-v4-core/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);
}
../squadswap-v4-core/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))
}
}
}
../squadswap-v4-core/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;
}
}
../squadswap-v4-core/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))
}
}
}
../squadswap-v4-core/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));
}
}
../squadswap-v4-core/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)
}
}
}
../squadswap-v4-core/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)
}
}
}
../squadswap-v4-core/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;
}
../squadswap-v4-core/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());
}
}
../squadswap-v4-core/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)
}
}
}
}
../squadswap-v4-core/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);
}
}
../squadswap-v4-core/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;
}
}
../squadswap-v4-core/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;
}
../squadswap-v4-core/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);
}
}
}
../squadswap-v4-core/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);
}
}
../squadswap-v4-core/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)
}
}
}
../squadswap-v4-core/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);
}
}
../squadswap-v4-core/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);
}
}
../squadswap-v4-core/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);
}
}
../squadswap-v4-core/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);
}
}
}
../squadswap-v4-core/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;
}
}
../squadswap-v4-core/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;
}
}
}
}
../squadswap-v4-core/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)))
}
}
}
../squadswap-v4-core/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)
}
}
}
../squadswap-v4-core/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)));
}
}
../squadswap-v4-core/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)
}
}
}
../squadswap-v4-core/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;
}
lib/permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allownce
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
lib/permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
src/base/BaseActionsRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.24;
import {IVault} from "squadswap-v4-core/src/interfaces/IVault.sol";
import {SafeCallback} from "./SafeCallback.sol";
import {CalldataDecoder} from "../libraries/CalldataDecoder.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";
/// @notice Abstract contract for performing a combination of actions on SquadSwapswap squadswap.
/// @dev Suggested uint256 action values are defined in Actions.sol, however any definition can be used
abstract contract BaseActionsRouter is SafeCallback {
using CalldataDecoder for bytes;
/// @notice emitted when different numbers of parameters and actions are provided
error InputLengthMismatch();
/// @notice emitted when an inheriting contract does not support an action
error UnsupportedAction(uint256 action);
constructor(IVault _vault) SafeCallback(_vault) {}
/// @notice internal function that triggers the execution of a set of actions on squadswap
/// @dev inheriting contracts should call this function to trigger execution
function _executeActions(bytes calldata data) internal {
vault.lock(data);
}
/// @notice function that is called by the Vault through the SafeCallback.lockAcquired
/// @param data Abi encoding of (bytes actions, bytes[] params)
/// where params[i] is the encoded parameters for actions[i]
function _lockAcquired(
bytes calldata data
) internal override returns (bytes memory) {
// abi.decode(data, (bytes, bytes[]));
(bytes calldata actions, bytes[] calldata params) = data
.decodeActionsRouterParams();
_executeActionsWithoutLock(actions, params);
return "";
}
function _executeActionsWithoutLock(
bytes calldata actions,
bytes[] calldata params
) internal {
uint256 numActions = actions.length;
if (numActions != params.length) revert InputLengthMismatch();
for (uint256 actionIndex = 0; actionIndex < numActions; actionIndex++) {
uint256 action = uint8(actions[actionIndex]);
_handleAction(action, params[actionIndex]);
}
}
/// @notice function to handle the parsing and execution of an action and its parameters
function _handleAction(
uint256 action,
bytes calldata params
) internal virtual;
/// @notice function that returns address considered executor of the actions
/// @dev The other context functions, _msgData and _msgValue, are not supported by this contract
/// In many contracts this will be the address that calls the initial entry point that calls `_executeActions`
/// `msg.sender` shouldn't be used, as this will be the vault contract that calls `lockAcquired`
/// If using ReentrancyLock.sol, this function can return _getLocker()
function msgSender() public view virtual returns (address);
/// @notice Calculates the address for a action
function _mapRecipient(address recipient) internal view returns (address) {
if (recipient == ActionConstants.MSG_SENDER) {
return msgSender();
} else if (recipient == ActionConstants.ADDRESS_THIS) {
return address(this);
} else {
return recipient;
}
}
/// @notice Calculates the payer for an action
function _mapPayer(bool payerIsUser) internal view returns (address) {
return payerIsUser ? msgSender() : address(this);
}
}
src/base/DeltaResolver.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.24;
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {ImmutableState} from "./ImmutableState.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";
/// @notice Abstract contract used to sync, send, and settle funds to the vault
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
abstract contract DeltaResolver is ImmutableState {
/// @notice Emitted trying to settle a positive delta.
error DeltaNotPositive(Currency currency);
/// @notice Emitted trying to take a negative delta.
error DeltaNotNegative(Currency currency);
/// @notice Emitted when the contract does not have enough balance to wrap or unwrap.
error InsufficientBalance();
/// @notice Take an amount of currency out of the vault
/// @param currency Currency to take
/// @param recipient Address to receive the currency
/// @param amount Amount to take
/// @dev Returns early if the amount is 0
function _take(
Currency currency,
address recipient,
uint256 amount
) internal {
if (amount == 0) return;
vault.take(currency, recipient, amount);
}
/// @notice Pay and settle a currency to the vault
/// @dev The implementing contract must ensure that the `payer` is a secure address
/// @param currency Currency to settle
/// @param payer Address of the payer
/// @param amount Amount to send
/// @dev Returns early if the amount is 0
function _settle(
Currency currency,
address payer,
uint256 amount
) internal {
if (amount == 0) return;
vault.sync(currency);
if (currency.isNative()) {
vault.settle{value: amount}();
} else {
_pay(currency, payer, amount);
vault.settle();
}
}
/// @notice Abstract function for contracts to implement paying tokens to the vault
/// @dev The recipient of the payment should be the vault
/// @param token The token to settle. This is known not to be the native currency
/// @param payer The address who should pay tokens
/// @param amount The number of tokens to send
function _pay(
Currency token,
address payer,
uint256 amount
) internal virtual;
/// @notice Obtain the full amount owed by this contract (negative delta)
/// @param currency Currency to get the delta for
/// @return amount The amount owed by this contract as a uint256
function _getFullDebt(
Currency currency
) internal view returns (uint256 amount) {
int256 _amount = vault.currencyDelta(address(this), currency);
// If the amount is positive, it should be taken not settled.
if (_amount > 0) revert DeltaNotNegative(currency);
// Casting is safe due to limits on the total supply of a pool
amount = uint256(-_amount);
}
/// @notice Obtain the full credit owed to this contract (positive delta)
/// @param currency Currency to get the delta for
/// @return amount The amount owed to this contract as a uint256
function _getFullCredit(
Currency currency
) internal view returns (uint256 amount) {
int256 _amount = vault.currencyDelta(address(this), currency);
// If the amount is negative, it should be settled not taken.
if (_amount < 0) revert DeltaNotPositive(currency);
amount = uint256(_amount);
}
/// @notice Calculates the amount for a settle action
function _mapSettleAmount(
uint256 amount,
Currency currency
) internal view returns (uint256) {
if (amount == ActionConstants.CONTRACT_BALANCE) {
return currency.balanceOfSelf();
} else if (amount == ActionConstants.OPEN_DELTA) {
return _getFullDebt(currency);
} else {
return amount;
}
}
/// @notice Calculates the amount for a take action
function _mapTakeAmount(
uint256 amount,
Currency currency
) internal view returns (uint256) {
if (amount == ActionConstants.OPEN_DELTA) {
return _getFullCredit(currency);
} else {
return amount;
}
}
/// @notice Calculates the sanitized amount before wrapping/unwrapping.
/// @param inputCurrency The currency, either native or wrapped native, that this contract holds
/// @param amount The amount to wrap or unwrap. Can be CONTRACT_BALANCE, OPEN_DELTA or a specific amount
/// @param outputCurrency The currency after the wrap/unwrap that the user may owe a balance in on the poolManager
function _mapWrapUnwrapAmount(
Currency inputCurrency,
uint256 amount,
Currency outputCurrency
) internal view returns (uint256) {
// if wrapping, the balance in this contract is in ETH
// if unwrapping, the balance in this contract is in WETH
uint256 balance = inputCurrency.balanceOf(address(this));
if (amount == ActionConstants.CONTRACT_BALANCE) {
// return early to avoid unnecessary balance check
return balance;
}
if (amount == ActionConstants.OPEN_DELTA) {
// if wrapping, the open currency on the PoolManager is WETH.
// if unwrapping, the open currency on the PoolManager is ETH.
// note that we use the DEBT amount. Positive deltas can be taken and then wrapped.
amount = _getFullDebt(outputCurrency);
}
if (amount > balance) revert InsufficientBalance();
return amount;
}
}
src/base/ImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IVault} from "squadswap-v4-core/src/interfaces/IVault.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IVault public immutable vault;
constructor(IVault _vault) {
vault = _vault;
}
}
src/base/Multicall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IMulticall} from "../interfaces/IMulticall.sol";
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(
bytes[] calldata data
) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(
data[i]
);
if (!success) {
// bubble up the revert reason
assembly ("memory-safe") {
revert(add(result, 0x20), mload(result))
}
}
results[i] = result;
}
}
}
src/base/NativeWrapper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IWETH9} from "../interfaces/external/IWETH9.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";
import {ImmutableState} from "./ImmutableState.sol";
/// @title Native Wrapper
/// @notice Used for wrapping and unwrapping native
abstract contract NativeWrapper is ImmutableState {
/// @notice The address for WETH9
IWETH9 public immutable WETH9;
/// @notice Thrown when an unexpected address sends ETH to this contract
error InvalidEthSender();
constructor(IWETH9 _weth9) {
WETH9 = _weth9;
}
/// @dev The amount should already be <= the current balance in this contract.
function _wrap(uint256 amount) internal {
if (amount > 0) WETH9.deposit{value: amount}();
}
/// @dev The amount should already be <= the current balance in this contract.
function _unwrap(uint256 amount) internal {
if (amount > 0) WETH9.withdraw(amount);
}
receive() external payable {
if (msg.sender != address(WETH9) && msg.sender != address(vault))
revert InvalidEthSender();
}
}
src/base/Permit2Forwarder.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {
IAllowanceTransfer
} from "permit2/src/interfaces/IAllowanceTransfer.sol";
/// @notice PermitForwarder allows permitting this contract as a spender on permit2
/// @dev This contract does not enforce the spender to be this contract, but that is the intended use case
contract Permit2Forwarder {
/// @notice the Permit2 contract to forward approvals
IAllowanceTransfer public immutable permit2;
constructor(IAllowanceTransfer _permit2) {
permit2 = _permit2;
}
/// @notice allows forwarding a single permit to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param permitSingle the permit data
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
function permit(
address owner,
IAllowanceTransfer.PermitSingle calldata permitSingle,
bytes calldata signature
) external payable returns (bytes memory err) {
// use try/catch in case an actor front-runs the permit, which would DOS multicalls
try permit2.permit(owner, permitSingle, signature) {} catch (
bytes memory reason
) {
err = reason;
}
}
/// @notice allows forwarding batch permits to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param _permitBatch a batch of approvals
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
function permitBatch(
address owner,
IAllowanceTransfer.PermitBatch calldata _permitBatch,
bytes calldata signature
) external payable returns (bytes memory err) {
// use try/catch in case an actor front-runs the permit, which would DOS multicalls
try permit2.permit(owner, _permitBatch, signature) {} catch (
bytes memory reason
) {
err = reason;
}
}
}
src/base/ReentrancyLock.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.24;
/// @notice A transient reentrancy lock, that stores the caller's address as the lock
contract ReentrancyLock {
// The slot holding the locker state, transiently. bytes32(uint256(keccak256("LockedBy")) - 1)
bytes32 constant LOCKED_BY_SLOT =
0x0aedd6bde10e3aa2adec092b02a3e3e805795516cda41f27aa145b8f300af87a;
error ContractLocked();
modifier isNotLocked() {
if (_getLocker() != address(0)) revert ContractLocked();
_setLocker(msg.sender);
_;
_setLocker(address(0));
}
function _setLocker(address locker) internal {
assembly ("memory-safe") {
tstore(LOCKED_BY_SLOT, locker)
}
}
function _getLocker() internal view returns (address locker) {
assembly ("memory-safe") {
locker := tload(LOCKED_BY_SLOT)
}
}
}
src/base/SafeCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.24;
import {
ILockCallback
} from "squadswap-v4-core/src/interfaces/ILockCallback.sol";
import {IVault} from "squadswap-v4-core/src/interfaces/IVault.sol";
import {ImmutableState} from "./ImmutableState.sol";
/// @title Safe Callback
/// @notice A contract that only allows the SS SquadSwapV4 Vault to call the lockAcquired function
abstract contract SafeCallback is ImmutableState, ILockCallback {
/// @notice Thrown when calling lockAcquired where the caller is not the Vault
error NotVault();
constructor(IVault _vault) ImmutableState(_vault) {}
/// @notice Only allow calls from the Vault contract
modifier onlyByVault() {
if (msg.sender != address(vault)) revert NotVault();
_;
}
/// @inheritdoc ILockCallback
/// @dev We force the onlyByVault modifier by exposing a virtual function after the onlyByVault check.
function lockAcquired(
bytes calldata data
) external onlyByVault returns (bytes memory) {
return _lockAcquired(data);
}
/// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the Vault
function _lockAcquired(
bytes calldata data
) internal virtual returns (bytes memory);
}
src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IVault} from "squadswap-v4-core/src/interfaces/IVault.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The SquadSwapswap SquadSwapV4 Vault contract
function vault() external view returns (IVault);
}
src/interfaces/IMulticall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
/// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
src/interfaces/IPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IImmutableState} from "./IImmutableState.sol";
/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is IImmutableState {
/// @notice Thrown when the block.timestamp exceeds the user-provided deadline
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when calling transfer, subscribe, or unsubscribe on CLPositionManager
/// or batchTransferFrom on BinPositionManager when the vault is locked.
/// @dev This is to prevent hooks from being able to trigger actions or notifications at the same time the position is being modified.
error VaultMustBeUnlocked();
/// @notice Thrown when the token ID is bind to an unexisting pool
error InvalidTokenID();
/// @notice Unlocks Vault and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param payload is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata payload, uint256 deadline) external payable;
/// @notice Batches actions for modifying liquidity without getting a lock from vault
/// @dev This must be called by a contract that has already locked the vault
/// @param actions the actions to perform
/// @param params the parameters to provide for the actions
function modifyLiquiditiesWithoutLock(bytes calldata actions, bytes[] calldata params) external payable;
}
src/interfaces/ISquadSwapV4Router.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PathKey} from "../libraries/PathKey.sol";
import {ICLRouterBase} from "../pool-cl/interfaces/ICLRouterBase.sol";
import {IBinRouterBase} from "../pool-bin/interfaces/IBinRouterBase.sol";
/// @title ISquadSwapV4Router
/// @notice Interface containing all the structs and errors for different squadswap swap types
interface ISquadSwapV4Router is ICLRouterBase, IBinRouterBase {
/// @notice Emitted when an exactInput swap does not receive its minAmountOut
error TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived);
/// @notice Emitted when an exactOutput is asked for more than its maxAmountIn
error TooMuchRequested(uint256 maxAmountInRequested, uint256 amountRequested);
/// @notice Emitted when an exactOutput swap or hop delivers less than requested
error ExactOutputUnfilled(uint256 amountOutRequested, uint256 amountOutReceived);
}
src/interfaces/external/IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IWETH9
/// @notice Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
src/libraries/ActionConstants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @title Action Constants
/// @notice Common constants used in actions
/// @dev Constants are gas efficient alternatives to their literal values
library ActionConstants {
/// @notice used to signal that an action should use the input value of the open delta on the vault
/// or of the balance that the contract holds
uint128 internal constant OPEN_DELTA = 0;
/// @notice used to signal that an action should use the contract's entire balance of a currency
/// This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit.
uint256 internal constant CONTRACT_BALANCE =
0x8000000000000000000000000000000000000000000000000000000000000000;
/// @notice used to signal that the recipient of an action should be the msgSender
address internal constant MSG_SENDER = address(1);
/// @notice used to signal that the recipient of an action should be the address(this)
address internal constant ADDRESS_THIS = address(2);
}
src/libraries/Actions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
// cl-pool actions
// liquidity actions
uint256 internal constant CL_INCREASE_LIQUIDITY = 0x00;
uint256 internal constant CL_DECREASE_LIQUIDITY = 0x01;
uint256 internal constant CL_MINT_POSITION = 0x02;
uint256 internal constant CL_BURN_POSITION = 0x03;
uint256 internal constant CL_INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
uint256 internal constant CL_MINT_POSITION_FROM_DELTAS = 0x05;
// swapping
uint256 internal constant CL_SWAP_EXACT_IN_SINGLE = 0x06;
uint256 internal constant CL_SWAP_EXACT_IN = 0x07;
uint256 internal constant CL_SWAP_EXACT_OUT_SINGLE = 0x08;
uint256 internal constant CL_SWAP_EXACT_OUT = 0x09;
// donate
/// @dev this is not supported in the position manager or router
uint256 internal constant CL_DONATE = 0x0a;
// closing deltas on the pool manager
// settling
uint256 internal constant SETTLE = 0x0b;
uint256 internal constant SETTLE_ALL = 0x0c;
uint256 internal constant SETTLE_PAIR = 0x0d;
// taking
uint256 internal constant TAKE = 0x0e;
uint256 internal constant TAKE_ALL = 0x0f;
uint256 internal constant TAKE_PORTION = 0x10;
uint256 internal constant TAKE_PAIR = 0x11;
uint256 internal constant CLOSE_CURRENCY = 0x12;
uint256 internal constant CLEAR_OR_TAKE = 0x13;
uint256 internal constant SWEEP = 0x14;
uint256 internal constant WRAP = 0x15;
uint256 internal constant UNWRAP = 0x16;
// minting/burning 6909s to close deltas
/// @dev this is not supported in the position manager or router
uint256 internal constant MINT_6909 = 0x17;
uint256 internal constant BURN_6909 = 0x18;
// bin-pool actions
// liquidity actions
uint256 internal constant BIN_ADD_LIQUIDITY = 0x19;
uint256 internal constant BIN_REMOVE_LIQUIDITY = 0x1a;
uint256 internal constant BIN_ADD_LIQUIDITY_FROM_DELTAS = 0x1b;
// swapping
uint256 internal constant BIN_SWAP_EXACT_IN_SINGLE = 0x1c;
uint256 internal constant BIN_SWAP_EXACT_IN = 0x1d;
uint256 internal constant BIN_SWAP_EXACT_OUT_SINGLE = 0x1e;
uint256 internal constant BIN_SWAP_EXACT_OUT = 0x1f;
// donate
uint256 internal constant BIN_DONATE = 0x20;
}
src/libraries/CalldataDecoder.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
/// @title Library for abi decoding in calldata
library CalldataDecoder {
using CalldataDecoder for bytes;
error SliceOutOfBounds();
/// @notice mask used for offsets and lengths to ensure no overflow
/// @dev no sane abi encoding will pass in an offset or length greater than type(uint32).max
/// (note that this does deviate from standard solidity behavior and offsets/lengths will
/// be interpreted as mod type(uint32).max which will only impact malicious/buggy callers)
uint256 constant OFFSET_OR_LENGTH_MASK = 0xffffffff;
uint256 constant OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN = 0xffffffe0;
/// @notice equivalent to SliceOutOfBounds.selector, stored in least-significant bits
uint256 constant SLICE_ERROR_SELECTOR = 0x3b99b53d;
/// @dev equivalent to: abi.decode(params, (bytes, bytes[])) in calldata (requires strict abi encoding)
function decodeActionsRouterParams(
bytes calldata _bytes
) internal pure returns (bytes calldata actions, bytes[] calldata params) {
assembly ("memory-safe") {
// Strict encoding requires that the data begin with:
// 0x00: 0x40 (offset to `actions.length`)
// 0x20: 0x60 + actions.length (offset to `params.length`)
// 0x40: `actions.length`
// 0x60: beginning of actions
// Verify actions offset matches strict encoding
let invalidData := xor(calldataload(_bytes.offset), 0x40)
actions.offset := add(_bytes.offset, 0x60)
actions.length := and(
calldataload(add(_bytes.offset, 0x40)),
OFFSET_OR_LENGTH_MASK
)
// Round actions length up to be word-aligned, and add 0x60 (for the first 3 words of encoding)
let paramsLengthOffset := add(
and(
add(actions.length, 0x1f),
OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN
),
0x60
)
// Verify params offset matches strict encoding
invalidData := or(
invalidData,
xor(calldataload(add(_bytes.offset, 0x20)), paramsLengthOffset)
)
let paramsLengthPointer := add(_bytes.offset, paramsLengthOffset)
params.length := and(
calldataload(paramsLengthPointer),
OFFSET_OR_LENGTH_MASK
)
params.offset := add(paramsLengthPointer, 0x20)
// Expected offset for `params[0]` is params.length * 32
// As the first `params.length` slots are pointers to each of the array element lengths
let tailOffset := shl(5, params.length)
let expectedOffset := tailOffset
for {
let offset := 0
} lt(offset, tailOffset) {
offset := add(offset, 32)
} {
let itemLengthOffset := calldataload(add(params.offset, offset))
// Verify that the offset matches the expected offset from strict encoding
invalidData := or(
invalidData,
xor(itemLengthOffset, expectedOffset)
)
let itemLengthPointer := add(params.offset, itemLengthOffset)
let length := add(
and(
add(calldataload(itemLengthPointer), 0x1f),
OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN
),
0x20
)
expectedOffset := add(expectedOffset, length)
}
// if the data encoding was invalid, or the provided bytes string isn't as long as the encoding says, revert
if or(
invalidData,
lt(
add(_bytes.length, _bytes.offset),
add(params.offset, expectedOffset)
)
) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
}
}
/// @dev equivalent to: abi.decode(params, (Currency)) in calldata
function decodeCurrency(
bytes calldata params
) internal pure returns (Currency currency) {
assembly ("memory-safe") {
if lt(params.length, 0x20) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency := calldataload(params.offset)
}
}
/// @dev equivalent to: abi.decode(params, (Currency, Currency)) in calldata
function decodeCurrencyPair(
bytes calldata params
) internal pure returns (Currency currency0, Currency currency1) {
assembly ("memory-safe") {
if lt(params.length, 0x40) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency0 := calldataload(params.offset)
currency1 := calldataload(add(params.offset, 0x20))
}
}
/// @dev equivalent to: abi.decode(params, (Currency, Currency, address)) in calldata
function decodeCurrencyPairAndAddress(
bytes calldata params
)
internal
pure
returns (Currency currency0, Currency currency1, address _address)
{
assembly ("memory-safe") {
if lt(params.length, 0x60) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency0 := calldataload(params.offset)
currency1 := calldataload(add(params.offset, 0x20))
_address := calldataload(add(params.offset, 0x40))
}
}
/// @dev equivalent to: abi.decode(params, (Currency, address)) in calldata
function decodeCurrencyAndAddress(
bytes calldata params
) internal pure returns (Currency currency, address _address) {
assembly ("memory-safe") {
if lt(params.length, 0x40) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency := calldataload(params.offset)
_address := calldataload(add(params.offset, 0x20))
}
}
/// @dev equivalent to: abi.decode(params, (Currency, address, uint256)) in calldata
function decodeCurrencyAddressAndUint256(
bytes calldata params
)
internal
pure
returns (Currency currency, address _address, uint256 amount)
{
assembly ("memory-safe") {
if lt(params.length, 0x60) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency := calldataload(params.offset)
_address := calldataload(add(params.offset, 0x20))
amount := calldataload(add(params.offset, 0x40))
}
}
/// @dev equivalent to: abi.decode(params, (Currency, uint256)) in calldata
function decodeCurrencyAndUint256(
bytes calldata params
) internal pure returns (Currency currency, uint256 amount) {
assembly ("memory-safe") {
if lt(params.length, 0x40) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency := calldataload(params.offset)
amount := calldataload(add(params.offset, 0x20))
}
}
/// @dev equivalent to: abi.decode(params, (uint256)) in calldata
function decodeUint256(
bytes calldata params
) internal pure returns (uint256 amount) {
assembly ("memory-safe") {
if lt(params.length, 0x20) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
amount := calldataload(params.offset)
}
}
/// @dev equivalent to: abi.decode(params, (Currency, uint256, bool)) in calldata
function decodeCurrencyUint256AndBool(
bytes calldata params
) internal pure returns (Currency currency, uint256 amount, bool boolean) {
assembly ("memory-safe") {
if lt(params.length, 0x60) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
currency := calldataload(params.offset)
amount := calldataload(add(params.offset, 0x20))
boolean := calldataload(add(params.offset, 0x40))
}
}
/// @notice Decode the `_arg`-th element in `_bytes` as `bytes`
/// @param _bytes The input bytes string to extract a bytes string from
/// @param _arg The index of the argument to extract
function toBytes(
bytes calldata _bytes,
uint256 _arg
) internal pure returns (bytes calldata res) {
uint256 length;
assembly ("memory-safe") {
// The offset of the `_arg`-th element is `32 * arg`, which stores the offset of the length pointer.
// shl(5, x) is equivalent to mul(32, x)
let lengthPtr := add(
_bytes.offset,
and(
calldataload(add(_bytes.offset, shl(5, _arg))),
OFFSET_OR_LENGTH_MASK
)
)
// the number of bytes in the bytes string
length := and(calldataload(lengthPtr), OFFSET_OR_LENGTH_MASK)
// the offset where the bytes string begins
let offset := add(lengthPtr, 0x20)
// assign the return parameters
res.length := length
res.offset := offset
// if the provided bytes string isn't as long as the encoding says, revert
if lt(add(_bytes.length, _bytes.offset), add(length, offset)) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
}
}
}
src/libraries/PathKey.sol
//SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {IHooks} from "squadswap-v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "squadswap-v4-core/src/interfaces/IPoolManager.sol";
struct PathKey {
Currency intermediateCurrency;
uint24 fee;
IHooks hooks;
IPoolManager poolManager;
bytes hookData;
bytes32 parameters;
}
using PathKeyLibrary for PathKey global;
library PathKeyLibrary {
/// @notice Get the pool and swap direction for a given PathKey
/// @param params the given PathKey
/// @param currencyIn the input currency
/// @return poolKey the pool key of the swap
/// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
function getPoolAndSwapDirection(
PathKey memory params,
Currency currencyIn
) internal pure returns (PoolKey memory poolKey, bool zeroForOne) {
(Currency currency0, Currency currency1) = currencyIn <
params.intermediateCurrency
? (currencyIn, params.intermediateCurrency)
: (params.intermediateCurrency, currencyIn);
zeroForOne = currencyIn == currency0;
poolKey = PoolKey(
currency0,
currency1,
params.hooks,
params.poolManager,
params.fee,
params.parameters
);
}
}
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
/// TODO after audits move this function to core's SafeCast.sol!
library SafeCastTemp {
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) revert SafeCastOverflow();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) revert SafeCastOverflow();
y = uint128(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) revert SafeCastOverflow();
return int128(int256(x));
}
}
src/libraries/SlippageCheck.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {BalanceDelta} from "squadswap-v4-core/src/types/BalanceDelta.sol";
import {SafeCastTemp} from "./SafeCast.sol";
/// @title Slippage Check Library
/// @notice a library for checking if a delta exceeds a maximum ceiling or fails to meet a minimum floor
library SlippageCheck {
using SafeCastTemp for int128;
error MaximumAmountExceeded(uint128 maximumAmount, uint128 amountRequested);
error MinimumAmountInsufficient(
uint128 minimumAmount,
uint128 amountReceived
);
/// @notice Revert if one or both deltas does not meet a minimum output
/// @param delta The principal amount of tokens to be removed, does not include any fees accrued
/// @param amount0Min The minimum amount of token0 to receive
/// @param amount1Min The minimum amount of token1 to receive
/// @dev This should be called when removing liquidity (burn or decrease)
function validateMinOut(
BalanceDelta delta,
uint128 amount0Min,
uint128 amount1Min
) internal pure {
// Called on burn or decrease, where we expect the returned delta to be positive.
// However, on pools where hooks can return deltas on modify liquidity, it is possible for a returned delta to be negative.
// Because we use SafeCast, this will revert in those cases when the delta is negative.
// This means this contract will NOT support pools where the hook returns a negative delta on burn/decrease.
if (delta.amount0().toUint128() < amount0Min) {
revert MinimumAmountInsufficient(
amount0Min,
delta.amount0().toUint128()
);
}
if (delta.amount1().toUint128() < amount1Min) {
revert MinimumAmountInsufficient(
amount1Min,
delta.amount1().toUint128()
);
}
}
/// @notice Revert if one or both deltas exceeds a maximum input
/// @param delta The principal amount of tokens to be added, does not include any fees accrued (which is possible on increase)
/// @param amount0Max The maximum amount of token0 to spend
/// @param amount1Max The maximum amount of token1 to spend
/// @dev This should be called when adding liquidity (mint or increase)
function validateMaxIn(
BalanceDelta delta,
uint128 amount0Max,
uint128 amount1Max
) internal pure {
// Called on mint or increase, where we expect the returned delta to be negative.
// However, on pools where hooks can return deltas on modify liquidity, it is possible for a returned delta to be positive (even after discounting fees accrued).
// Thus, we only cast the delta if it is guaranteed to be negative.
// And we do NOT revert in the positive delta case. Since a positive delta means the hook is crediting tokens to the user for minting/increasing liquidity, we do not check slippage.
// This means this contract will NOT support _positive_ slippage checks (minAmountOut checks) on pools where the hook returns a positive delta on mint/increase.
int256 amount0 = delta.amount0();
int256 amount1 = delta.amount1();
if (amount0 < 0 && amount0Max < uint128(uint256(-amount0))) {
revert MaximumAmountExceeded(
amount0Max,
uint128(uint256(-amount0))
);
}
if (amount1 < 0 && amount1Max < uint128(uint256(-amount1))) {
revert MaximumAmountExceeded(
amount1Max,
uint128(uint256(-amount1))
);
}
}
}
src/pool-bin/BinFungibleToken.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IBinFungibleToken} from "./interfaces/IBinFungibleToken.sol";
/**
* @notice Similar to ERC-1155, though without uri() and no onErc1155 callback when transfer is made
*/
abstract contract BinFungibleToken is IBinFungibleToken {
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice [user] -> [keccak256(abi.encode(poolId, binId)] -> [number of shares]
mapping(address => mapping(uint256 => uint256)) public balanceOf;
/// @notice [keccak256(abi.encode(poolId, binId)] -> [number of share]
mapping(uint256 => uint256) public totalSupply;
/// @notice [user] -> [operator] -> [is approved?]
mapping(address => mapping(address => bool)) public isApprovedForAll;
/// @notice Revert if "spender" is not approved to spend "from" token
modifier checkApproval(address from, address spender) {
if (!(spender == from || isApprovedForAll[from][spender])) {
revert BinFungibleToken_SpenderNotApproved(from, spender);
}
_;
}
/// @notice Enforces that the Vault is unlocked.
modifier onlyIfVaultUnlocked() virtual;
/*//////////////////////////////////////////////////////////////
LOGIC
//////////////////////////////////////////////////////////////*/
function name() public view virtual override returns (string memory) {
return "Bin Fungible Token";
}
function symbol() public view virtual override returns (string memory) {
return "BFT";
}
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
) public view virtual override returns (uint256[] memory balances) {
if (owners.length != ids.length)
revert BinFungibleToken_InvalidLength();
balances = new uint256[](owners.length);
// Unchecked because the only math done is incrementing
// the array index counter which cannot possibly overflow.
unchecked {
for (uint256 i; i < owners.length; ++i) {
balances[i] = balanceOf[owners[i]][ids[i]];
}
}
}
function approveForAll(
address operator,
bool approved
) public virtual override {
if (msg.sender == operator)
revert BinFungibleToken_SelfApproval(msg.sender);
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function batchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts
) public virtual override onlyIfVaultUnlocked {
if (ids.length != amounts.length)
revert BinFungibleToken_InvalidLength();
if (to == address(0) || to == address(this))
revert BinFungibleToken_AddressThisOrZero();
if (!(msg.sender == from || isApprovedForAll[from][msg.sender])) {
revert BinFungibleToken_SpenderNotApproved(from, msg.sender);
}
// Storing these outside the loop saves ~15 gas per iteration.
uint256 id;
uint256 amount;
for (uint256 i; i < ids.length; ) {
id = ids[i];
amount = amounts[i];
if (balanceOf[from][id] < amount)
revert BinFungibleToken_TransferExceedsBalance(
from,
id,
amount
);
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
++i;
}
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id, uint256 amount) internal {
if (to == address(0) || to == address(this))
revert BinFungibleToken_AddressThisOrZero();
totalSupply[id] += amount;
unchecked {
balanceOf[to][id] += amount;
}
}
function _burn(address from, uint256 id, uint256 amount) internal {
if (balanceOf[from][id] < amount)
revert BinFungibleToken_BurnExceedsBalance(from, id, amount);
unchecked {
totalSupply[id] -= amount;
balanceOf[from][id] -= amount;
}
}
}
src/pool-bin/interfaces/IBinFungibleToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBinFungibleToken {
error BinFungibleToken_AddressThisOrZero();
error BinFungibleToken_InvalidLength();
error BinFungibleToken_SelfApproval(address owner);
error BinFungibleToken_SpenderNotApproved(address from, address spender);
error BinFungibleToken_TransferExceedsBalance(address from, uint256 id, uint256 amount);
error BinFungibleToken_BurnExceedsBalance(address from, uint256 id, uint256 amount);
event TransferBatch(
address indexed sender, address indexed from, address indexed to, uint256[] ids, uint256[] amounts
);
event ApprovalForAll(address indexed account, address indexed sender, bool approved);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
/// @param id ID of the token
/// @return The total supply of token id
function totalSupply(uint256 id) external view returns (uint256);
/// @notice Get the balance of an account's tokens.
/// @param account The address of the token holder
/// @param id ID of the token
/// @return The account's balance of the token type requested
function balanceOf(address account, uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param accounts The addresses of the token holders
/// @param ids ID of the tokens
/// @return The account's balance of the token types requested (i.e. balance for each (owner, id) pair)
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function isApprovedForAll(address owner, address spender) external view returns (bool);
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function approveForAll(address operator, bool approved) external;
/// @notice Transfers `amounts` amount(s) of `ids` from the `from` address to the `to` address specified
/// @param from Source address
/// @param to Target address
/// @param ids IDs of each token type (order and length must match _values array)
/// @param amounts Transfer amounts per token type (order and length must match _ids array)
function batchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts) external;
}
src/pool-bin/interfaces/IBinPositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolId} from "squadswap-v4-core/src/types/PoolId.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {
IBinPoolManager
} from "squadswap-v4-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {IPositionManager} from "../../interfaces/IPositionManager.sol";
interface IBinPositionManager is IPositionManager {
error IdOverflows(int256);
error IdSlippageCaught(
uint256 activeIdDesired,
uint256 idSlippage,
uint24 activeId
);
error AddLiquidityInputActiveIdMismatch();
error LiquiditySlippageCaught(
uint24 binId,
uint256 minLiquidity,
uint256 liquidityMinted
);
/// @notice BinAddLiquidityParams
/// - amount0: Amount to send for token0
/// - amount1: Amount to send for token1
/// - amount0Max: Max amount to send for token0
/// - amount1Max: Max amount to send for token1
/// - activeIdDesired: Active id that user wants to add liquidity from
/// - idSlippage: Number of id that are allowed to slip
/// - deltaIds: List of delta ids to add liquidity (`deltaId = activeId - desiredId`)
/// - distributionX: Distribution of tokenX with sum(distributionX) = 1e18 (100%) or 0 (0%)
/// - distributionY: Distribution of tokenY with sum(distributionY) = 1e18 (100%) or 0 (0%)
/// - minLiquidities: Min amount of share minted for each bin, aligned with deltaIds. Pass 0 to skip a bin.
/// - to: Address of recipient
/// - hookData: Data to pass to the hook
struct BinAddLiquidityParams {
PoolKey poolKey;
uint128 amount0;
uint128 amount1;
uint128 amount0Max;
uint128 amount1Max;
uint256 activeIdDesired;
uint256 idSlippage;
int256[] deltaIds;
uint256[] distributionX;
uint256[] distributionY;
uint256[] minLiquidities;
address to;
bytes hookData;
}
/// @notice BinRemoveLiquidityParams
/// - amount0Min: Min amount to receive for token0
/// - amount1Min: Min amount to receive for token1
/// - ids: List of bin ids to remove liquidity
/// - amounts: List of share amount to remove for each bin
/// - from: Address of NFT holder to burn the NFT
/// - hookData: Data to pass to the hook
struct BinRemoveLiquidityParams {
PoolKey poolKey;
uint128 amount0Min;
uint128 amount1Min;
uint256[] ids;
uint256[] amounts;
address from;
bytes hookData;
}
/// @notice BinAddLiquidityFromDeltasParams
/// - amount0Max: Max amount to send for token0
/// - amount1Max: Max amount to send for token1
/// - activeIdDesired: Active id that user wants to add liquidity from
/// - idSlippage: Number of id that are allowed to slip
/// - deltaIds: List of delta ids to add liquidity (`deltaId = activeId - desiredId`)
/// - distributionX: Distribution of tokenX with sum(distributionX) = 1e18 (100%) or 0 (0%)
/// - distributionY: Distribution of tokenY with sum(distributionY) = 1e18 (100%) or 0 (0%)
/// - minLiquidities: Min amount of share minted for each bin, aligned with deltaIds. Pass 0 to skip a bin.
/// - to: Address of recipient
/// - hookData: Data to pass to the hook
struct BinAddLiquidityFromDeltasParams {
PoolKey poolKey;
uint128 amount0Max;
uint128 amount1Max;
uint256 activeIdDesired;
uint256 idSlippage;
int256[] deltaIds;
uint256[] distributionX;
uint256[] distributionY;
uint256[] minLiquidities;
address to;
bytes hookData;
}
function binPoolManager() external view returns (IBinPoolManager);
/// @notice Initialize a squadswap SS bin pool
/// @dev If the pool is already initialized, this function will not revert
/// @param key the PoolKey of the pool to initialize
/// @param activeId the active bin id of the pool
function initializePool(
PoolKey memory key,
uint24 activeId
) external payable;
/// @notice Return the position information associated with a given tokenId
/// @dev Revert if non-existent tokenId
/// @param tokenId Id of the token that represent position
/// @return poolKey the pool key of the position
/// @return binId the binId of the position
function positions(
uint256 tokenId
) external view returns (PoolKey memory poolKey, uint24 binId);
}
src/pool-bin/interfaces/IBinRouterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PathKey} from "../../libraries/PathKey.sol";
import {IImmutableState} from "../../interfaces/IImmutableState.sol";
interface IBinRouterBase is IImmutableState {
struct BinSwapExactInputSingleParams {
PoolKey poolKey;
bool swapForY;
uint128 amountIn;
uint128 amountOutMinimum;
bytes hookData;
}
struct BinSwapExactInputParams {
Currency currencyIn;
PathKey[] path;
uint128 amountIn;
uint128 amountOutMinimum;
}
struct BinSwapExactOutputSingleParams {
PoolKey poolKey;
bool swapForY;
uint128 amountOut;
uint128 amountInMaximum;
bytes hookData;
}
struct BinSwapExactOutputParams {
Currency currencyOut;
PathKey[] path;
uint128 amountOut;
uint128 amountInMaximum;
}
}
src/pool-bin/libraries/BinCalldataDecoder.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {IBinPositionManager} from "../interfaces/IBinPositionManager.sol";
import {ISquadSwapV4Router} from "../../interfaces/ISquadSwapV4Router.sol";
/// @title Library for abi decoding in bin pool calldata
library BinCalldataDecoder {
/// @notice equivalent to SliceOutOfBounds.selector, stored in least-significant bits
uint256 constant SLICE_ERROR_SELECTOR = 0x3b99b53d;
/// todo: <wip> see if tweaking to calldataload saves gas
/// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinAddLiquidityParams))
function decodeBinAddLiquidityParams(
bytes calldata params
)
internal
pure
returns (
IBinPositionManager.BinAddLiquidityParams calldata addLiquidityParams
)
{
assembly ("memory-safe") {
addLiquidityParams := add(
params.offset,
calldataload(params.offset)
)
}
}
/// todo: <wip> see if tweaking to calldataload saves gas
/// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinRemoveLiquidityParams))
function decodeBinRemoveLiquidityParams(
bytes calldata params
)
internal
pure
returns (
IBinPositionManager.BinRemoveLiquidityParams calldata removeLiquidityParams
)
{
assembly ("memory-safe") {
removeLiquidityParams := add(
params.offset,
calldataload(params.offset)
)
}
}
/// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinAddLiquidityFromDeltasParams))
function decodeBinAddLiquidityFromDeltasParams(
bytes calldata params
)
internal
pure
returns (
IBinPositionManager.BinAddLiquidityFromDeltasParams calldata addLiquidityParams
)
{
assembly ("memory-safe") {
addLiquidityParams := add(
params.offset,
calldataload(params.offset)
)
}
}
/// @dev equivalent to: abi.decode(params, (ISquadSwapV4Router.BinExactInputParams))
function decodeBinSwapExactInParams(
bytes calldata params
)
internal
pure
returns (ISquadSwapV4Router.BinSwapExactInputParams calldata swapParams)
{
// BinExactInputParams is a variable length struct so we just have to look up its location
assembly ("memory-safe") {
// only safety checks for the minimum length, where path is empty
// 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
if lt(params.length, 0xa0) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
swapParams := add(params.offset, calldataload(params.offset))
}
}
/// @dev equivalent to: abi.decode(params, (ISquadSwapV4Router.BinExactInputSingleParams))
function decodeBinSwapExactInSingleParams(
bytes calldata params
)
internal
pure
returns (
ISquadSwapV4Router.BinSwapExactInputSingleParams calldata swapParams
)
{
// BinExactInputSingleParams is a variable length struct so we just have to look up its location
assembly ("memory-safe") {
// only safety checks for the minimum length, where hookData is empty
// 0x160 = 11 * 0x20 -> 9 elements, bytes offset, and bytes length 0
if lt(params.length, 0x160) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
swapParams := add(params.offset, calldataload(params.offset))
}
}
/// @dev equivalent to: abi.decode(params, (ISquadSwapV4Router.BinExactOutputParams))
function decodeBinSwapExactOutParams(
bytes calldata params
)
internal
pure
returns (
ISquadSwapV4Router.BinSwapExactOutputParams calldata swapParams
)
{
// BinExactOutputParams is a variable length struct so we just have to look up its location
assembly ("memory-safe") {
// only safety checks for the minimum length, where path is empty
// 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
if lt(params.length, 0xa0) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
swapParams := add(params.offset, calldataload(params.offset))
}
}
/// @dev equivalent to: abi.decode(params, (ISquadSwapV4Router.BinExactOutputSingleParams))
function decodeBinSwapExactOutSingleParams(
bytes calldata params
)
internal
pure
returns (
ISquadSwapV4Router.BinSwapExactOutputSingleParams calldata swapParams
)
{
// BinExactOutputSingleParams is a variable length struct so we just have to look up its location
assembly ("memory-safe") {
// only safety checks for the minimum length, where hookData is empty
// 0x160 = 9 * 0x20 -> 9 elements, bytes offset, and bytes length 0
if lt(params.length, 0x160) {
mstore(0, SLICE_ERROR_SELECTOR)
revert(0x1c, 4)
}
swapParams := add(params.offset, calldataload(params.offset))
}
}
}
src/pool-bin/libraries/BinTokenLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity ^0.8.0;
import {PoolId} from "squadswap-v4-core/src/types/PoolId.sol";
/// @notice Library for computing the token of binId in a pool
library BinTokenLibrary {
function toTokenId(
PoolId poolId,
uint256 binId
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(poolId, binId)));
}
}
src/pool-cl/interfaces/ICLRouterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {PathKey} from "../../libraries/PathKey.sol";
import {IImmutableState} from "../../interfaces/IImmutableState.sol";
interface ICLRouterBase is IImmutableState {
/// @notice Parameters for a single-hop exact-input swap
struct CLSwapExactInputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountIn;
uint128 amountOutMinimum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-input swap
struct CLSwapExactInputParams {
Currency currencyIn;
PathKey[] path;
uint128 amountIn;
uint128 amountOutMinimum;
}
/// @notice Parameters for a single-hop exact-output swap
struct CLSwapExactOutputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountOut;
uint128 amountInMaximum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-output swap
struct CLSwapExactOutputParams {
Currency currencyOut;
PathKey[] path;
uint128 amountOut;
uint128 amountInMaximum;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=../squadswap-v4-core/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=../squadswap-v4-core/lib/forge-std/src/",
"lib/pancake-create3-factory/=lib/pancake-create3-factory/",
"openzeppelin-contracts/=../squadswap-v4-core/lib/openzeppelin-contracts/",
"pancake-create3-factory/=lib/pancake-create3-factory/",
"permit2/=lib/permit2/",
"solmate/=../squadswap-v4-core/lib/solmate/",
"squadswap-create3-factory/=lib/pancake-create3-factory/",
"squadswap-v4-core/=../squadswap-v4-core/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.