Verified contractPartialMIT
FloorPawn
Address0x5a1a69efeec448b1eac2174fa2f8e5c1188ab698
- Balance
0 ETH
- Transactions
89
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,129,032
- Creation transaction
- 0x440e985a16…f48ba03cbe
45 files
- src/pad/FloorPawn.solmain16.71 KB
- lib/solady/src/utils/SafeTransferLib.sol32.8 KB
- lib/v4-core/src/interfaces/IExtsload.sol1.02 KB
- lib/v4-core/src/interfaces/IExttload.sol699 B
- lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-core/src/interfaces/IPoolManager.sol12.84 KB
- lib/v4-core/src/interfaces/IProtocolFees.sol2.49 KB
- lib/v4-core/src/interfaces/callback/IUnlockCallback.sol488 B
- lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-core/src/interfaces/external/IERC6909Claims.sol3.16 KB
- lib/v4-core/src/libraries/BitMath.sol2.61 KB
- lib/v4-core/src/libraries/CurrencyReserves.sol1.29 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/FixedPoint128.sol297 B
- lib/v4-core/src/libraries/FixedPoint96.sol366 B
- lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/v4-core/src/libraries/Hooks.sol16.51 KB
- lib/v4-core/src/libraries/LPFeeLibrary.sol3.6 KB
- lib/v4-core/src/libraries/LiquidityMath.sol742 B
- lib/v4-core/src/libraries/Lock.sol930 B
- lib/v4-core/src/libraries/NonzeroDeltaCount.sol1.46 KB
- lib/v4-core/src/libraries/ParseBytes.sol1.2 KB
- lib/v4-core/src/libraries/Position.sol4.81 KB
- lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-core/src/libraries/SqrtPriceMath.sol14.08 KB
- lib/v4-core/src/libraries/StateLibrary.sol16.03 KB
- lib/v4-core/src/libraries/TickMath.sol12.38 KB
- lib/v4-core/src/libraries/TransientStateLibrary.sol2.36 KB
- lib/v4-core/src/libraries/UnsafeMath.sol1.17 KB
- lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-core/src/types/Currency.sol5.46 KB
- lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-core/src/types/PoolOperation.sol907 B
- src/base/TransientLock.sol1.59 KB
- src/base/TwoStepOwned.sol1.25 KB
- src/pad/DistrictRegistry.sol18.65 KB
- src/pad/PadFloorMath.sol6.36 KB
- src/pad/PadHook.sol47.71 KB
- src/pad/PadStreakMath.sol5.91 KB
- src/pad/interfaces/IPadExternal.sol3.48 KB
- src/pad/libraries/PadHookLib.sol7.63 KB
- src/pad/libraries/PadMath.sol5.38 KB
- src/pad/libraries/PadTypes.sol2.62 KB
src/pad/FloorPawn.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {TransientLock} from "../base/TransientLock.sol";
import {PadHook} from "./PadHook.sol";
import {PadHookLib} from "./libraries/PadHookLib.sol";
import {PadMath} from "./libraries/PadMath.sol";
/// @title FloorPawn (質, "the Shrine pawns your neko")
/// @notice A coin's own floor band lends its quote against escrowed coins valued at the floor. No price liquidation,
/// ever. Policy only: the hook's `deskOp` executes every operation and reverts `FloorWouldFall` if the published
/// floor (MAIN + physical band + lent quote, over H) would fall, so a bug here cannot lower a floor.
///
/// PAWN: escrow coins, receive up to 90% of their value at min(floor, price, slow reference), minus an upfront fee
/// of 1% of the principal per 30-day term (1-3 terms), which goes to the floor. Lent <= 80% of floor quote.
/// REPAY: anyone, any time, for the owner. Never blocked by the pool state: if the price sits inside the floor band
/// (the band cannot take the principal back as quote-only liquidity), the payment is taken anyway and held as
/// PoolManager claims of this desk; the loan is SETTLED-PENDING (can never be forfeited) and `settle()`
/// (anyone) returns the principal to the band and the coins to the owner once the price is above the band.
/// EXTEND: pay the next terms' fee (to the floor), at most 90 days ahead.
/// FORFEIT: anyone, only if ALL hold: past expiry + 7 days grace, not settled-pending, the price is above the band now
/// (repay would work), and the desk has not seen the price inside the band in the last 7 days ("fresh grace";
/// every desk call and the public `observe()` record it). The coins are BURNED and the principal written
/// off, which provably raises the floor (theorem T1: principal <= coins x floor price).
///
/// Per pool, the Pawn is switched on once and stays on: house coins (KINEKO) through `enableHouse`, every other coin
/// only through the immutable GRADUATION contract. No owner, no admin, no upgrade; the desk holds no ERC20 quote.
contract FloorPawn is IUnlockCallback, TransientLock {
using StateLibrary for IPoolManager;
uint256 public constant LTV_BPS = 9000;
uint256 public constant FEE_BPS_PER_TERM = 100;
uint256 public constant TERM = 30 days;
uint256 public constant MAX_TERMS = 3;
uint256 public constant GRACE = 7 days;
uint256 public constant FRESH_GRACE = 7 days;
uint256 public constant MAX_UTIL_BPS = 8000;
/// minimum principal, in USD at the district's reference (no dust loans)
uint256 public constant MIN_PRINCIPAL_USD = 10e18;
/// raw units a repayment adds to cover the exact-liquidity round-up (the surplus goes to the floor)
uint256 public constant REPAY_DUST = 16;
int24 internal constant BAND_WIDTH = 60;
uint256 internal constant BPS = 10_000;
uint256 internal constant Q96 = 0x1000000000000000000000000;
/// keccak256("kineko.floor.pawn.unlock") - 1
uint256 internal constant PAWN_UNLOCK_FLAG = 0x31d5a9c0e4b7f2a68c1e3d5b7f9a0c2e4d6b8f1a3c5e7d9b0f2a4c6e8d1b3f50;
IPoolManager public immutable POOL_MANAGER;
PadHook public immutable HOOK;
address public immutable GRADUATION;
struct Loan {
address owner;
uint64 expiry;
bool parked; // settled-pending: paid, waiting for the band to take the principal back
address coin;
uint128 coins;
uint128 principal; // owed at repayment (rounded up by the hook) == the hook's lentQuote share
}
mapping(address coin => bool) public pawnOn;
mapping(uint256 => Loan) public loans;
uint256 public nextId = 1;
mapping(address coin => uint256) public escrowed; // sum of loan coins of that coin held here
mapping(address coin => uint256) public outstanding; // sum of principals (== HOOK lentQuote of that pool)
mapping(address coin => uint256) public parkedClaims; // quote claims held here for settled-pending loans
mapping(address coin => uint64) public lastInBand; // last time any desk call saw the price inside the band
event PawnEnabled(address indexed coin, bool house);
event Pawned(uint256 indexed id, address indexed owner, address indexed coin, uint256 coins, uint256 principal, uint256 fee, uint64 expiry);
event Repaid(uint256 indexed id, address indexed payer, uint256 principal);
event RepayParked(uint256 indexed id, address indexed payer, uint256 amount);
event Settled(uint256 indexed id, uint256 principal);
event Extended(uint256 indexed id, uint256 fee, uint64 expiry);
event Forfeited(uint256 indexed id, uint256 coinsBurned, uint256 principalWrittenOff);
event InBand(address indexed coin, uint64 at);
error NotHouse();
error NotGraduation();
error PawnOff();
error AlreadyOn();
error TooMuch();
error TooSmall();
error BadTerms();
error NotYet();
error NoLoan();
error Parked();
error NotParked();
error InsideBand();
constructor(IPoolManager pm, PadHook hook, address graduation) {
POOL_MANAGER = pm;
HOOK = hook;
GRADUATION = graduation;
}
// ================================================================== switches (one-way)
/// @notice Permissionless: switch the Pawn on for a HOUSE pool (KINEKO; the flag is set only by the house launch).
function enableHouse(address coin) external {
PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, coin);
if (p.coin == address(0) || !p.house) revert NotHouse();
_enable(coin, true);
}
/// @notice The GRADUATION contract only: switch the Pawn on for a graduated coin.
function enable(address coin) external {
if (msg.sender != GRADUATION) revert NotGraduation();
if (PadHookLib.poolInfo(HOOK, coin).coin == address(0)) revert NoLoan();
_enable(coin, false);
}
function _enable(address coin, bool house) internal {
if (pawnOn[coin]) revert AlreadyOn();
pawnOn[coin] = true;
SafeTransferLib.safeApprove(coin, address(HOOK), type(uint256).max); // the hook pulls coins it must burn
emit PawnEnabled(coin, house);
}
// ================================================================== views
/// True iff the price is above the floor band (coin-tick >= bandLower + W): the band is quote-only, so a repayment
/// can go back into it, and a forfeit is allowed. False while the price sits inside (or below) the band.
function bandTakesQuote(address coin) public view returns (bool) {
PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, coin);
(, int24 t,,) = POOL_MANAGER.getSlot0(HOOK.poolIdOf(coin));
return PadMath.coinTickOf(p.coinIsToken0, t) >= p.bandLower + BAND_WIDTH;
}
/// Per-coin valuation cap (raw quote per raw coin, x1e36): min(published floor, current price, slow reference).
/// The slow reference follows the price down at once and rises <= 20 ticks per block (red-team R2: after burns the
/// floor can sit above the market; buy -> pawn at the floor -> walk away must not pay).
function capPrice36(address coin) public view returns (uint256) {
PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, coin);
(, int24 t,,) = POOL_MANAGER.getSlot0(HOOK.poolIdOf(coin));
int256 cur = PadMath.coinTickOf(p.coinIsToken0, t);
uint256 el = block.number > p.refBlock ? block.number - p.refBlock : 0;
if (el > 100_000) el = 100_000;
int256 ref = int256(p.refCoinTick) + int256(el) * 20;
int256 m = cur < ref ? cur : ref;
(int24 f,,,,) = PadHookLib.floorBacking(HOOK, coin);
if (int256(f) < m) m = f;
uint256 s = TickMath.getSqrtPriceAtTick(int24(m));
return FullMath.mulDiv(FullMath.mulDiv(s, s, Q96), 1e36, Q96);
}
/// Max principal for `coins` and the fee per term.
function quotePawn(address coin, uint256 coins, uint256 terms) public view returns (uint256 maxPrincipal, uint256 fee) {
maxPrincipal = FullMath.mulDiv(coins, capPrice36(coin), 1e36) * LTV_BPS / BPS;
fee = maxPrincipal * FEE_BPS_PER_TERM * terms / BPS;
}
/// Room left under the utilisation cap: lent <= 80% of (physical band quote + lent).
function lendable(address coin) public view returns (uint256) {
(, uint256 bandQ,,,) = PadHookLib.floorBacking(HOOK, coin);
uint256 lent = PadHookLib.poolInfo(HOOK, coin).lentQuote;
uint256 cap = (bandQ + lent) * MAX_UTIL_BPS / BPS;
return cap > lent ? cap - lent : 0;
}
/// Minimum principal (raw quote): $10 at the district's USD reference, at least 1,000 raw.
function minPrincipal(address coin) public view returns (uint256 m) {
PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, coin);
m = p.usdPerQuoteE18 == 0 ? 0 : FullMath.mulDiv(MIN_PRINCIPAL_USD, 10 ** uint256(p.quoteDecimals), p.usdPerQuoteE18);
if (m < 1000) m = 1000;
}
/// Whether `forfeit(id)` would pass its policy checks now.
function canForfeit(uint256 id) external view returns (bool) {
Loan memory l = loans[id];
if (l.owner == address(0) || l.parked) return false;
if (block.timestamp <= uint256(l.expiry) + GRACE) return false;
if (!bandTakesQuote(l.coin)) return false;
return block.timestamp >= uint256(lastInBand[l.coin]) + FRESH_GRACE;
}
// ================================================================== observation (fresh grace)
/// @notice Anyone (our keeper calls it hourly): record that the price is inside the band right now, if it is.
function observe(address coin) external returns (bool inBand) {
return _observe(coin);
}
function _observe(address coin) internal returns (bool inBand) {
inBand = !bandTakesQuote(coin);
if (inBand) {
lastInBand[coin] = uint64(block.timestamp);
emit InBand(coin, uint64(block.timestamp));
}
}
// ================================================================== pawn / repay / settle / extend / forfeit
/// @notice Escrow `coins` of `coin`, receive `principal - fee` of its quote now; owe `principal` (+ REPAY_DUST) by
/// expiry. `terms` = 1..3 months prepaid.
function pawn(address coin, uint256 coins, uint256 principal, uint256 terms, uint256 deadline)
external
nonReentrant
returns (uint256 id)
{
if (!pawnOn[coin]) revert PawnOff();
if (block.timestamp > deadline || terms == 0 || terms > MAX_TERMS) revert BadTerms();
if (_observe(coin)) revert InsideBand();
(uint256 maxP,) = quotePawn(coin, coins, terms);
if (principal > maxP || principal > lendable(coin)) revert TooMuch();
if (principal < minPrincipal(coin)) revert TooSmall();
uint256 fee = principal * FEE_BPS_PER_TERM * terms / BPS;
SafeTransferLib.safeTransferFrom(coin, msg.sender, address(this), coins);
uint256 owed = HOOK.deskOp(coin, 0, principal, fee, msg.sender, true, 0, 0, 0);
id = nextId++;
uint64 exp = uint64(block.timestamp + terms * TERM);
loans[id] = Loan(msg.sender, exp, false, coin, uint128(coins), uint128(owed));
escrowed[coin] += coins;
outstanding[coin] += owed;
emit Pawned(id, msg.sender, coin, coins, owed, fee, exp);
}
/// @notice Anyone may repay; the coins go back to the loan's owner. Never blocked by the pool state (see header).
function repay(uint256 id) external nonReentrant {
Loan memory l = loans[id];
if (l.owner == address(0)) revert NoLoan();
if (l.parked) revert Parked();
address q = PadHookLib.poolInfo(HOOK, l.coin).quote;
uint256 amt = uint256(l.principal) + REPAY_DUST;
if (_observe(l.coin)) {
// the band cannot take the principal now: take the payment as this desk's claims; settle() later
_payIn(q, msg.sender, address(this), amt);
loans[id].parked = true;
parkedClaims[l.coin] += amt;
emit RepayParked(id, msg.sender, amt);
return;
}
delete loans[id];
escrowed[l.coin] -= l.coins;
outstanding[l.coin] -= l.principal;
_payIn(q, msg.sender, address(HOOK), amt);
HOOK.deskOp(l.coin, 0, 0, 0, address(0), false, 0, l.principal, REPAY_DUST);
SafeTransferLib.safeTransfer(l.coin, l.owner, l.coins);
emit Repaid(id, msg.sender, l.principal);
}
/// @notice Anyone: finish a settled-pending repayment once the price is above the band.
function settle(uint256 id) external nonReentrant {
Loan memory l = loans[id];
if (!l.parked) revert NotParked();
if (_observe(l.coin)) return; // in band: only RECORD the sighting (a revert would roll the record back; the loan stays parked)
address q = PadHookLib.poolInfo(HOOK, l.coin).quote;
uint256 amt = uint256(l.principal) + REPAY_DUST;
delete loans[id];
escrowed[l.coin] -= l.coins;
outstanding[l.coin] -= l.principal;
parkedClaims[l.coin] -= amt;
POOL_MANAGER.transfer(address(HOOK), uint256(uint160(q)), amt);
HOOK.deskOp(l.coin, 0, 0, 0, address(0), false, 0, l.principal, REPAY_DUST);
SafeTransferLib.safeTransfer(l.coin, l.owner, l.coins);
emit Settled(id, l.principal);
}
/// @notice Pay the fee for `terms` more months (to the floor). Anyone may extend a loan.
function extend(uint256 id, uint256 terms) external nonReentrant {
Loan storage l = loans[id];
if (l.owner == address(0)) revert NoLoan();
if (l.parked) revert Parked();
_observe(l.coin);
uint256 base = l.expiry > block.timestamp ? l.expiry : block.timestamp;
uint256 exp = base + terms * TERM;
if (terms == 0 || exp > block.timestamp + MAX_TERMS * TERM) revert BadTerms();
uint256 fee = uint256(l.principal) * FEE_BPS_PER_TERM * terms / BPS;
l.expiry = uint64(exp);
_payIn(PadHookLib.poolInfo(HOOK, l.coin).quote, msg.sender, address(HOOK), fee);
HOOK.deskOp(l.coin, 0, 0, 0, address(0), false, 0, 0, fee);
emit Extended(id, fee, uint64(exp));
}
/// @notice Anyone, under the conditions in the header: burn the escrowed coins and write the principal off.
function forfeit(uint256 id) external nonReentrant {
Loan memory l = loans[id];
if (l.owner == address(0)) revert NoLoan();
if (l.parked) revert Parked();
if (block.timestamp <= uint256(l.expiry) + GRACE) revert NotYet();
if (_observe(l.coin)) return; // repay would be parked right now: never forfeit then; the sighting is recorded (a revert would undo it)
if (block.timestamp < uint256(lastInBand[l.coin]) + FRESH_GRACE) revert NotYet(); // fresh grace
delete loans[id];
escrowed[l.coin] -= l.coins;
outstanding[l.coin] -= l.principal;
HOOK.deskOp(l.coin, l.coins, 0, 0, address(0), false, l.principal, 0, 0);
emit Forfeited(id, l.coins, l.principal);
}
// ================================================================== internal
/// Moves `amt` quote from `payer` into the PoolManager as ERC-6909 claims of `to` (the hook, or this desk for a
/// settled-pending repayment). The desk never holds the ERC20.
function _payIn(address q, address payer, address to, uint256 amt) internal {
if (amt == 0) return;
_tstore(PAWN_UNLOCK_FLAG, 1);
POOL_MANAGER.unlock(abi.encode(q, payer, to, amt));
_tstore(PAWN_UNLOCK_FLAG, 0);
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
_consumeCallback(PAWN_UNLOCK_FLAG, address(POOL_MANAGER));
(address q, address payer, address to, uint256 amt) = abi.decode(data, (address, address, address, uint256));
POOL_MANAGER.sync(Currency.wrap(q));
SafeTransferLib.safeTransferFrom(q, payer, address(POOL_MANAGER), amt);
POOL_MANAGER.settle();
POOL_MANAGER.mint(to, uint256(uint160(q)), amt);
return "";
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) {
revert(codesize(), codesize())
} // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount := mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` implements `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented := and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
lib/v4-core/src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
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 granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @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);
}
lib/v4-core/src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/v4-core/src/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(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 that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @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 fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @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 tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @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 sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range 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.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @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 currency) 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
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
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-retrievable, 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 the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
lib/v4-core/src/interfaces/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @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 currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
lib/v4-core/src/interfaces/callback/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the 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);
}
lib/v4-core/src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
lib/v4-core/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
lib/v4-core/src/libraries/CurrencyReserves.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";
library CurrencyReserves {
using CustomRevert for bytes4;
/// bytes32(uint256(keccak256("ReservesOf")) - 1)
bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
/// bytes32(uint256(keccak256("Currency")) - 1)
bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;
function getSyncedCurrency() internal view returns (Currency currency) {
assembly ("memory-safe") {
currency := tload(CURRENCY_SLOT)
}
}
function resetCurrency() internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, 0)
}
}
function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
tstore(RESERVES_OF_SLOT, value)
}
}
function getSyncedReserves() internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(RESERVES_OF_SLOT)
}
}
}
lib/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 To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @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);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @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))
}
}
}
lib/v4-core/src/libraries/FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
lib/v4-core/src/libraries/FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
lib/v4-core/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then 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
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// 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
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use 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.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // 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 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
lib/v4-core/src/libraries/Hooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}
lib/v4-core/src/libraries/LPFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
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 mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @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 isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates 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 fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return 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 & REMOVE_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
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}
lib/v4-core/src/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}
lib/v4-core/src/libraries/Lock.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
// The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;
function unlock() internal {
assembly ("memory-safe") {
// unlock
tstore(IS_UNLOCKED_SLOT, true)
}
}
function lock() internal {
assembly ("memory-safe") {
tstore(IS_UNLOCKED_SLOT, false)
}
}
function isUnlocked() internal view returns (bool unlocked) {
assembly ("memory-safe") {
unlocked := tload(IS_UNLOCKED_SLOT)
}
}
}
lib/v4-core/src/libraries/NonzeroDeltaCount.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
// The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;
function read() internal view returns (uint256 count) {
assembly ("memory-safe") {
count := tload(NONZERO_DELTA_COUNT_SLOT)
}
}
function increment() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := add(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
/// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
/// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
function decrement() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := sub(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
}
lib/v4-core/src/libraries/ParseBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}
lib/v4-core/src/libraries/Position.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State 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 tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}
lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
}
/// @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) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/v4-core/src/libraries/SqrtPriceMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}
lib/v4-core/src/libraries/StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}
lib/v4-core/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
lib/v4-core/src/libraries/TransientStateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";
/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
/// @notice returns the reserves for the synced currency
/// @param manager The pool manager contract.
/// @return uint256 The reserves of the currency.
/// @dev returns 0 if the reserves are not synced or value is 0.
/// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
if (getSyncedCurrency(manager).isAddressZero()) return 0;
return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
}
function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
}
/// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
}
/// @notice Get the current delta for a caller in the given currency
/// @param target The credited account address
/// @param currency The currency for which to lookup the delta
function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
bytes32 key;
assembly ("memory-safe") {
mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
key := keccak256(0, 64)
}
return int256(uint256(manager.exttload(key)));
}
/// @notice Returns whether the contract is unlocked or not
function isUnlocked(IPoolManager manager) internal view returns (bool) {
return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
}
}
lib/v4-core/src/libraries/UnsafeMath.sol
// SPDX-License-Identifier: MIT
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)
}
}
}
lib/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 A BalanceDelta of 0
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)
}
}
}
lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/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 {
/// @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 ADDRESS_ZERO = 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.isAddressZero()) {
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.isAddressZero()) {
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.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/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 {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.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 pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
src/base/TransientLock.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title TransientLock
/// @notice One reentrancy lock per contract plus transient "callback expected" flags (EIP-1153, Cancun).
/// @dev Slots are fixed random constants so they cannot collide with anything else a contract stores in transient
/// storage. Every flag is set immediately before the external call that must call us back and cleared right after.
abstract contract TransientLock {
error Reentrancy();
error UnexpectedCallback();
/// keccak256("kineko.transient.lock") - 1
uint256 internal constant LOCK_SLOT = 0x1c8f6d4b0f1f86e4a2b0f7c7b1b3f8c5d0a8a3c6e1b8f5a2c7d4e9f0a1b2c3d4;
modifier nonReentrant() {
if (_tload(LOCK_SLOT) != 0) revert Reentrancy();
_tstore(LOCK_SLOT, 1);
_;
_tstore(LOCK_SLOT, 0);
}
function _isLocked() internal view returns (bool) {
return _tload(LOCK_SLOT) != 0;
}
function _tload(uint256 slot) internal view returns (uint256 v) {
assembly ("memory-safe") {
v := tload(slot)
}
}
function _tstore(uint256 slot, uint256 v) internal {
assembly ("memory-safe") {
tstore(slot, v)
}
}
/// @dev Reverts unless `msg.sender == expected` and the flag at `slot` is set; clears the flag so the same
/// expectation can be consumed only once.
function _consumeCallback(uint256 slot, address expected) internal {
if (msg.sender != expected || _tload(slot) == 0) revert UnexpectedCallback();
_tstore(slot, 0);
}
}
src/base/TwoStepOwned.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title TwoStepOwned
/// @notice Minimal two-step ownership. The owner is expected to be a multisig (behind a timelock on mainnet).
abstract contract TwoStepOwned {
error NotOwner();
error NotPendingOwner();
error ZeroAddress();
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
address public owner;
address public pendingOwner;
constructor(address owner_) {
if (owner_ == address(0)) revert ZeroAddress();
owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
function transferOwnership(address newOwner) external onlyOwner {
pendingOwner = newOwner; // zero cancels a pending transfer
emit OwnershipTransferStarted(owner, newOwner);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotPendingOwner();
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
}
src/pad/DistrictRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {TwoStepOwned} from "../base/TwoStepOwned.sol";
import {Hop, HopKind, DistrictConfig, RouteSpec, StreakParams} from "./libraries/PadTypes.sol";
import {IUniswapV3FactoryMin, IUniswapV3PoolMin, ICurvePoolMin} from "./interfaces/IPadExternal.sol";
interface IPadHookRoute {
function REGISTRY() external view returns (address);
function poolIdOf(address coin) external view returns (bytes32);
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory);
}
/// @title DistrictRegistry
/// @notice One entry per district (quote asset). Districts are added only through a timelock (propose the hash of the
/// full config + routes, execute the same calldata after `TIMELOCK`). Once added, a district's config and routes
/// are immutable. There are no buy caps. The guardian can only freeze / unfreeze BUYS (issuer freeze or pause);
/// allowlisted watcher bots can only freeze buys (one call); only the guardian unfreezes. Nothing here can touch a pool, its fees or its reserves, and nothing here is ever read on a sell.
contract DistrictRegistry is TwoStepOwned {
using StateLibrary for IPoolManager;
using PoolIdLibrary for PoolKey;
uint256 public constant TIMELOCK = 24 hours;
uint256 public constant GUARDIAN_TIMELOCK = 24 hours;
uint256 public constant MAX_HOPS = 4;
int24 public constant TICK_SPACING = 60;
uint24 public constant BASE_FEE = 10_000; // 1%
uint24 public constant MAX_SNIPE_FEE = 990_000; // 99%
uint16 public constant MAX_SNIPE_BLOCKS = 100;
IPoolManager public immutable POOL_MANAGER;
IUniswapV3FactoryMin public immutable V3_FACTORY;
address public immutable WETH;
address public guardian;
address public pendingGuardian;
uint256 public pendingGuardianEta;
mapping(address => bool) public isWatcher;
uint256 public districtCount;
// ---- creator streak parameters (timelocked >= 24 h; the hook applies them from each coin's next epoch boundary)
uint256 public constant STREAK_TIMELOCK = 24 hours;
uint32 public constant MIN_WINDOW = 1; // days
uint32 public constant MAX_WINDOW = 14; // days
uint16 public constant MAX_TIER_EPOCHS = 10_000;
/// global default (key 0) and per-district overrides (key = districtId)
mapping(uint256 => StreakParams) internal _streak;
mapping(uint256 => bool) public hasStreakOverride;
mapping(uint256 => StreakParams) public pendingStreak;
mapping(uint256 => uint256) public pendingStreakEta;
/// when the current params of `key` were executed (0 = since deployment): coins switch at their first epoch
/// boundary at or after this time, never earlier (no retroactive change)
mapping(uint256 => uint256) public streakEffectiveAt;
mapping(uint256 => DistrictConfig) internal _config;
/// @notice Buys blocked in a district (issuer freeze/pause). Read by the hook on buys only, never on sells.
mapping(uint256 => bool) public buysFrozen;
mapping(uint256 => mapping(address => Hop[])) internal _routes;
mapping(uint256 => address[]) internal _payTokens;
mapping(uint256 => string) public districtName;
/// proposal hash => earliest execution time
mapping(bytes32 => uint256) public proposalEta;
event DistrictProposed(bytes32 indexed proposalHash, uint256 eta);
event DistrictProposalCancelled(bytes32 indexed proposalHash);
event DistrictAdded(uint256 indexed districtId, address indexed quote, string name, bytes32 proposalHash);
event RouteAdded(uint256 indexed districtId, address indexed payToken, uint256 hops);
event BuysFrozen(uint256 indexed districtId, bool frozen, address indexed by);
event WatcherSet(address indexed watcher, bool allowed);
event GuardianProposed(address indexed next, uint256 eta);
event GuardianChanged(address indexed previous, address indexed next);
event StreakProposed(uint256 indexed key, StreakParams params, uint256 eta);
event StreakExecuted(uint256 indexed key, StreakParams params);
event StreakCancelled(uint256 indexed key);
error NotGuardian();
error NotWatcherOrGuardian();
error BadConfig();
error BadRoute(uint256 routeIndex, uint256 hopIndex);
error NotProposed();
error TooEarly();
error UnknownDistrict();
error DuplicatePayToken();
error GenesisOver();
error BadStreak();
/// @notice Launch-day shortcut: until this time the owner (the deployer, inside the deploy script) may add the starting
/// districts at once, with no 24 h wait. After it, every district goes through the timelocked proposal.
uint256 public immutable GENESIS_END;
constructor(address owner_, address guardian_, address watcher_, IPoolManager poolManager, address v3Factory, address weth)
TwoStepOwned(owner_)
{
GENESIS_END = block.timestamp + 12 hours;
if (watcher_ != address(0)) {
isWatcher[watcher_] = true; // initial freeze-only watcher bot (the guardian manages the list afterwards)
emit WatcherSet(watcher_, true);
}
if (guardian_ == address(0) || address(poolManager) == address(0) || v3Factory == address(0) || weth == address(0))
{
revert ZeroAddress();
}
guardian = guardian_;
// defaults (STREAK_VOLUME_CHECK.md): a day is alive if the rolling 7-day volume >= $50K; tiers at 28 / 84 days
_streak[0] = StreakParams({windowDays: 7, aliveUsd: 50_000e18, tier1Epochs: 28, tier2Epochs: 84});
POOL_MANAGER = poolManager;
V3_FACTORY = IUniswapV3FactoryMin(v3Factory);
WETH = weth;
emit GuardianChanged(address(0), guardian_);
}
modifier onlyGuardian() {
if (msg.sender != guardian) revert NotGuardian();
_;
}
// ------------------------------------------------------------------ timelocked add
function proposalHash(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(name, cfg, routes));
}
/// @notice Owner proposes a district. Everything is validated now and again at execution.
function proposeDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
external
onlyOwner
returns (bytes32 h)
{
_validate(cfg, routes);
h = proposalHash(name, cfg, routes);
uint256 eta = block.timestamp + TIMELOCK;
proposalEta[h] = eta;
emit DistrictProposed(h, eta);
}
function cancelDistrict(bytes32 h) external onlyOwner {
if (proposalEta[h] == 0) revert NotProposed();
delete proposalEta[h];
emit DistrictProposalCancelled(h);
}
/// @notice Anyone can execute a matured proposal (same calldata as proposed).
function executeDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
external
returns (uint256 id)
{
bytes32 h = proposalHash(name, cfg, routes);
uint256 eta = proposalEta[h];
if (eta == 0) revert NotProposed();
if (block.timestamp < eta) revert TooEarly();
delete proposalEta[h];
_validate(cfg, routes);
id = _add(name, cfg, routes, h);
}
/// @notice Genesis window only (see GENESIS_END): add a starting district immediately. Same validation as a proposal.
function seedDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
external
onlyOwner
returns (uint256 id)
{
if (block.timestamp > GENESIS_END) revert GenesisOver();
_validate(cfg, routes);
id = _add(name, cfg, routes, proposalHash(name, cfg, routes));
}
function _add(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes, bytes32 h)
internal
returns (uint256 id)
{
id = ++districtCount;
_config[id] = cfg;
districtName[id] = name;
for (uint256 r; r < routes.length; ++r) {
Hop[] storage dst = _routes[id][routes[r].payToken];
for (uint256 k; k < routes[r].hops.length; ++k) {
dst.push(routes[r].hops[k]);
}
_payTokens[id].push(routes[r].payToken);
emit RouteAdded(id, routes[r].payToken, routes[r].hops.length);
}
emit DistrictAdded(id, cfg.quote, name, h);
}
// ------------------------------------------------------------------ guardian / watchers
/// @notice One call to block new BUYS in a district (issuer pause/freeze). Guardian or an allowlisted watcher.
/// Sells are never read from here, so they cannot be affected.
function freezeBuys(uint256 id) external {
if (msg.sender != guardian && !isWatcher[msg.sender]) revert NotWatcherOrGuardian();
if (_config[id].quote == address(0)) revert UnknownDistrict();
buysFrozen[id] = true;
emit BuysFrozen(id, true, msg.sender);
}
/// @notice Only the guardian unfreezes.
function unfreezeBuys(uint256 id) external onlyGuardian {
if (_config[id].quote == address(0)) revert UnknownDistrict();
buysFrozen[id] = false;
emit BuysFrozen(id, false, msg.sender);
}
function setWatcher(address watcher, bool allowed) external onlyGuardian {
if (watcher == address(0)) revert ZeroAddress();
isWatcher[watcher] = allowed;
emit WatcherSet(watcher, allowed);
}
function proposeGuardian(address next) external onlyOwner {
if (next == address(0)) revert ZeroAddress();
pendingGuardian = next;
pendingGuardianEta = block.timestamp + GUARDIAN_TIMELOCK;
emit GuardianProposed(next, pendingGuardianEta);
}
function acceptGuardian() external {
address next = pendingGuardian;
if (next == address(0) || msg.sender != next) revert NotGuardian();
if (block.timestamp < pendingGuardianEta) revert TooEarly();
emit GuardianChanged(guardian, next);
guardian = next;
pendingGuardian = address(0);
pendingGuardianEta = 0;
}
// ------------------------------------------------------------------ streak parameters (timelocked)
/// @notice Owner proposes new streak params for a district (`key` = id) or the global default (`key` = 0).
function proposeStreakParams(uint256 key, StreakParams calldata sp) external onlyOwner {
_validateStreak(sp);
// a key may name a district that is not executed yet (e.g. OIL's $15K bar queued at deploy): owner-only,
// timelocked, and it only ever changes future creator tiers
pendingStreak[key] = sp;
pendingStreakEta[key] = block.timestamp + STREAK_TIMELOCK;
emit StreakProposed(key, sp, pendingStreakEta[key]);
}
function cancelStreakParams(uint256 key) external onlyOwner {
if (pendingStreakEta[key] == 0) revert NotProposed();
pendingStreakEta[key] = 0;
emit StreakCancelled(key);
}
/// @notice Anyone executes a matured proposal.
function executeStreakParams(uint256 key) external {
uint256 eta = pendingStreakEta[key];
if (eta == 0) revert NotProposed();
if (block.timestamp < eta) revert TooEarly();
pendingStreakEta[key] = 0;
_streak[key] = pendingStreak[key];
streakEffectiveAt[key] = block.timestamp;
if (key != 0) hasStreakOverride[key] = true;
emit StreakExecuted(key, _streak[key]);
}
/// @notice Effective streak params for a district (override if set, else the global default).
function streakParams(uint256 id) external view returns (StreakParams memory) {
return hasStreakOverride[id] ? _streak[id] : _streak[0];
}
/// @notice Effective params plus the time they took effect (hook hot path: 5 words).
function streakParamsAt(uint256 id)
external
view
returns (uint32 windowDays, uint96 aliveUsd, uint16 tier1Epochs, uint16 tier2Epochs, uint256 effectiveAt)
{
uint256 k = hasStreakOverride[id] ? id : 0;
StreakParams storage sp = _streak[k];
return (sp.windowDays, sp.aliveUsd, sp.tier1Epochs, sp.tier2Epochs, streakEffectiveAt[k]);
}
function _validateStreak(StreakParams calldata sp) internal pure {
if (
sp.windowDays < MIN_WINDOW || sp.windowDays > MAX_WINDOW || sp.aliveUsd == 0 || sp.tier1Epochs == 0
|| sp.tier2Epochs <= sp.tier1Epochs || sp.tier2Epochs > MAX_TIER_EPOCHS
) revert BadStreak();
}
// ------------------------------------------------------------------ views
function exists(uint256 id) external view returns (bool) {
return _config[id].quote != address(0);
}
function config(uint256 id) external view returns (DistrictConfig memory) {
return _config[id];
}
function route(uint256 id, address payToken) external view returns (Hop[] memory) {
return _routes[id][payToken];
}
function payTokens(uint256 id) external view returns (address[] memory) {
return _payTokens[id];
}
// ------------------------------------------------------------------ validation
function _validate(DistrictConfig calldata cfg, RouteSpec[] calldata routes) internal view {
if (cfg.quote == address(0) || cfg.quote.code.length == 0) revert BadConfig();
if (cfg.quoteDecimals > 36) revert BadConfig();
if (cfg.launchTick % TICK_SPACING != 0) revert BadConfig();
// both orientations must leave room for the full range and the floor band
int24 maxUsable = TickMath.maxUsableTick(TICK_SPACING);
if (cfg.launchTick <= -maxUsable + TICK_SPACING * 10 || cfg.launchTick >= maxUsable - TICK_SPACING * 10) {
revert BadConfig();
}
if (cfg.snipeStartFee < BASE_FEE || cfg.snipeStartFee > MAX_SNIPE_FEE) revert BadConfig();
if (cfg.snipeBlocks > MAX_SNIPE_BLOCKS) revert BadConfig();
if (cfg.usdPerQuoteE18 == 0) revert BadConfig();
for (uint256 r; r < routes.length; ++r) {
address pay = routes[r].payToken;
if (pay == cfg.quote) revert BadRoute(r, 0); // paying in the quote needs no route
for (uint256 q; q < r; ++q) {
if (routes[q].payToken == pay) revert DuplicatePayToken();
}
Hop[] calldata hops = routes[r].hops;
if (hops.length == 0 || hops.length > MAX_HOPS) revert BadRoute(r, 0);
address cur = pay;
for (uint256 k; k < hops.length; ++k) {
Hop calldata h = hops[k];
if (!_same(cur, h.tokenIn) || h.tokenIn == h.tokenOut) revert BadRoute(r, k);
_validateHop(h, r, k);
cur = h.tokenOut;
}
if (cur != cfg.quote) revert BadRoute(r, hops.length);
}
}
/// `coin` has a pad pool on `hook` whose quote is `other` and whose house flag is set (PadHook storage layout:
/// PoolInfo word 0 = coin, word 1 = quote, word 2 byte 18 = house; see PadHookLib).
function _isHousePool(address hook, address coin, address other) internal view returns (bool) {
bytes32 id = IPadHookRoute(hook).poolIdOf(coin);
if (id == bytes32(0)) return false;
bytes32[] memory w = IPadHookRoute(hook).extsload(keccak256(abi.encode(id, uint256(0))), 3);
return address(uint160(uint256(w[0]))) == coin && address(uint160(uint256(w[1]))) == other
&& (uint256(w[2]) >> 144) & 0xff != 0;
}
/// ETH (address(0)) and WETH are interchangeable at hop boundaries; the executor wraps/unwraps.
function _same(address a, address b) internal view returns (bool) {
if (a == b) return true;
return (a == address(0) && b == WETH) || (a == WETH && b == address(0));
}
function _validateHop(Hop calldata h, uint256 r, uint256 k) internal view {
if (h.kind == HopKind.V3) {
if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
address p = V3_FACTORY.getPool(h.tokenIn, h.tokenOut, h.fee);
if (p == address(0) || p != h.pool) revert BadRoute(r, k);
} else if (h.kind == HopKind.V4) {
if (h.pool != address(0)) revert BadRoute(r, k);
(address c0, address c1) = h.tokenIn < h.tokenOut ? (h.tokenIn, h.tokenOut) : (h.tokenOut, h.tokenIn);
PoolKey memory key = PoolKey({
currency0: Currency.wrap(c0),
currency1: Currency.wrap(c1),
fee: h.fee,
tickSpacing: h.tickSpacing,
hooks: IHooks(address(0)) // routes never use hooked pools (so never our own pad pools)
});
(uint160 sqrtP,,,) = POOL_MANAGER.getSlot0(key.toId());
if (sqrtP == 0) revert BadRoute(r, k);
} else if (h.kind == HopKind.PAD) {
// only a HOUSE pool (KINEKO) of a pad hook bound to THIS registry; both tokens ERC20 (no native ETH)
if (h.pool == address(0) || h.pool.code.length == 0) revert BadRoute(r, k);
if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
if (IPadHookRoute(h.pool).REGISTRY() != address(this)) revert BadRoute(r, k);
if (!_isHousePool(h.pool, h.tokenIn, h.tokenOut) && !_isHousePool(h.pool, h.tokenOut, h.tokenIn)) {
revert BadRoute(r, k);
}
} else if (h.kind == HopKind.CURVE) {
if (h.pool == address(0) || h.pool.code.length == 0) revert BadRoute(r, k);
if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
if (h.curveI < 0 || h.curveJ < 0 || h.curveI == h.curveJ) revert BadRoute(r, k);
if (ICurvePoolMin(h.pool).coins(uint256(uint8(h.curveI))) != h.tokenIn) revert BadRoute(r, k);
if (ICurvePoolMin(h.pool).coins(uint256(uint8(h.curveJ))) != h.tokenOut) revert BadRoute(r, k);
} else {
revert BadRoute(r, k);
}
}
}
src/pad/PadFloorMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {PadMath} from "./libraries/PadMath.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";
/// @title PadFloorMath
/// @notice Stateless floor-band search used by PadHook (split out for contract size). Pure functions only, no storage,
/// called with STATICCALL; deployed once by the hook's constructor.
contract PadFloorMath {
int24 public constant BAND_WIDTH = 60;
int24 public constant MAX_COIN_TICK = 887_220;
/// liquidity above this is never placed in one band (stays far below v4's per-tick maximum)
uint128 public constant MAX_BAND_LIQUIDITY = 1e32;
/// Highest band [u, u+W] (u = launchTick + k*W) entirely below the current price such that MAIN plus the band
/// hold at least `H` coins at price u, i.e. the dump floor is at or above u. Returns ok=false if none.
function bestBand(bool coin0, uint128 Lm, int24 tl, uint256 Q, uint256 H, int24 poolTick, int24 refTick)
external
pure
returns (bool ok, int24 u, uint128 L)
{
if (Q < 3) return (false, 0, 0);
// coin0: band pool range [u, u+W] is quote-only iff poolTick >= u+W
// coin1: band pool range [-u-W, -u] is quote-only iff poolTick < -u-W
int24 maxTop = coin0 ? poolTick : -poolTick - 1;
if (maxTop > refTick) maxTop = refTick; // never above the slow reference (anti-sandwich)
if (maxTop > MAX_COIN_TICK) maxTop = MAX_COIN_TICK;
if (maxTop - BAND_WIDTH < tl) return (false, 0, 0);
int256 kMax = (int256(maxTop) - BAND_WIDTH - tl) / BAND_WIDTH;
uint256 q = Q - 2; // leave rounding room for the add
int256 lo = 0;
int256 hi = kMax;
if (!_bandHolds(coin0, Lm, tl, q, H, tl)) return (false, 0, 0);
while (lo < hi) {
int256 mid = (lo + hi + 1) / 2;
if (_bandHolds(coin0, Lm, tl, q, H, int24(int256(tl) + mid * BAND_WIDTH))) lo = mid;
else hi = mid - 1;
}
u = int24(int256(tl) + lo * BAND_WIDTH);
L = PadMath.liquidityForQuote(coin0, q, u, u + BAND_WIDTH);
if (L == 0 || L > MAX_BAND_LIQUIDITY) return (false, 0, 0);
ok = true;
}
function _bandHolds(bool coin0, uint128 Lm, int24 tl, uint256 q, uint256 H, int24 u) internal pure returns (bool) {
uint128 L = PadMath.liquidityForQuote(coin0, q, u, u + BAND_WIDTH);
uint256 r = PadMath.coinsAt(coin0, Lm, tl, MAX_COIN_TICK, u) + PadMath.coinsBetween(coin0, L, u, u + BAND_WIDTH);
return r >= H;
}
/// Dump floor as a coin-tick: the highest coin-tick u at which MAIN + band would hold >= H coins. It depends only
/// on the liquidity layout and H, never on the current price, so trades cannot move it.
function floorTick(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H)
external
pure
returns (int24)
{
return _floorTick(coin0, Lm, tl, bandL, bandLower, H);
}
function _floorTick(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H)
internal
pure
returns (int24)
{
if (_reservesAt(coin0, Lm, tl, bandL, bandLower, tl) < H) return tl;
int24 lo = tl;
int24 hi = MAX_COIN_TICK;
while (lo < hi) {
int24 mid = int24((int256(lo) + int256(hi) + 1) / 2);
if (_reservesAt(coin0, Lm, tl, bandL, bandLower, mid) >= H) lo = mid;
else hi = mid - 1;
}
return lo;
}
// ------------------------------------------------------------------ Floor Pawn helpers
// The floor lends from its band. Lent principal is counted as VIRTUAL band quote at the band's current range, so the
// published floor = floorTick(Lm, bandL_physical + L(lentQuote), H). Safe because every loan is backed by escrowed
// coins worth >= its principal at the floor price (FLOOR_TECH_REPORT.md, theorem T1).
/// Liquidity that `q` quote buys over coin-ticks [a, a+W] placed below the price (rounded down).
function liqForQuote(bool coin0, uint256 q, int24 a) external pure returns (uint128) {
return PadMath.liquidityForQuote(coin0, q, a, a + BAND_WIDTH);
}
/// Liquidity a repaid principal restores so that physical + virtual stays exactly constant:
/// L(lent) - L(lent - principal) at the band's range.
function liqDelta(bool coin0, uint256 lent, uint256 principal, int24 a) external pure returns (uint128) {
return PadMath.liquidityForQuote(coin0, lent, a, a + BAND_WIDTH)
- PadMath.liquidityForQuote(coin0, lent - principal, a, a + BAND_WIDTH);
}
/// Virtual band liquidity: physical band + the liquidity the outstanding lent quote would buy at the band's range.
function virtualL(bool coin0, uint128 bandL, int24 bandLower, uint256 lentQ) public pure returns (uint128) {
uint256 v = uint256(bandL) + PadMath.liquidityForQuote(coin0, lentQ, bandLower, bandLower + BAND_WIDTH);
return v > type(uint128).max ? type(uint128).max : uint128(v);
}
/// Quote needed to add liquidity `L` over [a, a+W] below the price, rounded UP (what a repayment must bring).
function quoteForLiqUp(bool coin0, uint128 L, int24 a) external pure returns (uint256) {
(int24 lo, int24 hi) = PadMath.poolRange(coin0, a, a + BAND_WIDTH);
uint160 sA = TickMath.getSqrtPriceAtTick(lo);
uint160 sB = TickMath.getSqrtPriceAtTick(hi);
return coin0 ? SqrtPriceMath.getAmount1Delta(sA, sB, L, true) : SqrtPriceMath.getAmount0Delta(sA, sB, L, true);
}
/// Published dump floor with lent quote counted as virtual band quote.
function floorTickLent(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H, uint256 lentQ)
external
pure
returns (int24)
{
return _floorTick(coin0, Lm, tl, virtualL(coin0, bandL, bandLower, lentQ), bandLower, H);
}
function _reservesAt(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, int24 u)
internal
pure
returns (uint256)
{
return PadMath.coinsAt(coin0, Lm, tl, MAX_COIN_TICK, u)
+ PadMath.coinsAt(coin0, bandL, bandLower, bandLower + BAND_WIDTH, u);
}
}
src/pad/PadHook.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "v4-core/types/PoolOperation.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {TransientLock} from "../base/TransientLock.sol";
import {DistrictRegistry} from "./DistrictRegistry.sol";
import {DistrictConfig, StreakParams} from "./libraries/PadTypes.sol";
import {PadMath} from "./libraries/PadMath.sol";
import {PadFloorMath} from "./PadFloorMath.sol";
import {PadStreakMath} from "./PadStreakMath.sol";
import {IPadToken} from "./interfaces/IPadExternal.sol";
interface ICreatorVaultMin {
function register(address coin, address creator, address quote) external;
function accrue(address coin, uint256 amount) external;
function isActive(address coin) external view returns (bool);
}
/// @title PadHook
/// @notice The single Uniswap v4 hook behind every KINEKO Pad pool (COIN/QUOTE, dynamic fee, tick spacing 60).
///
/// Standard v4 accounting only: no return deltas, no virtual legs, no hook-initiated swaps. Every trade is a plain
/// PoolManager `Swap`; the fee is v4's native dynamic LP fee, written into pool state with `updateDynamicLPFee`
/// (never the per-swap override flag), so simulators and indexers see the real stored fee.
///
/// Liquidity: the hook owns exactly two positions per pool and nobody else can add or remove liquidity:
/// - MAIN: the whole coin supply, single-sided, from the district launch tick to the max usable tick (never touched
/// again: it alone can buy back every coin ever sold out of it, so sells always clear).
/// - FLOOR BAND: one tick-spacing-wide quote-only band funded by fees, placed by `collect()` right above the pool's
/// dump floor (the price reached if every circulating coin were sold), and re-placed only if that does not lower
/// the floor. See `PAD_NOTES.md` for the design and proofs.
///
/// There are no buy caps. Sells never read the registry or frozen mode, and their hook code cannot revert.
/// Phase 1: the Floor Pawn primitive (`deskOp` + the FloorWouldFall guard + lent / virtual-band accounting, design E of
/// FLOOR_TECH_REPORT.md). Views live in PadReader (reads this hook's storage through `extsload`) to fit EIP-170.
contract PadHook is IHooks, IUnlockCallback, TransientLock {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
using TransientStateLibrary for IPoolManager;
using BalanceDeltaLibrary for BalanceDelta;
// ------------------------------------------------------------------ constants
int24 public constant TICK_SPACING = 60;
int24 public constant BAND_WIDTH = 60;
int24 public constant MAX_COIN_TICK = 887_220; // TickMath.maxUsableTick(60)
uint24 public constant BASE_FEE = 10_000; // 1% in pips (the standard tier)
uint24 public constant BASE_FEE_2 = 20_000; // 2% tier (chosen by the creator at launch, immutable per coin)
/// house coin (KINEKO) fixed split of its 2% fee: platform 50% (1.00%), rewards 25% (0.50%), floor 25% (0.50%), creator 0 (no streak)
uint256 public constant HOUSE_PLATFORM_BPS = 5000;
uint256 public constant HOUSE_REWARDS_BPS = 2500;
uint256 internal constant PIPS = 1_000_000;
uint256 internal constant BPS = 10_000;
// ---- FEE SPLIT (adjust here before deploy; shares are bps of the 1% base fee, must sum to <= 10_000) ----
/// creator 0.40% / 0.50% / 0.60% by CREATOR STREAK (consecutive "alive" weeks), rewards 0.30%, platform 0.10%
/// (FeeRouterV2), the floor gets the remainder (0.20% / 0.10% / 0%) plus 100% of the anti-snipe surplus.
uint256 public constant CREATOR_BPS_T0 = 4000;
uint256 public constant CREATOR_BPS_T1 = 5000;
uint256 public constant CREATOR_BPS_T2 = 6000;
uint256 public constant REWARDS_BPS = 3000;
uint256 public constant PLATFORM_BPS = 1000;
// creator shares are fixed to exactly these three tiers (0.40 / 0.50 / 0.60%); only the streak thresholds, epoch
// length and "alive" volume come from the registry (timelocked, next-boundary)
/// the floor band may never sit above the slow reference price, which can rise at most this many ticks per block
/// (~0.2%): a same-block pump cannot move it at all, a multi-block pump must be held in the open market
int24 public constant REF_RISE_PER_BLOCK = 20;
bytes32 internal constant SALT_MAIN = bytes32(0);
bytes32 internal constant SALT_BAND = bytes32(uint256(1));
uint8 internal constant ACT_SEED = 1;
uint8 internal constant ACT_COLLECT = 2;
uint8 internal constant ACT_CLAIM = 3;
uint8 internal constant ACT_DESK = 4;
/// keccak256("kineko.pad.hook.unlock") - 1
uint256 internal constant UNLOCK_FLAG = 0x2b6a8f1d0c4e7a93b5d2e6f1a7c3b9d8e4f0a1b2c3d4e5f60718293a4b5c6d7e;
/// transient: fee applied to the current swap (set in beforeSwap, read in afterSwap)
uint256 internal constant FEE_SLOT = 0x5d1e3a7b9c2f4e6a8b0c1d3e5f7a9b2c4d6e8f0a1b3c5d7e9f1a2b4c6d8e0f12;
/// transient: pool id whose NEXT swap is the creator's bundled first buy (base fee), set only by the factory
uint256 internal constant CREATOR_BUY_SLOT = 0x7c9e1b3d5f7a2c4e6b8d0f1a3c5e7b9d2f4a6c8e0b1d3f5a7c9e2b4d6f8a0c13;
// ------------------------------------------------------------------ immutables
IPoolManager public immutable POOL_MANAGER;
DistrictRegistry public immutable REGISTRY;
address public immutable FACTORY;
/// platform share (0.2%) -> FeeRouterV2 (buffer + treasury)
address public immutable PLATFORM;
/// rewards pot (0.3%) -> RewardsVault
address public immutable REWARDS;
/// sell-side (coin) fees are handed to this contract, which sells them through the pool as normal swaps
address public immutable CONVERTER;
/// creator shares accrue here ("use it or lose it"); lapsed creators' new shares go to the floor
ICreatorVaultMin public immutable CREATOR_VAULT;
/// stateless floor-search math (deployed by this constructor, called with STATICCALL)
PadFloorMath public immutable FLOOR_MATH;
/// stateless streak evaluation (deployed by this constructor, called with STATICCALL)
PadStreakMath public immutable STREAK_MATH;
/// the floor desk (pawn + redemption policy); the only caller of deskOp
address public immutable DESK;
// ------------------------------------------------------------------ state
struct PoolInfo {
address coin;
address quote;
uint32 districtId;
uint64 launchBlock;
bool coinIsToken0;
int24 launchTick; // coin-tick of the opening price = MAIN lower bound
int24 bandLower; // coin-tick lower bound of the floor band (valid when bandLiquidity > 0)
uint24 snipeStartFee;
uint16 snipeBlocks;
uint24 storedFee; // mirror of the pool's stored dynamic LP fee
uint24 baseFee; // 1% or 2%: the coin's fee tier, fixed at launch
bool house; // KINEKO: fixed split, no creator share, no streak tiers (set only by the house launch path)
uint8 quoteDecimals;
uint128 liquidityMain;
uint128 bandLiquidity;
uint128 usdPerQuoteE18; // tier reference only
uint256 volumeUsdE18; // lifetime volume (both sides) in USD at the district reference
uint256 quoteVolume; // lifetime volume in quote units
uint256 pendingSurplus; // anti-snipe surplus not yet collected (goes 100% to the floor)
uint256 pendingFloor; // floor quote held as ERC-6909 claims until it can be placed
int24 refCoinTick; // slow reference price: follows the price down at once, rises <= REF_RISE_PER_BLOCK per block
uint64 refBlock;
int24 stickyTick; // converter reference: follows the pre-swap price by at most REF_RISE_PER_BLOCK per block, both ways
uint64 stickyBlock;
int24 openTick; // pre-swap price at the first swap of `openBlock` (block-open price)
uint64 openBlock;
// creator streak (see PAD_NOTES "Creator streak"): daily buckets, rolling-window alive test
uint32 lastDay; // every day before this one has been judged
uint16 streak; // consecutive alive days (with tier drops)
uint8 window; // params in force (snapshotted; switch at the next day boundary after a registry change)
uint16 tier1;
uint16 tier2;
uint96 aliveUsd;
// floor quote lent out by the desk (principal, rounded up); counted as VIRTUAL band quote
uint128 lentQuote;
}
mapping(PoolId => PoolInfo) internal _pools;
mapping(address coin => PoolId) public poolIdOf;
/// 14 daily USD-volume buckets per pool, two per word: [day:32][usd:96]
mapping(PoolId => uint256[7]) internal _dayRing;
/// fee shares whose push failed (e.g. recipient frozen by the issuer), held as ERC-6909 claims in the PoolManager
mapping(address recipient => mapping(address currency => uint256)) public owed;
/// ERC-6909 claims the hook holds per currency = sum(owed) + sum(pendingFloor) (invariant)
mapping(address currency => uint256) public claimsLedger;
// ------------------------------------------------------------------ events
event PoolSeeded(
PoolId indexed poolId, address indexed coin, uint32 indexed districtId, address creator, uint128 liquidity, uint256 coinsDeposited
);
event Referral(address indexed trader, address indexed referrer, PoolId indexed poolId, uint256 quoteVolume);
event Collected(
PoolId indexed poolId,
uint256 quoteFees,
uint256 coinFeesBurned,
uint256 toCreator,
uint256 toRewards,
uint256 toPlatform,
uint256 toFloor
);
event FloorPlaced(PoolId indexed poolId, int24 bandLower, uint128 bandLiquidity, uint256 bandQuote, int24 floorTick);
event FloorDeferred(PoolId indexed poolId, uint256 pendingFloor);
event CoinsBurned(PoolId indexed poolId, uint256 amount);
event CoinFeesToConverter(PoolId indexed poolId, uint256 amount);
event PayoutPushed(address indexed recipient, address indexed currency, uint256 amount);
event PayoutOwed(address indexed recipient, address indexed currency, uint256 amount);
event Claimed(address indexed recipient, address indexed currency, uint256 amount);
event StoredFeeSet(PoolId indexed poolId, uint24 fee);
// ------------------------------------------------------------------ errors
error NotPoolManager();
error NotFactory();
error UnknownPool();
error BadPoolKey();
error AlreadySeeded();
error BuysFrozen();
error LiquidityLocked();
error NothingOwed();
error AccountingError();
constructor(
IPoolManager poolManager,
DistrictRegistry registry,
address factory,
address platform,
address rewards,
address converter,
address creatorVault,
address desk
) {
DESK = desk;
if (converter == address(0) || creatorVault == address(0)) revert BadPoolKey();
CONVERTER = converter;
CREATOR_VAULT = ICreatorVaultMin(creatorVault);
FLOOR_MATH = new PadFloorMath();
STREAK_MATH = new PadStreakMath();
if (
address(poolManager) == address(0) || address(registry) == address(0) || factory == address(0)
|| platform == address(0) || rewards == address(0)
) revert BadPoolKey();
POOL_MANAGER = poolManager;
REGISTRY = registry;
FACTORY = factory;
PLATFORM = platform;
REWARDS = rewards;
Hooks.validateHookPermissions(IHooks(address(this)), getHookPermissions());
}
function getHookPermissions() public pure returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: true,
afterInitialize: false,
beforeAddLiquidity: true,
afterAddLiquidity: false,
beforeRemoveLiquidity: true,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
modifier onlyPoolManager() {
if (msg.sender != address(POOL_MANAGER)) revert NotPoolManager();
_;
}
modifier onlyFactory() {
if (msg.sender != FACTORY) revert NotFactory();
_;
}
// ================================================================== factory entry points
/// @notice Registers a freshly initialized pool and deposits the whole coin supply (held by this hook) as the MAIN
/// position. Factory only, once per pool.
function seed(PoolKey calldata key, address coin, uint32 districtId, address creator, int24 launchTick, uint24 baseFee, bool house)
external
onlyFactory
nonReentrant
returns (PoolId id)
{
id = key.toId();
if (_pools[id].coin != address(0) || PoolId.unwrap(poolIdOf[coin]) != bytes32(0)) revert AlreadySeeded();
DistrictConfig memory cfg = REGISTRY.config(districtId);
bool coin0 = Currency.unwrap(key.currency0) == coin;
address quote = coin0 ? Currency.unwrap(key.currency1) : Currency.unwrap(key.currency0);
if (
(!coin0 && Currency.unwrap(key.currency1) != coin) || quote != cfg.quote || address(key.hooks) != address(this)
|| key.fee != LPFeeLibrary.DYNAMIC_FEE_FLAG || key.tickSpacing != TICK_SPACING || creator == address(0)
|| launchTick < cfg.launchTick || launchTick % TICK_SPACING != 0
|| (baseFee != BASE_FEE && baseFee != BASE_FEE_2) || cfg.snipeStartFee < baseFee
) revert BadPoolKey();
// the factory must have initialized the pool exactly at the launch price
(uint160 sqrtP,,,) = POOL_MANAGER.getSlot0(id);
if (sqrtP != TickMath.getSqrtPriceAtTick(coin0 ? launchTick : -launchTick)) revert BadPoolKey();
PoolInfo storage p = _pools[id];
p.coin = coin;
p.quote = quote;
p.districtId = districtId;
p.launchBlock = uint64(block.number);
p.refCoinTick = launchTick;
p.refBlock = uint64(block.number);
p.stickyTick = launchTick;
p.stickyBlock = uint64(block.number);
p.openTick = launchTick;
p.openBlock = uint64(block.number);
{
StreakParams memory sp = REGISTRY.streakParams(districtId);
p.lastDay = uint32(block.timestamp / 1 days);
p.window = uint8(sp.windowDays);
p.tier1 = sp.tier1Epochs;
p.tier2 = sp.tier2Epochs;
p.aliveUsd = sp.aliveUsd;
}
p.coinIsToken0 = coin0;
p.launchTick = launchTick;
p.snipeStartFee = cfg.snipeStartFee;
p.snipeBlocks = cfg.snipeBlocks;
p.baseFee = baseFee;
p.house = house;
p.quoteDecimals = cfg.quoteDecimals;
p.usdPerQuoteE18 = cfg.usdPerQuoteE18;
poolIdOf[coin] = id;
CREATOR_VAULT.register(coin, creator, quote);
// stored fee starts at the anti-snipe level (dynamic pools start at 0)
_setStoredFee(key, p, cfg.snipeBlocks == 0 ? baseFee : cfg.snipeStartFee);
uint256 supply = IPadToken(coin).balanceOf(address(this));
uint128 L = PadMath.liquidityForCoins(coin0, supply, launchTick, MAX_COIN_TICK);
p.liquidityMain = L;
_unlock(abi.encode(ACT_SEED, abi.encode(id)));
emit PoolSeeded(id, coin, districtId, creator, L, supply - IPadToken(coin).balanceOf(address(this)));
_burnHeldCoins(id, coin); // rounding dust
}
/// @notice Marks the next swap on `id` (in this transaction) as the creator's bundled first buy: it pays the
/// base fee instead of the anti-snipe fee. Factory only; the flag lives in transient storage.
function openCreatorBuy(PoolId id) external onlyFactory {
_tstore(CREATOR_BUY_SLOT, uint256(PoolId.unwrap(id)));
}
// ================================================================== hook callbacks
function beforeInitialize(address sender, PoolKey calldata key, uint160) external view onlyPoolManager returns (bytes4) {
// only the factory creates pools with this hook (anyone else's initialize reverts)
if (sender != FACTORY) revert NotFactory();
if (key.fee != LPFeeLibrary.DYNAMIC_FEE_FLAG || key.tickSpacing != TICK_SPACING) revert BadPoolKey();
return IHooks.beforeInitialize.selector;
}
function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) {
revert LiquidityLocked();
}
/// No external LPs: the hook's own modifyLiquidity calls never reach here (v4 skips self-calls).
function beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external
view
onlyPoolManager
returns (bytes4)
{
revert LiquidityLocked();
}
function afterAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external
pure
returns (bytes4, BalanceDelta)
{
revert LiquidityLocked();
}
function beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external
view
onlyPoolManager
returns (bytes4)
{
revert LiquidityLocked();
}
function afterRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external
pure
returns (bytes4, BalanceDelta)
{
revert LiquidityLocked();
}
function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
PoolId id = key.toId();
PoolInfo storage p = _pools[id];
if (p.coin == address(0)) revert UnknownPool(); // unreachable: only seeded pools use this hook
bool isBuy = p.coinIsToken0 ? !params.zeroForOne : params.zeroForOne;
uint24 fee = p.baseFee;
if (isBuy) {
if (REGISTRY.buysFrozen(p.districtId)) revert BuysFrozen();
if (_tload(CREATOR_BUY_SLOT) == uint256(PoolId.unwrap(id))) {
_tstore(CREATOR_BUY_SLOT, 0);
} else {
fee = _buyFee(p);
}
}
if (fee != p.storedFee) _setStoredFee(key, p, fee);
_updateRef(id, p);
_tstore(FEE_SLOT, fee);
return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
/// @dev Never reverts (no caps): volume, anti-snipe surplus and the streak day ring only.
function afterSwap(address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData)
external
onlyPoolManager
returns (bytes4, int128)
{
PoolId id = key.toId();
PoolInfo storage p = _pools[id];
bool isBuy = p.coinIsToken0 ? !params.zeroForOne : params.zeroForOne;
int128 dq = p.coinIsToken0 ? delta.amount1() : delta.amount0(); // swapper's quote delta
uint256 vol;
if (isBuy) {
vol = dq < 0 ? uint256(uint128(-dq)) : 0;
uint256 fee = _tload(FEE_SLOT);
uint256 bf = p.baseFee;
if (fee > bf) p.pendingSurplus += FullMath.mulDiv(vol, fee - bf, PIPS);
} else {
vol = dq > 0 ? uint256(uint128(dq)) : 0;
}
unchecked {
// volume is bounded by int128 per swap; sums cannot realistically wrap, and wrapping would only
// affect creator tiers (never solvency), so it must not be able to revert a sell
p.quoteVolume += vol;
uint256 usd = FullMath.mulDiv(vol, p.usdPerQuoteE18, 10 ** uint256(p.quoteDecimals));
p.volumeUsdE18 += usd;
_addDayVolume(id, p, usd);
}
// optional referral: event only (hookData = abi.encode(referrer[, trader])); never used for logic
if (hookData.length >= 32) {
address referrer;
address trader = sender;
assembly ("memory-safe") {
referrer := and(calldataload(hookData.offset), 0xffffffffffffffffffffffffffffffffffffffff)
}
if (hookData.length >= 64) {
assembly ("memory-safe") {
trader := and(calldataload(add(hookData.offset, 32)), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
if (referrer != address(0)) emit Referral(trader, referrer, id, vol);
}
return (IHooks.afterSwap.selector, 0);
}
function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
revert LiquidityLocked();
}
function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
revert LiquidityLocked();
}
// ================================================================== permissionless fee handling
/// @notice Collects the pool's LP fees and splits them: quote fees -> creator / rewards / platform (pushed out
/// immediately; a failed push is kept as an ERC-6909 claim) and the floor; coin fees are burned; the floor
/// band is re-placed at the dump floor when that raises (never lowers) the floor. Anyone can call it.
function collect(address coin) external nonReentrant {
PoolId id = poolIdOf[coin];
if (_pools[id].coin == address(0)) revert UnknownPool();
bytes memory ret = _unlock(abi.encode(ACT_COLLECT, abi.encode(id)));
uint256 feeCoins = abi.decode(ret, (uint256));
if (feeCoins > 0) emit CoinFeesToConverter(id, feeCoins); // already taken to the converter in the unlock
_burnHeldCoins(id, coin); // floor-bought band coins / donations burn
}
/// @notice Pays `recipient` its owed `currency` (fee shares whose push failed). Anyone can call; pays only the recipient.
function claim(address recipient, address currency) external nonReentrant returns (uint256 amount) {
amount = owed[recipient][currency];
if (amount == 0) revert NothingOwed();
owed[recipient][currency] = 0;
claimsLedger[currency] -= amount;
_unlock(abi.encode(ACT_CLAIM, abi.encode(recipient, currency, amount)));
emit Claimed(recipient, currency, amount);
}
/// @notice Syncs the pool's stored fee with the schedule (e.g. to 1% right after the anti-snipe window) so that
/// simulators see the current buy fee before the next swap. Anyone can call.
function pokeFee(address coin) external nonReentrant {
PoolId id = poolIdOf[coin];
PoolInfo storage p = _pools[id];
if (p.coin == address(0)) revert UnknownPool();
uint24 fee = _buyFee(p);
if (fee != p.storedFee) _setStoredFee(_key(p), p, fee);
}
// ================================================================== converter credits
/// @notice The converter minted `floorAmt` quote claims to this hook (floor share of converted sell fees) and
/// `owedAmts` for recipients whose push failed. Verified against the real claim balance (ledger invariant).
function creditFromConverter(address coin, uint256 floorAmt, address[3] calldata to, uint256[3] calldata owedAmts)
external
nonReentrant
{
if (msg.sender != CONVERTER) revert NotFactory();
PoolInfo storage p = _pools[poolIdOf[coin]];
if (p.coin == address(0)) revert UnknownPool();
address q = p.quote;
uint256 total = floorAmt + owedAmts[0] + owedAmts[1] + owedAmts[2];
if (POOL_MANAGER.balanceOf(address(this), uint256(uint160(q))) < claimsLedger[q] + total) revert AccountingError();
claimsLedger[q] += total;
p.pendingFloor += floorAmt;
for (uint256 i; i < 3; ++i) {
if (owedAmts[i] > 0) {
owed[to[i]][q] += owedAmts[i];
emit PayoutOwed(to[i], q, owedAmts[i]);
}
}
}
// ================================================================== floor desk primitive
error NotDesk();
error FloorWouldFall();
/// @notice DESK only. One atomic desk operation, then the GUARD: the published floor (MAIN + physical band + lent
/// quote, over H) must not have fallen, whatever the desk asked for.
/// credit/extra: the desk minted credit + extra quote claims to this hook first; credit (repaid principal) goes back
/// into the band (exact virtual-liquidity restore, lentQuote -= credit); extra -> pendingFloor
/// burnCoins: pulled from the desk and burned (redemptions, defaulted pawn collateral)
/// pay/keep/to: removes pay quote from the quote-only band, sends pay - keep to `to` (keep + rounding -> floor claims)
/// lend: the principal owed for that payout (rounded UP) is added to lentQuote
/// writeOff: lent principal of a defaulted loan dropped (its coins are in burnCoins)
function deskOp(
address coin,
uint256 burnCoins,
uint256 pay,
uint256 keep,
address to,
bool lend,
uint256 writeOff,
uint256 credit,
uint256 extra
) external nonReentrant returns (uint256 owedQ) {
if (msg.sender != DESK) revert NotDesk();
PoolId id = poolIdOf[coin];
PoolInfo storage p = _pools[id];
address q = p.quote;
if (p.coin == address(0) || POOL_MANAGER.balanceOf(address(this), uint256(uint160(q))) < claimsLedger[q] + credit + extra) {
revert AccountingError();
}
int24 f0 = _pubFloor(p);
if (burnCoins > 0) {
SafeTransferLib.safeTransferFrom(coin, msg.sender, address(this), burnCoins);
_burnHeldCoins(id, coin);
}
owedQ = abi.decode(_unlock(abi.encode(ACT_DESK, abi.encode(id, pay, keep, to, credit, extra))), (uint256));
if (lend) p.lentQuote += uint128(owedQ);
p.lentQuote -= uint128(writeOff);
if (_pubFloor(p) < f0) revert FloorWouldFall();
}
function _pubFloor(PoolInfo storage p) internal view returns (int24) {
return _floorTickFor(p, _vL(p), p.bandLower, _effectiveSupply(p.coin));
}
function _doDesk(PoolId id, uint256 pay, uint256 keep, address to, uint256 credit, uint256 extra)
internal
returns (uint256 owedUp)
{
PoolInfo storage p = _pools[id];
if (credit + extra > 0) POOL_MANAGER.burn(address(this), uint256(uint160(p.quote)), credit + extra);
if (credit > 0) {
uint256 lent = p.lentQuote;
// exactly the virtual liquidity the principal leaves: physical + virtual stays constant
uint128 l = FLOOR_MATH.liqDelta(p.coinIsToken0, lent, credit, p.bandLower);
p.lentQuote = uint128(lent - credit);
if (l > 0) _bandMod(p, int256(uint256(l)));
}
if (pay > 0) {
uint128 dL = FLOOR_MATH.liqForQuote(p.coinIsToken0, pay, p.bandLower) + 1;
_bandMod(p, -int256(uint256(dL))); // over-draw underflows; a short payout makes _pendFloorDelta revert
POOL_MANAGER.take(Currency.wrap(p.quote), to, pay - keep);
owedUp = FLOOR_MATH.quoteForLiqUp(p.coinIsToken0, dL, p.bandLower);
}
_pendFloorDelta(p); // net quote left -> floor claims; reverts if the credit did not cover the add
}
/// Modifies the band by dL (quote-only: reverts if coins would move). Band position fees realised by the modify:
/// coin fees -> converter (as in collect), quote fees stay in the delta (-> floor claims).
function _bandMod(PoolInfo storage p, int256 dL) internal {
bool coin0 = p.coinIsToken0;
(int24 lo, int24 hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
(BalanceDelta d, BalanceDelta fees) = POOL_MANAGER.modifyLiquidity(
_key(p), ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: dL, salt: SALT_BAND}), ""
);
BalanceDelta prin = d - fees;
if ((coin0 ? prin.amount0() : prin.amount1()) != 0) revert AccountingError();
int128 fc = coin0 ? fees.amount0() : fees.amount1();
if (fc > 0) POOL_MANAGER.take(Currency.wrap(p.coin), CONVERTER, uint256(uint128(fc)));
p.bandLiquidity = uint128(uint256(int256(uint256(p.bandLiquidity)) + dL));
}
/// Net positive quote delta of this hook -> floor claims (pendingFloor); a negative delta reverts.
function _pendFloorDelta(PoolInfo storage p) internal {
int256 dq = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.quote));
if (dq < 0) revert AccountingError();
if (dq > 0) {
POOL_MANAGER.mint(address(this), uint256(uint160(p.quote)), uint256(dq));
p.pendingFloor += uint256(dq);
claimsLedger[p.quote] += uint256(dq);
}
}
// ================================================================== unlock
function _unlock(bytes memory data) internal returns (bytes memory ret) {
_tstore(UNLOCK_FLAG, 1);
ret = POOL_MANAGER.unlock(data);
_tstore(UNLOCK_FLAG, 0);
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
_consumeCallback(UNLOCK_FLAG, address(POOL_MANAGER));
(uint8 act, bytes memory rest) = abi.decode(data, (uint8, bytes));
if (act == ACT_SEED) {
_doSeed(abi.decode(rest, (PoolId)));
} else if (act == ACT_COLLECT) {
return abi.encode(_doCollect(abi.decode(rest, (PoolId))));
} else if (act == ACT_DESK) {
(PoolId id, uint256 pay, uint256 keep, address to, uint256 credit, uint256 extra) =
abi.decode(rest, (PoolId, uint256, uint256, address, uint256, uint256));
return abi.encode(_doDesk(id, pay, keep, to, credit, extra));
} else if (act == ACT_CLAIM) {
(address recipient, address currency, uint256 amount) = abi.decode(rest, (address, address, uint256));
uint256 cid = uint256(uint160(currency));
POOL_MANAGER.burn(address(this), cid, amount);
POOL_MANAGER.take(Currency.wrap(currency), recipient, amount);
} else {
revert AccountingError();
}
return "";
}
function _doSeed(PoolId id) internal {
PoolInfo storage p = _pools[id];
PoolKey memory key = _key(p);
(int24 lo, int24 hi) = PadMath.poolRange(p.coinIsToken0, p.launchTick, MAX_COIN_TICK);
(BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
key,
ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: int256(uint256(p.liquidityMain)), salt: SALT_MAIN}),
""
);
int128 dCoin = p.coinIsToken0 ? d.amount0() : d.amount1();
int128 dQuote = p.coinIsToken0 ? d.amount1() : d.amount0();
if (dQuote != 0 || dCoin >= 0) revert AccountingError();
Currency c = Currency.wrap(p.coin);
POOL_MANAGER.sync(c);
SafeTransferLib.safeTransfer(p.coin, address(POOL_MANAGER), uint256(uint128(-dCoin)));
POOL_MANAGER.settle();
}
struct CollectVars {
uint256 qFees;
uint256 cFees;
uint256 surplusUsed;
uint256 toCreator;
uint256 toRewards;
uint256 toPlatform;
uint256 toFloor;
}
function _doCollect(PoolId id) internal returns (uint256 feeCoins) {
PoolInfo storage p = _pools[id];
PoolKey memory key = _key(p);
bool coin0 = p.coinIsToken0;
CollectVars memory v;
// 1. fees of both positions (liquidityDelta 0 = fee collection only)
{
(int24 lo, int24 hi) = PadMath.poolRange(coin0, p.launchTick, MAX_COIN_TICK);
(BalanceDelta f,) = POOL_MANAGER.modifyLiquidity(
key, ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: 0, salt: SALT_MAIN}), ""
);
_addFees(v, f, coin0);
if (p.bandLiquidity > 0) {
(lo, hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
(f,) = POOL_MANAGER.modifyLiquidity(
key, ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: 0, salt: SALT_BAND}), ""
);
_addFees(v, f, coin0);
}
}
// sell-side coin fees go straight from the PoolManager to the converter (never held here), so the floor
// math keeps counting them as circulating: moving them can never lower the floor
if (v.cFees > 0) POOL_MANAGER.take(Currency.wrap(p.coin), CONVERTER, v.cFees);
// 2. split quote fees: anti-snipe surplus first (100% floor), the rest by the base shares
{
v.surplusUsed = p.pendingSurplus < v.qFees ? p.pendingSurplus : v.qFees;
p.pendingSurplus -= v.surplusUsed;
uint256 base = v.qFees - v.surplusUsed;
v.toRewards = base * (p.house ? HOUSE_REWARDS_BPS : REWARDS_BPS) / BPS;
if (p.house) {
v.toPlatform = base * HOUSE_PLATFORM_BPS / BPS; // KINEKO fixed split: creator 0, floor 25%
} else {
v.toCreator = base * _creatorBps(id) / BPS;
v.toPlatform = base * PLATFORM_BPS / BPS;
// use it or lose it: a lapsed creator's new share goes to the floor
if (!CREATOR_VAULT.isActive(p.coin)) v.toCreator = 0;
}
v.toFloor = v.qFees - v.toCreator - v.toRewards - v.toPlatform;
}
// 3. floor band
_placeFloor(id, p, key, v.toFloor);
// 4. push the fee shares out (a frozen recipient only blocks its own share, which stays owed)
if (v.toCreator > 0) {
// creator fees accrue as claims in the vault (not pushed)
POOL_MANAGER.mint(address(CREATOR_VAULT), uint256(uint160(p.quote)), v.toCreator);
CREATOR_VAULT.accrue(p.coin, v.toCreator);
}
_push(REWARDS, p.quote, v.toRewards);
_push(PLATFORM, p.quote, v.toPlatform);
// 5. settle: remaining coin deltas (band coins) are taken for the burn; net quote becomes / uses claims
{
int256 dc = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.coin));
if (dc < 0) revert AccountingError();
if (dc > 0) POOL_MANAGER.take(Currency.wrap(p.coin), address(this), uint256(dc));
int256 dqd = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.quote));
uint256 cid = uint256(uint160(p.quote));
if (dqd > 0) POOL_MANAGER.mint(address(this), cid, uint256(dqd));
else if (dqd < 0) POOL_MANAGER.burn(address(this), cid, uint256(-dqd));
}
emit Collected(id, v.qFees, v.cFees, v.toCreator, v.toRewards, v.toPlatform, v.toFloor);
feeCoins = v.cFees;
}
function _addFees(CollectVars memory v, BalanceDelta f, bool coin0) internal pure {
int128 fc = coin0 ? f.amount0() : f.amount1();
int128 fq = coin0 ? f.amount1() : f.amount0();
if (fc < 0 || fq < 0) revert AccountingError();
v.cFees += uint256(uint128(fc));
v.qFees += uint256(uint128(fq));
}
function _push(address to, address currency, uint256 amount) internal {
if (amount == 0) return;
try POOL_MANAGER.take(Currency.wrap(currency), to, amount) {
emit PayoutPushed(to, currency, amount);
} catch {
owed[to][currency] += amount;
claimsLedger[currency] += amount;
emit PayoutOwed(to, currency, amount);
}
}
// ------------------------------------------------------------------ floor band
struct FloorVars {
uint160 sqrtP;
int24 poolTick;
uint256 H; // coins the pool must hold at the floor (all non-burned coins not held by the hook)
int24 fOld;
uint256 bandQuote;
uint256 bandCoins;
uint256 Q;
int24 u;
uint128 L;
bool ok;
}
function _placeFloor(PoolId id, PoolInfo storage p, PoolKey memory key, uint256 floorAdd) internal {
FloorVars memory f;
(f.sqrtP, f.poolTick,,) = POOL_MANAGER.getSlot0(id);
bool coin0 = p.coinIsToken0;
// coins held by the hook (just-taken fee coins, donations) are burned after this unlock
f.H = _effectiveSupply(p.coin);
f.fOld = _floorTickFor(p, _vL(p), p.bandLower, f.H); // virtual band
if (p.bandLiquidity > 0) {
f.bandQuote = PadMath.quoteAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, f.sqrtP);
f.bandCoins = PadMath.coinsAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, f.sqrtP);
}
uint256 H2 = f.H > f.bandCoins ? f.H - f.bandCoins : 0; // band coins are burned on a re-place
f.Q = f.bandQuote + p.pendingFloor + floorAdd + p.lentQuote; // lent quote counts
(f.ok, f.u, f.L) = _bestBand(p, f.Q, H2, f.poolTick, _refNow(p, PadMath.coinTickOf(coin0, f.poolTick)));
if (!f.ok || f.u < f.fOld) {
// cannot raise the floor now: keep the new floor quote as claims for the next collect
p.pendingFloor += floorAdd;
claimsLedger[p.quote] += floorAdd;
emit FloorDeferred(id, p.pendingFloor);
return;
}
uint256 removedQ;
if (p.bandLiquidity > 0) {
(int24 lo, int24 hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
(BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
key,
ModifyLiquidityParams({
tickLower: lo,
tickUpper: hi,
liquidityDelta: -int256(uint256(p.bandLiquidity)),
salt: SALT_BAND
}),
""
);
int128 rq = coin0 ? d.amount1() : d.amount0();
if (rq < 0) revert AccountingError();
removedQ = uint256(uint128(rq));
}
uint256 used;
// physical part = total minus the liquidity the lent quote represents at the new range
{
uint128 lentL = FLOOR_MATH.liqForQuote(coin0, p.lentQuote, f.u);
f.L = f.L > lentL ? f.L - lentL : 0;
}
if (f.L > 0) {
(int24 lo, int24 hi) = PadMath.poolRange(coin0, f.u, f.u + BAND_WIDTH);
(BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
key,
ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: int256(uint256(f.L)), salt: SALT_BAND}),
""
);
int128 aq = coin0 ? d.amount1() : d.amount0();
int128 ac = coin0 ? d.amount0() : d.amount1();
if (aq > 0 || ac != 0) revert AccountingError(); // must be quote-only
used = uint256(uint128(-aq));
}
uint256 avail = removedQ + p.pendingFloor + floorAdd;
if (used > avail) revert AccountingError();
uint256 newPending = avail - used;
claimsLedger[p.quote] = claimsLedger[p.quote] - p.pendingFloor + newPending;
p.pendingFloor = newPending;
p.bandLower = f.u;
p.bandLiquidity = f.L;
emit FloorPlaced(id, f.u, f.L, used, f.u);
}
/// virtual band liquidity = physical + lent quote at the band's range
function _vL(PoolInfo storage p) internal view returns (uint128) {
return FLOOR_MATH.virtualL(p.coinIsToken0, p.bandLiquidity, p.bandLower, p.lentQuote);
}
function _bestBand(PoolInfo storage p, uint256 Q, uint256 H, int24 poolTick, int24 refTick)
internal
view
returns (bool, int24, uint128)
{
return FLOOR_MATH.bestBand(p.coinIsToken0, p.liquidityMain, p.launchTick, Q, H, poolTick, refTick);
}
function _floorTickFor(PoolInfo storage p, uint128 bandL, int24 bandLower, uint256 H) internal view returns (int24) {
return FLOOR_MATH.floorTick(p.coinIsToken0, p.liquidityMain, p.launchTick, bandL, bandLower, H);
}
/// Slow reference as of now, given the current coin-tick: min(current, stored + rise allowance since refBlock).
function _refNow(PoolInfo storage p, int24 cur) internal view returns (int24) {
uint256 rb = p.refBlock;
uint256 elapsed = block.number > rb ? block.number - rb : 0; // saturating: must never revert on a sell
if (elapsed > 100_000) elapsed = 100_000;
int256 cap = int256(p.refCoinTick) + int256(elapsed) * REF_RISE_PER_BLOCK;
return int256(cur) < cap ? cur : int24(cap);
}
/// Called before every swap (buys and sells) with the pre-swap price. Pure arithmetic + storage writes; cannot revert.
function _updateRef(PoolId id, PoolInfo storage p) internal {
(, int24 t,,) = POOL_MANAGER.getSlot0(id);
int24 cur = PadMath.coinTickOf(p.coinIsToken0, t);
if (p.stickyBlock != block.number) {
p.stickyTick = _stickyNow(p, cur);
p.stickyBlock = uint64(block.number);
p.openTick = cur;
p.openBlock = uint64(block.number);
}
int24 r = _refNow(p, cur);
if (r != p.refCoinTick || p.refBlock != block.number) {
p.refCoinTick = r;
p.refBlock = uint64(block.number);
}
}
function _effectiveSupply(address coin) internal view returns (uint256) {
uint256 ts = IPadToken(coin).totalSupply();
uint256 held = IPadToken(coin).balanceOf(address(this));
return ts > held ? ts - held : 0;
}
function _burnHeldCoins(PoolId id, address coin) internal {
uint256 bal = IPadToken(coin).balanceOf(address(this));
if (bal > 0) {
IPadToken(coin).burn(bal);
emit CoinsBurned(id, bal);
}
}
// ------------------------------------------------------------------ fees
function _buyFee(PoolInfo storage p) internal view returns (uint24) {
uint256 n = p.snipeBlocks;
uint256 lb = p.launchBlock;
uint256 elapsed = block.number > lb ? block.number - lb : 0;
uint256 bf = p.baseFee;
if (elapsed >= n) return uint24(bf);
uint256 start = p.snipeStartFee;
return uint24(start - (start - bf) * elapsed / n);
}
function _creatorBps(PoolId id) internal view returns (uint256) {
(uint16 streak, PadStreakMath.Params memory cur) = _streakNow(id, _pools[id]);
uint256 t = STREAK_MATH.tier(streak, cur.t1, cur.t2);
return t == 2 ? CREATOR_BPS_T2 : (t == 1 ? CREATOR_BPS_T1 : CREATOR_BPS_T0);
}
/// Lazy close-out of every fully elapsed day (see PadStreakMath). View; never reverts on its own.
function _streakNow(PoolId id, PoolInfo storage p) internal view returns (uint16 streak, PadStreakMath.Params memory cur) {
cur = PadStreakMath.Params(p.window, p.aliveUsd, p.tier1, p.tier2);
streak = p.streak;
uint256 today = block.timestamp / 1 days;
if (today <= p.lastDay) return (streak, cur);
(streak, cur) = STREAK_MATH.close(address(REGISTRY), p.districtId, _dayRing[id], p.lastDay, today, streak, cur);
}
/// On every swap: close out elapsed days (first trade of a new day), then add the volume to today's bucket.
function _addDayVolume(PoolId id, PoolInfo storage p, uint256 usd) internal {
uint256 today = block.timestamp / 1 days;
if (today > p.lastDay) {
(uint16 streak, PadStreakMath.Params memory cur) = _streakNow(id, p);
p.streak = streak;
p.window = cur.window;
p.aliveUsd = cur.bar;
p.tier1 = cur.t1;
p.tier2 = cur.t2;
p.lastDay = uint32(today);
}
unchecked {
uint256 slot = today % 14;
uint256 shift = (slot & 1) * 128;
uint256 w = _dayRing[id][slot >> 1];
uint256 half = (w >> shift) & ((1 << 128) - 1);
uint256 v = (half >> 96) == (today & 0xffffffff) ? half & ((1 << 96) - 1) : 0;
v = v + usd >= (1 << 96) ? (1 << 96) - 1 : v + usd;
_dayRing[id][slot >> 1] = (w & ~(((1 << 128) - 1) << shift)) | ((((today & 0xffffffff) << 96) | v) << shift);
}
}
function _setStoredFee(PoolKey memory key, PoolInfo storage p, uint24 fee) internal {
POOL_MANAGER.updateDynamicLPFee(key, fee);
p.storedFee = fee;
emit StoredFeeSet(key.toId(), fee);
}
function _key(PoolInfo storage p) internal view returns (PoolKey memory) {
(address c0, address c1) = p.coinIsToken0 ? (p.coin, p.quote) : (p.quote, p.coin);
return PoolKey({
currency0: Currency.wrap(c0),
currency1: Currency.wrap(c1),
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: TICK_SPACING,
hooks: IHooks(address(this))
});
}
// ================================================================== views
function _stickyNow(PoolInfo storage p, int24 cur) internal view returns (int24) {
uint256 sb = p.stickyBlock;
uint256 elapsed = block.number > sb ? block.number - sb : 0;
if (elapsed > 100_000) elapsed = 100_000;
int256 step = int256(elapsed) * REF_RISE_PER_BLOCK;
int256 st = p.stickyTick;
int256 c = cur;
if (c > st + step) return int24(st + step);
if (c < st - step) return int24(st - step);
return cur;
}
/// @notice Raw storage words [startSlot, startSlot + nSlots) for PadHookLib / PadReader (all views live there).
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory) {
assembly ("memory-safe") {
let memptr := mload(0x40)
let start := memptr
mstore(memptr, 0x20)
mstore(add(memptr, 0x20), nSlots)
memptr := add(memptr, 0x40)
let end := add(memptr, shl(5, nSlots))
for {} lt(memptr, end) {} {
mstore(memptr, sload(startSlot))
memptr := add(memptr, 0x20)
startSlot := add(startSlot, 1)
}
return(start, sub(end, start))
}
}
}
src/pad/PadStreakMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IStreakRegistry {
function streakParamsAt(uint256 id) external view returns (uint32, uint96, uint16, uint16, uint256);
}
/// @title PadStreakMath
/// @notice Stateless creator-streak evaluation used by PadHook (split out for contract size). Pure functions only,
/// called with STATICCALL; deployed once by the hook's constructor.
///
/// Data: a ring of 14 daily buckets per coin, two per word: bucket = [day:32][usd:96] (usd in 1e18, saturating),
/// slot = day % 14. Day index = block.timestamp / 1 days (UTC days).
///
/// Rule (STREAK_VOLUME_CHECK.md): each fully elapsed day `d` is judged once, lazily, on the first trade/collect of a later
/// day: ALIVE if the rolling sum of the `window` days ending at `d` is >= `bar`. Alive -> streak + 1. Dead -> drop one
/// tier and reset to that tier's threshold (streak >= t2 -> t1; otherwise 0). Tiers: >= t2 -> T2, >= t1 -> T1, else T0.
/// Parameters come with the time they took effect; a day is judged with the new parameters only if it STARTS at or
/// after that time (next day boundary, never retroactive). At the switch an earned tier is never lost.
contract PadStreakMath {
uint256 internal constant RING = 14;
struct Params {
uint8 window;
uint96 bar;
uint16 t1;
uint16 t2;
}
function bucketDay(uint256[7] memory ring, uint256 slot) internal pure returns (uint256 day, uint256 usd) {
uint256 w = ring[slot >> 1];
uint256 half = (w >> ((slot & 1) * 128)) & ((1 << 128) - 1);
return (half >> 96, half & ((1 << 96) - 1));
}
/// Rolling USD sum of the `window` days ending at day `d` (inclusive).
function rollingSum(uint256[7] memory ring, uint256 d, uint256 window) public pure returns (uint256 sum) {
unchecked {
for (uint256 s; s < RING; ++s) {
(uint256 bd, uint256 usd) = bucketDay(ring, s);
if (usd != 0 && bd <= d && d - bd < window) sum += usd;
}
}
}
function tier(uint16 streak, uint16 t1, uint16 t2) public pure returns (uint256) {
return streak >= t2 ? 2 : (streak >= t1 ? 1 : 0);
}
function _dead(uint16 streak, uint16 t1, uint16 t2) internal pure returns (uint16) {
return streak >= t2 ? t1 : 0;
}
/// Registry params + effective time via a failure-tolerant staticcall (on failure: keep the running params).
function newParams(address registry, uint256 districtId, Params memory old)
public
view
returns (Params memory n, uint256 effAt)
{
n = old;
effAt = type(uint256).max;
(bool ok, bytes memory r) = registry.staticcall{gas: 50_000}(
abi.encodeWithSelector(IStreakRegistry.streakParamsAt.selector, districtId)
);
if (!ok || r.length != 160) return (n, effAt);
(uint256 w, uint256 bar, uint256 t1, uint256 t2, uint256 e) = abi.decode(r, (uint256, uint256, uint256, uint256, uint256));
if (w == 0 || w > 14 || bar == 0 || bar > type(uint96).max || t1 == 0 || t2 <= t1 || t2 > type(uint16).max) {
return (n, effAt);
}
n = Params(uint8(w), uint96(bar), uint16(t1), uint16(t2));
effAt = e;
}
/// Judges days [lastDay, today) and returns the new streak and the params in force for `today`.
function close(
address registry,
uint256 districtId,
uint256[7] memory ring,
uint256 lastDay,
uint256 today,
uint16 streak,
Params memory oldP
) external view returns (uint16, Params memory) {
(Params memory newP, uint256 effAt) = newParams(registry, districtId, oldP);
return _close(ring, lastDay, today, streak, oldP, newP, effAt);
}
function _close(
uint256[7] memory ring,
uint256 lastDay,
uint256 today,
uint16 streak,
Params memory oldP,
Params memory newP,
uint256 effAt
) internal pure returns (uint16, Params memory) {
unchecked {
Params memory cur = oldP;
bool switched = !_differs(oldP, newP);
uint256 d = lastDay;
// days with possible volume in their window: at most 14 + 1 iterations
uint256 end = today;
uint256 hardStop = lastDay + RING + 1;
for (; d < end && d < hardStop; ++d) {
if (!switched && d * 1 days >= effAt) {
streak = _switch(streak, cur, newP);
cur = newP;
switched = true;
}
bool alive = rollingSum(ring, d, cur.window) >= cur.bar;
streak = alive ? (streak < type(uint16).max ? streak + 1 : streak) : _dead(streak, cur.t1, cur.t2);
}
// any remaining days have empty windows: all dead (two drops reach 0)
if (d < end) {
if (!switched) {
streak = _switch(streak, cur, newP);
cur = newP;
}
streak = _dead(_dead(streak, cur.t1, cur.t2), cur.t1, cur.t2);
} else if (!switched && today * 1 days >= effAt) {
streak = _switch(streak, cur, newP);
cur = newP;
}
return (streak, cur);
}
}
function _differs(Params memory a, Params memory b) internal pure returns (bool) {
return a.window != b.window || a.bar != b.bar || a.t1 != b.t1 || a.t2 != b.t2;
}
/// Streak counts days in both regimes; only the thresholds change. Never lose an earned tier.
function _switch(uint16 streak, Params memory o, Params memory n) internal pure returns (uint16) {
uint256 t = tier(streak, o.t1, o.t2);
uint16 minS = t == 2 ? n.t2 : (t == 1 ? n.t1 : 0);
return streak < minS ? minS : streak;
}
}
src/pad/interfaces/IPadExternal.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// Minimal external interfaces used by the pad contracts (only what we call).
interface IUniswapV3PoolMin {
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function swap(address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data)
external
returns (int256 amount0, int256 amount1);
}
interface IUniswapV3FactoryMin {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}
/// Curve plain / stableswap pools with int128 indices (e.g. tBTC/WBTC `0xB7EC…6726`).
interface ICurvePoolMin {
function coins(uint256 i) external view returns (address);
function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external returns (uint256);
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
}
interface IWETH9Min {
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
}
/// Permit2 SignatureTransfer (Uniswap), only what we use.
interface IPermit2Transfer {
struct TokenPermissions {
address token;
uint256 amount;
}
struct PermitTransferFrom {
TokenPermissions permitted;
uint256 nonce;
uint256 deadline;
}
struct SignatureTransferDetails {
address to;
uint256 requestedAmount;
}
function permitTransferFrom(
PermitTransferFrom calldata permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
}
/// Morpho UrdFactory (mainnet `0x9baA51245CDD28D8D74Afe8B3959b616E9ee7c8D`, verified on-chain 29 Sep 2026).
interface IUrdFactory {
function createUrd(
address initialOwner,
uint256 initialTimelock,
bytes32 initialRoot,
bytes32 initialIpfsHash,
bytes32 salt
) external returns (address);
function isUrd(address) external view returns (bool);
}
/// Morpho Universal Rewards Distributor (only what the vault calls or reads).
interface IUniversalRewardsDistributor {
function owner() external view returns (address);
function timelock() external view returns (uint256);
function root() external view returns (bytes32);
function pendingRoot() external view returns (bytes32 root, bytes32 ipfsHash, uint256 validAt);
function submitRoot(bytes32 newRoot, bytes32 newIpfsHash) external;
function acceptRoot() external;
function revokePendingRoot() external;
function claim(address account, address reward, uint256 claimable, bytes32[] calldata proof)
external
returns (uint256 amount);
function claimed(address account, address reward) external view returns (uint256);
}
interface IPadToken {
function burn(uint256 amount) external;
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
}
src/pad/libraries/PadHookLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";
import {PadHook} from "../PadHook.sol";
import {PadMath} from "./PadMath.sol";
import {PadStreakMath} from "../PadStreakMath.sol";
import {IPadToken} from "../interfaces/IPadExternal.sol";
/// @title PadHookLib
/// @notice PadHook's views, computed by the CALLER from the hook's storage (`PadHook.extsload`), so the hook fits EIP-170
/// with the Floor Pawn primitive ("view diet"). Internal library: every consumer only needs the hook address.
/// The layout is pinned by test/pad/PadReader.t.sol (every field written by real pad actions and read back) and
/// must change together with PadHook.PoolInfo.
library PadHookLib {
using StateLibrary for IPoolManager;
// forge inspect PadHook storageLayout: _pools @0, poolIdOf @1, _dayRing @2; PoolInfo = 12 words
uint256 internal constant POOLS_SLOT = 0;
uint256 internal constant DAY_RING_SLOT = 2;
uint256 internal constant POOL_INFO_WORDS = 12;
int24 internal constant BAND_WIDTH = 60;
int24 internal constant MAX_COIN_TICK = 887_220;
int24 internal constant TICK_SPACING = 60;
error UnknownPool();
function _u(bytes32 w, uint256 off, uint256 n) private pure returns (uint256) {
return (uint256(w) >> (off * 8)) & ((1 << (n * 8)) - 1);
}
function _i24(bytes32 w, uint256 off) private pure returns (int24) {
return int24(uint24(uint256(w) >> (off * 8)));
}
function slotOf(PoolId id) internal pure returns (bytes32) {
return keccak256(abi.encode(PoolId.unwrap(id), POOLS_SLOT));
}
/// The full PoolInfo of `coin` (all zero for an unknown coin).
function poolInfo(PadHook hook, address coin) internal view returns (PadHook.PoolInfo memory p) {
return poolInfoOf(hook, hook.poolIdOf(coin));
}
function poolInfoOf(PadHook hook, PoolId id) internal view returns (PadHook.PoolInfo memory p) {
bytes32[] memory w = hook.extsload(slotOf(id), POOL_INFO_WORDS);
p.coin = address(uint160(uint256(w[0])));
p.quote = address(uint160(uint256(w[1])));
p.districtId = uint32(_u(w[1], 20, 4));
p.launchBlock = uint64(_u(w[1], 24, 8));
p.coinIsToken0 = _u(w[2], 0, 1) != 0;
p.launchTick = _i24(w[2], 1);
p.bandLower = _i24(w[2], 4);
p.snipeStartFee = uint24(_u(w[2], 7, 3));
p.snipeBlocks = uint16(_u(w[2], 10, 2));
p.storedFee = uint24(_u(w[2], 12, 3));
p.baseFee = uint24(_u(w[2], 15, 3));
p.house = _u(w[2], 18, 1) != 0;
p.quoteDecimals = uint8(_u(w[2], 19, 1));
p.liquidityMain = uint128(uint256(w[3]));
p.bandLiquidity = uint128(uint256(w[3]) >> 128);
p.usdPerQuoteE18 = uint128(uint256(w[4]));
p.volumeUsdE18 = uint256(w[5]);
p.quoteVolume = uint256(w[6]);
p.pendingSurplus = uint256(w[7]);
p.pendingFloor = uint256(w[8]);
p.refCoinTick = _i24(w[9], 0);
p.refBlock = uint64(_u(w[9], 3, 8));
p.stickyTick = _i24(w[9], 11);
p.stickyBlock = uint64(_u(w[9], 14, 8));
p.openTick = _i24(w[9], 22);
p.openBlock = uint64(_u(w[10], 0, 8));
p.lastDay = uint32(_u(w[10], 8, 4));
p.streak = uint16(_u(w[10], 12, 2));
p.window = uint8(_u(w[10], 14, 1));
p.tier1 = uint16(_u(w[10], 15, 2));
p.tier2 = uint16(_u(w[10], 17, 2));
p.aliveUsd = uint96(_u(w[10], 19, 12));
p.lentQuote = uint128(uint256(w[11]));
}
/// The pool's coin and quote only (2 words): cheap "is this a pad coin" check for hot paths.
function coinAndQuote(PadHook hook, address coin) internal view returns (address c, address q) {
bytes32[] memory w = hook.extsload(slotOf(hook.poolIdOf(coin)), 2);
return (address(uint160(uint256(w[0]))), address(uint160(uint256(w[1]))));
}
function known(PadHook hook, address coin) internal view returns (PadHook.PoolInfo memory p) {
p = poolInfo(hook, coin);
if (p.coin == address(0)) revert UnknownPool();
}
function keyOf(PadHook hook, PadHook.PoolInfo memory p) internal pure returns (PoolKey memory) {
(address c0, address c1) = p.coinIsToken0 ? (p.coin, p.quote) : (p.quote, p.coin);
return PoolKey({
currency0: Currency.wrap(c0),
currency1: Currency.wrap(c1),
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: TICK_SPACING,
hooks: IHooks(address(hook))
});
}
function poolKeyOf(PadHook hook, address coin) internal view returns (PoolKey memory) {
return keyOf(hook, known(hook, coin));
}
function dayRing(PadHook hook, address coin) internal view returns (uint256[7] memory r) {
bytes32[] memory w =
hook.extsload(keccak256(abi.encode(PoolId.unwrap(hook.poolIdOf(coin)), DAY_RING_SLOT)), 7);
for (uint256 i; i < 7; ++i) {
r[i] = uint256(w[i]);
}
}
function effectiveSupply(PadHook hook, address coin) internal view returns (uint256) {
uint256 ts = IPadToken(coin).totalSupply();
uint256 held = IPadToken(coin).balanceOf(address(hook));
return ts > held ? ts - held : 0;
}
/// Published dump floor (coin-tick; lent quote counted as virtual band, exactly as the hook's guard computes it),
/// band quote physically in the pool, floor claims waiting, MAIN's quote, and their sum.
function floorBacking(PadHook hook, address coin)
internal
view
returns (int24 floorCoinTick, uint256 bandQuote, uint256 pendingFloorQuote, uint256 mainQuote, uint256 poolQuote)
{
PadHook.PoolInfo memory p = known(hook, coin);
(uint160 sqrtP,,,) = hook.POOL_MANAGER().getSlot0(hook.poolIdOf(coin));
bool coin0 = p.coinIsToken0;
floorCoinTick = hook.FLOOR_MATH().floorTickLent(
coin0, p.liquidityMain, p.launchTick, p.bandLiquidity, p.bandLower, effectiveSupply(hook, coin), p.lentQuote
);
bandQuote = PadMath.quoteAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, sqrtP);
pendingFloorQuote = p.pendingFloor;
mainQuote = PadMath.quoteAtSqrt(coin0, p.liquidityMain, p.launchTick, MAX_COIN_TICK, sqrtP);
poolQuote = bandQuote + pendingFloorQuote + mainQuote;
}
/// Current streak and creator share (bps of the base fee), lazy close-out applied (house coins: share 0).
function streakAndBps(PadHook hook, address coin) internal view returns (uint16 streak, uint256 creatorBps) {
PadHook.PoolInfo memory p = known(hook, coin);
PadStreakMath.Params memory cur = PadStreakMath.Params(p.window, p.aliveUsd, p.tier1, p.tier2);
streak = p.streak;
PadStreakMath sm = hook.STREAK_MATH();
uint256 today = block.timestamp / 1 days;
if (today > p.lastDay) {
(streak, cur) = sm.close(address(hook.REGISTRY()), p.districtId, dayRing(hook, coin), p.lastDay, today, streak, cur);
}
if (p.house) return (streak, 0);
uint256 t = sm.tier(streak, cur.t1, cur.t2);
creatorBps = t == 2 ? 6000 : (t == 1 ? 5000 : 4000); // PadHook.CREATOR_BPS_T2 / T1 / T0
}
}
src/pad/libraries/PadMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/libraries/FixedPoint96.sol";
/// @title PadMath
/// @notice Liquidity math for pad pools, written in "coin-tick" orientation: coin-tick `u` is the tick of the price
/// (raw quote per raw coin). If the coin is currency0 the pool tick is `u`; if it is currency1 the pool tick
/// is `-u`. A position over coin-ticks [a, b] maps to pool ticks [a, b] (coin0) or [-b, -a] (coin1).
/// All reserve estimates round DOWN, so floor figures are conservative.
library PadMath {
/// pool tick range of a coin-tick range
function poolRange(bool coin0, int24 a, int24 b) internal pure returns (int24 lower, int24 upper) {
return coin0 ? (a, b) : (-b, -a);
}
/// Coins held by liquidity `L` spread over coin-ticks [x, y] (x < y), i.e. the full coin capacity of that slice.
function coinsBetween(bool coin0, uint128 L, int24 x, int24 y) internal pure returns (uint256) {
if (L == 0 || x >= y) return 0;
if (coin0) {
return SqrtPriceMath.getAmount0Delta(TickMath.getSqrtPriceAtTick(x), TickMath.getSqrtPriceAtTick(y), L, false);
}
return SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(-y), TickMath.getSqrtPriceAtTick(-x), L, false);
}
/// Coins a position [a, b] would hold if the price were exactly at coin-tick u.
function coinsAt(bool coin0, uint128 L, int24 a, int24 b, int24 u) internal pure returns (uint256) {
if (u >= b) return 0;
return coinsBetween(coin0, L, u > a ? u : a, b);
}
/// Liquidity bought by `quoteAmt` of quote placed over coin-ticks [a, b] entirely BELOW the price (quote-only).
function liquidityForQuote(bool coin0, uint256 quoteAmt, int24 a, int24 b) internal pure returns (uint128) {
if (quoteAmt == 0) return 0;
(int24 lo, int24 hi) = poolRange(coin0, a, b);
uint160 sA = TickMath.getSqrtPriceAtTick(lo);
uint160 sB = TickMath.getSqrtPriceAtTick(hi);
uint256 L;
if (coin0) {
// quote = token1: L = amount1 * Q96 / (sB - sA)
L = FullMath.mulDiv(quoteAmt, FixedPoint96.Q96, sB - sA);
} else {
// quote = token0: L = amount0 * sA * sB / Q96 / (sB - sA)
uint256 inter = FullMath.mulDiv(sA, sB, FixedPoint96.Q96);
L = FullMath.mulDiv(quoteAmt, inter, sB - sA);
}
return L > type(uint128).max ? type(uint128).max : uint128(L);
}
/// Liquidity for `coinAmt` coins placed over coin-ticks [a, b] entirely ABOVE the price (coin-only).
function liquidityForCoins(bool coin0, uint256 coinAmt, int24 a, int24 b) internal pure returns (uint128) {
(int24 lo, int24 hi) = poolRange(coin0, a, b);
uint160 sA = TickMath.getSqrtPriceAtTick(lo);
uint160 sB = TickMath.getSqrtPriceAtTick(hi);
uint256 L;
if (coin0) {
uint256 inter = FullMath.mulDiv(sA, sB, FixedPoint96.Q96);
L = FullMath.mulDiv(coinAmt, inter, sB - sA);
} else {
L = FullMath.mulDiv(coinAmt, FixedPoint96.Q96, sB - sA);
}
return L > type(uint128).max ? type(uint128).max : uint128(L);
}
/// Quote held by a position [a, b] at pool sqrt price `sqrtP` (rounded down).
function quoteAtSqrt(bool coin0, uint128 L, int24 a, int24 b, uint160 sqrtP) internal pure returns (uint256) {
if (L == 0) return 0;
(int24 lo, int24 hi) = poolRange(coin0, a, b);
uint160 sA = TickMath.getSqrtPriceAtTick(lo);
uint160 sB = TickMath.getSqrtPriceAtTick(hi);
if (coin0) {
// quote = token1, present below the price
if (sqrtP <= sA) return 0;
uint160 top = sqrtP < sB ? sqrtP : sB;
return SqrtPriceMath.getAmount1Delta(sA, top, L, false);
}
// quote = token0, present above the price
if (sqrtP >= sB) return 0;
uint160 bot = sqrtP > sA ? sqrtP : sA;
return SqrtPriceMath.getAmount0Delta(bot, sB, L, false);
}
/// Coins held by a position [a, b] at pool sqrt price `sqrtP` (rounded down).
function coinsAtSqrt(bool coin0, uint128 L, int24 a, int24 b, uint160 sqrtP) internal pure returns (uint256) {
if (L == 0) return 0;
(int24 lo, int24 hi) = poolRange(coin0, a, b);
uint160 sA = TickMath.getSqrtPriceAtTick(lo);
uint160 sB = TickMath.getSqrtPriceAtTick(hi);
if (coin0) {
// coin = token0, present above the price
if (sqrtP >= sB) return 0;
uint160 bot = sqrtP > sA ? sqrtP : sA;
return SqrtPriceMath.getAmount0Delta(bot, sB, L, false);
}
if (sqrtP <= sA) return 0;
uint160 top = sqrtP < sB ? sqrtP : sB;
return SqrtPriceMath.getAmount1Delta(sA, top, L, false);
}
/// Current price as a coin-tick (conservative: rounds towards the lower coin price).
function coinTickOf(bool coin0, int24 poolTick) internal pure returns (int24) {
// coin1: pool tick t means pool price in [t, t+1); coin price in (-(t+1), -t]; use -(t+1)
return coin0 ? poolTick : -poolTick - 1;
}
}
src/pad/libraries/PadTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice One hop of a fixed district route, written in the forward direction (pay token -> district quote).
/// The reverse direction (quote -> receive token) walks the same hops backwards.
/// kind 1 = Uniswap v3 pool (checked against the v3 factory), 2 = Uniswap v4 pool WITHOUT hooks,
/// kind 3 = Curve int128-index pool (coins checked at registration), kind 4 = a HOUSE pad pool through the pad hook.
/// Native ETH: v4 hops use address(0); v3 and Curve hops use WETH. The executor wraps/unwraps between hops.
struct Hop {
uint8 kind;
address pool; // v3 / Curve pool address; unused (0) for v4
address tokenIn;
address tokenOut;
uint24 fee; // v3 fee tier or v4 static fee
int24 tickSpacing; // v4 only
int8 curveI; // Curve index of tokenIn
int8 curveJ; // Curve index of tokenOut
}
/// @notice Immutable district parameters (set once through the registry's timelock).
struct DistrictConfig {
address quote; // district quote asset (never native ETH)
uint8 quoteDecimals;
/// Opening price as a tick of (raw quote units per raw coin unit), i.e. in "coin = token0" orientation.
/// Must be a multiple of the pad tick spacing.
int24 launchTick;
uint24 snipeStartFee; // pips (1e6 = 100%), e.g. 800_000 = 80%
uint16 snipeBlocks; // blocks for the linear decay to the base fee
/// USD value (1e18 = $1) of ONE whole quote unit; used ONLY for the creator fee tiers, never for pricing.
uint128 usdPerQuoteE18;
// no buy caps of any kind (user decision): no per-trade, per-coin or district-wide ceiling
}
/// @notice Creator-streak parameters (per district, or the registry's global default). Days are UTC days.
struct StreakParams {
uint32 windowDays; // rolling window, 1 .. 14 days
uint96 aliveUsd; // a day is "alive" if the coin's USD-referenced volume over the window ending that day >= this
uint16 tier1Epochs; // streak (days) >= tier1 -> creator 0.50%
uint16 tier2Epochs; // streak (days) >= tier2 -> creator 0.60%
}
/// @notice A route for one pay/receive token of a district.
struct RouteSpec {
address payToken; // address(0) = ETH
Hop[] hops;
}
library HopKind {
uint8 internal constant V3 = 1;
uint8 internal constant V4 = 2;
uint8 internal constant CURVE = 3;
/// a HOUSE pad pool (KINEKO/XAUT) through the pad hook: `pool` = the hook, dynamic fee, tick spacing 60. Used by
/// the GOLD/KINEKO district (ETH/USDC/USDT -> XAUT -> KINEKO) and by FeeRouterV2 / WarChest conversions.
uint8 internal constant PAD = 4;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/src/",
"metamorpho/=lib/metamorpho-v1.1/src/",
"solady/=lib/solady/src/",
"v4-core/=lib/v4-core/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
"lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"metamorpho-v1.1/=lib/metamorpho-v1.1/",
"morpho-blue-irm/=lib/metamorpho-v1.1/lib/morpho-blue-irm/src/",
"openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"solmate/=lib/v4-core/lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.