Verified contractPartialMIT
QuantumVaultV2
Address0x1b884346b79185c862fc573b68bfdc1f4590102c
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,171,848
- Creation transaction
- 0x65637ee26f…fb941e99c8
- Libraries
- src/libraries/FeeRouter.sol:FeeRouter0xf383…54c9f2src/libraries/VaultMath.sol:VaultMath0x9b6d…211940src/libraries/VenueAdapter.sol:VenueAdapter0xb4ac…19dc60src/libraries/PositionQueue.sol:PositionQueue0xc6fe…e3993f
24 files
- src/QuantumVaultV2.solmain118.21 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol795 B
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.83 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.38 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28.31 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/IUniswapV3.sol4.54 KB
- src/libraries/FeeRouter.sol5.91 KB
- src/libraries/PositionQueue.sol13.67 KB
- src/libraries/VaultMath.sol13.82 KB
- src/libraries/VenueAdapter.sol5.81 KB
src/QuantumVaultV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {VaultMath} from "./libraries/VaultMath.sol";
import {FeeRouter} from "./libraries/FeeRouter.sol";
import {PositionQueue} from "./libraries/PositionQueue.sol";
import {VenueAdapter} from "./libraries/VenueAdapter.sol";
import {
INonfungiblePositionManager,
IUniswapV3Factory,
IUniswapV3Pool
} from "./interfaces/IUniswapV3.sol";
// L-03: `ISwapRouter` is intentionally NOT imported — V2 has no swap path (Guarantee: no protocol swap).
/// @title QuantumVault
/// @notice Custodial, actively-managed Uniswap v3 concentrated-liquidity vault (QuantumPools — Option A).
/// Each deposit opens a Uniswap v3 position held by the vault but owned by the depositor.
/// A keeper bot harvests fees and rebalances ranges. A performance fee on *fees only*
/// accrues to the treasury.
/// @dev Custody hardening vs. the SnuggleVault reference:
/// - withdraw() is always available (never blocked by pause);
/// - the keeper can only run LP maintenance (harvest/rebalance) — it can never move funds
/// to an arbitrary address;
/// - rescueERC721 cannot touch a tracked user position;
/// - performance fee is capped on-chain.
/// Intended owner is a Timelock controlled by a multisig.
///
/// =============================================================================================
/// FOUR GUARANTEES, AND EXACTLY WHAT EACH ONE MEANS
/// =============================================================================================
/// Each of these is enforced by the SHAPE of the contract, not by configuration or by the keeper
/// behaving well. The limits are stated with them, because a guarantee whose caveats are hidden is
/// worse than no guarantee.
///
/// 1. NO SWAP FEES. This contract contains no swap path at all — no router, no `_balanceSwap`, no
/// single-sided deposit — asserted by QuantumVaultV2.guarantees.t.sol. A snuggle re-enters
/// SINGLE-SIDED and DIRECTIONAL, so there is never anything to convert: when price leaves your
/// range the market has already converted the position to one asset, and the new range is placed
/// entirely on that asset's side.
/// LIMIT: withdrawing returns BOTH tokens at the current ratio. If you want one of them, you swap
/// outside. This contract will not do it for you, and will not charge you for it.
///
/// 2. NO SLIPPAGE FROM US. No swap means no swap slippage and no price impact — providing liquidity
/// is not trading. Every deposit and withdrawal additionally carries `amount0Min`/`amount1Min`
/// bounds that YOU set.
/// LIMIT: this is not a promise about the pool. Impermanent loss is real, and the value of a
/// position still moves with price. "No slippage" means we never execute a trade against you.
///
/// 3. NO MEV EXTRACTION BY THE PROTOCOL. The keeper cannot take value: `harvest()` pays
/// `pos.owner`, never `msg.sender`; every fund-moving path is owner-gated; and the keeper never
/// chooses ticks on the snuggle path — the range is derived on-chain from the position's own
/// `rangeWidthTicks`. The invariant suite asserts the keeper's token balance is zero after
/// ~40,000 randomised keeper actions.
/// LIMIT: this is about US, not about the chain. Any public transaction can be observed and
/// front-run by third parties; a rebalance mint can be JIT-sandwiched at the POOL level like any
/// other. What we guarantee is that the protocol and its keeper extract nothing from you.
///
/// 4. WITHDRAW WHENEVER YOU LIKE — AND NOBODY ELSE EVER CAN.
/// Two halves, and your funds depend on both.
///
/// WE CANNOT STOP YOU. Close your position the moment you want to. No notice period, no review,
/// no verification step, no approval queue, no evaluation window, no allow-list or account flag —
/// the contract contains zero such constructs — and no pause: `withdraw` and `withdrawFraction`
/// carry no pause modifier, so they keep working even while every other function is halted.
/// v1's `minPositionHoldTime` has been removed ENTIRELY, field and checks and setter parameter,
/// so the ability to introduce a waiting period no longer exists. This is not a policy we promise
/// to keep. It is a lever we do not have: an owner, the timelock, or someone holding a stolen
/// owner key cannot delay your withdrawal, because no code path exists that would let them.
///
/// AND NOBODY ELSE CAN DO IT FOR YOU. A withdrawal is authorised by the wallet that owns the
/// position — not by us, not by the 2-of-2 Safe, not by the timelock. Those govern the protocol's
/// own settings and CANNOT REACH INTO A POSITION: `rescueERC721` refuses to touch a tracked one,
/// and every fund-moving path is gated on the position's owner. The keeper cannot do it either —
/// it may only harvest, compound and re-range, and it is never paid.
///
/// So the security model is one sentence: WE CANNOT STOP YOU, AND WE CANNOT DO IT FOR YOU. Your
/// key is the only thing that moves your money, which is exactly the property a custodial vault
/// normally gives up. Proved by an invariant that PAUSES the vault and then closes every live
/// position as its owner, and by a source-level test that fails the build if a gate is ever added.
/// LIMIT: lose your wallet and nobody — including us — can recover the position for you. That is
/// the cost of the guarantee, and it is the honest half of "only you can withdraw".
/// =============================================================================================
///
/// =============================================================================================
/// WHY OUR REBALANCE COSTS LESS: WE HAND THE CONVERSION TO THE MARKET
/// =============================================================================================
/// Every managed pool has to solve the same problem — price leaves your range, and the position is
/// now sitting in the wrong shape. Almost everyone solves it by TRADING. They swap you back into the
/// right ratio and re-open.
///
/// That trade happens at the far end of the move, which is the worst price in the whole run. And it
/// is FINAL. If price gives half of it back an hour later, that recovery is not yours — it belongs
/// to whoever you sold to. The loss stops being paper and becomes booked.
///
/// We do not trade. We re-open entirely on one side of the price and let the pool do the converting,
/// tick by tick, as price travels back through the range. You convert at every price along the way
/// instead of at one — so your average lands near the MIDDLE of the move rather than at its edge,
/// and you are collecting fees for the whole journey rather than paying to exit it.
///
/// Illustrative, on a 5% run that then retraces 3%:
///
/// Swap-and-recenter You convert once, at +5%. The retrace is not yours.
/// ~5% of divergence, locked in, minus the swap fee and slippage.
///
/// Snuggle (this contract) You convert gradually across the retrace. Average near +3.5%.
/// ~3.5% of divergence, still unrealised, plus fees earned throughout.
///
/// Numbers illustrate the mechanism; they are not a forecast. The size of the benefit depends on how
/// far price retraces, and a move that never comes back gives none of it. What IS structural is that
/// converting across a range can never be worse than converting at its edge, and that we charge no
/// swap fee for doing it — see guarantees 1 and 2.
/// =============================================================================================
///
/// =============================================================================================
/// WHERE YOUR FEES GO: THE GEOMETRY DECIDES WHAT *CAN* COMPOUND. YOU DECIDE HOW MUCH DOES.
/// =============================================================================================
/// A snuggle re-opens entirely on one side of the price, so the new position can only absorb ONE of
/// the two tokens. That is not a setting — it is the shape of the position. Fees earned in the other
/// token cannot go back in at any ratio, so they come to you as cash.
///
/// Other vaults present this as intelligent fee splitting. It is worth being exact: the geometry
/// decides it, not the vault. Whatever ratio you end up with is whatever the market happened to hand
/// you that day, and it drifts with which side of the range price exited.
///
/// We take the step past that. The geometry still decides what CAN compound — nothing changes
/// physics — but you decide how much of it actually does, and it holds on every single harvest
/// instead of varying:
///
/// SPLIT (default, 50/50) half the token you hold goes straight back to work; the other half,
/// plus everything in the token the range cannot use, arrives as cash.
/// COMPOUND_ALL everything the range can absorb goes back in.
/// WALLET_ALL every fee comes to you; the position keeps only its principal.
/// MATCHING the geometry's own answer, stated honestly as what it is.
/// ROUTE send the compounding share to a DIFFERENT position you already hold —
/// a blue-chip or stablecoin book — instead of compounding the risk back
/// into the pair that produced it.
///
/// Whichever you choose, NO SWAP HAPPENS. The share that cannot compound was never going to, and the
/// share that can, does. Nobody is trading on your behalf to force a ratio — which is exactly how a
/// "smart split" would have to be implemented if the vault insisted on an exact number across BOTH
/// tokens. See `FeeRouter.route`; the arithmetic is one function and it is unit-tested.
/// =============================================================================================
contract QuantumVaultV2 is Ownable2Step, Pausable, ReentrancyGuard, ERC721Holder {
using SafeERC20 for IERC20;
// --- constants ---
uint256 public constant BPS = 10_000;
uint256 public constant MAX_PROTOCOL_FEE_BPS = 3_000; // 30% hard cap on the performance fee
// L-03: MAX_SWAP_SLIPPAGE_BPS removed — a v1 balancing-swap constant with no V2 use (V2 never swaps); it
// only added a misleading public ABI getter.
// --- rebalance state-machine constants (P1.6, SnuggleVault-faithful) ---
// Hashlock M-03 (2026-09): MIN_OOR_TRACKING_INTERVAL removed, with its TrackingIntervalNotMet error. It
// refused action 3 (reset) for the first five minutes of an episode, so an in-range observation inside
// that window did NOT end it: the episode kept its original start, and a later exit could be snuggled
// without the position ever being continuously out of range for `rebalanceDelay`. A reset is now
// accepted the moment the oracle tick is in range. No consumer on the V2 path reads the getter (keeper-worker's
// vaultAbi(2) never declared it); keeper/src/abi.ts + keeper.ts readLoopContext and site/assets/quantum-vault.abi.json
// are V1-shaped and must drop both symbols as part of the V2 cutover, or that keeper's loop throws on the new vault.
uint32 public constant MAX_REBALANCE_DELAY = 7 days; // upper bound on a position's rebalance delay
/// @dev The recommended default: half of each harvest compounds, half arrives as spendable cash.
/// A position left entirely on auto-compound grows but never pays anything out, which reads
/// as "earning nothing" to the person who owns it; one set entirely to wallet never benefits
/// from its own fees. Half and half is the setting most people would choose if asked.
uint16 public constant DEFAULT_COMPOUND_BPS = 5_000;
int24 internal constant MIN_TICK = -887272; // Uniswap v3 usable tick bounds
int24 internal constant MAX_TICK = 887272;
uint160 internal constant MIN_SQRT_RATIO = 4295128739; // Uniswap v3 sqrtPrice bounds
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
// --- immutable-ish config ---
INonfungiblePositionManager public immutable positionManager;
IUniswapV3Factory public immutable uniswapFactory;
// --- fees ---
address public treasury;
// Treasury timelock (maxfi.tech hardening pattern: "24-hour timelocks on treasury changes").
// Re-pointing where the fees go is announced on-chain a full day before it takes effect,
// so clients can see (and exit ahead of) a hostile redirect.
uint256 public performanceFeeBps;
// Fee-change rate limit (maxfi.tech hardening pattern: "fees can only change ±5% per 6 hours").
// A compromised or hasty owner cannot spike the fee in one tx; reaching the cap takes days, in public.
uint256 public constant FEE_STEP_BPS = 500; // max ±5% (500 bps) change per window
uint256 public constant FEE_STEP_WINDOW = 6 hours;
uint256 public lastFeeChangeAt;
mapping(address => bool) public feeExempt;
// Per-user performance-fee override in bps (0 = use the default performanceFeeBps). The vault is
// token-denominated and has no USD oracle, so the deposit-size TIER (a larger TOTAL USD deposit
// across a user's positions earns a lower rate) is computed OFF-CHAIN by the keeper and written
// here via setUserFee. A keeper may only LOWER a user's rate below the default; only the owner may
// raise it — and every value is bounded by MAX_PROTOCOL_FEE_BPS — so this can never overcharge.
mapping(address => uint16) public userFeeBps;
// --- referrer split + wallet floor (FEE_MODEL.md v3) ---
// The 15% performance fee is split treasury + referrer, copying the SnuggleVault model: the referrer
// receives `referrerFeeBps` of the taxable fee (default 300 = 3%), the treasury gets the rest (12%).
// If `referrer` is unset (address(0)) the whole cut goes to the treasury. referrerFeeBps is always
// clamped to the effective rate so it can never exceed the total fee.
address public referrer;
uint256 public referrerFeeBps;
// Performance-fee cuts that could not be delivered to treasury/referrer at settlement time (e.g. the
// recipient was blocklisted or reverted on receipt) are escrowed here and pulled later via
// claimProtocolFees — so a bad protocol recipient can never freeze a user's non-pausable withdrawal.
// token => recipient (treasury/referrer) => amount owed.
mapping(address => mapping(address => uint256)) public owedProtocolFees;
// internal peer-audit M-01 cleanup (2026-09-08; NOT Hashlock M-01): v1's IL-offset / `walletFloorBps` model was REMOVED in v2. There is no
// walletFloorBps state, no ilOffset call site, and settlement no longer sizes an IL offset — net fees are
// routed once by the position's fee mode in _routeFees (SPLIT / COMPOUND_ALL / WALLET_ALL / ROUTE). The
// old wallet-floor/IL-gap comments that used to sit here were describing a feature the contract no longer has.
event ReferrerUpdated(address indexed referrer);
event ReferrerFeeUpdated(uint256 bps);
event ReferrerPaid(address indexed token, uint256 amount);
event ProtocolFeesEscrowed(address indexed token, address indexed to, uint256 amount);
event ProtocolFeesClaimed(address indexed token, address indexed to, uint256 amount);
// --- swap router (for single-sided deposits); 0 = single-sided disabled ---
// --- keeper balancing-swap safety (P1.6): 0 = keeper-directed balancing swap disabled ---
// A keeper-directed re-center swap is only allowed when this AND `twapInterval` are set, and it is
// hard-bounded on-chain to `maxSwapSlippageBps` from the TWAP price so a compromised keeper cannot
// sandwich the vault's own swap. The keeper never sets its own slippage floor.
// --- keepers ---
mapping(address => bool) public authorizedKeepers;
// --- limits ---
uint256 public maxPositionsPerUser; // 0 = unlimited
uint256 public maxTotalPositions; // 0 = unlimited
// --- range / oracle guards (0 = disabled) ---
int24 public minRangeWidthTicks; // reject ranges narrower than this
int24 public maxRangeWidthTicks; // reject ranges wider than this
uint32 public twapInterval; // seconds; 0 disables the TWAP deviation check
int24 public maxTwapDeviationTicks; // reject if |spot - twap| exceeds this; 0 disables
// --- pool registry ---
struct PoolConfig {
address pool;
address token0;
address token1;
// The pool's second key: a FEE on Uniswap and PancakeSwap, a TICK SPACING on Aerodrome
// Slipstream. One field because a pool has exactly one of them, and `slipstream` says which.
uint24 fee;
bool active;
// Which interface shape this venue speaks. Recorded ONCE, at registration, rather than probed
// per call: it cannot change, and rediscovering it on every mint would cost gas forever.
// Free in storage — `token1 + fee + active` leaves 8 spare bytes in this slot.
bool slipstream;
}
mapping(bytes32 => PoolConfig) public pools;
bytes32[] public poolIds;
// --- positions (keyed by Uniswap v3 tokenId) ---
struct Position {
address owner;
bytes32 poolId;
uint40 createdAt;
bool exists;
}
mapping(uint256 => Position) public positions;
uint256 public totalActivePositions;
mapping(address => uint256[]) private _userTokenIds;
mapping(uint256 => uint256) private _userIndex;
uint256[] private _allTokenIds;
mapping(uint256 => uint256) private _allIndex;
// --- per-position auto-management strategy (P1.6). Kept separate from Position so the
// positions() getter/ABI stays stable. outOfRangeSince == 0 means "not tracking". ---
/// @notice The settings `depositWithStrategy` applies in the same transaction as the mint.
struct StrategyArgs {
int24 rangeWidthTicks;
uint32 rebalanceDelay;
bool autoSnuggle;
bool autoCompound;
uint8 feeMode; // FeeRouter.Mode, ROUTE refused here
uint16 compoundBps;
}
struct Strategy {
int24 rangeWidthTicks; // width (in ticks) preserved across auto-rebalances; 0 = auto-rebalance off
uint32 rebalanceDelay; // seconds a position must be continuously OOR before action 2 is allowed
uint40 outOfRangeSince; // timestamp OOR tracking began; 0 = not tracking
bool autoSnuggle; // opt-in to keeper-driven auto-rebalance
bool autoCompound; // kept for ABI continuity with v1; `feeMode` is authoritative in v2
uint8 feeMode; // FeeRouter.Mode — where net fees go at settlement
uint16 compoundBps; // share re-invested under SPLIT/ROUTE; 5000 = half back in, half to wallet
// ARMED: opened entirely to one side of price, waiting for the market to arrive. Such a
// position is out of range BY DESIGN — it converts as price travels through it — and the
// vault cannot otherwise tell it apart from a position that DRIFTED out and needs rescuing.
// Re-ranging the first kind destroys the entry the owner deliberately placed, so while this
// is set the keeper must leave the position alone. Cleared the moment price first enters the
// range; from then on it earns on both sides and snuggles like any other position, and it
// never goes back to true — a mission that has begun does not un-begin.
//
// Stored as "armed" rather than "activated" so the common case — a range that contains spot
// at mint — writes nothing at all. Only a deliberate one-sided entry pays for the flag.
bool armed;
// Which side an ARMED range was placed on (true = entirely above spot). Needed so that price
// crossing all the way through the range between keeper passes still counts as arrival.
bool armedAbove;
// Hashlock L-01 (2026-09): whether `feeMode`/`compoundBps` were CHOSEN. Without this the vault could not
// tell "never set" from "set to zero" — COMPOUND_ALL is mode 0 and SPLIT/0 is a legal policy — so
// setStrategy and _recenter read an all-zero struct as "unset", rewrote it to the advertised
// SPLIT/5000 default and silently discarded a deliberate zero policy. Set by setFeeMode, and by
// setStrategy/_recenter when they materialize the default; carried onto every successor with the
// rest of the struct and deleted with it. Free in storage: the slot goes from 19 to 20 of 32 bytes.
bool feeModeSet;
}
mapping(uint256 => Strategy) public strategies;
/// @notice For FeeRouter.Mode.ROUTE: the position that receives this one's compounded share.
/// @dev Held outside `Strategy` because only routed positions ever set it; widening the struct to
/// a second storage slot for a field most positions leave at zero would cost every position.
mapping(uint256 => uint256) public feeRouteTarget;
/// @notice old tokenId -> the tokenId a snuggle replaced it with. A ROUTE target is a position,
/// and a position changes tokenId every time it is re-centred; without this the route
/// silently became a wallet payout after the target's first snuggle.
mapping(uint256 => uint256) public successorOf;
/// @notice Tokens the owner has committed to a position but which are not in the LP yet.
/// @dev WHY QUEUE RATHER THAN TOP UP IMMEDIATELY: adding liquidity to a live position requires
/// both tokens in the range's *current* ratio, so a plain top-up silently refunds most of one
/// side. A rebalance already exits and re-mints the whole position, so folding new capital in
/// at that moment needs no swap and lands at a ratio the new range can actually absorb.
///
/// Tokens are pulled at QUEUE time, not at rebalance time. Pulling later would make a keeper
/// action depend on an allowance and balance that may have moved since — a keeper action that
/// can fail for reasons outside the keeper's control is a liveness bug. Queued funds are never
/// trapped: `cancelQueuedDeposit` returns them on demand.
mapping(uint256 => PositionQueue.PendingDeposit) public pendingDeposits;
/// @notice A width/delay change that lands at the next rebalance rather than immediately.
/// @dev `setStrategy` clears `outOfRangeSince`, so editing width mid-countdown restarts the
/// out-of-range timer and pushes the rebalance further away — the opposite of what someone
/// adjusting settings during a drawdown intends. Queuing applies the change during
/// settlement, when the timer is being reset anyway, so nothing in flight is disturbed.
mapping(uint256 => PositionQueue.PendingStrategy) internal pendingStrategies;
// --- per-position fee & IL-offset accounting (FEE_MODEL.md v2, §4). Kept in its own mapping so
// the positions()/strategies() getters/ABI stay stable. Tracking is PER-TOKEN (D2): the
// performance-fee choke-point never touches the oracle; only the IL-offset SIZING uses the
// TWAP (D3). Survives re-centers (carried onto the new tokenId) because Uniswap zeroes
// `tokensOwed` on every collect — the running accumulator is the only durable record. ---
struct FeeAccounting {
uint256 principal0; // cost basis (token0) stamped at deposit; NEVER taxed, NEVER spent by fee logic
uint256 principal1; // cost basis (token1)
uint256 feesEarnedCumulative0; // running total of token0 trading fees EVER collected by this position
uint256 feesEarnedCumulative1; // running total of token1 trading fees ever collected
uint256 feesTaxed0; // high-water mark: token0 fees the performance fee has ALREADY been applied to
uint256 feesTaxed1; // high-water mark: token1 fees already taxed
// Hashlock M-02 (2026-09): the sub-unit part of the performance fee, carried into the next taxing
// of this position in NUMERATOR units (fee-token wei × BPS, so each half is always < BPS): token0's
// remainder in the low 128 bits, token1's in the high 128 bits. The cut on a slice is
// `(taxable × bps + carried) / BPS` and the modulus is carried, so N small collections pay exactly
// what one collection of their sum would. Before this, a slice under 7 raw units (at 1500 bps)
// rounded to a zero cut while still being checkpointed as taxed above, and the protocol's share of
// it was lost for good. Lives in this struct so it is snapshotted, carried onto the snuggle
// successor and cleared on close with the rest of the accounting. One packed word rather than two:
// one storage word less per position and two stack slots less through `_tax` (this contract inlines
// OZ Math.mulDiv, whose untagged assembly disables via_ir's stack-to-memory relief).
uint256 feeRemainder;
}
mapping(uint256 => FeeAccounting) public feeAccounting;
/// @notice Keeper-supplied execution parameters for a re-center. v2 has NO swap path at all, so
/// these are slippage floors and a deadline and nothing else — a re-entry is always
/// symmetric re-center by first balancing the exited principal via the configured router.
/// @dev Bundled purely to keep `_recenter` inside the EVM stack limit under via_ir — three
/// separate arguments pushed it one slot too deep.
struct RecenterPlan {
int24 lower;
int24 upper;
bool isToken0Side;
}
struct RebalanceParams {
uint256 decreaseAmount0Min; // slippage floor when removing the old position's liquidity
uint256 decreaseAmount1Min;
uint256 mintAmount0Min; // slippage floor when minting the new position
uint256 mintAmount1Min;
uint256 deadline;
}
// --- events ---
event PoolAdded(bytes32 indexed poolId, address token0, address token1, uint24 fee);
event PoolRemoved(bytes32 indexed poolId);
event PositionCreated(
address indexed owner, bytes32 indexed poolId, uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1
);
event PositionWithdrawn(address indexed owner, bytes32 indexed poolId, uint256 indexed tokenId, uint256 amount0, uint256 amount1);
event FeesHarvested(uint256 indexed tokenId, uint256 collected0, uint256 collected1, uint256 fee0, uint256 fee1);
event FeesCollected(uint256 indexed tokenId, uint256 collected0, uint256 collected1);
event FeeTaxed(uint256 indexed tokenId, uint256 taxable0, uint256 taxable1, uint256 cut0, uint256 cut1);
event Rebalanced(address indexed owner, bytes32 indexed poolId, uint256 oldTokenId, uint256 newTokenId, int24 tickLower, int24 tickUpper);
event PerformanceFeeUpdated(uint256 bps);
event UserFeeUpdated(address indexed user, uint256 bps);
event TreasuryUpdated(address treasury);
event KeeperUpdated(address keeper, bool allowed);
event FeeExemptUpdated(address account, bool exempt);
event LimitsUpdated(uint256 maxPerUser, uint256 maxTotal, uint256 minHold);
event RangeConfigUpdated(int24 minWidth, int24 maxWidth, uint32 twapInterval, int24 maxTwapDeviation);
event Compounded(uint256 indexed tokenId, uint256 added0, uint256 added1);
event StrategyUpdated(
uint256 indexed tokenId, int24 rangeWidthTicks, uint32 rebalanceDelay, bool autoSnuggle, bool autoCompound
);
event FeeModeUpdated(uint256 indexed tokenId, uint8 mode, uint16 compoundBps, uint256 routeTokenId);
event TrackingStarted(uint256 indexed tokenId, uint40 outOfRangeSince);
/// @notice Price has reached a position that was opened waiting for it. From here it earns on
/// both sides and snuggles normally if price leaves again.
event PositionActivated(uint256 indexed tokenId);
event TrackingReset(uint256 indexed tokenId);
event KeeperActionExecuted(uint256 indexed tokenId, uint8 action, uint256 newTokenId);
// --- errors ---
error PoolNotActive();
error BadTicks();
error ZeroAmounts();
error NoPosition();
error NotPositionOwner();
error PositionInRange();
error NotKeeper();
error FeeTooHigh();
error FeeChangeTooSoon();
error FeeStepTooLarge();
error ZeroAddress();
error PoolExists();
error PoolDoesNotExist();
error TrackedPosition();
error TooManyPositions();
error RangeTooNarrow();
error RangeTooWide();
error TwapDeviation();
error BadSwapAmount();
error NotOutOfRange();
error AlreadyTracking();
error NotTracking();
error DelayNotMet();
error StillOutOfRange();
error AutoSnuggleDisabled();
error NotActivated();
error BadActionType();
error NoChange();
error BadStrategy();
constructor(address owner_, address positionManager_, address treasury_, uint256 performanceFeeBps_)
Ownable(owner_)
{
_nonZero(positionManager_);
_nonZero(treasury_);
_checkFee(performanceFeeBps_);
positionManager = INonfungiblePositionManager(positionManager_);
uniswapFactory = IUniswapV3Factory(INonfungiblePositionManager(positionManager_).factory());
treasury = treasury_;
performanceFeeBps = performanceFeeBps_;
referrerFeeBps = 300; // 3% of fees to the referrer (12% treasury) — matches the copied model
}
// =========================================================================
// User actions
// =========================================================================
/// @notice Open a concentrated-liquidity position in an approved pool. Both assets required (v1).
function deposit(
bytes32 poolId,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) external whenNotPaused nonReentrant returns (uint256 tokenId) {
tokenId = _deposit(poolId, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline);
}
/// @notice One signature after the token approvals: open the position AND set its strategy and fee policy
/// in the same transaction. Behaves exactly like `deposit` followed by `setStrategy` and `setFeeMode`
/// from the same owner, except the ROUTE fee mode is refused here (it needs a second, existing
/// position; choose it afterwards with `setFeeMode`). Why this exists: the vault mints with a blank
/// strategy and the keeper never acts on a blank one, so a dropped or wallet-rejected follow-up
/// signature left positions that never snuggled (Base #6159714, 2026-10-05). Same validation, same
/// events, same storage as the two-step path — only the number of signatures changes.
function depositWithStrategy(
bytes32 poolId,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline,
StrategyArgs calldata s
) external whenNotPaused nonReentrant returns (uint256 tokenId) {
if (s.feeMode == uint8(FeeRouter.Mode.ROUTE)) revert BadStrategy();
tokenId = _deposit(poolId, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline);
_applyStrategy(tokenId, poolId, s.rangeWidthTicks, s.rebalanceDelay, s.autoSnuggle, s.autoCompound);
_applyFeeMode(tokenId, s.feeMode, s.compoundBps, 0);
}
function _deposit(
bytes32 poolId,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) internal returns (uint256 tokenId) {
PoolConfig storage p = pools[poolId];
if (!p.active) revert PoolNotActive();
_validateRange(p, tickLower, tickUpper);
if (amount0Desired == 0 && amount1Desired == 0) revert ZeroAmounts();
if (amount0Desired > 0) IERC20(p.token0).safeTransferFrom(msg.sender, address(this), amount0Desired);
if (amount1Desired > 0) IERC20(p.token1).safeTransferFrom(msg.sender, address(this), amount1Desired);
// identical approve → mint → revoke → refund → track → stamp → emit sequence as the
// single-sided path; shared through _openPosition so the mint block exists once in bytecode.
tokenId = _openPosition(
p, poolId, msg.sender, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline
);
}
/// @notice Deposit a single asset. The vault swaps `swapAmountIn` of it into the other token via
/// the configured router, then opens the position with the resulting balances. The optimal
/// split is computed off-chain (frontend/keeper); on-chain slippage is bounded by `amountOutMin`.
/// @notice Close your position fully: collect all fees, remove all liquidity, tax 100% of the
/// not-yet-taxed fee slice to the treasury, and return principal + net fees. Burns the NFT.
/// @dev Settlement event 6.1 (close, tax 100%). Always available, even while the vault is paused
/// for new deposits. The performance fee is taken ONLY from the newly-taxable fee slice
/// (`feesEarnedCumulative − feesTaxed`, per token) — never from principal (I1), and never twice
/// (I2): the cut is paid out of the tokens actually collected here, so it is bounded by the
/// realized fees and can never dip into the deposited principal.
function withdraw(uint256 tokenId, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
external
nonReentrant
{
_withdrawInto(tokenId, msg.sender, amount0Min, amount1Min, deadline);
}
/// @notice Withdraw to an address you nominate, instead of your own wallet. The escape hatch for a
/// wallet a token has blocklisted (USDC/USDT can freeze an address): without this, such an
/// owner could never receive their own principal. OWNER-GATED and not pausable, exactly like
/// withdraw — the caller must still own the position; only the DESTINATION changes, so this
/// cannot be used to move anyone else's funds.
function withdrawTo(uint256 tokenId, address recipient, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
external
nonReentrant
{
_nonZero(recipient);
_withdrawInto(tokenId, recipient, amount0Min, amount1Min, deadline);
}
function _withdrawInto(uint256 tokenId, address payee, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
internal
{
Position memory pos = _requireOwner(tokenId);
PoolConfig storage p = pools[pos.poolId];
// FREEZE-VECTOR FIX (High, 2026-09-08): route any QUEUED (pending) capital to the withdrawal
// DESTINATION, not pos.owner. The refund inside _removePosition (reached via _exitLiquidity below)
// always targets pos.owner, so a blocklisted owner — the exact case withdrawTo exists for — could
// never recover their queued funds (and cannot self-cancel: unqueue reverts once the position is
// gone, and the vault has no ERC-20 rescue). refundIfAny DELETES the entry, so _removePosition's
// later refund is then a no-op. For a plain withdraw() where payee == owner this is unchanged.
PositionQueue.refundIfAny(pendingDeposits, tokenId, p.token0, p.token1, payee);
// 1) collect all outstanding fees to the vault (liquidity still present → collect returns fees
// only) and accrue them to the running cumulative.
// 2) tax 100% of the not-yet-taxed fee slice → treasury (the ONLY place treasury is credited).
// With tax-on-collect that slice IS the freshly-collected one, and `_takeFee` clamps to the
// not-yet-taxed remainder regardless. Taken BEFORE the exit because the exit clears
// feeAccounting; the vault already holds c0/c1 so the cut is fully covered.
(uint256 c0, uint256 c1, uint256 cut0, uint256 cut1) = _collectAndTax(tokenId, pos.owner, p);
// 3) remove all liquidity, collect the principal (and anything previously compounded back in)
// to the VAULT, burn the emptied NFT and drop tracking (also clears feeAccounting). Same
// sequence as a re-center's exit, shared.
(uint256 p0, uint256 p1) = _exitLiquidity(tokenId, amount0Min, amount1Min, deadline);
// 4) everything collected here minus the cut goes to the owner (principal + net fees). cut is
// bounded by the realized fees, so out >= principal (I1).
uint256 out0 = c0 + p0 - cut0;
uint256 out1 = c1 + p1 - cut1;
_pay2(p.token0, p.token1, payee, out0, out1);
emit PositionWithdrawn(pos.owner, pos.poolId, tokenId, out0, out1);
}
/// @notice Withdraw a fraction (`fractionBps` of 10_000) of your position. Collects all outstanding
/// fees, taxes the whole freshly-collected slice once, returns `fraction × principal` plus
/// ALL of the net fees, and scales the remaining cost basis down by the same fraction.
/// @dev Settlement event 6.2 (withdrawal of a fraction). FIX-A: the accrued net fees are the owner's
/// and are paid out in full — nothing is re-injected into the LP. Re-injecting a single-sided
/// net-fee remainder made increaseLiquidity mint zero liquidity and revert (single-sided fees are
/// common), which could brick withdrawFraction; paying all net fees out can never revert and is
/// economically correct. Never taxes principal (I1); taxed exactly once (I2). Always available
/// (not pausable), like the full close.
function withdrawFraction(
uint256 tokenId,
uint256 fractionBps,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) external nonReentrant {
Position memory pos = _requireOwner(tokenId);
// 0 < fraction < BPS; a full close (== BPS) uses withdraw(). One check, one error.
if (fractionBps == 0 || fractionBps >= BPS) revert BadSwapAmount();
PoolConfig storage p = pools[pos.poolId];
// 1) collect ALL outstanding fees to the vault and accrue them.
// 2) FIX-3: with tax-on-collect everything collected before now is already taxed, so the taxable
// base is the freshly-collected slice ONLY. Tax ALL of it now (advancing the high-water mark to
// cumulative), so nothing untaxed is ever re-injected into the LP. `net{0,1}` is what remains of
// this collection after the cut; the owner takes the withdrawn fraction of it, the rest stays
// invested.
(uint256 c0, uint256 c1, uint256 cut0, uint256 cut1) = _collectAndTax(tokenId, pos.owner, p);
uint256 net0 = c0 - cut0;
uint256 net1 = c1 - cut1;
// 3) remove `fraction` of the liquidity and collect that principal to the vault.
_decrease(
tokenId, uint128(Math.mulDiv(_liquidityOf(tokenId), fractionBps, BPS)), amount0Min, amount1Min, deadline
);
(uint256 pp0, uint256 pp1) = _collectAll(tokenId);
// 4) FIX-A: pay the owner the WHOLE net-fee slice — do NOT re-inject any remainder into the LP.
// The old code re-added the un-withdrawn `(1−f)` net-fee remainder via increaseLiquidity. When
// fees are one-sided (e.g. net1 == 0) and the position is in range, increaseLiquidity computes
// liquidity = min(fromToken0, fromToken1) = 0 and UniswapV3Pool.mint reverts on
// require(amount > 0). Single-sided fees are common, so that path could brick withdrawFraction.
// The accrued fees are the owner's; paying them all out can never revert (no single-sided mint)
// and is economically correct — the remaining `(1−f)` position simply keeps `(1−f)` principal
// and zero accrued fees.
//
// 5) pay the owner: withdrawn principal + ALL net fees. `pp{0,1}` is bounded by the liquidity
// actually removed, so principal is never over-returned.
uint256 out0 = pp0 + net0;
uint256 out1 = pp1 + net1;
// 6) scale the cost basis down by the withdrawn fraction (principal is never taxed).
FeeAccounting storage fa = feeAccounting[tokenId];
fa.principal0 = Math.mulDiv(fa.principal0, BPS - fractionBps, BPS);
fa.principal1 = Math.mulDiv(fa.principal1, BPS - fractionBps, BPS);
_pay2(p.token0, p.token1, pos.owner, out0, out1);
emit PositionWithdrawn(pos.owner, pos.poolId, tokenId, out0, out1);
}
/// @notice Collect a position's fees and pay them out to the owner. OWNER ONLY (a keeper cannot harvest).
/// @dev D1: a harvest that pays fees to the owner IS taxed — the freshly collected fee slice is
/// treated as a withdrawal of fees and the performance fee is applied to it (once). A plain
/// `compound` (which re-invests rather than paying out) instead stays untaxed until exit.
function harvest(uint256 tokenId) external nonReentrant returns (uint256 net0, uint256 net1) {
// OWNER ONLY. harvest sends ALL net fees to the wallet, which would override a COMPOUND_ALL or
// SPLIT owner's standing feeMode if a keeper could trigger it. The keeper honours feeMode on the
// snuggle path (FeeRouter); manual harvest is the owner explicitly choosing to take fees now.
Position memory pos = _requireOwner(tokenId);
PoolConfig storage p = pools[pos.poolId];
(uint256 c0, uint256 c1, uint256 cut0, uint256 cut1) = _collectAndTax(tokenId, pos.owner, p);
net0 = c0 - cut0;
net1 = c1 - cut1;
if (net0 > 0) IERC20(p.token0).safeTransfer(pos.owner, net0);
if (net1 > 0) IERC20(p.token1).safeTransfer(pos.owner, net1);
emit FeesHarvested(tokenId, c0, c1, cut0, cut1);
}
/// @notice Collect a position's fees and re-deploy the NET (post-fee) fees into the same position
/// (auto-compound). OWNER ONLY (a keeper cannot compound; auto-compound runs per feeMode on the snuggle path).
/// @dev D1 (v2): compound IS taxed — tax-on-collect. The freshly-collected fees pay the performance
/// cut to the treasury BEFORE anything is re-invested, so only the net fees fold into LP
/// liquidity. This is the single-tax rule's collection point for the compound path: after this
/// call `feesTaxed == feesEarnedCumulative`, so NO untaxed fees are ever folded into liquidity
/// (which the old defer-tax model did, causing withdraw to revert once the AMM converted the
/// untaxed token0 slice to token1). Taxed exactly once (I2) is still enforced by the high-water
/// mark, now always caught up. Any net dust that does not fit the ratio is returned to the owner
/// (already taxed, so it is neither taxed again nor double-counted later).
function compound(uint256 tokenId, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
external
nonReentrant
returns (uint256 added0, uint256 added1)
{
// OWNER ONLY, same reason as harvest: compound folds ALL net fees into LP, overriding a
// WALLET_ALL owner's feeMode if a keeper could trigger it. Auto-compound happens per feeMode on
// the snuggle path. A future keeper-driven compound must route through FeeRouter, not this path.
Position memory pos = _requireOwner(tokenId);
PoolConfig storage p = pools[pos.poolId];
// 1) collect + accrue to cumulative
(uint256 c0, uint256 c1) = _collectFees(tokenId);
if (c0 == 0 && c1 == 0) return (0, 0);
// 2) FIX-1: tax the freshly-collected fees NOW (advances the high-water mark to cumulative), then
// re-invest only the net. No untaxed fees ever remain inside the LP.
(uint256 cut0, uint256 cut1) = _takeFee(tokenId, pos.owner, p.token0, p.token1, c0, c1);
uint256 net0 = c0 - cut0;
uint256 net1 = c1 - cut1;
if (net0 == 0 && net1 == 0) {
emit Compounded(tokenId, 0, 0);
return (0, 0);
}
// internal peer-audit M-03 FIX (2026-09-08; NOT Hashlock M-03): a ONE-SIDED net-fee slice (exactly one of net0/net1 is zero — common) mints
// zero liquidity on an in-range position and reverts increaseLiquidity, bricking compound() until both
// sides accrue. Mirror withdrawFraction's FIX-A: pay the net out to the owner instead of attempting the
// mint — already taxed, economically correct, and can never revert. Both-sided net still compounds as
// before; nothing is lost or stuck, and harvest/snuggle remain available.
if (net0 == 0 || net1 == 0) {
_pay2(p.token0, p.token1, pos.owner, net0, net1);
emit Compounded(tokenId, 0, 0);
return (0, 0);
}
IERC20(p.token0).forceApprove(address(positionManager), net0);
IERC20(p.token1).forceApprove(address(positionManager), net1);
(, added0, added1) = positionManager.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: net0,
amount1Desired: net1,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline
})
);
IERC20(p.token0).forceApprove(address(positionManager), 0);
IERC20(p.token1).forceApprove(address(positionManager), 0);
// 3) net ratio-dust that could not be re-invested is already taxed → return it to the owner.
// Do NOT touch the cumulative/taxed marks: these fees were earned and taxed exactly once.
_pay2(p.token0, p.token1, pos.owner, net0 - added0, net1 - added1);
emit Compounded(tokenId, added0, added1);
}
/// @notice Configure keeper-driven auto-management for one of your positions (P1.6).
/// @dev Only the position owner. When `autoSnuggle` is on, `rangeWidthTicks` must be a positive
/// multiple of the pool tickSpacing and satisfy the vault's range-width guards; the keeper
/// re-centers to this width around the (TWAP) tick via the track→delay→rebalance machine.
/// Changing the strategy always clears any in-flight out-of-range tracking timer.
function setStrategy(
uint256 tokenId,
int24 rangeWidthTicks,
uint32 rebalanceDelay,
bool autoSnuggle,
bool autoCompound
) external {
Position memory pos = _requireOwner(tokenId);
_applyStrategy(tokenId, pos.poolId, rangeWidthTicks, rebalanceDelay, autoSnuggle, autoCompound);
}
/// @dev The body of `setStrategy`, shared with `depositWithStrategy`. Ownership is the caller's job.
function _applyStrategy(
uint256 tokenId,
bytes32 poolId,
int24 rangeWidthTicks,
uint32 rebalanceDelay,
bool autoSnuggle,
bool autoCompound
) internal {
if (rebalanceDelay > MAX_REBALANCE_DELAY) revert BadStrategy();
// Any non-zero width is validated, not only when auto is on: manualSnuggle uses a stored
// width whenever it is > 0, so an unaligned one would reach a mint.
if (autoSnuggle || rangeWidthTicks != 0) {
PositionQueue.validateWidth(rangeWidthTicks, pools[poolId].pool, minRangeWidthTicks, maxRangeWidthTicks);
}
// A direct edit supersedes anything queued. Otherwise the older queued width would land at
// the next rebalance ON TOP of the newer setting, and the last thing the owner did would lose.
delete pendingStrategies[tokenId];
// Preserve the fee routing across a strategy edit. Someone changing their range width has
// said nothing about where they want their fees to go, and silently resetting that to the
// default would quietly redirect their income.
// Hashlock L-01 (2026-09): `feeModeSet` is the ONLY "has a fee policy been chosen" signal. A zero-valued
// policy (COMPOUND_ALL, or SPLIT with 0 bps) is a real choice and is carried verbatim; the
// advertised default is materialized only for a position whose owner never chose one.
Strategy storage prev = strategies[tokenId];
uint8 mode = prev.feeMode;
uint16 cbps = prev.compoundBps;
if (!prev.feeModeSet) {
mode = uint8(FeeRouter.Mode.SPLIT); // never configured before → the recommended default
cbps = DEFAULT_COMPOUND_BPS;
}
strategies[tokenId] = Strategy({
rangeWidthTicks: rangeWidthTicks,
rebalanceDelay: rebalanceDelay,
outOfRangeSince: 0,
autoSnuggle: autoSnuggle,
autoCompound: autoCompound,
feeMode: mode,
compoundBps: cbps,
feeModeSet: true,
// Carried, never re-set. Changing your settings must not re-arm a position the market
// has already reached, or an owner could dodge the gate by touching a slider.
armed: prev.armed,
armedAbove: prev.armedAbove
});
emit StrategyUpdated(tokenId, rangeWidthTicks, rebalanceDelay, autoSnuggle, autoCompound);
}
// =========================================================================
// v2: fee routing, queued capital, queued setting changes
// =========================================================================
/// @notice Choose where this position's net fees go at each settlement.
/// @param mode 0 COMPOUND_ALL · 1 WALLET_ALL · 2 SPLIT · 3 MATCHING · 4 ROUTE
/// @param compoundBps share re-invested under SPLIT/ROUTE (5000 = half in, half to wallet)
/// @param routeTokenId under ROUTE, the position that receives the compounded share; else 0
/// @dev ROUTE is the conservative option: it lets fees earned by a volatile pair accumulate into
/// a position you already hold in something steadier, instead of compounding risk into the
/// pair that produced them. The target must be a live position with the SAME owner — routing
/// to someone else's position would be a transfer of value dressed up as a setting.
///
/// No swap happens. The compounded share is credited to the target's queued capital and can
/// only be absorbed at the target's next rebalance, and only to the extent the target's pool
/// actually uses those tokens. Anything it cannot use is returned to the wallet then. This is
/// what keeps the zero-swap property true across every fee mode.
function setFeeMode(uint256 tokenId, uint8 mode, uint16 compoundBps, uint256 routeTokenId) external {
_requireOwner(tokenId);
_applyFeeMode(tokenId, mode, compoundBps, routeTokenId);
}
/// @dev The body of `setFeeMode`, shared with `depositWithStrategy`. Ownership is the caller's job.
function _applyFeeMode(uint256 tokenId, uint8 mode, uint16 compoundBps, uint256 routeTokenId) internal {
if (mode > uint8(FeeRouter.Mode.ROUTE)) revert BadStrategy();
if (!FeeRouter.validate(FeeRouter.Mode(mode), compoundBps, routeTokenId)) revert BadStrategy();
if (routeTokenId != 0) {
if (routeTokenId == tokenId) revert BadStrategy(); // a position cannot feed itself
if (_load(routeTokenId).owner != msg.sender) revert NotPositionOwner();
}
Strategy storage s = strategies[tokenId];
s.feeMode = mode;
s.compoundBps = compoundBps;
s.feeModeSet = true; // Hashlock L-01 (2026-09): a chosen policy — zero-valued or not — is never re-defaulted
feeRouteTarget[tokenId] = routeTokenId;
emit FeeModeUpdated(tokenId, mode, compoundBps, routeTokenId);
}
/// @notice Commit extra capital now; it enters the position at its next rebalance.
/// @dev Both tokens are accepted so the new capital arrives in whatever ratio the next range
/// needs. Sending only one side is allowed and simply means the other side contributes
/// nothing to the mint — the surplus is refunded at settlement rather than held forever.
function queueDeposit(uint256 tokenId, uint256 amount0, uint256 amount1) external nonReentrant {
Position memory pos = _requireOwner(tokenId);
PoolConfig storage p = pools[pos.poolId];
// (0, 0) is the CANCEL, handled inside — queueing and un-queueing on one entry point is one
// fewer way to get them the wrong way round. Only QUEUEING is pausable: queued tokens are the
// owner's money that has not been invested yet, and a pause must never be able to hold them.
if (amount0 != 0 || amount1 != 0) _requireNotPaused();
PositionQueue.queueOrCancel(pendingDeposits, tokenId, p.token0, p.token1, amount0, amount1, msg.sender);
}
function queueStrategyChange(
uint256 tokenId,
int24 rangeWidthTicks,
uint32 rebalanceDelay,
bool setWidth,
bool setDelay
) external {
Position memory pos = _requireOwner(tokenId);
PositionQueue.queueStrategy(
pendingStrategies, tokenId, rangeWidthTicks, rebalanceDelay, setWidth, setDelay,
pools[pos.poolId].pool, MAX_REBALANCE_DELAY, minRangeWidthTicks, maxRangeWidthTicks
);
}
/// @dev Move queued capital into the amounts about to be minted, and clear the queue.
// =========================================================================
// Keeper actions (LP-only maintenance — cannot move funds to arbitrary addresses)
// =========================================================================
// `rebalance(tokenId, newTickLower, newTickUpper, ...)` was removed here.
//
// It let an authorized keeper choose the new range directly, bounded only by the width config.
// Every other keeper path derives the range ON-CHAIN from the position's own `rangeWidthTicks`,
// so this was the single place where a compromised keeper could pick where your liquidity sat.
// The snuggle covers every case it served, and without it the guarantee is unqualified: the
// keeper advances the machine, it never chooses the ticks.
/// @notice Drive the SnuggleVault-faithful out-of-range state machine for a position. Keeper-only.
/// The vault derives the new range on-chain from the position's own `rangeWidthTicks`,
/// so the keeper never chooses ticks — it only advances the machine.
/// @param action 1 = start tracking (position just went OOR), 2 = rebalance (after the delay),
/// 3 = reset tracking (price came back in range; accepted immediately — no minimum tracked
/// time, Hashlock M-03).
/// @dev Out-of-range is evaluated on the oracle tick (TWAP when `twapInterval` is set, else spot),
/// upper-exclusive: `tick < tickLower || tick >= tickUpper`. Action 2 requires `autoSnuggle`,
/// continuous OOR for `rebalanceDelay`, and re-centers to `rangeWidthTicks` around the tick.
function executeKeeperAction(uint256 tokenId, uint8 action, RebalanceParams calldata rp)
external
whenNotPaused
nonReentrant
returns (uint256 newTokenId)
{
_requireKeeper();
newTokenId = _keeperAction(tokenId, action, rp);
}
/// @notice Advance several positions in ONE transaction.
/// @dev WHY THIS EXISTS: a rebalance is free to the depositor because the keeper submits the
/// transaction and therefore pays for it. That makes the keeper's gas budget the thing that
/// decides how tight a range we can afford to defend — and one transaction per position pays
/// the 21,000-gas floor, the calldata, and a cold read of the pool and the factory, over and
/// over. Batched, those are paid once and every position after the first reads warm storage.
/// Cheaper rebalances and tighter ranges are the same conversation.
///
/// ALL OR NOTHING, deliberately. Isolating each position would need an external self-call
/// and a re-entrancy carve-out to go with it, which is a lot of surface to buy something the
/// keeper can already do: it filters off-chain before submitting, and on a revert it falls
/// back to one-at-a-time and finds the bad position that way. A batch that half-succeeded
/// would also be far harder to reason about after the fact than one that did not happen.
function executeKeeperActionBatch(
uint256[] calldata tokenIds,
uint8[] calldata actions,
RebalanceParams calldata rp
) external whenNotPaused nonReentrant returns (uint256[] memory newTokenIds) {
_requireKeeper();
uint256 n = tokenIds.length;
if (n == 0 || n != actions.length) revert BadActionType();
newTokenIds = new uint256[](n);
for (uint256 i; i < n; ++i) {
newTokenIds[i] = _keeperAction(tokenIds[i], actions[i], rp);
}
}
function _keeperAction(uint256 tokenId, uint8 action, RebalanceParams calldata rp)
internal
returns (uint256 newTokenId)
{
Position memory pos = _load(tokenId);
address pool = pools[pos.poolId].pool;
Strategy storage s = strategies[tokenId];
(bool oor, int24 tickLower, int24 tickUpper) = _rangeState(tokenId, pool);
if (action == 1) {
// start tracking
// An ARMED position (price has never entered its range) is out of range BY DESIGN. It is
// waiting for the market, not stranded by it. Starting the rebalance clock here is what
// would eventually re-range it to hug spot and destroy the entry the owner chose.
if (s.armed) revert NotActivated();
if (s.outOfRangeSince != 0) revert AlreadyTracking();
if (!oor) revert NotOutOfRange();
s.outOfRangeSince = uint40(block.timestamp);
emit TrackingStarted(tokenId, s.outOfRangeSince);
} else if (action == 2) {
// rebalance (delay-gated)
if (!s.autoSnuggle || s.rangeWidthTicks <= 0) revert AutoSnuggleDisabled();
// No `activated` check here, and it is not an omission: `outOfRangeSince` is written in
// exactly one place (action 1), which DOES require activation, and `armed` never goes
// back to false. So NotTracking below already implies it. If a future edit ever gives
// `outOfRangeSince` a second writer, put the check back — the guard is one SLOAD and we
// are 20 bytes from the EIP-170 ceiling, which is the only reason it is inferred here.
if (s.outOfRangeSince == 0) revert NotTracking();
if (!oor) revert NotOutOfRange();
if (block.timestamp < uint256(s.outOfRangeSince) + s.rebalanceDelay) revert DelayNotMet();
newTokenId = _rebalanceAuto(tokenId, s.rangeWidthTicks, rp);
} else if (action == 3) {
if (s.armed) {
// The market has reached an armed range: inside it, or all the way past it on the far
// side (a wick through between two keeper passes is still arrival). Judged on SPOT —
// the oracle that armed it — never the TWAP, whose lag could disarm a range price has
// not touched. Takes nothing and can only be called when true; nothing to abuse.
if (!VaultMath.arrived(pool, tickLower, tickUpper, s.armedAbove)) revert StillOutOfRange();
s.armed = false;
emit PositionActivated(tokenId);
} else {
// Came back in range on its own: stop the rebalance clock. No minimum tracked time
// (Hashlock M-03, 2026-09): refusing this while genuinely in range let the episode outlive
// the in-range visit, and the next exit was snuggled against a delay that was never served.
// The old five-minute gate protected nothing: StillOutOfRange below already refuses a reset
// while OOR, so a keeper never could flap the timer to postpone a due snuggle.
if (oor) revert StillOutOfRange();
if (s.outOfRangeSince == 0) revert NotTracking();
s.outOfRangeSince = 0;
emit TrackingReset(tokenId);
}
} else {
revert BadActionType();
}
emit KeeperActionExecuted(tokenId, action, newTokenId);
}
/// @notice Force an immediate snuggle, bypassing the delay machine. POSITION OWNER ONLY.
/// @dev A snuggle only fires when the position is OUT of range — matching SnuggleVault, whose
/// `manualSnuggle` reverts `PositionInRange()`. Re-centering an in-range position just
/// crystallizes impermanent loss (the traditional churn a snuggle exists to avoid), so it is
/// rejected here too. Manual bypasses the DELAY, never the out-of-range requirement. The
/// re-entry is single-sided and directional (VaultMath.recenterRange) at the position's
/// `rangeWidthTicks` (or its current width if no strategy is set).
function manualSnuggle(uint256 tokenId, RebalanceParams calldata rp)
external
whenNotPaused
nonReentrant
returns (uint256 newTokenId)
{
Position memory pos = _requireOwner(tokenId);
// OOR-only guard on the oracle (TWAP-when-configured) tick, upper-exclusive.
(bool oor, int24 curLower, int24 curUpper) = _rangeState(tokenId, pools[pos.poolId].pool);
if (!oor) revert PositionInRange();
// Same guard as the keeper's. A position price has never reached is waiting on purpose, and
// snuggling it would replace the range the owner deliberately placed. If they truly want out
// of the strategy, `withdraw` is always available.
if (strategies[tokenId].armed) revert NotActivated();
int24 width = strategies[tokenId].rangeWidthTicks > 0 ? strategies[tokenId].rangeWidthTicks : (curUpper - curLower);
newTokenId = _rebalanceAuto(tokenId, width, rp);
}
// =========================================================================
// Admin (owner = timelock/multisig)
// =========================================================================
/// @notice Register a Uniswap-shaped pool (Uniswap v3, PancakeSwap v3, Robinhood), keyed by FEE.
function addPool(address tokenA, address tokenB, uint24 fee) external onlyOwner returns (bytes32 poolId) {
return _addPool(tokenA, tokenB, int24(fee), false);
}
/// @notice Register an Aerodrome Slipstream pool, keyed by TICK SPACING.
/// @dev A separate entry point rather than a `bool` argument on `addPool`, deliberately. This is
/// called by a multisig from a hand-assembled payload, and a boolean in the twelfth byte of a
/// calldata blob is exactly the kind of thing that gets flipped by accident and noticed by
/// nobody. Two names cannot be confused; one bool can. Registering the wrong shape would
/// revert here rather than silently, but a reverted governance batch still costs 48 hours.
function addPoolSlipstream(address tokenA, address tokenB, int24 tickSpacing)
external
onlyOwner
returns (bytes32 poolId)
{
return _addPool(tokenA, tokenB, tickSpacing, true);
}
function _addPool(address tokenA, address tokenB, int24 key, bool slipstream)
internal
returns (bytes32 poolId)
{
_nonZero(tokenA);
_nonZero(tokenB);
(address token0, address token1) = _sort(tokenA, tokenB);
address pool = VenueAdapter.resolvePool(address(uniswapFactory), token0, token1, key, slipstream);
poolId = _poolId(token0, token1, key, slipstream);
if (pools[poolId].token0 != address(0)) revert PoolExists();
pools[poolId] = PoolConfig({
pool: pool, token0: token0, token1: token1,
fee: uint24(int24(key)), active: true, slipstream: slipstream
});
poolIds.push(poolId);
emit PoolAdded(poolId, token0, token1, uint24(int24(key)));
}
/// @notice Grow a pool's oracle history so it can serve a TWAP. A freshly created pool stores one
/// observation; `observe(secondsAgo > 0)` reverts on it (OLD), and since the keeper's
/// out-of-range check reads the oracle, a TWAP config on an un-provisioned pool would refuse
/// every keeper action for that pool's positions until it warms up. Call this once after
/// addPool, BEFORE enabling a TWAP (setRangeConfig twapInterval > 0), then let a few swaps
/// populate it.
/// @dev The RECOMMENDED config is spot (twapInterval = 0), where observe() is never called and this
/// is unnecessary — the corrected USDG/DELL batch uses 0 for exactly this reason. This tool
/// exists so a TWAP config is safe when deliberately chosen. Idempotent: cardinality only grows.
function provisionOracle(bytes32 poolId, uint16 cardinality) external onlyOwner {
address pool = pools[poolId].pool;
if (pool == address(0)) revert PoolDoesNotExist();
IUniswapV3Pool(pool).increaseObservationCardinalityNext(cardinality);
}
function removePool(bytes32 poolId) external onlyOwner {
if (pools[poolId].token0 == address(0)) revert PoolDoesNotExist();
pools[poolId].active = false;
emit PoolRemoved(poolId);
}
/// @notice Rate-limited fee change: at most ±FEE_STEP_BPS per FEE_STEP_WINDOW, always ≤ MAX_PROTOCOL_FEE_BPS.
/// Lowering the fee is also stepped so a flip-flop attack can't oscillate accounting.
function setPerformanceFee(uint256 bps) external onlyOwner {
_checkFee(bps);
if (block.timestamp < lastFeeChangeAt + FEE_STEP_WINDOW) revert FeeChangeTooSoon();
uint256 cur = performanceFeeBps;
uint256 step = bps > cur ? bps - cur : cur - bps;
if (step > FEE_STEP_BPS) revert FeeStepTooLarge();
lastFeeChangeAt = block.timestamp;
performanceFeeBps = bps;
emit PerformanceFeeUpdated(bps);
}
/// @notice Set the referrer address that receives `referrerFeeBps` of the performance fee. address(0)
/// sends the whole cut to the treasury. Owner only.
function setReferrer(address referrer_) external onlyOwner {
referrer = referrer_;
emit ReferrerUpdated(referrer_);
}
/// @notice Set the referrer's share of the performance fee in bps (owner only). Capped at
/// MAX_PROTOCOL_FEE_BPS; it is additionally clamped to the effective rate at pay-out, so the
/// referrer + treasury split can never exceed the total fee taken.
function setReferrerFee(uint256 bps) external onlyOwner {
_checkFee(bps);
referrerFeeBps = bps;
emit ReferrerFeeUpdated(bps);
}
/// @notice Set a user's deposit-tier performance fee in bps. The tier is computed OFF-CHAIN from
/// the user's TOTAL USD deposits across positions (a larger total earns a lower rate);
/// pass 0 to clear the override and fall back to the default (OWNER ONLY). The owner may set
/// any rate up to MAX_PROTOCOL_FEE_BPS; an authorized keeper may only LOWER a user's rate from
/// that user's current effective fee, and may never pass 0 (clearing the override would snap
/// the effective rate up to the default via the 0 sentinel) — so a compromised keeper can
/// never overcharge. For a 0% rate use setFeeExempt instead.
function setUserFee(address user, uint256 bps) external {
if (msg.sender != owner() && !authorizedKeepers[msg.sender]) revert NotKeeper();
_checkFee(bps);
// FIX-4: a non-owner (keeper) may only LOWER a user's rate from that user's CURRENT effective
// fee — never raise it. Gating on the default (performanceFeeBps) let a keeper raise a
// below-default user back up toward the default; gate on the user's own current fee instead.
// FIX-B: the keeper must also never set bps == 0. bps == 0 clears the override, and _feeBpsFor
// treats userFeeBps[user] == 0 as "no override → use the default", so a keeper could clear a
// discounted user's override and snap their effective rate UP to the default via the 0 sentinel.
// Clearing the override (0) stays owner-only; a 0% user rate is achieved via feeExempt (owner-only).
if (msg.sender != owner()) {
if (bps == 0) revert FeeTooHigh();
uint256 current = _userRate(user);
if (bps > current) revert FeeTooHigh();
}
userFeeBps[user] = uint16(bps);
emit UserFeeUpdated(user, bps);
}
/// @notice Point the performance fee at a new address.
/// @dev This USED to be a 24-hour propose/apply pair. It was removed, not weakened: `onlyOwner`
/// is a 2-of-2 Safe behind a 48-hour timelock, so the change already cannot happen without
/// two signatures and two days of public notice. A 24-hour delay nested inside a 48-hour one
/// can never be the binding constraint — it only ever added a second transaction to forget,
/// a second state machine to audit, and ~600 bytes to a contract that is up against the
/// EIP-170 limit. Rotating a compromised treasury stays possible, which is the capability
/// that actually mattered.
function setTreasury(address treasury_) external onlyOwner {
_nonZero(treasury_);
treasury = treasury_;
emit TreasuryUpdated(treasury_);
}
function setKeeper(address keeper, bool allowed) external onlyOwner {
authorizedKeepers[keeper] = allowed;
emit KeeperUpdated(keeper, allowed);
}
/// @notice Set the swap router used for single-sided deposits (e.g. Uniswap SwapRouter02). 0 disables single-sided.
/// @notice Enable/size the keeper balancing-swap price band (bps from the TWAP price). 0 disables the
/// keeper-directed swap entirely (auto re-centers then use the swap-free one-sided re-entry).
/// @dev The keeper-directed swap also requires `twapInterval > 0`. The band is a HARD on-chain bound,
/// so a compromised keeper cannot sandwich the vault's own swap for more than `bps`.
function setFeeExempt(address account, bool exempt) external onlyOwner {
feeExempt[account] = exempt;
emit FeeExemptUpdated(account, exempt);
}
/// @notice Position-count caps. There is deliberately NO hold-time parameter — see `setLimits`
/// in v1, which had one. A `minPositionHoldTime` is a lock on other people's money, and
/// leaving the ability to set it means "you can always withdraw" is a promise the owner
/// can revoke. Removing the field makes it unrevocable: no owner, no timelock, and no
/// compromised key can stop a depositor closing their position.
function setLimits(uint256 maxPerUser, uint256 maxTotal) external onlyOwner {
maxPositionsPerUser = maxPerUser;
maxTotalPositions = maxTotal;
emit LimitsUpdated(maxPerUser, maxTotal, 0);
}
/// @notice Configure range-width and TWAP-deviation guards for deposits/rebalances. Any 0 disables that check.
function setRangeConfig(int24 minWidth, int24 maxWidth, uint32 twapInterval_, int24 maxTwapDeviation)
external
onlyOwner
{
minRangeWidthTicks = minWidth;
maxRangeWidthTicks = maxWidth;
twapInterval = twapInterval_;
maxTwapDeviationTicks = maxTwapDeviation;
emit RangeConfigUpdated(minWidth, maxWidth, twapInterval_, maxTwapDeviation);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/// @notice Revoke a leftover token approval to the position manager (defense-in-depth).
function emergencyRevokeApproval(address token) external onlyOwner {
IERC20(token).forceApprove(address(positionManager), 0);
}
/// @notice Rescue an ERC-721 that is NOT a tracked user position (e.g. an accidental transfer).
function rescueERC721(address nft, uint256 tokenId, address to) external onlyOwner {
if (nft == address(positionManager) && positions[tokenId].exists) revert TrackedPosition();
_nonZero(to);
IERC721Minimal(nft).safeTransferFrom(address(this), to, tokenId);
}
/// @notice Pull performance fees that could NOT be delivered to `to` (treasury or referrer) at
/// settlement time — e.g. `to` was temporarily blocklisted on `token` (see the freeze-vector
/// fix in _payTo). Permissionless: the funds only ever go to the recorded recipient `to`, never
/// the caller, so anyone can trigger delivery once `to` can receive again. CEI-ordered under
/// nonReentrant; if `to` still cannot receive, the transfer reverts and the escrow is preserved.
function claimProtocolFees(address token, address to) external nonReentrant {
uint256 owed = owedProtocolFees[token][to];
if (owed == 0) return;
uint256 bal = IERC20(token).balanceOf(address(this));
uint256 pay = owed <= bal ? owed : bal;
owedProtocolFees[token][to] = owed - pay;
if (pay > 0) IERC20(token).safeTransfer(to, pay);
emit ProtocolFeesClaimed(token, to, pay);
}
// =========================================================================
// Views
// =========================================================================
function userTokenIds(address user) external view returns (uint256[] memory) {
return _userTokenIds[user];
}
function allTokenIds() external view returns (uint256[] memory) {
return _allTokenIds;
}
function poolCount() external view returns (uint256) {
return poolIds.length;
}
/// @notice The id of a Uniswap-shaped pool (Uniswap, PancakeSwap, Robinhood). Unchanged.
function computePoolId(address tokenA, address tokenB, uint24 fee) external pure returns (bytes32) {
(address token0, address token1) = _sort(tokenA, tokenB);
return _poolId(token0, token1, int24(fee), false);
}
/// @notice The id of an Aerodrome Slipstream pool, keyed by tick spacing.
function computePoolIdSlipstream(address tokenA, address tokenB, int24 tickSpacing)
external
pure
returns (bytes32)
{
(address token0, address token1) = _sort(tokenA, tokenB);
return _poolId(token0, token1, tickSpacing, true);
}
function _sort(address a, address b) internal pure returns (address, address) {
return a < b ? (a, b) : (b, a);
}
/// @dev The canonical pool key.
///
/// THE VENUE ONLY ENTERS THE PREIMAGE FOR SLIPSTREAM, and that asymmetry is deliberate. A
/// Uniswap-shaped id keeps its original three-field preimage, so every id ever derived —
/// on-chain, in the site, in a signed Safe payload — still resolves to the same pool. Adding
/// a fourth field unconditionally would have silently repointed all of them.
///
/// Slipstream ids get the extra field because they need it: a Uniswap 100-bps pool and a
/// Slipstream spacing-100 pool on the same pair would otherwise collide, and the second
/// registration would be refused as "pool exists" for a pool that does not. Slipstream had no
/// ids before today, so nothing can be broken by giving them a distinct shape.
function _poolId(address token0, address token1, int24 key, bool slipstream)
internal
pure
returns (bytes32)
{
return slipstream
? keccak256(abi.encode(token0, token1, key, true))
: keccak256(abi.encode(token0, token1, uint24(int24(key))));
}
// =========================================================================
// Internal
// =========================================================================
/// @dev Load a position and require it exists AND that `msg.sender` is its owner. Same checks, same
/// errors, same order as before — shared so the pair exists once in bytecode (EIP-170 diet).
function _requireOwner(uint256 tokenId) internal view returns (Position memory pos) {
pos = _load(tokenId);
if (pos.owner != msg.sender) revert NotPositionOwner();
}
function _nonZero(address a) internal pure {
if (a == address(0)) revert ZeroAddress();
}
function _checkFee(uint256 bps) internal pure {
if (bps > MAX_PROTOCOL_FEE_BPS) revert FeeTooHigh();
}
/// @dev A user's current rate before exemption/cap: the tier override when set, else the default.
function _userRate(address user) internal view returns (uint256) {
return userFeeBps[user] > 0 ? uint256(userFeeBps[user]) : performanceFeeBps;
}
function _requireKeeper() internal view {
if (!authorizedKeepers[msg.sender]) revert NotKeeper();
}
/// @dev Load a position and require it exists. The one exists-check in bytecode.
function _load(uint256 tokenId) internal view returns (Position memory pos) {
pos = positions[tokenId];
if (!pos.exists) revert NoPosition();
}
// L-03: `_requireOwnerOrKeeper` removed — a dead owner-OR-keeper gate from when harvest/compound allowed
// keepers. Both are OWNER-ONLY in V2 (they use _requireOwner), so it had no callers; keeping it implied a
// keeper could reach those fee paths, which the audit flagged as misleading.
/// @dev Sweep every token currently owed on `tokenId` to the vault. Shared by every collect site so
/// the CollectParams struct is built once in bytecode (EIP-170 diet — semantics unchanged).
function _collectAll(uint256 tokenId) internal returns (uint256 a0, uint256 a1) {
(a0, a1) = positionManager.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
}
/// @dev Transfer both tokens to `to`, skipping zero amounts. Shared by every paired payout site so
/// the guard+transfer pair exists once in bytecode (EIP-170 diet). `harvest` is written out
/// on purpose: guarantees.t.sol greps its two literal lines to prove the keeper is never paid.
function _pay2(address token0, address token1, address to, uint256 a0, uint256 a1) internal {
if (a0 > 0) IERC20(token0).safeTransfer(to, a0);
if (a1 > 0) IERC20(token1).safeTransfer(to, a1);
}
/// @dev The fields of positionManager.positions() the vault uses. THE one 12-value decode in
/// bytecode; every tick/liquidity read goes through here (EIP-170 diet).
function _posInfo(uint256 tokenId) internal view returns (int24 lower, int24 upper, uint128 liquidity) {
(,,,,, lower, upper, liquidity,,,,) = positionManager.positions(tokenId);
}
/// @dev Current tick bounds of `tokenId`.
function _ticksOf(uint256 tokenId) internal view returns (int24 lower, int24 upper) {
(lower, upper,) = _posInfo(tokenId);
}
/// @dev Current liquidity of `tokenId`. Shared accessor (EIP-170 diet — semantics unchanged).
function _liquidityOf(uint256 tokenId) internal view returns (uint128 liquidity) {
(,, liquidity) = _posInfo(tokenId);
}
/// @dev Burn `liquidity` from `tokenId` (no-op at zero), bounded by the caller's slippage floors.
/// Shared by every decrease site so the params struct is built once (EIP-170 diet).
function _decrease(uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
internal
{
if (liquidity > 0) {
positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: tokenId,
liquidity: liquidity,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline
})
);
}
}
// =========================================================================
// Fee model choke-points (FEE_MODEL.md §4, §5, §7)
// =========================================================================
/// @dev THE single fee-collection choke-point. Collect all currently-owed tokens (only accrued
/// trading fees while the position still holds liquidity) to the vault and add them to the
/// running per-token cumulative. Every path that collects Uniswap fees routes through here so
/// the accumulator survives the `collect` that zeroes Uniswap's `tokensOwed`. Takes NO fee and
/// pays NO one — that is `_takeFee`'s job — so it is safe to call anywhere fees must be accrued.
function _collectFees(uint256 tokenId) internal returns (uint256 c0, uint256 c1) {
(c0, c1) = _collectAll(tokenId);
FeeAccounting storage fa = feeAccounting[tokenId];
fa.feesEarnedCumulative0 += c0;
fa.feesEarnedCumulative1 += c1;
emit FeesCollected(tokenId, c0, c1);
}
/// @dev Collect the position's fees and tax the freshly-collected slice at once (tax-on-collect).
/// Shared by every path that pays fees out so the pair exists once in bytecode.
function _collectAndTax(uint256 tokenId, address feeOwner, PoolConfig storage p)
internal
returns (uint256 c0, uint256 c1, uint256 cut0, uint256 cut1)
{
(c0, c1) = _collectFees(tokenId);
(cut0, cut1) = _takeFee(tokenId, feeOwner, p.token0, p.token1, c0, c1);
}
/// @dev THE single place `treasury` is ever credited (I6). Applies the tiered, capped rate to ONLY
/// the requested newly-taxable slice (per token), advances the taxed high-water mark so the same
/// fee can never be taxed twice (I2), and transfers the cut to the treasury. `taxable{0,1}` is
/// clamped to the not-yet-taxed remainder, so the base is fees only — never principal (I1) — and
/// the caller must ensure the vault physically holds at least the cut (it always does: the cut is
/// a fraction of realized fees the caller has already collected to the vault).
function _takeFee(
uint256 tokenId,
address feeOwner,
address token0,
address token1,
uint256 taxable0,
uint256 taxable1
) internal returns (uint256 cut0, uint256 cut1) {
FeeAccounting storage fa = feeAccounting[tokenId];
uint256 u0 = fa.feesEarnedCumulative0 - fa.feesTaxed0;
uint256 u1 = fa.feesEarnedCumulative1 - fa.feesTaxed1;
if (taxable0 > u0) taxable0 = u0; // never tax what is already taxed (I2)
if (taxable1 > u1) taxable1 = u1;
fa.feesTaxed0 += taxable0;
fa.feesTaxed1 += taxable1;
(cut0, cut1, fa.feeRemainder) =
_tax(tokenId, feeOwner, token0, token1, taxable0, taxable1, fa.feeRemainder);
}
/// @dev Rate lookup + protocol payout + FeeTaxed, shared by the storage (`_takeFee`) and memory
/// (`_settleAndOffset`) taxing paths so the sequence exists once in bytecode. Callers advance
/// the taxed high-water mark, and persist the returned fee remainder (Hashlock M-02: `rem` in,
/// `newRem` out — one packed word, token0 in the low 128 bits, token1 in the high; see
/// `_distributeCut`), themselves. Single protocol-payout point: split the cut
/// treasury/referrer and transfer (balance-clamped, FIX-5). Returns the total actually sent so
/// the caller's owner-payout math stays consistent — no settlement/withdraw can ever revert on
/// an insufficient balance.
function _tax(
uint256 tokenId,
address feeOwner,
address token0,
address token1,
uint256 taxable0,
uint256 taxable1,
uint256 rem
) internal returns (uint256 cut0, uint256 cut1, uint256 newRem) {
uint256 bps = _feeBpsFor(feeOwner);
// Unpack the carried remainders, tax each token with its own carry, re-pack what is left. Each
// half is < BPS, so the halves can never overlap.
uint256 r1;
(cut0, newRem) = _distributeCut(token0, taxable0, bps, rem & type(uint128).max);
(cut1, r1) = _distributeCut(token1, taxable1, bps, rem >> 128);
newRem |= r1 << 128;
emit FeeTaxed(tokenId, taxable0, taxable1, cut0, cut1);
}
/// @dev Transfer `amount` of `token` to `to`, CLAMPED to the vault's actual balance (FIX-5) and a
/// no-op for a zero recipient/amount. Returns the amount actually sent. In the sound model the
/// cut is always a fraction of fees already collected to the vault, so the clamp never binds — it
/// is a last-resort guard that keeps any settlement path from reverting on a token the vault does
/// not fully hold.
function _payTo(address token, address to, uint256 amount) internal returns (uint256 sent) {
if (amount == 0 || to == address(0)) return 0;
uint256 bal = IERC20(token).balanceOf(address(this));
sent = amount <= bal ? amount : bal;
if (sent == 0) return 0;
// FREEZE-VECTOR FIX (Medium, 2026-09-08): _payTo delivers the performance-fee cut to treasury/
// referrer on the NON-PAUSABLE user paths (withdraw/withdrawTo/withdrawFraction/harvest). If that
// recipient is a blocklisted address, or a contract that reverts on receipt, a plain safeTransfer
// would revert the WHOLE user withdrawal — freezing every non-fee-exempt holder of that token until
// governance rotates the address (48h timelock). So attempt delivery non-revertingly; on ANY failure
// escrow the amount for a later pull (claimProtocolFees) and continue. The user is never blocked and
// the protocol loses nothing — the cut still leaves the owner's slice and stays in the vault owed to
// `to`. `sent` is returned regardless, so the owner-payout math (out = collected - cut) is unchanged.
(bool ok, bytes memory ret) = token.call(abi.encodeCall(IERC20.transfer, (to, sent)));
if (ok && (ret.length == 0 || abi.decode(ret, (bool)))) return sent; // delivered as before
owedProtocolFees[token][to] += sent; // undeliverable now → escrow
emit ProtocolFeesEscrowed(token, to, sent);
}
/// @dev THE single place fees leave to the protocol (I6). Splits the performance-fee cut on `taxable`
/// at rate `bps` into a referrer share (`referrerFeeBps`, clamped to `bps`, only when a referrer
/// is set) and the treasury remainder, and transfers both (balance-clamped). The base is fees
/// only (`taxable`, already clamped to the not-yet-taxed remainder by the caller) — never
/// principal (I1) — and the referrer share can never exceed the total, so referrer + treasury
/// together are always exactly the `bps` cut. Returns the total actually sent to the protocol
/// and the sub-unit fee numerator to carry into the next taxing of the same position (Hashlock M-02).
/// @dev The effective performance-fee rate for a position owner: the per-user tier override when set,
/// else the default, zero when fee-exempt, and ALWAYS hard-capped at MAX_PROTOCOL_FEE_BPS (I4)
/// on every path (the setters cap too; this is defense-in-depth so no path can exceed 30%).
function _feeBpsFor(address feeOwner) internal view returns (uint256 bps) {
if (feeExempt[feeOwner]) return 0;
bps = _userRate(feeOwner);
if (bps > MAX_PROTOCOL_FEE_BPS) bps = MAX_PROTOCOL_FEE_BPS;
}
function _distributeCut(address token, uint256 taxable, uint256 bps, uint256 rem)
internal
returns (uint256 sent, uint256 newRem)
{
if (taxable == 0 || bps == 0) return (0, rem);
// Hashlock M-02 (2026-09): carry the sub-unit fee instead of flooring it away. `rem` is the
// numerator (< BPS) left by the previous taxing of this position; this slice's modulus is
// handed back for the caller to persist. Over any sequence of collections the protocol thus
// receives exactly floor(Σ taxable × bps / BPS) — the same as one aggregate collection — and
// `total` still never exceeds `taxable` (bps < BPS and rem < BPS), so the cut is always covered
// by the fees just collected (I1). The carried fraction is rate-independent, so a tier or fee
// change mid-stream stays exact; on a full close whatever is carried (< 1 raw unit) is forfeited.
uint256 num = taxable * bps + rem;
uint256 total = num / BPS;
newRem = num % BPS;
uint256 refBps = referrerFeeBps;
if (refBps > bps) refBps = bps; // referrer share can never exceed the total rate
uint256 refCut = referrer != address(0) ? (taxable * refBps) / BPS : 0;
if (refCut > total) refCut = total;
uint256 sentRef = _payTo(token, referrer, refCut);
if (sentRef > 0) emit ReferrerPaid(token, sentRef);
uint256 sentTre = _payTo(token, treasury, total - refCut);
sent = sentRef + sentTre;
}
/// @dev Re-center settlement (FEE_MODEL.md §6.3/§7). Called AFTER fees are collected and principal is
/// exited to the vault, working from the in-memory accounting snapshot `fa` (storage was cleared
/// by `_exitLiquidity`). Order is D4: take the performance-fee cut on the whole not-yet-taxed
/// slice FIRST (→ treasury). v2 STOPS there: where the NET fees go is decided ONCE by the position's
/// fee mode in `_routeFees` — the removed v1 IL-offset / `walletFloorBps` sizing (`min(netFees, gap)`)
/// is gone (internal peer-audit M-01, 2026-09-08; NOT Hashlock M-01). Returns the accounting to carry onto
/// the new position (taxed now == cumulative; cost basis
/// reset to the exited principal — fees are additive, principal conserved, I5) and the token
/// amounts to add to the new mint.
function _settleAndOffset(
uint256 tokenId,
PoolConfig storage p,
address owner_,
FeeAccounting memory fa,
uint256 bal0,
uint256 bal1
) internal returns (uint256 reinv0, uint256 reinv1) {
// FIX-2: with tax-on-collect (FIX-1) there are never any pre-existing untaxed in-LP fees, so the
// not-yet-taxed slice `u{0,1}` here is ONLY the fees freshly collected this tx (everything prior —
// including anything a compound folded in — is already taxed and already excluded by the
// high-water mark). We tax that slice once and size the IL offset from its NET; already-taxed
// fees are neither re-taxed nor separately re-invested (they ride along inside `bal`).
uint256 u0 = fa.feesEarnedCumulative0 - fa.feesTaxed0;
uint256 u1 = fa.feesEarnedCumulative1 - fa.feesTaxed1;
fa.feesTaxed0 += u0; // advance the high-water mark to cumulative: taxed exactly once (I2)
fa.feesTaxed1 += u1;
// 12% treasury + 3% referrer, balance-clamped. The carried fee remainder is read from and written
// back to the memory snapshot, so it lands on the successor with the rest of `fa` (Hashlock M-02).
uint256 cut0;
uint256 cut1;
(cut0, cut1, fa.feeRemainder) =
_tax(tokenId, owner_, p.token0, p.token1, u0, u1, fa.feeRemainder);
// v2: settlement now STOPS at the tax. Where the net fees go is decided once, by the
// position's fee mode, in `_routeFees`.
//
// v1 split the net here using the global `walletFloorBps` and an IL-gap calculation, and v2
// then split whatever survived a second time. Two mechanisms deciding the same question is how
// a user ends up unable to explain their own payout: the "50%" they chose would have been 50%
// of whatever the floor happened to leave, not 50% of their fees. One decision, one owner.
reinv0 = u0 - cut0;
reinv1 = u1 - cut1;
// cost basis of the re-centered position is the exited principal (I5: principal conserved)
fa.principal0 = bal0;
fa.principal1 = bal1;
}
function _validateRange(PoolConfig storage p, int24 tickLower, int24 tickUpper) internal view {
if (tickLower >= tickUpper) revert BadTicks();
int24 width = tickUpper - tickLower;
if (minRangeWidthTicks > 0 && width < minRangeWidthTicks) revert RangeTooNarrow();
if (maxRangeWidthTicks > 0 && width > maxRangeWidthTicks) revert RangeTooWide();
if (twapInterval > 0 && maxTwapDeviationTicks > 0) {
if (VaultMath.twapDeviation(p.pool, twapInterval) > maxTwapDeviationTicks) revert TwapDeviation();
}
}
// _twapTick → VaultMath.twapTick (external library); the vault has no remaining direct caller.
/// @dev Oracle tick used for out-of-range tests and re-centering: TWAP when `twapInterval` is
/// configured (>0), otherwise the current spot tick from slot0.
function _oracleTick(address pool) internal view returns (int24) {
return VaultMath.oracleTick(pool, twapInterval);
}
/// @dev The position's current tick bounds and whether the oracle tick sits outside them.
/// Shared by the keeper machine and manualSnuggle so the read+test exists once.
function _rangeState(uint256 tokenId, address pool) internal view returns (bool oor, int24 lower, int24 upper) {
(lower, upper) = _ticksOf(tokenId);
oor = _isOutOfRange(_oracleTick(pool), lower, upper);
}
/// @dev Upper-exclusive out-of-range test, matching the SnuggleVault reference.
function _isOutOfRange(int24 tick, int24 tickLower, int24 tickUpper) internal pure returns (bool) {
return tick < tickLower || tick >= tickUpper;
}
/// @dev Choose a tick-aligned range of `width` ticks to redeploy (bal0, bal1) around `tick`.
/// With both tokens present (an in-range exit) it centers symmetrically. With a single
/// token (an out-of-range exit) it places a one-sided range on that token's side of the
/// tick, so the re-mint always succeeds WITHOUT the keeper performing a swap — consistent
/// with the "keeper is LP-only" custody model. `width` is a multiple of tickSpacing.
/// @dev The snuggle range is ALWAYS single-sided and DIRECTIONAL — never a symmetric straddle. A
/// symmetric re-center at the price crystallizes IL; the snuggle instead parks the held token
/// one tick-space PAST the price and lets the market DCA it back at a better average (zero swap,
/// zero slippage). `isToken0` is chosen by the caller from TICK GEOMETRY (`currentTick <
/// oldTickLower`), NOT token balances — fee dust on the minor side would otherwise pick the
/// wrong direction and evict the principal (SnuggleVault's V36-01 fix). This mirrors
/// SnuggleVault `TickMath._buildDirectionalRange`. `width` is a multiple of tickSpacing.
/// @dev Balance the position's exited principal (bal0, bal1) for a symmetric re-center: swap
/// `amountIn` of one side into the other via the configured router. The keeper reaches this via
/// `executeKeeperAction` action 2 but does NOT set the slippage floor: the swap is HARD-bounded
/// to `maxSwapSlippageBps` of the TWAP price by an oracle-derived sqrtPriceLimitX96, so a
/// compromised keeper cannot sandwich it past the band. Output stays in the vault and is
/// redeployed to the owner. Returns the position's balances adjusted by the ACTUAL swap deltas.
// _sqrt and _getSqrtRatioAtTick → moved to VaultMath (external library) to keep the vault runtime
// under the EIP-170 24,576-byte contract-size limit.
/// @dev Auto re-center core (state-machine + manualSnuggle path): harvest fees to the owner, exit
/// all principal, optionally balance it with a swap (SnuggleVault-style symmetric snuggle),
/// derive a balance-aware range of `width` ticks around the oracle tick, mint the new
/// position, refund leftover, and carry the strategy forward (tracking reset).
function _rebalanceAuto(uint256 tokenId, int24 width, RebalanceParams memory rp)
internal
returns (uint256 newTokenId)
{
address pool = pools[positions[tokenId].poolId].pool;
// PLACEMENT USES SPOT, not the oracle. The out-of-range DECISION was already made against the
// oracle by the caller, so a manipulated spot cannot TRIGGER a rebalance — but composition
// follows spot and nothing else, so a range placed against the TWAP can straddle spot and
// leave the mint with nothing for one leg. That deadlocked v1 after a whipsaw.
int24 spot = VaultMath.oracleTick(pool, 0);
// DIRECTION by tick geometry, read BEFORE the exit burns the NFT: price below the old range
// -> we hold token0 -> the new range goes ABOVE spot; at/above -> token1 -> BELOW.
// Never by token balance (fee dust picks the wrong side).
(int24 oldLower, int24 oldUpper) = _ticksOf(tokenId);
// The out-of-range DECISION may have been made on the TWAP; the PLACEMENT is made on spot. If
// spot is still inside the old range while the average has left it, the exit is two-sided and
// a one-sided mint would eject a whole leg of principal to the wallet. Refuse: both oracles
// must agree the position has left, and then the direction below is unambiguous.
if (spot >= oldLower && spot < oldUpper) revert NotOutOfRange();
bool isToken0 = spot < oldLower;
// A queued width change must land before the range is derived from it.
// Read WITHOUT consuming it — `_recenter` applies and clears it later. Reads one field, not
// the whole Strategy: the full struct copy was 110 bytes of decode for a single int24.
PositionQueue.PendingStrategy memory q = pendingStrategies[tokenId];
int24 pendingWidth = q.setWidth ? q.rangeWidthTicks : strategies[tokenId].rangeWidthTicks;
if (pendingWidth > 0) width = pendingWidth;
(int24 lower, int24 upper) =
VaultMath.recenterRange(spot, width, isToken0, IUniswapV3Pool(pool).tickSpacing());
// A snuggle leaves the new range one spacing past spot, i.e. out of range by design. If price
// has not moved since, the same [lower, upper) comes out again — burning and re-minting an
// identical position every rebalanceDelay for nothing but gas. Refuse.
if (lower == oldLower && upper == oldUpper) revert NoChange();
newTokenId = _recenter(tokenId, RecenterPlan(lower, upper, isToken0), rp);
}
/// @dev Follow a ROUTE target through the snuggles it has had since it was set. Bounded: a
/// target that has re-centred more than 16 times since this source last did resolves to 0,
/// which is the existing wallet fallback, and the compacted id is written to the source's
/// successor so the walk shortens every time the source itself snuggles.
function _liveTarget(uint256 t) internal view returns (uint256) {
for (uint256 i; i < 16 && t != 0 && !positions[t].exists; ++i) t = successorOf[t];
return (t != 0 && positions[t].exists) ? t : 0;
}
/// @dev The whole re-center sequence, shared by both paths so they can never drift apart again.
/// They already did: `rebalance()` ran neither v2 step, so it force-reinvested 100% of fees
/// whatever the owner had chosen and refunded their queued capital instead of folding it in.
/// Two copies of a sequence this order-sensitive is how that happens.
///
/// ORDER IS LOAD-BEARING. Everything the exit destroys must be snapshotted BEFORE it runs:
/// `_exitLiquidity` reaches `_removePosition`, which deletes strategies, pendingStrategies,
/// feeRouteTarget and (via refund) pendingDeposits for this tokenId.
function _recenter(uint256 tokenId, RecenterPlan memory plan, RebalanceParams memory rp)
internal
returns (uint256 newTokenId)
{
Position memory pos = positions[tokenId];
PoolConfig storage p = pools[pos.poolId];
Strategy memory s = strategies[tokenId];
// internal M-02 FIX (2026-09-08; NOT Hashlock M-02): settle a NEVER-CONFIGURED strategy under the ADVERTISED default
// — SPLIT + DEFAULT_COMPOUND_BPS — not the raw feeMode==0 which decodes to COMPOUND_ALL. Without this,
// an owner who deposits and calls manualSnuggle without ever calling setStrategy compounds 100% of
// net fees instead of the 50/50 the header/marketing promise. Mirrors setStrategy's
// "never configured → SPLIT" default, and the defaulted `s` also carries onto the re-minted position
// (via _finishRecenter). Keeper auto-snuggle is unaffected: it requires autoSnuggle, only ever set by
// setStrategy, which already materializes SPLIT — so the guard below is false on that path.
// Hashlock L-01 (2026-09): "never configured" is the explicit `feeModeSet` flag, NOT an all-zero struct —
// an owner who chose COMPOUND_ALL (mode 0) or SPLIT/0 and never called setStrategy is settled
// under exactly that policy, and the successor inherits it via _finishRecenter.
if (!s.feeModeSet) {
s.feeMode = uint8(FeeRouter.Mode.SPLIT);
s.compoundBps = DEFAULT_COMPOUND_BPS;
s.feeModeSet = true; // same self-describing state setStrategy leaves; not load-bearing
}
// Hashlock M-01 (2026-09): consume the queued width/delay HERE, before the exit. `_exitLiquidity`
// reaches `_removePosition`, which deletes `pendingStrategies[tokenId]` (the teardown delete
// added for the peer audit's L-01 — not Hashlock's L-01). Applying AFTER that read an empty
// slot: the successor carried the OLD stored width and a queued delay never landed at all.
// Placed AFTER the never-configured default above: the successor's fee policy is settled before
// anything else touches `s` (test_M01_queuedWidthOnUnconfiguredPosition_keepsSplitDefault pins
// it). `s` is memory and `_finishRecenter`
// writes it onto the new tokenId, so both fields survive the exit. `_rebalanceAuto` already
// read (without consuming) the same slot for the mint geometry, so range and stored width agree.
(s.rangeWidthTicks, s.rebalanceDelay) =
PositionQueue.applyStrategy(pendingStrategies, tokenId, s.rangeWidthTicks, s.rebalanceDelay);
uint256 routeTarget = _liveTarget(feeRouteTarget[tokenId]);
// Take the queue into memory first, so _removePosition's refund sees nothing and the capital
// is folded into the new position instead of handed back.
(uint256 add0, uint256 add1) = PositionQueue.consume(pendingDeposits, tokenId, 0, 0);
// Queued capital folded into this mint is NEW principal, not earnings, so it must land in the
// cost basis — otherwise P&L reads generous by exactly the queued amount until the next full
// withdraw. _settleAndOffset stamps principal from the EXITED balance only, so carry the queued
// portion separately and add it after.
(uint256 q0, uint256 q1) = (add0, add1);
// Snapshot the accounting BEFORE the exit clears storage; `fa` is a memory reference and the
// callees below mutate it in place (accrue, tax, reset basis).
FeeAccounting memory fa = feeAccounting[tokenId];
{
// Scoped so `bal0`/`bal1` do not stay live through the mint — via_ir runs out of stack
// otherwise. Everything the mint needs is accumulated into add0/add1 as we go.
// HEAD: collect the position's fees (accruing them onto the snapshot) and exit all
// principal to the vault.
(uint256 c0, uint256 c1) = _collectFees(tokenId);
fa.feesEarnedCumulative0 += c0;
fa.feesEarnedCumulative1 += c1;
(uint256 bal0, uint256 bal1) =
_exitLiquidity(tokenId, rp.decreaseAmount0Min, rp.decreaseAmount1Min, rp.deadline);
(uint256 reinv0, uint256 reinv1) = _settleAndOffset(tokenId, p, pos.owner, fa, bal0, bal1);
(reinv0, reinv1) = _routeFees(s, p, tokenId, routeTarget, pos.owner, reinv0, reinv1, plan.isToken0Side);
add0 += bal0 + reinv0;
add1 += bal1 + reinv1;
}
// _settleAndOffset set principal = exited balance; queued capital is additional principal.
fa.principal0 += q0;
fa.principal1 += q1;
_validateRange(p, plan.lower, plan.upper);
newTokenId = _finishRecenter(
p, pos, tokenId, s, fa, routeTarget, plan.lower, plan.upper,
add0, add1, rp.mintAmount0Min, rp.mintAmount1Min, rp.deadline
);
}
/// @dev Apply the position's fee mode to the share the IL offset left available.
/// Returns what should still be folded into THIS position's mint; everything else has already
/// been paid out or credited elsewhere by the time this returns.
function _routeFees(
Strategy memory s,
PoolConfig storage p,
uint256 tokenId,
uint256 routeTarget,
address owner_,
uint256 avail0,
uint256 avail1,
bool isToken0Side
) internal returns (uint256, uint256) {
if (avail0 == 0 && avail1 == 0) return (0, 0);
// `s` is the caller's snapshot, taken BEFORE _exitLiquidity deleted strategies[tokenId].
// Never re-read it from storage here — that returns a zeroed struct mid-rebalance.
FeeRouter.Mode mode = FeeRouter.Mode(s.feeMode);
(uint256 keep0, uint256 keep1, uint256 out0, uint256 out1) =
FeeRouter.route(avail0, avail1, mode, s.compoundBps, isToken0Side);
PositionQueue.payOut(p.token0, p.token1, owner_, out0, out1);
if (mode != FeeRouter.Mode.ROUTE || (keep0 == 0 && keep1 == 0)) return (keep0, keep1);
// ROUTE: credit the compounded share to another position the owner holds, as QUEUED capital.
// Queued, not minted: the target has its own range and its own schedule, and forcing a mint
// here would rebalance a position whose owner did not ask for it. It lands at the target's
// next rebalance, swap-free.
// Passed in, NOT read from storage: _removePosition deletes feeRouteTarget during the exit
// that has already happened by the time this runs. Reading it here returned 0 and silently
// downgraded ROUTE to a wallet payout — the same deleted-storage mistake as `strategies`,
// one variable over, introduced while fixing that one.
PoolConfig storage tp = pools[positions[routeTarget].poolId];
PositionQueue.routeToTarget(
pendingDeposits, tokenId, routeTarget, tp.token0, tp.token1, tp.active,
p.token0, p.token1, owner_, keep0, keep1
);
return (0, 0);
}
/// @dev Shared re-center TAIL: mint the new position, preserve the owner's ORIGINAL entry time (so a
/// keeper re-center can never reset the withdraw hold clock), carry the strategy forward with
/// tracking cleared, carry the (now fully-taxed) accounting, and emit. `pos` is the pre-exit
/// memory snapshot. Identical in both re-center paths — factored out for the EIP-170 diet.
function _finishRecenter(
PoolConfig storage p,
Position memory pos,
uint256 oldTokenId,
Strategy memory s,
FeeAccounting memory fa,
uint256 routeTarget,
int24 lower,
int24 upper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) internal returns (uint256 newTokenId) {
(newTokenId,,,) = _mintInto(
p, pos.poolId, pos.owner, lower, upper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline
);
positions[newTokenId].createdAt = pos.createdAt;
successorOf[oldTokenId] = newTokenId;
s.outOfRangeSince = 0;
strategies[newTokenId] = s;
// Carry the route target too. Without this ROUTE works exactly once and then silently becomes
// a wallet payout, because the successor tokenId has no target and nothing tells the owner.
if (routeTarget != 0) feeRouteTarget[newTokenId] = routeTarget;
feeAccounting[newTokenId] = fa;
emit Rebalanced(pos.owner, pos.poolId, oldTokenId, newTokenId, lower, upper);
}
/// @dev Decrease all liquidity, collect everything to the vault, burn the NFT, and drop tracking.
/// Returns the token balances the position released into the vault.
function _exitLiquidity(uint256 tokenId, uint256 amount0Min, uint256 amount1Min, uint256 deadline)
internal
returns (uint256 bal0, uint256 bal1)
{
_decrease(tokenId, _liquidityOf(tokenId), amount0Min, amount1Min, deadline);
(bal0, bal1) = _collectAll(tokenId);
positionManager.burn(tokenId);
_removePosition(tokenId); // clears positions[tokenId] and strategies[tokenId]
}
/// @dev Mint a fresh vault-held position from principal already in the vault, refund any unused
/// amount to `to`, and start tracking it. Does not emit (caller emits the right event).
function _mintInto(
PoolConfig storage p,
bytes32 poolId,
address to,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) internal returns (uint256 tokenId, uint128 liquidity, uint256 used0, uint256 used1) {
IERC20(p.token0).forceApprove(address(positionManager), amount0Desired);
IERC20(p.token1).forceApprove(address(positionManager), amount1Desired);
(tokenId, liquidity, used0, used1) = VenueAdapter.mint(
address(positionManager), p.slipstream, p.token0, p.token1, int24(p.fee),
tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline
);
IERC20(p.token0).forceApprove(address(positionManager), 0);
IERC20(p.token1).forceApprove(address(positionManager), 0);
_pay2(p.token0, p.token1, to, amount0Desired - used0, amount1Desired - used1);
_addPosition(to, poolId, tokenId);
// ARMED vs ACTIVE, decided here because this is where the range is known. A range containing
// spot is earning from block one, so it is active immediately — the ordinary case. A range
// opened entirely to one side of price is ARMED: it earns nothing yet and is out of range on
// purpose, so the keeper must leave it alone until the market reaches it.
{
uint8 side = VaultMath.armedSide(p.pool, tickLower, tickUpper);
if (side != 0) {
Strategy storage st = strategies[tokenId];
st.armed = true;
st.armedAbove = side == 1;
}
}
}
// L-03 cleanup (2026-09-08): the orphaned internal `_rebalanceTo` (keeper-chooses-explicit-ticks
// re-center, a v1 remnant) was removed. It had ZERO callers yet re-embedded the exact tick-picking
// semantics H-02 closed, and compiled into bytecode near the EIP-170 ceiling for nothing. The only live
// re-center entry points are the snuggle paths (executeKeeperAction / manualSnuggle), which derive the
// ticks themselves — no external actor ever chooses ticks.
/// @dev Shared mint + refund + tracking. Assumes the desired amounts are already held by the vault.
function _openPosition(
PoolConfig storage p,
bytes32 poolId,
address onBehalf,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) internal returns (uint256 tokenId) {
uint128 liquidity;
uint256 used0;
uint256 used1;
(tokenId, liquidity, used0, used1) = _mintInto(
p, poolId, onBehalf, tickLower, tickUpper, amount0Desired, amount1Desired, amount0Min, amount1Min, deadline
);
// stamp the cost basis; fee accounting starts at zero (FEE_MODEL.md §11)
feeAccounting[tokenId] = FeeAccounting({
principal0: used0,
principal1: used1,
feesEarnedCumulative0: 0,
feesEarnedCumulative1: 0,
feesTaxed0: 0,
feesTaxed1: 0,
feeRemainder: 0
});
emit PositionCreated(onBehalf, poolId, tokenId, liquidity, used0, used1);
}
function _addPosition(address owner_, bytes32 poolId, uint256 tokenId) internal {
if (maxPositionsPerUser != 0 && _userTokenIds[owner_].length >= maxPositionsPerUser) revert TooManyPositions();
if (maxTotalPositions != 0 && totalActivePositions >= maxTotalPositions) revert TooManyPositions();
positions[tokenId] = Position({owner: owner_, poolId: poolId, createdAt: uint40(block.timestamp), exists: true});
_userIndex[tokenId] = _userTokenIds[owner_].length;
_userTokenIds[owner_].push(tokenId);
_allIndex[tokenId] = _allTokenIds.length;
_allTokenIds.push(tokenId);
totalActivePositions += 1;
}
/// @dev Remove `tokenId` from an index-tracked array by swapping the last element into its slot.
function _swapPop(uint256[] storage arr, mapping(uint256 => uint256) storage idx, uint256 tokenId) internal {
uint256 i = idx[tokenId];
uint256 last = arr.length - 1;
if (i != last) {
uint256 moved = arr[last];
arr[i] = moved;
idx[moved] = i;
}
arr.pop();
delete idx[tokenId];
}
function _removePosition(uint256 tokenId) internal {
Position storage pos = positions[tokenId];
address owner_ = pos.owner;
// REFUND ANY QUEUED CAPITAL THAT IS NOT BEING FOLDED IN. A snuggle takes the queue into memory
// and clears it before it gets here, so this fires only on the paths that ABANDON the position:
// `withdraw` / `withdrawTo` (which now routes the queued refund to the withdrawal recipient — see the
// freeze-vector fix in _withdrawInto, so this call is a no-op there). The v1 `rebalance()`/_rebalanceTo
// path that also reached here without the v2 steps was removed (H-02 closed, L-03 cleanup).
//
// Without this the money is unrecoverable. `pendingDeposits` survived _removePosition, and
// `cancelQueuedDeposit` reverts NoPosition() once the position is gone — and v2 has no ERC-20
// rescue, only rescueERC721. A routine keeper rebalance would have silently orphaned a user's
// queued deposit forever. Refunding here is unconditional and needs no one to notice.
PoolConfig storage qp = pools[pos.poolId];
PositionQueue.refundIfAny(pendingDeposits, tokenId, qp.token0, qp.token1, owner_);
delete feeRouteTarget[tokenId]; // per-position; would otherwise point at a burned tokenId
// swap-and-pop from the owner's array, then from the global array
_swapPop(_userTokenIds[owner_], _userIndex, tokenId);
_swapPop(_allTokenIds, _allIndex, tokenId);
delete positions[tokenId];
delete strategies[tokenId];
delete pendingStrategies[tokenId]; // internal peer-audit L-01 (2026-09-08; NOT Hashlock L-01): clear the queued strategy too, or it orphans on teardown
delete feeAccounting[tokenId];
totalActivePositions -= 1;
}
}
interface IERC721Minimal {
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
* {IERC721-setApprovalForAll}.
*/
abstract contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 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²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/IUniswapV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice Minimal subset of the Uniswap v3 NonfungiblePositionManager used by QuantumVault.
interface INonfungiblePositionManager {
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
function mint(MintParams calldata params)
external
payable
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (uint128 liquidity, uint256 amount0, uint256 amount1);
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
function collect(CollectParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
function burn(uint256 tokenId) external payable;
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
function factory() external view returns (address);
}
interface IUniswapV3Factory {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}
/// @notice Minimal SwapRouter02-style interface (no deadline in the struct).
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
}
interface IUniswapV3Pool {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
// uint32, NOT uint8. Uniswap v3 packs one protocol-fee byte here; PancakeSwap v3 packs
// FOUR and declares uint32, and a real Base pool returns 222,825,800 — which a uint8
// return type refuses to decode, reverting every single read of the pool. That killed
// all 30 fork tests against PancakeSwap and would have made the venue simply not work.
//
// uint32 is correct for both: ABI-encodes to the same 32-byte word either way, and the
// wider type accepts every value the narrower one can hold. Nothing in this repo reads
// the field — it is decoded and discarded — so widening it costs nothing and is the
// difference between supporting a Uniswap fork and not.
uint32 feeProtocol,
bool unlocked
);
function tickSpacing() external view returns (int24);
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
}
src/libraries/FeeRouter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @title FeeRouter
/// @notice Decides where a position's net fees go at settlement time: compounded back in, paid out
/// to the wallet, split between the two, or routed to another position the owner holds.
///
/// @dev This lives in a library for two reasons. The obvious one is EIP-170 — the vault has barely
/// a kilobyte of headroom. The better one is that fee routing is pure arithmetic over amounts,
/// so it can be reasoned about and unit-tested without a chain, a pool, or a position.
///
/// WHY "MATCHING" IS ITS OWN MODE, and why it is the honest description of what a snuggle does:
/// a snuggle re-enters SINGLE-SIDED, so only fees denominated in the token that side needs can
/// physically be folded back into the new position. The other token's fees have nowhere to go
/// and must be paid out. That is not a policy choice — it is the geometry. Because trading fees
/// accrue in both tokens at broadly similar rates, MATCHING lands near a 50/50 outcome on its
/// own, which is what an observer of a live single-sided vault actually sees.
///
/// SPLIT exists because "near 50/50 on average" is not the same promise as "50/50". A user told
/// that half their fees come back as cash should get half on every harvest, not a figure that
/// drifts with whichever side of the range price happened to exit.
///
/// SPLIT therefore divides the MATCHING side — the token the position has actually been
/// converted into — and pays the non-matching side out whole. Half of the token you now hold
/// goes back into the position; the other half, plus everything in the token the new range
/// cannot use, arrives in the wallet.
library FeeRouter {
uint256 internal constant BPS = 10_000;
enum Mode {
COMPOUND_ALL, // 0 — everything available is re-invested (subject to the IL-offset cap)
WALLET_ALL, // 1 — everything is paid out; the position keeps only its principal
SPLIT, // 2 — `compoundBps` of the MATCHING side re-invested, everything else paid out
MATCHING, // 3 — the side the new range can use is re-invested; the other side is paid out
ROUTE // 4 — the compounded share is credited to ANOTHER position instead of this one
}
/// @notice Split net fees into the part to re-invest and the part to pay out.
/// @param net0 net (post-performance-fee) token0 fees available
/// @param net1 net token1 fees available
/// @param mode routing mode
/// @param compoundBps share to re-invest, in bps — only read for SPLIT and ROUTE
/// @param isToken0Side true when the new single-sided range is denominated in token0
/// @return reinv0 token0 to fold into a position (this one, or the route target)
/// @return reinv1 token1 to fold into a position
/// @return out0 token0 to pay out to the owner's wallet
/// @return out1 token1 to pay out to the owner's wallet
function route(uint256 net0, uint256 net1, Mode mode, uint256 compoundBps, bool isToken0Side)
public
pure
returns (uint256 reinv0, uint256 reinv1, uint256 out0, uint256 out1)
{
if (net0 == 0 && net1 == 0) return (0, 0, 0, 0);
if (mode == Mode.WALLET_ALL) return (0, 0, net0, net1);
if (mode == Mode.COMPOUND_ALL) return (net0, net1, 0, 0);
if (mode == Mode.MATCHING) {
// Only the matching side can enter a single-sided range; the other side is paid out
// because there is physically nowhere else for it to go.
return isToken0Side ? (net0, uint256(0), uint256(0), net1) : (uint256(0), net1, net0, uint256(0));
}
// SPLIT and ROUTE share the same arithmetic; they differ only in WHERE `reinv` is applied,
// which is the caller's business, not this function's.
//
// THE SPLIT APPLIES TO THE MATCHING SIDE ONLY, and this is the crux of the whole mode. After a
// snuggle the position has been converted by the market into ONE token, and the new range is
// denominated in that token. So "half back in, half to my wallet" can only mean half of THAT
// token. The other side cannot enter the range at any ratio, so splitting it would be theatre:
// the compounded half would be handed to the mint, rejected, and refunded to the same wallet
// it would have reached directly — the same outcome by a longer route.
if (isToken0Side) {
reinv0 = compoundBps >= BPS ? net0 : (net0 * compoundBps) / BPS;
// Subtract rather than compute the complement: with integer division the two halves must
// add back to exactly `net`, or dust accretes in the vault forever.
out0 = net0 - reinv0;
out1 = net1; // non-matching side — nowhere to go but the wallet
} else {
reinv1 = compoundBps >= BPS ? net1 : (net1 * compoundBps) / BPS;
out1 = net1 - reinv1;
out0 = net0;
}
}
/// @notice Validate a mode/parameter pair before it is stored.
/// @dev Rejecting a nonsensical configuration at write time is worth the bytecode: a bad
/// `compoundBps` would otherwise sit dormant and only surface as a surprising payout
/// months later, when the position finally rebalances.
function validate(Mode mode, uint256 compoundBps, uint256 routeTokenId) internal pure returns (bool) {
if (compoundBps > BPS) return false;
if (mode == Mode.ROUTE) return routeTokenId != 0 && compoundBps > 0;
// A route target on a non-route mode is a sign the caller believes something that is not
// true about where their fees are going.
return routeTokenId == 0;
}
}
src/libraries/PositionQueue.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {FeeRouter} from "./FeeRouter.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3.sol";
/// @title PositionQueue
/// @notice Capital and setting changes that a position owner commits now and that take effect at the
/// position's next rebalance, plus the fee routing that runs at the same moment.
///
/// @dev Everything here is `public`, so the vault DELEGATECALLs into it and this bytecode does not
/// count against the vault's EIP-170 budget. That is not merely a size trick: these operations
/// are self-contained state transitions over their own mappings, so keeping them out of the
/// vault leaves the vault's own file about custody and position lifecycle.
///
/// Because these are delegatecalls, `address(this)` is the VAULT and storage writes land in the
/// vault's storage. The mappings are passed in as storage pointers, which is what keeps the
/// layout owned by the vault rather than duplicated here.
library PositionQueue {
using SafeERC20 for IERC20;
/// @notice Tokens committed to a position that are not in the LP yet.
struct PendingDeposit {
uint128 amount0;
uint128 amount1;
}
/// @notice A width/delay change waiting for the next rebalance.
struct PendingStrategy {
int24 rangeWidthTicks;
uint32 rebalanceDelay;
bool setWidth;
bool setDelay;
}
error AmountOverflow();
error NothingQueued();
event DepositQueued(uint256 indexed tokenId, uint256 added0, uint256 added1, uint256 total0, uint256 total1);
event DepositUnqueued(uint256 indexed tokenId, uint256 amount0, uint256 amount1);
event QueuedDepositApplied(uint256 indexed tokenId, uint256 amount0, uint256 amount1);
// Same signatures the vault declared. A `public` library function is DELEGATECALLed, so these are
// emitted FROM the vault's address with the same topics as before — indistinguishable to anything
// watching the chain, which is the property that makes moving them safe.
event StrategyChangeQueued(uint256 indexed tokenId, int24 rangeWidthTicks, uint32 rebalanceDelay, bool setWidth, bool setDelay);
event StrategyChangeApplied(uint256 indexed tokenId, int24 rangeWidthTicks, uint32 rebalanceDelay);
error BadStrategy();
error RangeTooNarrow();
error RangeTooWide();
event FeesRouted(uint256 indexed fromTokenId, uint256 indexed toTokenId, uint256 amount0, uint256 amount1);
/// @notice Pull `amount0/1` from `from` and hold it against `tokenId` until its next rebalance.
/// @dev Tokens are taken NOW rather than at rebalance time. Deferring the transfer would make a
/// keeper action depend on an allowance and balance that may have moved in the meantime, and
/// a keeper action that fails for reasons outside the keeper's control is a liveness bug.
/// @dev Pulls from `msg.sender` — NOT from a caller-supplied address, deliberately.
/// This took a `from` parameter, and every caller correctly passed `msg.sender` after an
/// ownership check. But a signature that ACCEPTS an arbitrary `from` is a drain waiting for
/// the next caller who forgets that check: anyone who had approved the vault could be pulled
/// from. Slither flags it `arbitrary-send-erc20` and is right to.
/// These are `public` library functions, so the vault reaches them by DELEGATECALL and
/// `msg.sender` here is the vault's own caller — the position owner. Same behaviour, and the
/// mistake can no longer be made.
function queue(
mapping(uint256 => PendingDeposit) storage q,
uint256 tokenId,
address token0,
address token1,
uint256 amount0,
uint256 amount1
) public {
if (amount0 > 0) IERC20(token0).safeTransferFrom(msg.sender, address(this), amount0);
if (amount1 > 0) IERC20(token1).safeTransferFrom(msg.sender, address(this), amount1);
PendingDeposit storage d = q[tokenId];
uint256 n0 = uint256(d.amount0) + amount0;
uint256 n1 = uint256(d.amount1) + amount1;
// Checked, never cast: silently truncating someone's deposit is the worst failure available
// here, and reverting costs them only a transaction.
if (n0 > type(uint128).max || n1 > type(uint128).max) revert AmountOverflow();
d.amount0 = uint128(n0);
d.amount1 = uint128(n1);
emit DepositQueued(tokenId, amount0, amount1, n0, n1);
}
/// @notice Return queued capital to `to`. Unconditional by design.
/// @dev No hold time and no keeper involvement: this money was never committed to a position, so
/// anything that could delay its return would be a trap rather than a safeguard.
function unqueue(
mapping(uint256 => PendingDeposit) storage q,
uint256 tokenId,
address token0,
address token1,
address to
) public {
PendingDeposit memory d = q[tokenId];
if (d.amount0 == 0 && d.amount1 == 0) revert NothingQueued();
delete q[tokenId];
if (d.amount0 > 0) IERC20(token0).safeTransfer(to, d.amount0);
if (d.amount1 > 0) IERC20(token1).safeTransfer(to, d.amount1);
emit DepositUnqueued(tokenId, d.amount0, d.amount1);
}
/// @notice Refund whatever is still queued, if anything. Safe to call unconditionally.
/// @dev Exists so the vault can call this on EVERY position teardown without carrying the branch
/// itself. A position removed by `withdraw` or by a plain `rebalance()` never reaches the
/// snuggle path that folds the queue in, and `cancelQueuedDeposit` reverts once the position
/// is gone — with no ERC-20 rescue in the vault, the money would be unrecoverable.
function refundIfAny(
mapping(uint256 => PendingDeposit) storage q,
uint256 tokenId,
address token0,
address token1,
address to
) public {
PendingDeposit memory d = q[tokenId];
if (d.amount0 == 0 && d.amount1 == 0) return;
delete q[tokenId];
if (d.amount0 > 0) IERC20(token0).safeTransfer(to, d.amount0);
if (d.amount1 > 0) IERC20(token1).safeTransfer(to, d.amount1);
emit DepositUnqueued(tokenId, d.amount0, d.amount1);
}
/// @notice Fold queued capital into the balances about to be minted and clear the queue.
function consume(mapping(uint256 => PendingDeposit) storage q, uint256 tokenId, uint256 bal0, uint256 bal1)
public
returns (uint256, uint256)
{
PendingDeposit memory d = q[tokenId];
if (d.amount0 == 0 && d.amount1 == 0) return (bal0, bal1);
delete q[tokenId];
emit QueuedDepositApplied(tokenId, d.amount0, d.amount1);
return (bal0 + d.amount0, bal1 + d.amount1);
}
/// @notice Send the compounded share to ANOTHER position's queue, paying out whatever will not fit.
/// @dev Queued rather than minted on purpose: the target has its own range and its own schedule,
/// and minting into it here would rebalance a position whose owner did not ask for it. It
/// lands at the target's next rebalance, swap-free.
/// Anything the target's pool cannot use goes to the wallet rather than into a queue that
/// could never be spent.
function routeToTarget(
mapping(uint256 => PendingDeposit) storage q,
uint256 fromTokenId,
uint256 target,
address targetToken0,
address targetToken1,
bool targetActive,
address token0,
address token1,
address owner_,
uint256 keep0,
uint256 keep1
) public {
uint256 c0 = targetActive ? creditRoute(q, target, targetToken0, targetToken1, token0, keep0) : 0;
uint256 c1 = targetActive ? creditRoute(q, target, targetToken0, targetToken1, token1, keep1) : 0;
payOut(token0, token1, owner_, keep0 - c0, keep1 - c1);
if (c0 > 0 || c1 > 0) emit FeesRouted(fromTokenId, target, c0, c1);
}
/// @notice Credit `amount` of `token` to `target`'s queue, but only if the target's pool uses it.
/// @dev A token the target's pool cannot use would sit in a queue that can never be spent. The
/// caller pays the remainder out to the wallet rather than letting it strand here.
function creditRoute(
mapping(uint256 => PendingDeposit) storage q,
uint256 target,
address targetToken0,
address targetToken1,
address token,
uint256 amount
) public returns (uint256) {
if (amount == 0) return 0;
PendingDeposit storage d = q[target];
if (token == targetToken0) {
uint256 n = uint256(d.amount0) + amount;
if (n > type(uint128).max) return 0;
d.amount0 = uint128(n);
return amount;
}
if (token == targetToken1) {
uint256 n = uint256(d.amount1) + amount;
if (n > type(uint128).max) return 0;
d.amount1 = uint128(n);
return amount;
}
return 0;
}
/// @notice Pay the wallet share of routed fees out immediately.
/// @dev Paid at settlement, not held for later: fee income the owner cannot see arrive is how
/// "where are my fees?" begins, and a balance parked in the vault is indistinguishable from
/// one that was never earned.
function payOut(address token0, address token1, address to, uint256 out0, uint256 out1) public {
if (out0 > 0) IERC20(token0).safeTransfer(to, out0);
if (out1 > 0) IERC20(token1).safeTransfer(to, out1);
}
/// @notice Emit the routed-fee record. Kept here so the event lives with the logic that causes it.
function noteRouted(uint256 from, uint256 to, uint256 amount0, uint256 amount1) public {
if (amount0 > 0 || amount1 > 0) emit FeesRouted(from, to, amount0, amount1);
}
/// @notice The width rules, in one place. `setStrategy` and `queueStrategy` were checking the
/// same four things in two places, which is two places for them to drift apart.
function validateWidth(int24 rangeWidthTicks, address pool, int24 minWidth, int24 maxWidth) public view {
if (rangeWidthTicks <= 0) revert BadStrategy();
if (rangeWidthTicks % IUniswapV3Pool(pool).tickSpacing() != 0) revert BadStrategy();
if (minWidth > 0 && rangeWidthTicks < minWidth) revert RangeTooNarrow();
if (maxWidth > 0 && rangeWidthTicks > maxWidth) revert RangeTooWide();
}
/// @notice Queue a width/delay change, or cancel one. Lives here rather than in the vault purely
/// for EIP-170 headroom — the vault is the thing up against the 24,576-byte ceiling, and
/// library code is DELEGATECALLed from its own address.
/// @dev Both flags false is the CANCEL. Folding it into the same entry point keeps queueing and
/// un-queueing impossible to confuse. Validation happens HERE, at queue time, not at
/// settlement: a change that turned out to be invalid mid-rebalance would revert the whole
/// keeper action and strand the position out of range — the one moment it must not fail.
function queueStrategy(
mapping(uint256 => PendingStrategy) storage q,
uint256 tokenId,
int24 rangeWidthTicks,
uint32 rebalanceDelay,
bool setWidth,
bool setDelay,
address pool,
uint32 maxDelay,
int24 minWidth,
int24 maxWidth
) public {
if (!setWidth && !setDelay) {
delete q[tokenId];
emit StrategyChangeQueued(tokenId, 0, 0, false, false);
return;
}
if (setDelay && rebalanceDelay > maxDelay) revert BadStrategy();
if (setWidth) validateWidth(rangeWidthTicks, pool, minWidth, maxWidth);
q[tokenId] = PendingStrategy({
rangeWidthTicks: rangeWidthTicks, rebalanceDelay: rebalanceDelay, setWidth: setWidth, setDelay: setDelay
});
emit StrategyChangeQueued(tokenId, rangeWidthTicks, rebalanceDelay, setWidth, setDelay);
}
/// @notice Apply a queued change to a strategy in memory, and clear it. Returns the possibly
/// updated width and delay for the caller to write back.
function applyStrategy(mapping(uint256 => PendingStrategy) storage q, uint256 tokenId, int24 width, uint32 delay)
public
returns (int24, uint32)
{
PendingStrategy memory pending = q[tokenId];
if (!pending.setWidth && !pending.setDelay) return (width, delay);
if (pending.setWidth) width = pending.rangeWidthTicks;
if (pending.setDelay) delay = pending.rebalanceDelay;
delete q[tokenId];
emit StrategyChangeApplied(tokenId, width, delay);
return (width, delay);
}
/// @notice Queue a deposit top-up, or cancel one. (0, 0) is the cancel and returns what is held.
function queueOrCancel(
mapping(uint256 => PendingDeposit) storage q,
uint256 tokenId,
address token0,
address token1,
uint256 amount0,
uint256 amount1,
address from
) public {
if (amount0 == 0 && amount1 == 0) {
unqueue(q, tokenId, token0, token1, from);
return;
}
queue(q, tokenId, token0, token1, amount0, amount1);
}
}
src/libraries/VaultMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3.sol";
/// @notice Pure price/tick math extracted from QuantumVault so it lives in its OWN deployed contract
/// (DELEGATECALL-linked) instead of inlined bytecode. This keeps the vault runtime under the
/// EIP-170 24,576-byte limit. `public` (not `internal`) is deliberate — internal would re-inline.
library VaultMath {
/// @dev `slot0()` reverted or returned fewer than the two words the vault reads.
error Slot0Failed();
uint256 internal constant BPS = 10_000;
int24 internal constant MAX_TICK = 887272;
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @dev Uniswap v3 `TickMath.getSqrtRatioAtTick` (canonical port) — sqrt price (Q64.96) at `tick`.
function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
uint256 ratio =
absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @dev Floor square root (Babylonian) — converts a price-band ratio to a sqrt-price factor.
function sqrt(uint256 x) public pure returns (uint256 y) {
if (x == 0) return 0;
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/// @dev Value of (amount0, amount1) denominated in token1 at the given sqrt price (Q64.96). Used only
/// to SIZE the IL offset (D3) — never in the per-token fee path (D2). mulDiv keeps the squared
/// sqrt price from overflowing.
function valueInToken1(uint256 amount0, uint256 amount1, uint160 sqrtPriceX96) public pure returns (uint256) {
// price0in1 * 2^96 = sqrtP^2 / 2^96
uint256 priceX96 = Math.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96);
return amount1 + Math.mulDiv(amount0, priceX96, 1 << 96);
}
/// @dev Arithmetic-mean tick over `interval` seconds (requires sufficient pool observation
/// cardinality). Moved verbatim out of QuantumVault for the EIP-170 diet.
function twapTick(address pool, uint32 interval) public view returns (int24) {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = interval;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 diff = tickCumulatives[1] - tickCumulatives[0];
int24 twap = int24(diff / int56(uint56(interval)));
if (diff < 0 && (diff % int56(uint56(interval)) != 0)) twap--;
return twap;
}
/// @dev Tick-aligned, ALWAYS single-sided and DIRECTIONAL snuggle range of `width` ticks placed one
/// tick-space PAST `tick` on the held token's side. `isToken0` is decided by the CALLER from tick
/// geometry (never balances) — see QuantumVault._autoRecenterRange. Moved verbatim out of the vault
/// for the EIP-170 diet; geometry is unchanged.
function recenterRange(int24 tick, int24 width, bool isToken0, int24 spacing)
public
pure
returns (int24 lower, int24 upper)
{
if (isToken0) {
// price fell BELOW the old range → holding token0 → range STRICTLY ABOVE the tick.
int24 up = (tick / spacing) * spacing;
if (tick > 0 && tick % spacing != 0) up += spacing;
lower = up;
if (lower <= tick) lower += spacing;
upper = lower + width;
} else {
// price rose ABOVE the old range → holding token1 → range STRICTLY BELOW the tick.
int24 dn = (tick / spacing) * spacing;
if (tick < 0 && tick % spacing != 0) dn -= spacing;
upper = dn;
if (upper >= tick) upper -= spacing;
lower = upper - width;
}
int24 maxUsable = (MAX_TICK / spacing) * spacing;
int24 minUsable = -maxUsable;
if (lower < minUsable) lower = minUsable;
if (upper > maxUsable) upper = maxUsable;
}
/// @dev The tick the vault prices everything on: the TWAP when `interval > 0`, else the spot tick.
/// Moved verbatim out of QuantumVault for the EIP-170 diet.
/// @notice Where does a freshly minted range sit relative to spot? 0 = contains spot (live from
/// block one), 1 = entirely ABOVE spot, 2 = entirely BELOW. Non-zero means ARMED, and which
/// side is remembered so that price crossing all the way THROUGH the range later — between
/// two keeper passes, or while the keeper was out of gas — still counts as the market having
/// arrived. Without that bit a wick through an armed range strands it armed forever.
function armedSide(address pool, int24 lower, int24 upper) public view returns (uint8) {
int24 t = oracleTick(pool, 0);
if (t >= lower && t < upper) return 0;
return t < lower ? 1 : 2;
}
/// @notice Has the market reached an armed range? Inside it, OR past it on the far side — "the
/// market has been through it" is provably true in the second case and nothing about it is
/// abusable. Decided on SPOT, the same oracle that armed it: seeding on spot and clearing on
/// a TWAP would let a lagging average disarm a range price has not reached.
function arrived(address pool, int24 lower, int24 upper, bool above) public view returns (bool) {
int24 t = oracleTick(pool, 0);
if (t >= lower && t < upper) return true;
return above ? t >= upper : t < lower;
}
/// @notice Is spot currently INSIDE [lower, upper)? Used to decide whether a freshly minted
/// position is live from block one or is an armed one-sided entry waiting for the market.
/// @dev Lives here rather than in the vault purely for EIP-170 headroom: the vault is within a
/// few hundred bytes of the ceiling and library code is DELEGATECALLed from its own address.
function isInRange(address pool, int24 lower, int24 upper) public view returns (bool) {
int24 t = oracleTick(pool, 0);
return t >= lower && t < upper;
}
function oracleTick(address pool, uint32 interval) public view returns (int24) {
if (interval > 0) return twapTick(pool, interval);
(, int24 spot) = _slot0(pool);
return spot;
}
/// @dev `slot0` has THREE shapes in the wild and a typed call fails on the ones it was not
/// written for:
/// Uniswap v3 — (uint160, int24, uint16, uint16, uint16, uint8 feeProtocol, bool)
/// PancakeSwap — (uint160, int24, uint16, uint16, uint16, uint32 feeProtocol, bool)
/// Slipstream — (uint160, int24, uint16, uint16, uint16, bool) <- no feeProtocol
/// PancakeSwap's live feeProtocol of 222,825,800 will not decode into a `uint8`, and
/// Slipstream's six fields underrun a seven-field decode. Both revert EVERY read of the pool
/// — not a degraded mode, the venue simply does not work.
///
/// sqrtPriceX96 and tick are the first two words in all three, and they are the only two this
/// vault has ever used. So take two words and ignore the rest of the buffer: venue-agnostic
/// by construction, rather than by a list of venues somebody has to keep current.
function _slot0(address pool) internal view returns (uint160 sqrtPriceX96, int24 tick) {
(bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSignature("slot0()"));
if (!ok || ret.length < 64) revert Slot0Failed();
assembly {
sqrtPriceX96 := mload(add(ret, 32))
tick := signextend(2, mload(add(ret, 64)))
}
}
/// @dev |spot − twap| in ticks, for the vault's TWAP-deviation guard. Moved verbatim out of
/// QuantumVault for the EIP-170 diet; the caller still owns the threshold and the revert.
function twapDeviation(address pool, uint32 interval) public view returns (int24 dev) {
(, int24 spot) = _slot0(pool);
int24 twap = twapTick(pool, interval);
dev = spot > twap ? spot - twap : twap - spot;
}
/// @dev HARD on-chain price bound for the keeper-directed balancing swap: sqrtLimit = oracleSqrt *
/// sqrt(1 ± bps/BPS), taken in sqrt space explicitly (1e18 fixed point) so the band is not ~doubled,
/// clamped to the Uniswap sqrtPrice bounds. `skip` is true when spot is ALREADY past the bound in
/// the swap direction — the caller must then perform no swap. Moved verbatim out of QuantumVault for
/// the EIP-170 diet; the band is unchanged, and the keeper still never chooses it.
function swapPriceLimit(address pool, uint32 interval, uint256 maxSwapSlippageBps, bool zeroForOne)
public
view
returns (uint160 limit, bool skip)
{
uint160 oracleSqrt = getSqrtRatioAtTick(twapTick(pool, interval));
(uint160 currentSqrt,) = _slot0(pool);
if (zeroForOne) {
limit = uint160((uint256(oracleSqrt) * sqrt(((BPS - maxSwapSlippageBps) * 1e18) / BPS)) / 1e9); // floor
if (limit <= MIN_SQRT_RATIO) limit = MIN_SQRT_RATIO + 1;
skip = limit >= currentSqrt;
} else {
uint256 raw = (uint256(oracleSqrt) * sqrt(((BPS + maxSwapSlippageBps) * 1e18) / BPS)) / 1e9; // ceiling
if (raw >= MAX_SQRT_RATIO) raw = MAX_SQRT_RATIO - 1;
limit = uint160(raw);
skip = limit <= currentSqrt;
}
}
/// @dev Downside IL-offset split (FEE_MODEL.md §7, D3/D4), valued at `tick` (the vault's oracle tick,
/// TWAP when configured). Moved verbatim out of QuantumVault for the EIP-170 diet; the wallet floor,
/// the `min(netFeeValue, gap)` cap and the early returns are unchanged.
function ilOffset(
int24 tick,
uint256 principal0,
uint256 principal1,
uint256 bal0,
uint256 bal1,
uint256 net0,
uint256 net1,
uint256 walletFloorBps
) public pure returns (uint256 reinv0, uint256 reinv1, uint256 ownerFee0, uint256 ownerFee1) {
uint160 sqrtP = getSqrtRatioAtTick(tick);
uint256 holdValue = valueInToken1(principal0, principal1, sqrtP);
uint256 lpValue = valueInToken1(bal0, bal1, sqrtP);
uint256 gapValue = holdValue > lpValue ? holdValue - lpValue : 0;
uint256 netValue = valueInToken1(net0, net1, sqrtP);
if (gapValue == 0 || netValue == 0) {
// upside (no IL to backfill) or no net fees → everything to the owner's wallet
return (0, 0, net0, net1);
}
// Wallet floor (v3): always reserve `walletFloorBps` of the net for the owner's wallet, then offset
// the IL gap from the REMAINDER only.
uint256 floorValue = Math.mulDiv(netValue, walletFloorBps, BPS);
uint256 avail = netValue > floorValue ? netValue - floorValue : 0;
uint256 offsetValue = gapValue < avail ? gapValue : avail;
if (offsetValue == 0) {
// floor leaves no room to offset (or nothing available) → everything to the wallet
return (0, 0, net0, net1);
}
reinv0 = Math.mulDiv(net0, offsetValue, netValue);
reinv1 = Math.mulDiv(net1, offsetValue, netValue);
ownerFee0 = net0 - reinv0;
ownerFee1 = net1 - reinv1;
}
}
src/libraries/VenueAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @title VenueAdapter — the two calls where concentrated-liquidity DEXs stop agreeing
///
/// @notice Every venue this vault runs on is a Uniswap v3 fork, and almost all of the interface is
/// genuinely identical across them: `positions`, `increaseLiquidity`, `decreaseLiquidity`,
/// `collect`, `burn` and `factory` are byte-for-byte the same on Uniswap, PancakeSwap and
/// Aerodrome Slipstream, all verified against live contracts on Base.
///
/// Exactly two calls diverge, and this library is the whole of the difference:
///
/// 1. FINDING A POOL. Uniswap and PancakeSwap key a pool by its FEE, `getPool(a, b, uint24)`.
/// Slipstream keys it by TICK SPACING, `getPool(a, b, int24)` — different types, different
/// selectors. Calling the wrong one does not return zero, it reverts.
///
/// 2. MINTING. Slipstream's `MintParams` carries `int24 tickSpacing` where Uniswap carries
/// `uint24 fee`, and adds a trailing `uint160 sqrtPriceX96` for initialising a pool that
/// does not exist yet. Different struct, different selector: `0xb5007d1f`, and Uniswap's
/// `0x88316456` is absent from Slipstream's bytecode entirely.
///
/// @dev WHY A LIBRARY. Measured, not assumed. The vault sits against the EIP-170 24,576-byte ceiling,
/// and library code is DELEGATECALLed from its own address, so it costs the vault only the call.
/// The counter-example is recorded in the repo history: moving a SHORT validator into a library
/// once ADDED 72 bytes, because the plumbing outweighed the body. This body is large enough that
/// the trade goes the right way — an adapter inlined into the vault would not fit at all.
///
/// A pool records which shape it is at REGISTRATION, once, rather than being probed on every
/// call. Probing would cost gas forever to rediscover something that cannot change, and a
/// try/catch around a factory call is a poor way to learn a fact you already knew when you
/// registered the pool.
library VenueAdapter {
error PoolDoesNotExist();
error MintFailed();
/// @notice Resolve a pool address from the venue's factory.
/// @param key The pool's second key: a FEE for Uniswap-shaped venues, a TICK SPACING for
/// Slipstream. Held as int24 because that is the wider of the two in practice — every real
/// fee tier (100 … 10000) and every real spacing (1 … 200) fits comfortably.
function resolvePool(address factory, address token0, address token1, int24 key, bool slipstream)
public
view
returns (address pool)
{
bytes memory data = slipstream
? abi.encodeWithSignature("getPool(address,address,int24)", token0, token1, key)
: abi.encodeWithSignature("getPool(address,address,uint24)", token0, token1, uint24(int24(key)));
(bool ok, bytes memory ret) = factory.staticcall(data);
// A wrong-shape call REVERTS rather than returning zero, so both failures collapse to the same
// honest answer: we could not find this pool, and registration must not proceed.
if (!ok || ret.length < 32) revert PoolDoesNotExist();
pool = abi.decode(ret, (address));
if (pool == address(0)) revert PoolDoesNotExist();
}
/// @notice Mint a position on either venue shape.
/// @dev `sqrtPriceX96 = 0` on the Slipstream path: that field initialises a pool that does not
/// exist yet, and this vault only ever mints into a pool the owner already registered — so
/// zero is both correct and the safer value, since a non-zero one would let a mint create a
/// pool at a price of the caller's choosing.
function mint(
address npm,
bool slipstream,
address token0,
address token1,
int24 key,
int24 tickLower,
int24 tickUpper,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
uint256 deadline
) public returns (uint256 tokenId, uint128 liquidity, uint256 used0, uint256 used1) {
bytes memory data = slipstream
? abi.encodeWithSelector(
0xb5007d1f, // mint((address,address,int24,int24,int24,uint256,uint256,uint256,uint256,address,uint256,uint160))
token0, token1, key, tickLower, tickUpper,
amount0Desired, amount1Desired, amount0Min, amount1Min,
address(this), deadline, uint160(0)
)
: abi.encodeWithSelector(
0x88316456, // mint((address,address,uint24,int24,int24,uint256,uint256,uint256,uint256,address,uint256))
token0, token1, uint24(int24(key)), tickLower, tickUpper,
amount0Desired, amount1Desired, amount0Min, amount1Min,
address(this), deadline
);
// DELEGATECALL context: `address(this)` is the VAULT, so the position NFT is minted to the
// vault exactly as it was before this library existed. That is what keeps custody unchanged.
(bool ok, bytes memory ret) = npm.call(data);
// Bubble the position manager's own reason ("Price slippage check", "LOK", "M0"…) instead of
// collapsing every failed deposit, snuggle and manual re-centre into one four-byte error that
// nobody can act on. MintFailed is kept only for a success that returned too little data.
if (!ok) { assembly { revert(add(ret, 32), mload(ret)) } }
if (ret.length < 128) revert MintFailed();
(tokenId, liquidity, used0, used1) = abi.decode(ret, (uint256, uint128, uint256, uint256));
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/libraries/FeeRouter.sol": {
"FeeRouter": "0xF383d5408Aa36005B59952a05cE84D098e54C9f2"
},
"src/libraries/VaultMath.sol": {
"VaultMath": "0x9b6D35FA063ddB11d7e59ef00454C9134e211940"
},
"src/libraries/VenueAdapter.sol": {
"VenueAdapter": "0xb4ACC0209fC349EC509362CcA7d5fC4C5719dc60"
},
"src/libraries/PositionQueue.sol": {
"PositionQueue": "0xC6Fe2Ac3b6Ba2b089F263324634aF37E45E3993F"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.