Verified contractExactMIT
PrecisionPool
Address0x26240ee31dbcc552418e89eabfbb89d4496e034a
- Balance
0.69786 ETH
- Transactions
237
- Compiler
solc 0.8.36
- Same code
35 more contracts
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,734,018
- Creation transaction
- 0x128b37a006…0cb50fdf98
5 files
- src/pools/PrecisionPool.solmain98.29 KB
- lib/solady/src/tokens/ERC20.sol31.12 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
- src/pools/PriceTape.sol19.65 KB
src/pools/PrecisionPool.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
import {PriceTape, IPriceTape} from "./PriceTape.sol";
import {ERC20} from "../../lib/solady/src/tokens/ERC20.sol";
import {SafeTransferLib} from "../../lib/solady/src/utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "../../lib/solady/src/utils/FixedPointMathLib.sol";
/// @title IPrecisionHook
/// @notice Hook interface for a bounded fee surcharge and post-swap callback.
/// @dev The pool caps the fee and does not revert on callback failure.
///
/// DO NOT BUILD A CONTROLLER THAT DEPENDS ON `afterSwap` FOR ACCOUNTING.
/// `feeFor` is `view`, so a hook whose rate depends on accumulated history
/// has to write that history in `afterSwap` — and `afterSwap` is
/// best-effort: it runs under `HOOK_GAS` and the pool swallows its failure
/// (`if (!ok) emit HookCallFailed(h)`). A caller can therefore starve the
/// callback while the swap itself still succeeds, freezing the hook's
/// counters. Any rate derived from them then drifts in the attacker's
/// favour, which is worst for exactly the flow-responsive designs that
/// want history in the first place — dynamic fees, inventory targeting,
/// anything VRGDA-shaped.
///
/// Derive the rate from state the POOL owns and `feeFor` can read
/// directly — reserves, LP supply, the price tape — rather than from a
/// private counter. Reserves in particular already ARE the inventory
/// signal an inventory-targeting hook wants, and no callback can starve
/// them. Treat `afterSwap` as notification, never as bookkeeping.
interface IPrecisionHook {
/// @notice Additional fee in pips, on top of the pool's base fee.
/// @dev This is `view` so the lens can reproduce the swap's fee.
function feeFor(address sender, address tokenIn, uint256 amountIn) external view returns (uint256 extraFee);
function afterSwap(address sender, address tokenIn, uint256 amountIn, uint256 amountOut, address to) external;
}
/// @title PrecisionPool
/// @notice Concentrated constant-product pool for one pair and fixed price
/// range, with ERC-20 LP shares.
/// @dev Real reserves are combined with virtual reserves derived from LP
/// supply. Bounds are raw token1/token0 prices, represented as square
/// roots scaled by 1e18; token decimals must already be reflected in them.
/// The first deposit supplies an initial price; later deposits are
/// proportional and unused amounts are refunded. Boundary seeds are
/// supported. Swaps that leave the range are rejected.
///
/// FEES STAY IN THE RESERVES, SO THE CURVE IS NOT EXACT. Output is priced
/// on the input net of fees, but the reserves keep the LP portion of that
/// fee. The effective product therefore grows above L-squared over time
/// while the virtual offsets, derived from an unchanged LP supply, do not
/// follow it. Two consequences integrators must model rather than assume
/// away:
///
/// - `totalSupply` is the liquidity the offsets are built from, NOT
/// sqrt(XY) of the live reserves, and the two diverge with volume;
/// - a position reaching a range boundary is not guaranteed to have
/// converted entirely into one asset. It may sit at the bound still
/// holding some of the other side - that residue is retained fees and
/// belongs to the LPs.
///
/// AN UNNAMED POOL CAN BE SEEDED BY ANYONE, AT ANY IN-BAND PRICE. When
/// `feeRecipient` is zero there is no creator to check, so the first
/// depositor sets the opening price and does not need the factory to do
/// it. A squatter can therefore seed a market someone else intended to
/// open, pin it at a corner of the band, and leave `createAndSeed` to
/// revert `Exists()` for the real creator, who is left depositing
/// proportionally into a price they did not choose. `MIN_RESOLUTION` and
/// the seed price tolerance make this cost real capital rather than dust,
/// and a bad opening price is arbitrageable - but on a wide band a corner
/// is cheap to pin. Deploy anything with a frontend as a NAMED market
/// (`feeRecipient != 0`), which only its creator can seed.
///
/// THE POOL ADDRESS IS NOT A TRUST ANCHOR, AND `factory` IS. This
/// constructor is PUBLIC and validates `factory_` with nothing but
/// `code.length != 0`, so anyone can deploy a pool naming a factory of
/// their own. Combined with the constant token name below, such a pool is
/// visually identical to a canonical one in a wallet or an approval
/// prompt. It cannot reach a canonical pool's reserves - the two share no
/// state - and its own reserves are still bounded the same way, so this is
/// approval-surface risk rather than a flaw in the accounting.
///
/// The check is one call and every consumer must make it: `pool.factory()`
/// against the canonical factory, or equivalently `factory.isPool(pool)`.
/// `PrecisionPoolLens` does it for you - it is constructed with one
/// factory and returns an empty struct for anything that factory did not
/// create - so reading pools through the lens is the check. Reading them
/// from a raw address is not.
///
/// EVERY POOL'S LP TOKEN IS CALLED "Precision LP" / "pLP". The name is a
/// compile-time constant because the EIP-2612 domain caches its hash, so
/// wallets and explorers will render the shares of every market in this
/// family identically and only the token address distinguishes them.
/// Signatures are still domain-separated by address and chain ID, so this
/// is not a replay concern; it is a display one, and interfaces should
/// label a position by its pair and band rather than by this symbol.
///
/// This is auto-compounding growing-K behaviour, deliberately: fees
/// accrue to share value with no separate accumulator and no harvest
/// call. Quoters and any limit-order-style integration should compute
/// terminal inventory from the reserves rather than from the idealised
/// curve. See test_RetainedFeesOvercollateraliseWithoutBreakingTheBand.
contract PrecisionPool is ERC20, IPriceTape {
using SafeTransferLib for address;
uint256 constant WAD = 1e18;
/// @dev Fee denominator; fees are expressed in pips.
uint256 constant FEE_DENOM = 1_000_000;
/// @dev Sent to the dead address on the initial mint to prevent share-price
/// inflation against a tiny supply.
uint256 constant MIN_LIQUIDITY = 1000;
/// @dev Maximum creator share of the base fee (50%).
uint256 constant MAX_CREATOR_SHARE = 5_000;
uint256 constant BPS = 10_000; // basis points
/// @dev Minimum virtual reserve on each side of a newly seeded pool.
/// Both virtual reserves are floored functions of supply, so a pool
/// seeded with only a handful of raw units on one side has no
/// resolution to represent its own price. Withdrawals floor too, and
/// on such a pool they retain the thin side disproportionately: the
/// price then drifts genuinely - not as a rounding artifact - until it
/// leaves the band for good, because a proportional deposit preserves
/// the ratio and a swap cannot re-enter the band in one step from an
/// emptied reserve. Requiring real resolution at creation keeps pools
/// out of that regime, and a seed is the only moment the pool can
/// refuse without stranding anyone.
uint256 constant MIN_RESOLUTION = 1e6;
/// @dev Maximum combined base fee and hook surcharge (10%).
///
/// THIS BOUNDS THE RATE, NOT THE PROPORTION ANY SINGLE TRADE PAYS.
/// Both fees are taken as the difference from a floored remainder,
/// which rounds the charge UP - deliberately, because flooring the fee
/// lets a trade split finely enough pay nothing at all. The cost is
/// that a trade of a few raw units pays a whole unit: two raw units at
/// a nominal 1 pip pay one unit, an effective 50%, and a hook
/// surcharge on top of that can reach two thirds. The absolute
/// overcharge is bounded by one raw unit of the input token per fee
/// class per swap and is negligible at any size worth trading, but a
/// frontend quoting only the nominal pip rate will misstate it. Quote
/// the fee from `extraFee` and this rate rather than assuming the
/// nominal proportion holds at raw-unit sizes.
uint256 constant MAX_TOTAL_FEE = 100_000;
/// @dev Reciprocal of the tolerance allowed between the requested seed
/// price and the price the pool actually opens at (100 = 1%).
uint256 constant SEED_PRICE_TOLERANCE = 100;
/// @dev Upper bound for WAD-scaled square-root prices. Together with the
/// liquidity cap, it keeps virtual-reserve arithmetic bounded.
uint256 constant MAX_SQRT_PRICE = 1e36;
/// @dev LP supply is the curve liquidity; the cap keeps virtual reserves
/// within uint256 arithmetic.
uint256 constant MAX_LIQUIDITY = type(uint128).max;
/// @dev Gas limit for each hook callback.
uint256 constant HOOK_GAS = 150_000;
/// @dev Price-history resolution. The fine tape is written by trades; the
/// coarse tape is folded from finished fine bars, so a swap pays for
/// one live bar regardless of how many timeframes are kept. Every
/// other timeframe a chart wants is an exact client-side aggregation.
uint256 public constant FINE_PERIOD = 5 minutes;
uint256 public constant COARSE_PERIOD = 4 hours;
/// @dev ~21 hours of five-minute bars and ~42 days of four-hour bars.
/// Both rings are `PriceTape.BARS` deep; the depth is fixed in the
/// library so the index is a mask rather than a length read.
uint256 constant FINE_BARS = PriceTape.BARS;
uint256 constant COARSE_BARS = PriceTape.BARS;
/// @dev Transient slot used by the reentrancy guard.
uint256 constant _REENTRANCY_SLOT = 0xab143c06;
/// @notice Canonical token pair; address(0) represents native ETH.
address public immutable token0;
address public immutable token1;
/// @notice The only contract permitted to settle a prefunded factory route.
/// @dev Direct callers use `swapExactIn` and `addLiquidityExact`, which
/// pull their assets in the same call. Keeping the balance-delta
/// settlement private to the factory prevents a later caller from
/// claiming assets somebody else transferred in an earlier transaction.
address public immutable factory;
/// @notice Lower bound of the raw token1/token0 price range, sqrt-scaled by 1e18.
uint256 public immutable sqrtPLow;
/// @notice Upper bound of the raw token1/token0 price range, sqrt-scaled by 1e18.
uint256 public immutable sqrtPHigh;
/// @notice Base swap fee in pips.
uint256 public immutable fee;
/// @notice Bounded surcharge provider and post-swap observer; zero if none.
address public immutable hook;
/// @notice Recipient of the creator fee share and hook configuration.
/// Address(0) means no recipient is configured.
address public immutable feeRecipient;
/// @notice Creator's share of the base fee, in basis points.
uint256 public immutable creatorFeeBps;
uint128 public reserve0;
uint128 public reserve1;
/// @notice Hook fees earned but not yet collected.
/// @dev Accrued fees are excluded from balances available to LPs and swaps.
uint256 public hookOwed0;
uint256 public hookOwed1;
/// @notice Creator fees earned but not yet collected.
uint256 public creatorOwed0;
uint256 public creatorOwed1;
/// @dev Fine and coarse price history. Two tapes, not five: coarse candles
/// are exact aggregations of fine ones and are rolled up by the client,
/// so a trade only ever writes the fine tape's single live bar.
/// FINE_PERIOD * FINE_BARS of history at five-minute resolution, and
/// COARSE_PERIOD * COARSE_BARS at four-hour, per pool.
PriceTape.Tape private _fine;
PriceTape.Tape private _coarse;
error Bad();
error NotHook();
error Overflow();
error HookedNoPartialFill();
error NotFactory();
error Reentrancy();
error ZeroAmount();
error InvalidToken();
error BalanceDeficit();
error NotFeeRecipient();
error PriceOutOfRange();
error UnsupportedToken();
error InsufficientOutput();
error InsufficientLiquidity();
event Swap(address indexed tokenIn, uint256 amountIn, uint256 amountOut, address indexed to);
event HookFee(address indexed tokenIn, uint256 amount, uint256 extraFee);
event HookFeeCollected(address indexed to, uint256 amount0, uint256 amount1);
event CreatorFeeCollected(address indexed to, uint256 amount0, uint256 amount1);
/// @dev Emitted when the post-swap callback fails.
event HookCallFailed(address indexed hook);
/// @dev The indexed address is the LP share recipient, which need not be
/// the payer or the refund recipient.
event AddLiquidity(address indexed recipient, uint256 amount0, uint256 amount1, uint256 lp);
event RemoveLiquidity(address indexed provider, uint256 lp, uint256 amount0, uint256 amount1);
modifier nonReentrant() {
assembly ("memory-safe") {
if tload(_REENTRANCY_SLOT) {
mstore(0x00, 0xab143c06)
revert(0x1c, 0x04)
}
tstore(_REENTRANCY_SLOT, 1)
}
_;
assembly ("memory-safe") {
tstore(_REENTRANCY_SLOT, 0)
}
}
/// @dev Repeats the factory's dependency and arithmetic checks for direct
/// deployments.
constructor(
address factory_,
address token0_,
address token1_,
uint256 sqrtPLow_,
uint256 sqrtPHigh_,
uint256 fee_,
address hook_,
address feeRecipient_,
uint256 creatorFeeBps_
) {
if (factory_.code.length == 0) revert Bad();
if (token0_ >= token1_) revert Bad();
if (token1_.code.length == 0 || (token0_ != address(0) && token0_.code.length == 0)) revert Bad();
if (hook_ != address(0) && hook_.code.length == 0) revert Bad();
if (sqrtPLow_ == 0 || sqrtPHigh_ <= sqrtPLow_ || sqrtPHigh_ > MAX_SQRT_PRICE) revert Bad();
// Reserve room for the hook surcharge.
if (fee_ >= MAX_TOTAL_FEE) revert Bad();
(factory, token0, token1, sqrtPLow, sqrtPHigh, fee) = (factory_, token0_, token1_, sqrtPLow_, sqrtPHigh_, fee_);
hook = hook_;
// A nonzero creator share requires a recipient. A recipient without a
// share is allowed so a surcharge hook can identify its controller.
if (creatorFeeBps_ > MAX_CREATOR_SHARE) revert Bad();
if (creatorFeeBps_ != 0 && feeRecipient_ == address(0)) revert Bad();
(feeRecipient, creatorFeeBps) = (feeRecipient_, creatorFeeBps_);
}
/// @dev Native input is accepted only by an exact-input entry point. A
/// naked transfer would otherwise become anonymous balance surplus.
///
/// The constructor is deliberately NOT payable for the same reason. A
/// payable one lets a deployment endow the pool with ETH before any
/// entry point exists to credit it through, and the no-sweep policy
/// below then strands it for good. The factory always deploys with
/// zero value, but the factory is not a chokepoint: this constructor is
/// public, direct deployment is a supported path (see its own note),
/// and a pool with no `feeRecipient` can be seeded without the factory
/// ever being involved. So the guarantee has to hold here, not upstream.
///
/// Payable is the cheaper of the two, and by almost nothing: measured
/// A/B, it saves 15 gas and 5 bytes of creation code against the
/// 3,883,913 a `createPool` costs - 0.0004%, once, at deployment.
/// Constructor code is never part of the runtime, so no swap and no
/// deposit pays the difference either way. Recorded because that
/// number is the whole argument for the other choice, and the next
/// person to weigh it should not have to measure it again.
///
/// Closing this does NOT make the balance unforgeable: `selfdestruct`
/// and block rewards reach a contract without calling it, so a
/// native-token0 pool can still hold ETH no entry point ever credited.
/// That surplus is stranded rather than stealable - but NOT uniformly
/// by this contract's own doing, and the distinction matters to anyone
/// auditing the boundary:
///
/// - The DIRECT entry points (`swapExactIn`, `swapUpTo`,
/// `addLiquidityExact`) tie what they credit to `msg.value` or to
/// a pull they performed themselves, so the guarantee is local.
/// - The FACTORY entry points (`swapFromFactory`,
/// `swapUpToFromFactory`, `addLiquidityFromFactory`) do not pull.
/// They accept a DECLARED amount and bound it only by
/// `available - reserve`, so on the ERC-20 side an unaccounted
/// surplus sitting here is within what a declaration could reach.
/// Native value is still checked against `msg.value` on all three.
///
/// Solvency holds either way - reserves never exceed balances - and
/// nothing is currently claimable, because `PrecisionPoolFactory`
/// forwards exactly what it declares and proves it did with its own
/// checkpoint. But that is a FACTORY invariant, not one enforced here,
/// and it is the reason `factory` is immutable and the settlement
/// functions are gated to it. Anyone reviewing this pool in isolation
/// should not take "declared equals forwarded" on the pool's word.
///
/// The alternative, a sweep,
/// would be a permission to move funds out of an otherwise
/// permissionless immutable contract, which is a strictly worse thing
/// to hold than the dust it recovers.
receive() external payable {
revert Bad();
}
/// @notice Current sqrt price in raw token1/token0, scaled by 1e18.
/// @dev Derived from the pool's virtual and real reserves.
function sqrtPriceCurrent() public view returns (uint256) {
return _sqrtPrice(totalSupply(), reserve0, reserve1);
}
function _sqrtPrice(uint256 supply, uint256 r0, uint256 r1) internal view returns (uint256) {
if (supply == 0) return 0;
uint256 vX = _virtual0(supply, sqrtPHigh) + r0;
if (vX == 0) return 0;
return FixedPointMathLib.sqrt(FixedPointMathLib.fullMulDiv(_virtual1(supply, sqrtPLow) + r1, WAD * WAD, vX));
}
/// @dev Checks the price ratio directly, avoiding a square-root operation.
function _priceInRange(uint256 vX, uint256 vY) internal view returns (bool) {
if (vX == 0) return false;
uint256 ratio = FixedPointMathLib.fullMulDiv(vY, WAD * WAD, vX);
uint256 lo = sqrtPLow;
uint256 hiExclusive = sqrtPHigh + 1;
unchecked {
return ratio >= lo * lo && ratio < hiExclusive * hiExclusive;
}
}
/// @dev Squared price as the range check sees it. Zero X reads as zero so
/// an empty side compares as far below the floor rather than reverting.
function _ratio(uint256 vX, uint256 vY) internal pure returns (uint256) {
if (vX == 0) return 0;
return FixedPointMathLib.fullMulDiv(vY, WAD * WAD, vX);
}
/// @dev How far a squared price sits outside the band; zero when inside.
/// Used to let a deposit into an out-of-band pool through only when it
/// does not make the excursion worse.
///
/// THE TWO SIDES ARE NOT REALLY COMMENSURABLE. A miss below the floor
/// and a miss above the ceiling are both returned as bare distances in
/// squared-price units and compared as if interchangeable, so a
/// deposit that carried the price from one side of the band clean over
/// to the other could in principle pass on a smaller number while
/// being no better. It is unreachable rather than handled: the only
/// caller applies this to a PROPORTIONAL deposit, which moves the
/// ratio by rounding alone, and no rounding step crosses a whole band.
/// That is a property of the caller, not of this function - anything
/// else that starts comparing misses must re-establish it.
function _bandMiss(uint256 ratio) internal view returns (uint256) {
uint256 lo = sqrtPLow;
uint256 hiExclusive = sqrtPHigh + 1;
unchecked {
uint256 floorSq = lo * lo;
uint256 ceilSq = hiExclusive * hiExclusive;
if (ratio < floorSq) return floorSq - ratio;
if (ratio >= ceilSq) return ratio - ceilSq + 1;
return 0;
}
}
/// @dev True when at least one direction admits a swap that would actually
/// succeed. This mirrors `_swapExact` rather than approximating it:
/// the smallest gross input that survives fee rounding, the real
/// output formula, a strictly positive output within the real reserve,
/// and the post-swap range check. A one-unit fee-free quote is not
/// equivalent - it treats a zero output as executable, and it ignores
/// that the retained input includes the LP fee and so moves the price
/// further than the priced amount does.
/// @dev Fees are taken at the worst case a future trade could see, so a
/// hooked pool must be executable even under the maximum surcharge the
/// hook is ever allowed to return.
function _tradeable(uint256 x, uint256 y, uint256 r0, uint256 r1) internal view returns (bool) {
// The hook's surcharge is taken FIRST and the base fee applies to what
// is left, so the two cannot be collapsed into one aggregate rate: the
// real transition floors twice, and a single combined rate floors once.
uint256 surcharge = hook != address(0) ? MAX_TOTAL_FEE - fee : 0;
if (r1 != 0 && _executable(x, y, r0, r1, surcharge, true)) return true;
if (r0 != 0 && _executable(y, x, r1, r0, surcharge, false)) return true;
return false;
}
/// @param augIn Augmented reserve on the input side, `augOut` on the output.
/// @param surcharge Worst-case hook surcharge in pips; zero without a hook.
/// @param zeroForOne Which way round to reassemble the post-swap pair.
/// @dev Reproduces `_swapExact` exactly on the smallest input that can
/// clear it: surcharge, then base fee, then creator cut, each with the
/// same rounding, and the same reserve-room and range tests against
/// the same quantities the swap uses.
function _executable(
uint256 augIn,
uint256 augOut,
uint256 rIn,
uint256 rOut,
uint256 surcharge,
bool zeroForOne
) internal view returns (bool) {
if (augOut <= 1) return false;
// Smallest priced amount that does not round its output to zero:
// floor(a * augOut / (augIn + a)) >= 1 <=> a * (augOut - 1) >= augIn.
// Testing a one-unit input instead would reject pools whose smallest
// executable trade is simply larger than one unit.
uint256 need = FixedPointMathLib.divUp(augIn, augOut - 1);
if (need == 0) need = 1;
if (need > type(uint128).max) return false;
// Invert the two floors in the order the swap applies them: the base
// fee acts on `net`, and the surcharge acts on the gross input that
// produces that `net`.
uint256 netMin = FixedPointMathLib.fullMulDivUp(need, FEE_DENOM, FEE_DENOM - fee);
if (netMin > type(uint128).max) return false;
uint256 gross = FixedPointMathLib.fullMulDivUp(netMin, FEE_DENOM, FEE_DENOM - surcharge);
if (gross > type(uint128).max) return false;
// Now replay the transition forward on that input, with the nested
// floors the swap actually performs rather than a single combined one.
uint256 net = FixedPointMathLib.fullMulDiv(gross, FEE_DENOM - surcharge, FEE_DENOM);
uint256 priced = FixedPointMathLib.fullMulDiv(net, FEE_DENOM - fee, FEE_DENOM);
if (priced == 0) return false;
uint256 creatorCut;
uint256 creatorBps = creatorFeeBps;
if (creatorBps != 0) {
creatorCut = FixedPointMathLib.fullMulDivUp(net - priced, creatorBps, BPS);
}
// Only what stays in the reserves is checked for room, and only what
// stays in them moves the price - the hook and creator cuts do neither.
uint256 kept = net - creatorCut;
if (kept > type(uint128).max - rIn) return false;
uint256 out = FixedPointMathLib.fullMulDiv(priced, augOut, augIn + priced);
if (out == 0 || out > rOut) return false;
unchecked {
return zeroForOne
? _priceInRange(augIn + kept, augOut - out)
: _priceInRange(augOut - out, augIn + kept);
}
}
function _virtual0(uint256 liquidity, uint256 hi) internal pure returns (uint256) {
// The factory caps liquidity and the price range so this product fits.
unchecked {
return liquidity * WAD / hi;
}
}
function _virtual1(uint256 liquidity, uint256 lo) internal pure returns (uint256) {
// The factory caps liquidity and the price range so this product fits.
unchecked {
return liquidity * lo / WAD;
}
}
// -------------------------------------------------------------------- SWAP
/// @notice Pull exactly `amountIn` from the caller and settle the swap.
/// @dev Pulls and settles the input in the same transaction.
///
/// NO DEADLINE. A transaction that sits in the mempool executes
/// whenever it is finally mined, so a direct caller is writing an
/// option the market can exercise against them - the standard reason
/// AMM routers carry one. It is omitted here rather than forgotten:
/// every routed path already has a deadline at the router, and the
/// loss on this path is bounded by `minOut`, which the caller sets.
/// What a deadline adds over `minOut` is protection against a trade
/// that is still ABOVE the floor but stale, and paying for that on
/// every swap to serve direct callers - who are the minority here and
/// can set `minOut` tightly - was the trade rejected. If you call this
/// directly from an EOA, set `minOut` as though there were no deadline,
/// because there is not.
function swapExactIn(address tokenIn, uint256 amountIn, uint256 minOut, address to)
external
payable
nonReentrant
returns (uint256 amountOut)
{
bool zeroForOne = _direction(tokenIn);
if (amountIn == 0) revert ZeroAmount();
if (zeroForOne && token0 == address(0)) {
if (msg.value != amountIn) revert Bad();
} else {
if (msg.value != 0) revert Bad();
_pullExact(tokenIn, msg.sender, amountIn);
}
(amountOut,) = _swapExact(msg.sender, tokenIn, zeroForOne, amountIn, minOut, to, false, address(0));
}
/// @notice Swap AT MOST `amountIn`, filling to the band's edge and
/// returning the remainder to the caller.
/// @dev The routing counterpart to `swapExactIn`. A band refuses a trade
/// that would leave its range rather than clamping, which makes a
/// quote that was correct at block N a revert at block N+2 and gives
/// an aggregator nothing to route around. This entry point fills what
/// the band can take and hands back the rest, so a leg sized from a
/// stale quote degrades to a partial fill at a price the caller
/// already accepted instead of failing.
///
/// `minOut` applies to the output actually produced, so a caller that
/// wants all-or-nothing behaviour can still demand it. Callers
/// chaining across pools should check the returned `consumed`.
///
/// NOT AVAILABLE ON A HOOKED POOL: see `_swapExact`.
function swapUpTo(address tokenIn, uint256 amountIn, uint256 minOut, address to)
external
payable
nonReentrant
returns (uint256 amountOut, uint256 consumed)
{
bool zeroForOne = _direction(tokenIn);
if (amountIn == 0) revert ZeroAmount();
if (zeroForOne && token0 == address(0)) {
if (msg.value != amountIn) revert Bad();
} else {
if (msg.value != 0) revert Bad();
_pullExact(tokenIn, msg.sender, amountIn);
}
return _swapExact(msg.sender, tokenIn, zeroForOne, amountIn, minOut, to, true, msg.sender);
}
/// @notice Partial-fill settlement of an amount already forwarded by the
/// factory, refunding the unconsumed input to `refundTo`.
/// @dev Same authentication and `originator` caveats as `swapFromFactory`.
function swapUpToFromFactory(
address originator,
address tokenIn,
uint256 amountIn,
uint256 minOut,
address to,
address refundTo
) external payable nonReentrant returns (uint256 amountOut, uint256 consumed) {
if (msg.sender != factory) revert NotFactory();
if (refundTo == address(0) || refundTo == address(this)) revert Bad();
bool zeroForOne = _direction(tokenIn);
if (amountIn == 0) revert ZeroAmount();
if (zeroForOne && token0 == address(0)) {
if (msg.value != amountIn) revert Bad();
} else if (msg.value != 0) {
revert Bad();
}
return _swapExact(originator, tokenIn, zeroForOne, amountIn, minOut, to, true, refundTo);
}
/// @notice Settle an exact amount already forwarded by the factory.
/// @dev Callable only by the factory after it has forwarded exactly the
/// declared input amount.
/// @param originator Who the factory says is trading. On a routed swap the
/// immediate caller is the factory, so without this every routed
/// trade would present the factory to the hook - a sender-keyed
/// discount would leak to everyone routing, or be denied to them all.
///
/// IT IS NOT AUTHENTICATED. The router reaches the factory through a
/// public executor that does not forward the payer, so nobody in
/// this path can prove who the trader is. Treat it as a label for
/// accounting and analytics. A hook that grants privilege on it is
/// unsafe, and that is a property of the routing topology rather
/// than something this contract can fix.
function swapFromFactory(
address originator,
address tokenIn,
uint256 amountIn,
uint256 minOut,
address to
) external payable nonReentrant returns (uint256 amountOut) {
if (msg.sender != factory) revert NotFactory();
bool zeroForOne = _direction(tokenIn);
if (amountIn == 0) revert ZeroAmount();
if (zeroForOne && token0 == address(0)) {
if (msg.value != amountIn) revert Bad();
} else if (msg.value != 0) {
revert Bad();
}
(amountOut,) = _swapExact(originator, tokenIn, zeroForOne, amountIn, minOut, to, false, address(0));
}
/// @dev One swap transition against already-loaded state.
///
/// Shared by the executing path and the partial-fill search so the two
/// cannot drift: a search that models the transition even slightly
/// differently from the swap will hand back a size that reverts, which
/// is the exact failure partial fill exists to remove.
///
/// Take the hook surcharge first, then apply the base fee to the rest.
/// Both are derived as a DIFFERENCE from a rounded-down remainder
/// rather than computed and floored directly. Flooring the fee rounds
/// in the trader's favour, and below `FEE_DENOM/rate` raw units it
/// floors to zero outright - so a trade split finely enough pays no
/// fee at all. Nothing carries a remainder between calls and the
/// reentrancy guard clears each time, so plain batching was sufficient
/// to exploit it. Rounding the remainder down and taking the fee as
/// what is left over means every nonzero trade pays at least one raw
/// unit, or produces no executable output and reverts.
///
/// The creator share comes from the base fee and does not change the
/// amount used for pricing. It rounds UP, for the same reason the fees
/// themselves do: flooring it sends the whole share to zero whenever
/// the base fee is a single raw unit, which a trade split finely
/// enough can arrange for every slice - the fee is still paid, but
/// none of it reaches the configured recipient. Rounding up removes
/// that entirely at no storage cost. The bias it introduces runs the
/// other way and is bounded by one raw unit of the input token per
/// swap, which lands with the LPs' side of a fee they only ever get a
/// configured fraction of. Ceiling can never exceed the fee itself,
/// since the share is capped at half of it.
///
/// @dev `hasRoom` reports whether the reserve, overflow, and band
/// constraints hold. It is MONOTONE DECREASING in `amountIn` and is
/// what the partial-fill search bisects. A zero `amountOut` is a
/// SEPARATE condition running the opposite way - it turns on as size
/// grows - so the fillable set is an interval rather than a prefix or
/// a suffix, and the caller checks that half itself. Bisecting the
/// conjunction finds nothing.
///
/// THAT MONOTONICITY IS CONDITIONAL ON THE POOL BEING IN BAND, and the
/// hardcoded `true` at `amountIn == 0` is what hides it. A pool can sit
/// OUTSIDE its band without anyone misbehaving - both virtual reserves
/// are floored functions of supply, so burning toward the dead minimum
/// can leave a state the band no longer contains, which is the case
/// `_addLiquidity`'s `_bandMiss` repair path exists for. From out
/// there, a swap in the direction of the band moves the price back
/// INTO it, so the real predicate runs false -> true -> false: an
/// interval, not a suffix, and the zero case is a claim about an empty
/// trade rather than a report of the pool's actual state.
///
/// THIS IS NOT A SAFETY BUG, and the reason is worth stating because
/// it is not the bisection that saves it. `lo` is only ever advanced to
/// a size a real probe confirmed, `_swapExact` re-runs `hasRoom` on the
/// size it is about to commit, and a `lo` of zero is refused outright.
/// The worst outcome is a suboptimal or empty partial fill on a pool
/// that was already out of band - reachable only through the same
/// dust-scale regime, and repaired by a deposit, not by a better
/// search. Do not "fix" the zero case by reporting the live band state
/// here without re-reading `_maxIn` and `PrecisionRoute._maxRouteIn`
/// together: both encode "zero has room" as a loop invariant.
function _transitionAt(Transition memory t, uint256 amountIn)
internal
view
returns (uint256 amountOut, uint256 kept, uint256 hookCut, uint256 creatorCut, bool hasRoom)
{
if (amountIn == 0) return (0, 0, 0, 0, true);
if (hook != address(0)) {
hookCut = amountIn - FixedPointMathLib.fullMulDiv(amountIn, FEE_DENOM - t.surcharge, FEE_DENOM);
}
uint256 net = amountIn - hookCut;
uint256 feeAmount = net - FixedPointMathLib.fullMulDiv(net, FEE_DENOM - fee, FEE_DENOM);
uint256 creatorBps = creatorFeeBps;
if (creatorBps != 0) creatorCut = FixedPointMathLib.fullMulDivUp(feeAmount, creatorBps, BPS);
kept = net - creatorCut;
if (kept > type(uint128).max - t.rIn) return (0, 0, 0, 0, false);
uint256 inAfterFee = net - feeAmount;
// A priced amount of zero buys nothing, and computing that explicitly
// rather than through `fullMulDiv` avoids the one state where the
// divisor is also zero: a pool burned down to its dead shares on a band
// wide enough to floor `_virtual0` away has `rIn + vIn == 0`, and
// `fullMulDiv(0, y, 0)` reverts with `MulDivFailed` instead of the
// `InsufficientOutput` the caller should see.
if (inAfterFee != 0) {
amountOut = FixedPointMathLib.fullMulDiv(inAfterFee, t.rOut + t.vOut, t.rIn + t.vIn + inAfterFee);
}
if (amountOut > t.rOut) return (0, 0, 0, 0, false);
uint256 nextIn = t.rIn + t.vIn + kept;
uint256 nextOut = t.rOut + t.vOut - amountOut;
hasRoom = t.zeroForOne ? _priceInRange(nextIn, nextOut) : _priceInRange(nextOut, nextIn);
}
/// @dev Loaded swap state, grouped so the search can replay a transition
/// without repeating the storage reads.
struct Transition {
bool zeroForOne;
uint256 rIn;
uint256 rOut;
uint256 vIn;
uint256 vOut;
uint256 surcharge;
}
/// @dev Largest input at or below `amountIn` that the band still admits.
///
/// Found by bisection, not algebra. The obvious closed form - reserve
/// room out to the bound - is WRONG: the input reserve grows by
/// `kept`, which retains the LP fee, while the output is priced on
/// `inAfterFee`, which does not. The two sides of the post-swap ratio
/// therefore advance under different quantities and the boundary
/// condition does not separate into anything a uint256 can solve
/// without a 512-bit square root.
///
/// Bisection over `[0, amountIn]` costs about log2(amountIn) replays
/// of pure memory arithmetic, and is only ever paid on the clamping
/// path - a swap that fits inside the band returns on the first probe.
function _maxIn(Transition memory t, uint256 amountIn) internal view returns (uint256) {
(,,,, bool roomAtFull) = _transitionAt(t, amountIn);
if (roomAtFull) return amountIn;
// Invariant: `lo` has room, `hi` does not. Zero trivially has room.
uint256 lo;
uint256 hi = amountIn;
while (hi - lo > 1) {
uint256 mid = lo + (hi - lo) / 2;
(,,,, bool roomMid) = _transitionAt(t, mid);
if (roomMid) lo = mid;
else hi = mid;
}
return lo;
}
/// @notice Output for `amountIn`, and whether the band admits it.
///
/// @dev The quote a CHAINED caller needs. `_maxIn` clamps one pool against
/// its own band, which is the whole problem when the pool is hop `i`
/// of a route: the input arriving here is whatever the previous hop
/// produced, so a router cannot size this leg without first knowing
/// what every leg does. Exposing the transition lets the router search
/// the ROUTE and clamp once, at the front, where the leftover is still
/// the caller's own input token rather than an intermediate nobody
/// asked to hold.
///
/// This runs `_transitionAt` - the same function `_swapExact` runs, not
/// a reimplementation of it - so the quote cannot drift from execution.
/// That property is the point: a search modelling the transition even
/// slightly differently hands back a size that reverts, which is the
/// exact failure a partial fill exists to remove.
///
/// `fits` folds in the zero-output refusal as well as the band, so it
/// is the whole executability predicate for this size. Pass the address
/// the pool will SEE at execution as `sender`, not the end user: a
/// hook may key its surcharge on it, and the quote must sample the same
/// rate the swap will.
///
/// ON A HOOKED POOL THIS IS ADVISORY, NOT A PREDICTION. `feeFor` is
/// `view`, which constrains it to not writing - it does NOT constrain
/// it to answering the same way twice. A hook may key its rate on
/// block number, timestamp, its own storage, `tx.origin`, or the pool
/// state a pending transaction is about to change, so the surcharge
/// sampled here can differ from the one the swap applies, anywhere up
/// to `MAX_TOTAL_FEE - fee`. That is bounded and it is the hook's
/// prerogative - the hook is immutable per pool and its ceiling is
/// enforced in `extraFee` - but it means a quote taken here is a
/// sample, not a commitment. `minOut` is what actually protects the
/// trade; size it against the worst case, not against this number.
/// On an unhooked pool the quote is exact.
///
/// DO NOT BISECT `fits`. It is the conjunction of two conditions that
/// run in OPPOSITE directions - the band closes as size grows, the
/// zero-output refusal opens - so the fillable set is an interval, and
/// a search that halves against `fits` can step over that interval
/// entirely and report that nothing fills when something does. This is
/// the same trap `_transitionAt` documents for the pool's own `_maxIn`,
/// which is why that search bisects `hasRoom` alone. A chained caller
/// wanting to size a route must do the same, against
/// `quoteTransition` below, and check the zero-output half once at the
/// end. `fits` is for asking about ONE size, not for searching sizes.
function quoteExactIn(address sender, address tokenIn, uint256 amountIn)
external
view
returns (uint256 amountOut, bool fits)
{
bool hasRoom;
(amountOut, hasRoom) = _quote(sender, tokenIn, amountIn);
fits = hasRoom && amountOut != 0;
if (!fits) amountOut = 0;
}
/// @notice The raw transition: the output for `amountIn`, and whether the
/// BAND alone admits it, with the zero-output refusal left to the
/// caller.
///
/// @dev The searchable half of `quoteExactIn`. `hasRoom` is MONOTONE
/// DECREASING in `amountIn` - and true at zero - so it is the predicate
/// a partial-fill search over a route bisects, exactly as the pool's
/// own `_maxIn` bisects it for a single pool. Having found the largest
/// size the band admits, check `amountOut != 0` there once: output is
/// monotone increasing, so a zero at that size means no smaller size
/// fills either.
///
/// `amountOut` is returned unmasked here even when it is zero or the
/// band refuses, because a chained search needs the real figure to feed
/// the next hop. `quoteExactIn` masks it; this does not.
function quoteTransition(address sender, address tokenIn, uint256 amountIn)
external
view
returns (uint256 amountOut, bool hasRoom)
{
return _quote(sender, tokenIn, amountIn);
}
function _quote(address sender, address tokenIn, uint256 amountIn)
internal
view
returns (uint256 amountOut, bool hasRoom)
{
bool zeroForOne = _direction(tokenIn);
uint256 supply = totalSupply();
if (supply == 0) return (0, false);
// Matches `_transitionAt`: an empty trade leaves the price where it is,
// so the band trivially admits it. `quoteExactIn` still reports it as
// not fitting, via the zero output.
if (amountIn == 0) return (0, true);
Transition memory t;
t.zeroForOne = zeroForOne;
(t.rIn, t.rOut, t.vIn, t.vOut) = zeroForOne
? (uint256(reserve0), uint256(reserve1), _virtual0(supply, sqrtPHigh), _virtual1(supply, sqrtPLow))
: (uint256(reserve1), uint256(reserve0), _virtual1(supply, sqrtPLow), _virtual0(supply, sqrtPHigh));
if (hook != address(0)) t.surcharge = extraFee(sender, tokenIn, amountIn);
(amountOut,,,, hasRoom) = _transitionAt(t, amountIn);
}
function _swapExact(
address sender,
address tokenIn,
bool zeroForOne,
uint256 amountIn,
uint256 minOut,
address to,
bool allowPartial,
address refundTo
) internal returns (uint256 amountOut, uint256 consumed) {
if (to == address(0) || to == address(this)) revert Bad();
uint256 r0 = reserve0;
uint256 r1 = reserve1;
(uint256 available0, uint256 available1) = _assertBacked(r0, r1);
uint256 supply = totalSupply();
if (supply == 0) revert InsufficientLiquidity();
Transition memory t;
t.zeroForOne = zeroForOne;
(t.rIn, t.rOut, t.vIn, t.vOut) = zeroForOne
? (r0, r1, _virtual0(supply, sqrtPHigh), _virtual1(supply, sqrtPLow))
: (r1, r0, _virtual1(supply, sqrtPLow), _virtual0(supply, sqrtPHigh));
// Only the authenticated input amount may move the curve; other
// balance surplus remains unaccounted.
uint256 availableIn = zeroForOne ? available0 : available1;
if (amountIn > availableIn - t.rIn) revert BalanceDeficit();
if (hook != address(0)) t.surcharge = extraFee(sender, tokenIn, amountIn);
consumed = amountIn;
if (allowPartial) {
// The surcharge is sampled once, at the requested size. On a hooked
// pool the hook may return a different rate for the clamped size,
// which would make the search's model wrong at exactly the boundary
// it is searching for - so partial fill is refused there rather
// than approximated. Hooked pools keep the all-or-nothing
// behaviour and callers size them from the lens.
if (hook != address(0)) revert HookedNoPartialFill();
consumed = _maxIn(t, amountIn);
if (consumed == 0) revert InsufficientOutput();
}
uint256 kept;
uint256 hookCut;
uint256 creatorCut;
bool hasRoom;
(amountOut, kept, hookCut, creatorCut, hasRoom) = _transitionAt(t, consumed);
// Do not accept a rounded-zero output. Without `allowPartial` a trade
// that leaves the band is refused outright rather than clamped.
if (amountOut == 0 || !hasRoom) revert InsufficientOutput();
if (amountOut < minOut) revert InsufficientOutput();
uint256 next0 = zeroForOne ? t.rIn + kept : t.rOut - amountOut;
uint256 next1 = zeroForOne ? t.rOut - amountOut : t.rIn + kept;
if (hookCut != 0 || creatorCut != 0) {
_accrueFees(zeroForOne, hookCut, creatorCut, tokenIn, t.surcharge);
}
// Keep the input less the hook and creator cuts in the reserves.
_setReserves(next0, next1);
_pay(zeroForOne ? token1 : token0, to, amountOut);
// Return the unconsumed input. Written after reserves are settled so a
// callback-capable token sees committed state. `_pay` measures its own
// before-balance, so the output having already left is accounted for
// rather than something this call has to compensate for.
if (consumed < amountIn) {
unchecked {
_pay(tokenIn, refundTo, amountIn - consumed);
}
}
emit Swap(tokenIn, consumed, amountOut, to);
_record(zeroForOne, consumed, amountOut);
_afterSwap(sender, tokenIn, consumed, amountOut, to);
}
/// @dev Write the trade to the price tape. One storage write per swap; the
/// bucket rollover adds two more, once every FINE_PERIOD.
///
/// The price recorded is the EXECUTED price — output over input,
/// including fee and slippage — because a tape should show what
/// actually traded, not a mid nobody could have taken. It is raw
/// token1-per-token0 scaled by 1e18, the same convention as this
/// pool's own `sqrtPLow`/`sqrtPHigh`, so token decimals are NOT
/// normalised here and a reader applies them alongside the pair.
///
/// THE TAPE CANNOT REPRESENT A RAW PRICE BELOW 1e-18. The 1e18 scale is
/// fixed because it is what makes one chart client work against every
/// adopter of `IPriceTape`, so a pair whose raw token1-per-token0 price
/// is under that floor records bars of zero. Reaching it takes an
/// extreme decimal mismatch - roughly an 18-decimal token0 against a
/// token1 worth less than 1e-18 of it per raw unit - which the band
/// permits, since `sqrtPLow` only has to be nonzero. Nothing else is
/// affected: pricing, reserves, and the range check never consult the
/// tape, so such a pool trades correctly and merely charts flat. It is
/// recorded here rather than repaired because the repair would be a
/// per-pool scale factor, and a bar whose units depend on which pool
/// emitted it is worse for readers than a bar that is legibly empty.
///
/// THIS TAPE IS NOT AN ORACLE. DO NOT PRICE ANYTHING AGAINST IT.
/// It is a chart, and it is CHEAP TO POISON - by design, not by
/// oversight. The price printed is the executed one, fee included, and
/// the fee is deliberately rounded up from a floored remainder, so
/// below roughly `FEE_DENOM / fee` raw units of input a trade pays a
/// large multiple of the nominal rate and prints a correspondingly
/// distorted price. At 500 pips that is about 2,000 raw units - a
/// couple of dollars on an 8-decimal token0. `high` and `low` are
/// extrema over the bar, so a single such trade marks the bar for its
/// whole life, and `fold` carries it into the coarse tape.
///
/// There is no defence here worth building, because the same bar is
/// also movable by anyone willing to trade the price there and back
/// for the cost of two fees. A contract that needs a manipulation-
/// resistant price must derive it from the reserves, over a window it
/// chooses, with its own cost-of-attack analysis. Charting is the
/// whole intended use.
function _record(bool zeroForOne, uint256 amountIn, uint256 amountOut) internal {
uint256 price = zeroForOne
? FixedPointMathLib.fullMulDiv(amountOut, 1e18, amountIn)
: FixedPointMathLib.fullMulDiv(amountIn, 1e18, amountOut);
// Volume is always quoted in token0 so bars from both directions add up.
// GROSS ON ONE SIDE, NET ON THE OTHER: a token0-in trade prints the
// input before fees, a token1-in trade prints the output after them, so
// two economically identical trades differ by roughly the fee rate.
// Sub-percent, invisible on a chart, and `IPriceTape` already calls
// volume a lower bound - recorded so nobody chases the discrepancy.
uint256 volume = zeroForOne ? amountIn : amountOut;
uint256 done = PriceTape.print(_fine, price, volume, FINE_PERIOD);
if (done != 0) PriceTape.fold(_coarse, done, FINE_PERIOD, COARSE_PERIOD);
}
// -------------------------------------------------------------- PRICE TAPE
/// @inheritdoc IPriceTape
function tapePeriods() external pure override returns (uint256[] memory periods) {
periods = new uint256[](2);
(periods[0], periods[1]) = (FINE_PERIOD, COARSE_PERIOD);
}
/// @inheritdoc IPriceTape
function tapePair() external view override returns (address base, address quote) {
(base, quote) = (token0, token1);
}
/// @inheritdoc IPriceTape
/// @dev Any period other than the two recorded returns nothing rather than
/// guessing; a client aggregates fine bars for the timeframes between.
function tape(uint256 period, uint256 count) external view override returns (uint256[] memory) {
if (period == FINE_PERIOD) return PriceTape.recent(_fine, FINE_PERIOD, count);
if (period == COARSE_PERIOD) return PriceTape.recent(_coarse, COARSE_PERIOD, count);
return new uint256[](0);
}
function _direction(address tokenIn) internal view returns (bool zeroForOne) {
zeroForOne = tokenIn == token0;
if (!zeroForOne && tokenIn != token1) revert InvalidToken();
}
/// @notice Return the hook surcharge for a trade, clamped to the fee ceiling.
/// @dev A revert or invalid return is treated as zero. RUNNING OUT OF GAS
/// IS NOT, and the difference is the whole point of the check below.
///
/// MAPPING FAILURE TO ZERO IS SAFE HERE AND NOT SAFE IN `afterSwap`,
/// and the reason is arithmetic rather than judgement. Both run under
/// the same budget and the same 63/64 rule, so in both the callee gets
/// `min(HOOK_GAS, 63/64 * gasleft())`. The question is whether a
/// trader can squeeze the callee out of gas and still have their own
/// call succeed - because on THIS path that would buy them the trade
/// at base fee with the surcharge silently dropped.
///
/// They cannot. Let `G` be the gas left at the staticcall, `C` what
/// `feeFor` needs, and `R` the rest of the swap. Starving it requires
/// `63/64 * G < C`; an out-of-gas callee consumes everything
/// forwarded, so what survives is `G/64`, and finishing requires
/// `G/64 >= R`. Together those give `R < C/63`. And `C` cannot exceed
/// `HOOK_GAS`, because that is all the hook is ever handed - so
/// starvation needs the ENTIRE remainder of the swap to cost under
/// `HOOK_GAS / 63`, about 2,400 gas. Two reserve writes alone exceed
/// that, before the transfer or the tape. The attempt costs the trader
/// 63 times what it costs the hook, which is the whole reason it is
/// not worth defending against.
///
/// `afterSwap` is starvable for exactly the reason this is not: it
/// runs LAST, so its `R` is approximately zero and the inequality is
/// satisfiable. The asymmetry the header describes is real and this is
/// where it comes from.
///
/// An earlier revision guarded this with a `gasleft()` floor. That was
/// removed: it defended a threat the 63/64 rule already closes, while
/// adding a revert to a `view` that quoting callers may legitimately
/// run under a bounded gas budget. See
/// test_FeeForCannotBeStarvedAtAnyGasLimit.
function extraFee(address sender, address tokenIn, uint256 amountIn) public view returns (uint256) {
address h = hook;
if (h == address(0)) return 0;
uint256 budget = HOOK_GAS;
bool ok;
uint256 answer;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, shl(224, 0xc5096a69)) // `feeFor(address,address,uint256)`.
mstore(add(m, 0x04), and(sender, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 0x24), and(tokenIn, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 0x44), amountIn)
ok := staticcall(budget, h, m, 0x64, m, 0x20)
ok := and(ok, eq(returndatasize(), 0x20))
answer := mload(m)
}
if (!ok) return 0;
uint256 room = MAX_TOTAL_FEE - fee;
return answer > room ? room : answer;
}
function _accrueFees(bool zeroForOne, uint256 hookCut, uint256 creatorCut, address tokenIn, uint256 surcharge)
internal
{
// Counters are uint256. Accrual is cumulative while reserves are not -
// the same units can be traded back and forth indefinitely - so a
// narrower counter is not bounded by reserve size and could saturate
// after enough directional volume. Once saturated every further swap
// in that direction reverts, permanently if the payee can no longer
// collect. The backing balances are uint256 already, so nothing is
// gained by narrowing the claim against them.
//
// CHECKED, not `unchecked`, and the width argument above is the reason
// rather than a reason to skip it. Width makes the counter unreachable;
// wrapping would make it CATASTROPHIC if it were ever reached, because
// `_assertBacked` compares `balance < reserve + owed` and a wrapped
// `owed` turns that solvency test into a permanent pass while inflating
// the `available` figure the swap path sizes its input against. The two
// failure modes are not symmetric: reverting here costs a swap on a pool
// nobody can reach, and wrapping here costs the pool. Each swap adds at
// most one uint128, so overflow needs on the order of 1e39 swaps - the
// check is unreachable in the same sense the wrap is, and it is the one
// of the two that fails safe. It is not on any hot path either: this
// function only runs when a hook or creator share is actually accruing.
if (hookCut != 0) {
if (zeroForOne) hookOwed0 += hookCut;
else hookOwed1 += hookCut;
emit HookFee(tokenIn, hookCut, surcharge);
}
if (creatorCut != 0) {
if (zeroForOne) creatorOwed0 += creatorCut;
else creatorOwed1 += creatorCut;
}
}
/// @notice Sweep accrued creator fees.
/// @dev Callable only by `feeRecipient`.
///
/// BOTH SIDES ARE PAID OR NEITHER IS. If one token reverts on transfer
/// - a paused token, a `to` blacklisted by one issuer - the other side
/// cannot be collected either. `to` is an argument precisely so the
/// recipient-specific cases are recoverable by naming a different
/// address; a token-wide pause simply has to be waited out. Accruals
/// are uint256 and nothing expires, so nothing is lost by waiting.
function collectCreatorFees(address to) external nonReentrant returns (uint256 a0, uint256 a1) {
if (msg.sender != feeRecipient) revert NotFeeRecipient();
if (to == address(0) || to == address(this)) revert Bad();
// Solvency is still asserted before anything is paid out; `_pay` takes
// its own snapshot, so the balances themselves are not needed here.
_assertBacked(reserve0, reserve1);
(a0, a1) = (creatorOwed0, creatorOwed1);
(creatorOwed0, creatorOwed1) = (0, 0);
if (a0 != 0) _pay(token0, to, a0);
if (a1 != 0) _pay(token1, to, a1);
emit CreatorFeeCollected(to, a0, a1);
}
/// @notice Sweep accrued hook fees.
/// @dev Callable only by the configured hook.
function collectHookFees(address to) external nonReentrant returns (uint256 a0, uint256 a1) {
if (msg.sender != hook) revert NotHook();
if (to == address(0) || to == address(this)) revert Bad();
_assertBacked(reserve0, reserve1);
(a0, a1) = (hookOwed0, hookOwed1);
(hookOwed0, hookOwed1) = (0, 0);
if (a0 != 0) _pay(token0, to, a0);
if (a1 != 0) _pay(token1, to, a1);
emit HookFeeCollected(to, a0, a1);
}
/// @dev Called after reserves and output are settled, while the reentrancy
/// guard is active. Failure is reported but does not revert the swap.
function _afterSwap(address sender, address tokenIn, uint256 amountIn, uint256 amountOut, address to)
internal
{
address h = hook;
if (h == address(0)) return;
uint256 budget = HOOK_GAS;
bool ok;
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, shl(224, 0x3da8b865)) // `afterSwap(address,address,uint256,uint256,address)`.
mstore(add(m, 0x04), and(sender, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 0x24), and(tokenIn, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(m, 0x44), amountIn)
mstore(add(m, 0x64), amountOut)
mstore(add(m, 0x84), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
ok := call(budget, h, 0, m, 0xa4, codesize(), 0x00)
}
if (!ok) emit HookCallFailed(h);
}
// --------------------------------------------------------------- LIQUIDITY
/// @notice Deposit both sides and mint LP shares.
/// @dev Pulls exact amounts from the caller and refunds unused amounts.
/// @param sqrtPriceInit Initial price for an empty pool; ignored afterwards.
/// @param amount0 Token0 amount, or exact `msg.value` for native token0.
/// @param amount1 Token1 amount.
/// @param minLP Minimum LP shares to mint.
/// @param to LP share recipient.
function addLiquidityExact(uint256 sqrtPriceInit, uint256 amount0, uint256 amount1, uint256 minLP, address to)
external
payable
nonReentrant
returns (uint256 lp, uint256 used0, uint256 used1)
{
if (token0 == address(0)) {
if (msg.value != amount0) revert Bad();
} else {
if (msg.value != 0) revert Bad();
_pullExact(token0, msg.sender, amount0);
}
_pullExact(token1, msg.sender, amount1);
return _addLiquidity(sqrtPriceInit, amount0, amount1, minLP, to, msg.sender);
}
/// @notice Mint against assets forwarded by the factory.
/// @dev The factory transfers ERC-20 amounts and forwards native value in
/// the same call.
function addLiquidityFromFactory(
uint256 sqrtPriceInit,
uint256 amount0,
uint256 amount1,
uint256 minLP,
address to,
address refundTo
) external payable nonReentrant returns (uint256 lp, uint256 used0, uint256 used1) {
if (msg.sender != factory) revert NotFactory();
if (token0 == address(0)) {
// A zero value is valid for an upper-bound, token1-only seed.
if (msg.value != amount0) revert Bad();
} else if (msg.value != 0) {
revert Bad();
}
return _addLiquidity(sqrtPriceInit, amount0, amount1, minLP, to, refundTo);
}
function _addLiquidity(
uint256 sqrtPriceInit,
uint256 amount0,
uint256 amount1,
uint256 minLP,
address to,
address refundTo
) internal returns (uint256 lp, uint256 used0, uint256 used1) {
if (to == address(0) || to == address(this)) revert Bad();
if (refundTo == address(0) || refundTo == address(this)) revert Bad();
uint256 r0 = reserve0;
uint256 r1 = reserve1;
(uint256 available0, uint256 available1) = _assertBacked(r0, r1);
// Do not credit unrelated balance surplus to this deposit.
if (amount0 > available0 - r0 || amount1 > available1 - r1) {
revert BalanceDeficit();
}
uint256 supply = totalSupply();
if (supply == 0) {
// A named market must be initialized through the factory.
if (feeRecipient != address(0) && msg.sender != factory) revert NotFactory();
// Bounds are inclusive; a boundary seed is one-sided.
if (sqrtPriceInit < sqrtPLow || sqrtPriceInit > sqrtPHigh) revert PriceOutOfRange();
(lp, used0, used1) = _seed(amount0, amount1, sqrtPLow, sqrtPHigh, sqrtPriceInit);
if (lp <= MIN_LIQUIDITY) revert InsufficientLiquidity();
if (used0 == 0 && used1 == 0) revert InsufficientLiquidity();
unchecked {
lp -= MIN_LIQUIDITY;
}
_mint(address(0xdead), MIN_LIQUIDITY);
} else {
(lp, used0, used1) = _proportional(amount0, amount1, r0, r1, supply);
if (lp > MAX_LIQUIDITY - supply) revert InsufficientLiquidity();
}
if (lp < minLP) revert InsufficientLiquidity();
// The seed's two bound corrections run in sequence, and the upper one
// can undo the lower one: zeroing `used1` to respect the ceiling can
// leave the pool below its floor. Rounding in the proportional path can
// nudge the price similarly. Neither is caught by the corrections
// themselves, so the postcondition is asserted here against the state
// actually about to be committed - the same one swaps already enforce.
//
// Without it a seed can pass every guard, mint shares, burn the
// permanent minimum, and leave a pool priced outside its own range with
// one side empty, which cannot trade in either direction. Refusing the
// deposit is strictly better than creating that pool.
//
// Deliberately NOT applied to removals: making an exit conditional on a
// price check could trap liquidity, which is a worse failure than the
// one this prevents.
{
uint256 postSupply = supply == 0 ? lp + MIN_LIQUIDITY : supply + lp;
uint256 postR0 = r0 + used0;
uint256 postR1 = r1 + used1;
uint256 postX = _virtual0(postSupply, sqrtPHigh) + postR0;
uint256 postY = _virtual1(postSupply, sqrtPLow) + postR1;
if (!_priceInRange(postX, postY)) {
// A pool can be outside its band without anyone misbehaving:
// both virtual reserves are floored functions of supply, so
// burning liquidity down toward the dead minimum can leave a
// state the band no longer contains. Refusing every deposit
// there is what makes the excursion permanent - swaps must
// land back inside the band in one step, which an emptied
// output reserve cannot do, and a proportional deposit holds
// the ratio and so fails this same check. The pool would keep
// its reserves and never trade again.
//
// So a deposit into an already-out-of-band pool is allowed
// when it does not push the price further out. That restores
// the repair path - anyone can grow the pool back to a
// resolution where the band holds - without giving anyone a
// way to move a healthy pool out of its range: if the pool is
// in band, `miss` is zero and only an in-band result passes.
if (supply == 0) revert PriceOutOfRange();
uint256 preMiss = _bandMiss(
_ratio(_virtual0(supply, sqrtPHigh) + r0, _virtual1(supply, sqrtPLow) + r1)
);
if (preMiss == 0) revert PriceOutOfRange();
if (_bandMiss(_ratio(postX, postY)) > preMiss) revert PriceOutOfRange();
}
// Being inside the band is not the same as being tradeable. The
// band is a property of the floored price representation; whether
// an integer trade exists is a property of the reserves. A seed
// whose whole output reserve is worth less than one raw unit of
// the other token satisfies the first and fails the second: the
// smallest possible swap already asks for more than the pool
// holds, and output is monotone in input, so every swap reverts.
// Such a pool is immutable and permanently inert, so refuse to
// create it.
if (supply == 0) {
if (!_tradeable(postX, postY, postR0, postR1)) revert InsufficientLiquidity();
if (
_virtual0(postSupply, sqrtPHigh) < MIN_RESOLUTION
|| _virtual1(postSupply, sqrtPLow) < MIN_RESOLUTION
) revert InsufficientLiquidity();
// `sqrtPriceInit` is an argument to the seed, not merely a hint
// to it: liquidity is floored, the amounts it requires are
// ceiled, and the two bound corrections below can move the
// result again, so the price the pool actually opens at is not
// the one that was asked for. Checking only the immutable band
// is far too loose - a seed can succeed several percent away
// from its own argument and hand the seeder an instant
// arbitrage, with `minLP` constraining shares but nothing
// constraining price. The resolution floor above bounds the
// real rounding error to parts per million, so a band this wide
// rejects nothing legitimate and catches the case where the
// requested price was not honoured at all.
unchecked {
uint256 wantSq = sqrtPriceInit * sqrtPriceInit;
uint256 gotSq = _ratio(postX, postY);
uint256 slack = wantSq / SEED_PRICE_TOLERANCE;
if (gotSq < wantSq - slack || gotSq > wantSq + slack) revert PriceOutOfRange();
}
} else {
// A later deposit is proportional, but proportional is not the
// same as liveness-preserving: both virtual reserves are
// floored functions of supply, and minting shares moves them by
// a different rounding than the real reserves it adds. A
// deposit can therefore land a pool that had exactly one
// executable trade in a state that has none, which on an
// immutable market is permanent for as long as nobody repairs
// it. Enlarging the reserves does not by itself rule that out.
//
// So preserve liveness rather than assert it: a deposit into a
// tradeable pool must leave it tradeable, while a deposit into
// a pool that already has no executable trade is allowed
// through unconditionally. That keeps the repair path open -
// growing a stuck pool back to a workable resolution is exactly
// the deposit this check must not block - and it never lets a
// healthy pool be deposited into the dead state. Reverting an
// add strands nothing, which is why the same treatment is not
// extended to removals.
if (_tradeable(_virtual0(supply, sqrtPHigh) + r0, _virtual1(supply, sqrtPLow) + r1, r0, r1)) {
if (!_tradeable(postX, postY, postR0, postR1)) revert InsufficientLiquidity();
}
}
}
_setReserves(r0 + used0, r1 + used1);
_mint(to, lp);
// Write reserves before refunding so callbacks see settled state.
if (amount0 > used0) _pay(token0, refundTo, amount0 - used0);
if (amount1 > used1) _pay(token1, refundTo, amount1 - used1);
emit AddLiquidity(to, used0, used1, lp);
}
/// @dev Compute liquidity from each side and use the smaller result.
/// Boundary prices are supported and produce one-sided liquidity.
function _seed(uint256 in0, uint256 in1, uint256 sl, uint256 sh, uint256 s)
internal
pure
returns (uint256 lp, uint256 used0, uint256 used1)
{
if (s == sl) {
// x = L * (1/s - 1/sh) -> L = x * s * sh / (sh - s)
lp = FixedPointMathLib.fullMulDiv(FixedPointMathLib.fullMulDiv(in0, s, sh - s), sh, WAD);
} else if (s == sh) {
// y = L * (s - sl) -> L = y / (s - sl)
lp = FixedPointMathLib.fullMulDiv(in1, WAD, s - sl);
} else {
uint256 lpFrom0 = FixedPointMathLib.fullMulDiv(FixedPointMathLib.fullMulDiv(in0, s, sh - s), sh, WAD);
uint256 lpFrom1 = FixedPointMathLib.fullMulDiv(in1, WAD, s - sl);
lp = FixedPointMathLib.min(lpFrom0, lpFrom1);
}
if (lp == 0) revert ZeroAmount();
if (lp > MAX_LIQUIDITY) revert InsufficientLiquidity();
// Round requirements up so the pool is not underfunded.
//
// ONE CEILING, NOT TWO. The requirement is `L * (sh - s) * WAD /
// (sh * s)`, and computing it as two nested `fullMulDivUp`s rounds up
// twice - overshooting the true figure by as much as `WAD / s + 1` raw
// units. `lp` is floor-derived from `in0`, so the exact requirement is
// always affordable; the overshoot is not, and the check at the end of
// this function then rejects a seed whose amounts the caller computed
// correctly from the same formula. It is also ASYMMETRIC - `used1`
// ceilings once and provably cannot overshoot - so the failure looks
// arbitrary from outside. At a low `s` the gap is large: around 1e8 raw
// units at `s = 1e10`.
//
// Fusing the two divisions removes it exactly, and both intermediates
// stay in range: `(sh - s) * WAD <= 1e54` and `sh * s <= 1e72`, with
// `fullMulDivUp` carrying the 512-bit numerator.
used0 = FixedPointMathLib.fullMulDivUp(lp, (sh - s) * WAD, sh * s);
used1 = FixedPointMathLib.fullMulDivUp(lp, s - sl, WAD);
// Refuse anything the reserves could not hold before doing arithmetic
// on it. `_setReserves` would reject these amounts at the end of the
// deposit anyway, so nothing new is turned away - but `maxY` below
// divides `x * sh^2` by 1e36, and for a seed near the bottom of the
// price range `used0` grows by a factor of `WAD / s`. That quotient
// leaves uint256 well before `used0` itself does, so without this the
// caller gets Solady's `MulDivFailed` instead of a stated reason.
// Corrections below only ever lower these, so checking here is enough.
if (used0 > type(uint128).max || used1 > type(uint128).max) revert InsufficientLiquidity();
// Remove rounding excess if it would put the discrete price outside
// the configured range.
uint256 v0 = _virtual0(lp, sh);
uint256 v1 = _virtual1(lp, sl);
// The resolution floor, hoisted from `_addLiquidity`. Not a new
// constraint: `lp` here IS the `postSupply` the caller checks against
// `MIN_RESOLUTION` a few lines later - the seed's `MIN_LIQUIDITY` is
// subtracted from the return value and added straight back - so the
// accept/reject boundary is unchanged and this rejects nothing that
// would otherwise have been created.
//
// It is hoisted because `maxX` below divides `y * 1e36` by `sl * sl`,
// and the old `v1 != 0` guard only pinned `sl >= WAD / lp`. At that
// floor the quotient approaches `lp * lp`, which leaves uint256 at the
// top of the liquidity cap - so a pathological low-`sl` seed reached
// Solady's `MulDivFailed` instead of a stated reason, and reached it
// BEFORE the check that was going to refuse it anyway. Requiring 1e6 of
// resolution instead pins `sl >= 1e24 / lp` and bounds the same quotient
// by `lp * lp / 1e6`, six orders of magnitude clear. Same class as the
// `inAfterFee` guard in `_transitionAt` and the `supply == 0` guard in
// `_removeLiquidity`, and fixed the same way: order the checks so the
// contract's own error is what the caller sees.
if (v0 < MIN_RESOLUTION || v1 < MIN_RESOLUTION) revert InsufficientLiquidity();
uint256 x = v0 + used0;
uint256 y = v1 + used1;
uint256 maxX = FixedPointMathLib.fullMulDiv(y, WAD * WAD, sl * sl);
if (x > maxX) {
used0 = maxX > v0 ? maxX - v0 : 0;
x = v0 + used0;
}
uint256 maxY = FixedPointMathLib.fullMulDiv(x, sh * sh, WAD * WAD);
if (y > maxY) used1 = maxY > v1 ? maxY - v1 : 0;
if (used0 > in0 || used1 > in1) revert InsufficientLiquidity();
}
/// @dev Uses the pool's reserve ratio, so the deposit does not move price.
function _proportional(uint256 in0, uint256 in1, uint256 r0, uint256 r1, uint256 supply)
internal
pure
returns (uint256 lp, uint256 used0, uint256 used1)
{
// An empty side does not constrain the proportional amount.
uint256 lpFrom0 = r0 == 0 ? type(uint256).max : FixedPointMathLib.fullMulDiv(in0, supply, r0);
uint256 lpFrom1 = r1 == 0 ? type(uint256).max : FixedPointMathLib.fullMulDiv(in1, supply, r1);
lp = FixedPointMathLib.min(lpFrom0, lpFrom1);
if (lp == 0 || lp == type(uint256).max) revert ZeroAmount();
used0 = r0 == 0 ? 0 : FixedPointMathLib.fullMulDivUp(lp, r0, supply);
used1 = r1 == 0 ? 0 : FixedPointMathLib.fullMulDivUp(lp, r1, supply);
if (used0 > in0 || used1 > in1) revert InsufficientLiquidity();
}
/// @notice Burn LP shares for a pro-rata slice of both reserves.
/// @dev Two things here can revert - a zero-payout burn, and a token that
/// does not credit the recipient exactly. Neither is a price guard:
/// the RANGE and TRADEABILITY postconditions that `_addLiquidity`
/// enforces are deliberately absent, because an exit blocked by where
/// the price happens to sit is a worse failure than the one such a
/// guard would prevent. See `removeLiquidityLossy` for the exit that
/// survives a token which starts taking a fee on transfer.
///
/// Unguarded by those postconditions, then, and for this reason: an
/// exit that can revert on price is a worse
/// failure than the one a guard here would prevent. Both virtual
/// reserves are floored functions of supply, so a burn can move the
/// represented price by up to one raw unit of virtual reserve even
/// though the real withdrawal is exactly proportional. On any pool
/// whose reserves are large next to one raw unit that is dust and the
/// next swap prices normally; the pathological case is a pool holding
/// less than one input unit is worth, where a burn can leave the state
/// with no executable trade until someone deposits again. The seed
/// guard keeps pools out of that regime at creation, and the state is
/// repairable by anyone with a single unit of liquidity, so it is a
/// dust-scale liveness quirk rather than a fund risk.
function removeLiquidity(uint256 lp, uint256 min0, uint256 min1, address to)
public
nonReentrant
returns (uint256 amount0, uint256 amount1)
{
return _removeLiquidity(lp, min0, min1, to);
}
/// @notice Degraded pro-rata exit for a pool whose token has turned
/// hostile: tolerates short credit, a shortfall against the
/// reserves, and one side being untransferable entirely.
///
/// @dev THE ESCAPE HATCH. `_pullExact` and `_pay` demand exact movement,
/// which is what keeps reserves honest and what makes the pool seize
/// up the moment a token stops behaving. On an immutable contract
/// that seizure is permanent, so there has to be one path out. This is
/// it, and it is built for three distinct failures - the first two of
/// which an earlier revision of this function did NOT survive:
///
/// 1. THE BALANCE FALLS WITHOUT A TRANSFER. USDT's owner can zero a
/// blacklisted holder's balance outright; a rebasing token can
/// contract; an upgrade can burn. Then `balance < reserve`, and
/// `_assertBacked` reverts - which would take down every function
/// in the contract INCLUDING this one, stranding the healthy side
/// of the pool along with the damaged one. So this path does not
/// assert backing. It clamps each payout to what the pool can
/// actually spend, which is strictly stronger: the assertion only
/// refuses when it detects a shortfall, whereas the clamp cannot
/// overpay even when the assertion would have passed. The clamp
/// is `lp/supply` of the SURVIVING balance rather than the
/// balance itself, so a shortfall is shared in proportion and
/// being first out of a damaged pool is worth nothing.
///
/// 2. ONE SIDE CANNOT BE TRANSFERRED AT ALL. A paused token, or a
/// `to` blacklisted by one issuer, reverts its leg and with it
/// the whole call - so an LP could not withdraw their ETH because
/// the USDC leg failed. `take0`/`take1` let the caller abandon a
/// side and leave through the other. The abandoned side's claim
/// is still burned and still written off the reserves: it is
/// forfeited to the remaining holders, which is a real loss and
/// the caller's decision to make.
///
/// 3. THE RECIPIENT IS CREDITED LESS THAN THE POOL IS DEBITED, i.e.
/// a fee switch flipped after deployment. `_settle` keeps the
/// debit check and drops the credit check.
///
/// RESERVES FALL BY THE FULL PRO-RATA CLAIM, NOT BY WHAT WAS PAID,
/// and that is what keeps this from becoming a bank run. Were the
/// write-down limited to what was actually transferred, the first
/// exit out of a short pool would take its claim whole and leave the
/// entire shortfall to the slowest holder. Writing off the full claim
/// gives every holder their share of the damage and makes exit order
/// irrelevant.
///
/// IT GRANTS NO NEW AUTHORITY. Still pro-rata, still burns only the
/// caller's own shares, still cannot reach accrued hook or creator
/// fees - the clamp subtracts them - and still refuses a burn that
/// pays out nothing. Under a well-behaved token it is indistinguishable
/// from `removeLiquidity`; use that one unless it is actually
/// reverting.
///
/// ONE SHAPE REMAINS UNSERVEABLE. A token that debits the pool
/// `amount + fee` - charging on top of the transfer rather than out of
/// it - still fails `_settle`'s debit check. Relaxing that to `>=`
/// would take the excess out of the balance backing other holders,
/// and writing reserves down by the larger observed debit instead pays
/// the exiting LP more than their shares. Both socialise the fee; the
/// honest position is that such a token cannot be used in a pool that
/// accounts proportionally.
/// @param take0 Whether to attempt the token0 leg. Pass false to abandon
/// that side's claim and exit through the other one alone.
/// @param take1 As `take0`, for token1.
/// @return paid0 What actually left the pool on the token0 side, which is
/// the pro-rata claim CLAMPED to what the pool can still spend, and
/// zero when `take0` is false. Under a transfer fee the recipient
/// receives less than this again.
/// @return paid1 As `paid0`, for token1.
function removeLiquidityLossy(uint256 lp, uint256 min0, uint256 min1, address to, bool take0, bool take1)
external
nonReentrant
returns (uint256 paid0, uint256 paid1)
{
if (lp == 0) revert ZeroAmount();
if (to == address(0) || to == address(this)) revert Bad();
if (!take0 && !take1) revert ZeroAmount();
uint256 r0 = reserve0;
uint256 r1 = reserve1;
// NOT `_assertBacked`. That is the whole point of this function: a
// shortfall is the condition it exists to escape, not a reason to
// refuse. Paying out is made safe by clamping to what the pool can
// actually spend, which is a stronger guarantee than the assertion -
// it cannot overpay even when the assertion would have passed.
uint256 supply = totalSupply();
if (supply == 0) revert InsufficientLiquidity();
uint256 amount0 = FixedPointMathLib.fullMulDiv(lp, r0, supply);
uint256 amount1 = FixedPointMathLib.fullMulDiv(lp, r1, supply);
if (amount0 == 0 && amount1 == 0) revert ZeroAmount();
// RESERVES FALL BY THE FULL PRO-RATA CLAIM, NOT BY WHAT WAS PAID.
// This is what stops the escape hatch becoming a bank run. If the pool
// is short, the first exit would otherwise take its claim whole and
// leave the entire shortfall to whoever is slowest; writing off the
// full claim instead makes every holder carry their share of it, and
// the exit order stops mattering. It also only ever moves reserves
// DOWN faster than balances, so what backs the remaining holders can
// only improve.
_burn(msg.sender, lp);
_setReserves(r0 - amount0, r1 - amount1);
// THE CLAMP IS PRO-RATA ON THE SURVIVING BALANCE, not on the raw
// balance. Clamping to `spendable` alone would still hand the first
// exit everything left standing - a holder with half the shares would
// take the whole remainder, because their claim exceeds it - which is
// the run this function must not create. Taking `lp/supply` of what
// actually survives instead leaves `balance/reserve` exactly where it
// was: both sides scale by `(supply - lp)/supply`, so a degraded pool
// stays a proportional claim on its real holdings and exit order
// carries no advantage at all.
//
// On a healthy pool `spendable >= reserve`, so this is `amount` and the
// clamp is invisible.
if (take0) {
paid0 = FixedPointMathLib.min(
amount0, FixedPointMathLib.fullMulDiv(lp, _spendable(token0, _owed0()), supply)
);
if (paid0 != 0) _settle(token0, to, paid0, false);
}
if (take1) {
paid1 = FixedPointMathLib.min(
amount1, FixedPointMathLib.fullMulDiv(lp, _spendable(token1, _owed1()), supply)
);
if (paid1 != 0) _settle(token1, to, paid1, false);
}
// Bounds what LEAVES THE POOL, which is the figure this path can
// actually promise. The strict exit checks the pro-rata claim instead,
// because there the two are equal by construction.
if (paid0 < min0 || paid1 < min1) revert InsufficientOutput();
if (paid0 == 0 && paid1 == 0) revert ZeroAmount();
emit RemoveLiquidity(msg.sender, lp, amount0, amount1);
}
/// @dev Hook and creator claims on each side, which no exit may spend.
///
/// Checked, for the reason `_accrueFees` states: this figure is the
/// right-hand side of the solvency test, so a wrap here reads as "the
/// pool owes almost nothing" and passes an assertion that should fail.
function _owed0() internal view returns (uint256 owed) {
if (hook != address(0)) owed = hookOwed0;
if (creatorFeeBps != 0) owed += creatorOwed0;
}
function _owed1() internal view returns (uint256 owed) {
if (hook != address(0)) owed = hookOwed1;
if (creatorFeeBps != 0) owed += creatorOwed1;
}
/// @dev What the pool could pay out right now without touching accrued
/// fees. Saturates at zero instead of reverting, because this is the
/// degraded path and a shortfall is the input, not an error.
function _spendable(address token, uint256 owed) internal view returns (uint256) {
uint256 bal = _balance(token);
unchecked {
return bal > owed ? bal - owed : 0;
}
}
function _removeLiquidity(uint256 lp, uint256 min0, uint256 min1, address to)
internal
returns (uint256 amount0, uint256 amount1)
{
if (lp == 0) revert ZeroAmount();
if (to == address(0) || to == address(this)) revert Bad();
uint256 r0 = reserve0;
uint256 r1 = reserve1;
_assertBacked(r0, r1);
uint256 supply = totalSupply();
// An unseeded pool has no shares to burn, and `_burn` below would say
// so - but the division runs first and would surface Solady's
// `MulDivFailed` instead. Same class as the `inAfterFee` guard in
// `_transitionAt`, and fixed the same way: a stated reason rather than
// a library panic. Unreachable once seeded, since `MIN_LIQUIDITY` is
// burned to the dead address and never returns supply to zero.
if (supply == 0) revert InsufficientLiquidity();
// Rounds down, so the dust stays with the holders who remain.
amount0 = FixedPointMathLib.fullMulDiv(lp, r0, supply);
amount1 = FixedPointMathLib.fullMulDiv(lp, r1, supply);
// A burn that pays out nothing on either side is refused. It is not a
// theft - the caller is destroying their own shares for free - but it
// shrinks the supply the virtual offsets are derived from while leaving
// the real reserves untouched, which walks the represented price toward
// the bare `r1/r0` ratio and, for a mid-band position, out of the band.
// Self-funded and needing on the order of `max(r0, r1)` transactions to
// matter, so not practically exploitable - but it is a free lever on the
// one invariant the whole contract is built around, and no honest caller
// wants a zero-payout withdrawal.
if (amount0 == 0 && amount1 == 0) revert ZeroAmount();
if (amount0 < min0 || amount1 < min1) revert InsufficientOutput();
_burn(msg.sender, lp);
_setReserves(r0 - amount0, r1 - amount1);
if (amount0 != 0) _pay(token0, to, amount0);
if (amount1 != 0) _pay(token1, to, amount1);
emit RemoveLiquidity(msg.sender, lp, amount0, amount1);
}
// ----------------------------------------------------------------- ERC-20
/// @dev The name hash is fixed; pool address and chain ID still separate
/// each permit domain.
function _constantNameHash() internal pure override returns (bytes32) {
return 0x97afff290dde66c4a8458ec3623f0fe8e943ac845271886a6598e35deed20617;
}
/// @notice LP token name.
function name() public pure override returns (string memory) {
return "Precision LP";
}
/// @notice LP token symbol.
function symbol() public pure override returns (string memory) {
return "pLP";
}
/// @dev Canonical Permit2 holds an infinite allowance over LP shares.
///
/// This is Solady's default, and it is restated here so it is a
/// DECISION rather than something inherited from a dependency bump: an
/// immutable pool that silently trusts a third-party contract with
/// every holder's position is not something to discover from a diff.
/// Permit2 still requires the owner's signature, so this grants no
/// party the ability to move shares unilaterally; what it accepts is
/// that a bug in Permit2 would reach LP shares as it would reach any
/// other Permit2-enabled token.
///
/// Kept enabled because it matches the stack these shares live in -
/// zRouter and zSwap already fund swaps through Permit2, and the zap
/// exists so an LP position can be exited inside a route, which is
/// exactly the flow a signature-based transfer serves. Returning false
/// here is a one-line change and costs only that convenience.
function _givePermit2InfiniteAllowance() internal pure override returns (bool) {
return true;
}
// ---------------------------------------------------------------- HELPERS
function _setReserves(uint256 r0, uint256 r1) internal {
if (r0 > type(uint128).max || r1 > type(uint128).max) revert Overflow();
(reserve0, reserve1) = (uint128(r0), uint128(r1));
}
function _balance(address token) internal view returns (uint256) {
return token == address(0) ? address(this).balance : token.balanceOf(address(this));
}
function _pullExact(address token, address from, uint256 amount) internal {
if (amount == 0) return;
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
uint256 afterBalance = token.balanceOf(address(this));
if (afterBalance < beforeBalance || afterBalance - beforeBalance != amount) revert UnsupportedToken();
}
/// @dev Returns only the SPENDABLE figures. The raw balances used to be
/// returned too, for callers to hand to `_pay`; `_settle` now measures
/// its own immediately before each transfer, so passing them around
/// only invited someone to reuse a stale one.
function _assertBacked(uint256 r0, uint256 r1)
internal
view
returns (uint256 available0, uint256 available1)
{
// Shared with the degraded exit's clamp rather than restated. What
// counts as owed is the one definition both paths have to agree on:
// if they ever drifted, one would treat fees as spendable while the
// other did not, and only the looser one would be noticed.
uint256 owed0 = _owed0();
uint256 owed1 = _owed1();
uint256 balance0 = _balance(token0);
uint256 balance1 = _balance(token1);
// The SUM is checked and the difference is not, which is the way round
// that matters. `reserve + owed` wrapping would make this comparison
// pass on a pool that is deeply insolvent - the one thing the whole
// contract is built to detect - so it must revert instead. The
// subtractions below cannot underflow once the comparison has held,
// since `balance >= reserve + owed >= owed`.
if (balance0 < r0 + owed0 || balance1 < r1 + owed1) revert BalanceDeficit();
unchecked {
(available0, available1) = (balance0 - owed0, balance1 - owed1);
}
}
/// @dev Measures its OWN before-balance rather than accepting one from the
/// caller. The callers all pay twice - both reserves, both fee sides,
/// or an output followed by a refund - and a snapshot taken once at the
/// top of those functions is already stale by the second payout. It
/// only diverges when something changes the balance mid-call, which
/// needs a token that hands control to a recipient during transfer:
/// that recipient sends the OTHER token to the pool, and this
/// reconciliation then reads its own arithmetic as a broken token and
/// reverts `UnsupportedToken` on a payout that was perfectly correct.
///
/// The reentrancy guard does not cover it. A plain ERC-20 transfer
/// INTO the pool never calls the pool, so nothing about that flow is
/// reentrant - the guard has nothing to catch, and the stale figure is
/// the only thing that goes wrong.
///
/// Reading it here costs almost nothing on any path: `_assertBacked`
/// has already touched both token contracts and this pool's own balance
/// slot in each of them, and the line below touches the token again, so
/// the extra read is warm in both the address and the slot.
function _pay(address token, address to, uint256 amount) private {
_settle(token, to, amount, true);
}
/// @dev `exactCredit` false drops ONLY the requirement that the recipient
/// be credited the full amount. The debit check is never optional: it
/// is what makes the reserve write this function's caller performs
/// true, so relaxing it would let a misbehaving token desynchronise
/// reserves from balances - the one thing the whole contract is built
/// to prevent. Reachable exclusively through `removeLiquidityLossy`.
///
/// Every caller rejects `to == address(this)`, which is what keeps the
/// two halves from describing the same balance and contradicting.
function _settle(address token, address to, uint256 amount, bool exactCredit) private {
if (token == address(0)) {
to.safeTransferETH(amount);
return;
}
uint256 senderBefore = token.balanceOf(address(this));
uint256 recipientBefore = token.balanceOf(to);
token.safeTransfer(to, amount);
uint256 senderAfter = token.balanceOf(address(this));
uint256 recipientAfter = token.balanceOf(to);
if (senderAfter > senderBefore || senderBefore - senderAfter != amount) revert UnsupportedToken();
if (recipientAfter < recipientBefore) revert UnsupportedToken();
if (exactCredit && recipientAfter - recipientBefore != amount) revert UnsupportedToken();
}
}
lib/solady/src/tokens/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/// @dev The allowance of Permit2 is fixed at infinity.
error Permit2AllowanceIsFixedAtInfinity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
/// If you need to use a different version, override `_versionHash`.
bytes32 private constant _DEFAULT_VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @dev The canonical Permit2 address.
/// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
/// Enabled by default. To disable, override `_givePermit2InfiniteAllowance()`.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return type(uint256).max;
}
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
// Code duplication is for zero-cost abstraction if possible.
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
if iszero(eq(caller(), _PERMIT2)) {
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev If you need a different value, override this function.
function _versionHash() internal view virtual returns (bytes32 result) {
result = _DEFAULT_VERSION_HASH;
}
/// @dev For inheriting contracts to increment the nonce.
function _incrementNonce(address owner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
sstore(nonceSlot, add(1, sload(nonceSlot)))
}
}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && value != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PERMIT2 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
///
/// This value should be kept constant after contract initialization,
/// or else the actual allowance values may not match with the {Approval} events.
/// For best performance, return a compile-time constant for zero-cost abstraction.
function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
return true;
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` does not implement `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented :=
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/pools/PriceTape.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @title PriceTape
/// @notice Compressed on-chain OHLCV history: a chart any client can read with
/// `eth_call`, with no indexer, no subgraph and no trusted server.
/// @dev A public good, not a private feature. Any contract that knows the price
/// of something can adopt this by holding a `Tape` and calling `print` —
/// AMM pools, orderbooks, auctions, oracles. Readers only need
/// `IPriceTape` (below) and the pure decoders here, so one chart client
/// works against every adopter.
///
/// DESIGN
/// Logs are the usual home for trade history, but reading them requires an
/// indexer, which is exactly the centralised dependency a decentralised
/// exchange should not have. Storage is readable by anyone with an RPC
/// forever, so this pays gas to keep the data reachable from chain state.
///
/// The cost floor is one `SSTORE` per trade. Everything here exists to
/// avoid exceeding it:
///
/// - A bar is ONE slot, so a trade writes once and never grows.
/// - Prices are 4-byte floats (24-bit mantissa, 8-bit binary exponent):
/// ~7 significant digits over any range a real pair reaches, where
/// fixed-point would spend most of its bits on magnitudes that never
/// occur.
/// - The ring is indexed by `bucket % length`, so a bucket in which nobody
/// traded costs nothing and leaves a hole rather than a write.
/// - Ring slots are rewritten every lap, so after the first lap every
/// store is the 5,000-gas non-zero case, never the 22,100-gas init.
///
/// Coarse candles are exact aggregations of fine ones, so adopters should
/// keep one fine tape plus one coarse tape and let clients roll up the
/// rest. Storing a ring per timeframe would multiply the per-trade write,
/// which is the one number worth protecting.
library PriceTape {
/// @dev A bar occupies a single 256-bit slot:
///
/// bits 0..31 bucket uint32 unix / period, 0 means empty
/// bits 32..63 open float32
/// bits 64..95 high float32
/// bits 96..127 low float32
/// bits 128..159 close float32
/// bits 160..191 volume float32 base-token volume in this bar
/// bits 192..207 count uint16 trades, saturating
/// bits 208..255 unused
///
/// `open` is stored rather than inferred from the previous bar's close
/// because a ring with holes has no reliable previous bar.
///
/// The ring is a FIXED 256 entries rather than a dynamic array. A
/// dynamic ring costs a cold `SLOAD` of its length plus a bounds check
/// on every rollover, and buys nothing an adopter wants: the period is
/// still theirs to choose, and 256 bars is the useful depth at any of
/// them - 21 hours at five minutes, 42 days at four hours. Fixing it
/// also makes `bucket % 256` a mask, computes the slot without a
/// length read, and removes the two length stores from construction.
/// @dev Ring depth. A power of two so the index is a mask, not a division.
uint256 internal constant BARS = 256;
struct Tape {
/// @dev Bar currently accumulating; also the newest bar.
uint256 live;
/// @dev Finalised bars, indexed by `bucket % BARS`.
uint256[BARS] ring;
}
/// @dev Trade counter saturates rather than wrapping into the volume field.
uint256 internal constant MAX_COUNT = type(uint16).max;
/// @notice Compress a value to a 4-byte float: `mantissa << exponent`.
/// @dev Relative error is below 2**-23 (~1.2e-7), which is far finer than
/// any chart pixel, and the representable range covers every price a
/// 1e18-scaled pair can produce.
///
/// IT TRUNCATES RATHER THAN ROUNDS, so the error is one-sided: every
/// packed value is at or below the real one, `high` included, where a
/// bias upward would be the conservative direction. Immaterial at
/// chart resolution and not worth the branch, but it is a bias and not
/// the symmetric error the bound above sounds like.
///
/// `pack(0) == 0`, and that interacts with `low`. A bar whose `low`
/// takes a zero can never be raised again - `if (p < lowP)` will not
/// lift it - so a single trade whose price underflows the 1e18 scale
/// pins the bar's low at zero for its whole life and `fold` carries it
/// into the coarse candle. On an adopter whose prices can legitimately
/// round to zero that turns "charts flat" into "charts a spike to
/// zero".
function pack(uint256 v) internal pure returns (uint32) {
if (v == 0) return 0;
uint256 msb = _msb(v);
if (msb < 24) return uint32(v); // exponent 0, exact
uint256 shift;
unchecked {
shift = msb - 23; // keep 24 significant bits
}
return uint32((shift << 24) | (v >> shift));
}
/// @notice Expand a 4-byte float back to an integer.
/// @dev Lossy in the low bits by construction; never reverts.
///
/// TOTAL ONLY BECAUSE `pack` IS ITS SOLE PRODUCER. The shift is
/// unchecked, and `pack` can never emit an exponent above 232 - the
/// msb of a uint256 is at most 255 and it keeps 23 - so the worst case
/// is `(2**24 - 1) << 232`, just under 2**256. `decode` is advertised
/// as a reader for ANY adopter's bars, so a client feeding it a
/// hand-built word rather than one this library produced is outside
/// that argument and can wrap.
function unpack(uint32 p) internal pure returns (uint256) {
unchecked {
return uint256(p & 0xffffff) << (p >> 24);
}
}
/// @notice Index of the highest set bit of a non-zero value.
function _msb(uint256 x) private pure returns (uint256 r) {
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
r := or(r, shl(2, lt(0xf, shr(r, x))))
r := or(r, shl(1, lt(0x3, shr(r, x))))
r := or(r, lt(0x1, shr(r, x)))
}
}
// ------------------------------------------------------------------ codec
function encode(uint32 bucket, uint32 open, uint32 high, uint32 low, uint32 close, uint32 volume, uint16 count)
internal
pure
returns (uint256 bar)
{
unchecked {
bar = uint256(bucket) | (uint256(open) << 32) | (uint256(high) << 64) | (uint256(low) << 96)
| (uint256(close) << 128) | (uint256(volume) << 160) | (uint256(count) << 192);
}
}
function bucketOf(uint256 bar) internal pure returns (uint32) {
return uint32(bar);
}
/// @notice Decode a bar into chart-ready integers.
/// @dev `bucket == 0` marks an empty slot; the other fields are then zero.
function decode(uint256 bar)
internal
pure
returns (uint32 bucket, uint256 open, uint256 high, uint256 low, uint256 close, uint256 volume, uint16 count)
{
bucket = uint32(bar);
open = unpack(uint32(bar >> 32));
high = unpack(uint32(bar >> 64));
low = unpack(uint32(bar >> 96));
close = unpack(uint32(bar >> 128));
volume = unpack(uint32(bar >> 160));
count = uint16(bar >> 192);
}
// ------------------------------------------------------------------ write
/// @notice Record a trade at `price` for `volume` of the base token.
/// @dev Exactly one storage write in the common case, plus one more on the
/// first trade of a new bucket. `price` is the EXECUTED price — what
/// actually traded, including fee and slippage — which is what a tape
/// should show, rather than an untradeable mid.
/// @param period Bar width in seconds; must be non-zero.
///
/// THE BUCKET IS A uint32 OF `block.timestamp / period`, so the
/// period an adopter picks decides when the tape wraps. At five
/// minutes that is somewhere past the year 40,000; at `period = 1`
/// it is 2106. This is a public-good library and the choice is the
/// adopter's, so it is stated here rather than assumed away.
/// `fold` casts to `uint32` on the same arithmetic and truncates
/// silently if anyone ever folds with `srcPeriod > period`.
/// @return finalised The bar just closed and moved to the ring, or zero if
/// this trade landed in the bar already open. Adopters cascade this
/// into a coarser tape with `fold`, which is what keeps a trade at
/// one write no matter how many timeframes are kept.
function print(Tape storage self, uint256 price, uint256 volume, uint256 period)
internal
returns (uint256 finalised)
{
uint32 bucket = uint32(block.timestamp / period);
// Bucket 0 marks an empty slot, so never write one. Only reachable in
// the first `period` seconds of 1970, i.e. tests with a zeroed clock.
if (bucket == 0) return 0;
uint256 live = self.live;
uint32 p = pack(price);
if (bucketOf(live) != bucket) {
// Roll the finished bar into the ring, then open a fresh one. A
// ring position is reused every lap, so this store is the cheap
// non-zero case once the tape has run for one full lap.
if (live != 0) {
self.ring[bucketOf(live) & (BARS - 1)] = live;
finalised = live;
}
self.live = encode(bucket, p, p, p, p, pack(volume), 1);
return finalised;
}
// Update the extremes IN PACKED SPACE. The float format is
// `exponent << 24 | mantissa` with the mantissa normalised to 24 bits,
// which makes the packed integer MONOTONIC in the value it encodes: a
// larger exponent always outranks a smaller one, equal exponents
// compare by mantissa, and any value below 2**24 encodes with exponent
// zero and so sorts below every value above it. Comparing packed
// therefore gives exactly the same answer as comparing unpacked, while
// avoiding the unpack-compare-repack round trip for open, high, and
// low. Only volume needs real arithmetic, so only volume is expanded.
uint32 openP = uint32(live >> 32);
uint32 highP = uint32(live >> 64);
uint32 lowP = uint32(live >> 96);
if (p > highP) highP = p;
// `low` starts at the bar's open, so it is only zero for a zero price.
if (p < lowP) lowP = p;
uint256 vol = unpack(uint32(live >> 160));
uint16 count = uint16(live >> 192);
unchecked {
self.live = encode(
bucket, openP, highP, lowP, p, pack(vol + volume), count < MAX_COUNT ? count + 1 : uint16(MAX_COUNT)
);
}
}
/// @notice Merge a finished bar from a finer tape into this coarser one.
/// @dev Aggregating is exact: a four-hour candle built from forty-eight
/// five-minute candles is the same candle the trades would have
/// produced directly. So a coarse tape costs one write per FINE bar,
/// not one per trade, and keeping several timeframes stays affordable.
/// @param bar A bar returned by `print` on the finer tape.
/// @param srcPeriod The finer tape's bar width, to recover the wall clock.
/// @param period This tape's bar width.
/// @return finalised The coarse bar just closed, for cascading further.
function fold(Tape storage self, uint256 bar, uint256 srcPeriod, uint256 period)
internal
returns (uint256 finalised)
{
if (bar == 0 || period == 0 || srcPeriod == 0) return 0;
uint32 bucket = uint32((uint256(bucketOf(bar)) * srcPeriod) / period);
if (bucket == 0) return 0;
// Same packed-space treatment as `print`: the source bar's fields are
// already in this format, so a fold is masks and comparisons rather
// than a decode and a re-encode. Volume alone is expanded, because
// summing it is real arithmetic.
uint32 oP = uint32(bar >> 32);
uint32 hP = uint32(bar >> 64);
uint32 lP = uint32(bar >> 96);
uint32 cP = uint32(bar >> 128);
uint256 v = unpack(uint32(bar >> 160));
uint16 n = uint16(bar >> 192);
uint256 live = self.live;
if (bucketOf(live) != bucket) {
if (live != 0) {
self.ring[bucketOf(live) & (BARS - 1)] = live;
finalised = live;
}
self.live = encode(bucket, oP, hP, lP, cP, pack(v), n);
return finalised;
}
uint32 openP = uint32(live >> 32);
uint32 highP = uint32(live >> 64);
uint32 lowP = uint32(live >> 96);
if (hP > highP) highP = hP;
if (lP < lowP) lowP = lP;
uint256 vol = unpack(uint32(live >> 160));
uint16 count = uint16(live >> 192);
unchecked {
uint256 total = uint256(count) + n;
self.live = encode(
bucket, openP, highP, lowP, cP, pack(vol + v), total < MAX_COUNT ? uint16(total) : uint16(MAX_COUNT)
);
}
}
// ------------------------------------------------------------------- read
/// @notice The newest `count` bars, newest first, as raw packed slots.
/// @dev Buckets with no trades are returned as zero, so a caller can tell a
/// flat market from an idle one. Callers decode with `decode`.
function recent(Tape storage self, uint256 period, uint256 count) internal view returns (uint256[] memory bars) {
// Bounded before allocating. `count` arrives from the caller through
// `IPriceTape.tape`, and a large one blows memory before the loop even
// starts. Nothing above the ring depth can be anything but zero, so the
// excess was never information - it was only a way to make a `view`
// that other contracts read run out of gas.
if (count > BARS) count = BARS;
bars = new uint256[](count);
if (count == 0 || period == 0) return bars;
uint256 live = self.live;
uint256 newest = uint256(uint32(block.timestamp / period));
// A DORMANT POOL'S LAST BAR IS IN NEITHER PLACE, so return it here or
// it is unreachable. The live bar only reaches the ring when the NEXT
// trade finalises it, and the walk below matches buckets against the
// wall clock - so once trading stops and `newest` advances past it, the
// final bar is not in the window and not in the ring. Past `BARS`
// periods of quiet its slot has been lapped or never written, and no
// value of `count` recovers it.
//
// That is exactly the case the zero-encoding exists to distinguish: a
// reader could not tell "never traded" from "traded, then went quiet",
// which is the one question a chart of a dormant market has to answer.
//
// Placing it at index 0 does not corrupt the time axis, because every
// bar carries its own `bucket` and a client reads position from that
// rather than from the array index. The index is newest-first ordering,
// not a timestamp.
if (live != 0 && bucketOf(live) < newest - (newest < count ? newest : count - 1)) {
bars[0] = live;
return bars;
}
for (uint256 i; i != count; ++i) {
if (i > newest) break; // before the epoch of this period
uint256 bucket = newest - i;
if (bucket == bucketOf(live) && live != 0) {
bars[i] = live;
continue;
}
// Bucket zero is never written, so it can never match a slot.
if (bucket == 0) continue;
uint256 bar = self.ring[bucket & (BARS - 1)];
// A ring slot holds whatever bucket last mapped to it, which may be
// a full lap old. Only accept it if it is the bucket asked for.
if (bucketOf(bar) == bucket) bars[i] = bar;
}
}
}
/// @title IPriceTape
/// @notice Minimal read interface for charting any adopting contract.
///
/// @dev NOT AN ORACLE. A tape records what an adopter printed, and an adopter
/// prints executed trades - so a bar costs whatever the smallest trade on
/// that venue costs, and `high`/`low` are extrema that one such trade
/// fixes for the life of the bar. Nothing here is time-weighted, nothing
/// is manipulation-resistant, and an adopter is free to print whatever it
/// likes. Read it to draw a candlestick. Do not settle, liquidate,
/// collateralise, or price anything against it.
/// @dev Deliberately tiny: one call returns everything a candlestick chart
/// needs. A client that speaks this interface can chart every adopter
/// without knowing anything else about them, which is what makes this a
/// standard rather than one protocol's feature.
interface IPriceTape {
/// @notice Bar widths this contract records, in seconds, finest first.
function tapePeriods() external view returns (uint256[] memory);
/// @notice The newest `count` bars for `period`, newest first, packed.
/// @dev Zero entries are buckets in which nothing traded. Decode with
/// `PriceTape.decode`: (bucket, open, high, low, close, volume, count).
///
/// Prices are RAW `token1` per RAW `token0`, scaled by 1e18, so a bar
/// is direction-free. Token decimals are NOT normalised: a client
/// charting a non-18-decimal pair must apply the decimal difference
/// itself, from `tapePair()`. (An earlier version of this line claimed
/// the opposite; the adopters never did it, and the doc is the spec for
/// an interface whose whole point is that one client reads every
/// implementation, so it is the doc that was wrong.)
///
/// Volume is in `token0` units, and it is a LOWER BOUND rather than a
/// measurement. Each accumulation re-packs the running total into the
/// 24-bit mantissa of a float32, so once a bar's total passes 2**n an
/// individual trade below 2**(n-24) adds exactly zero, and `fold`
/// compounds the same truncation into the coarse bar. The relative
/// error is under ~1.2e-7 per accumulation and invisible on a chart,
/// which is what this field is for; do not settle anything against it.
///
/// A COARSE BAR LAGS BY ONE FINE BAR. Coarse bars are folded from fine
/// bars only as those finish, so the live fine bar - up to one fine
/// period of the most recent trading - is never included in the coarse
/// tape. Read the fine tape for the leading edge.
function tape(uint256 period, uint256 count) external view returns (uint256[] memory);
/// @notice The pair a tape prices, as (base, quote). Native asset is address(0).
function tapePair() external view returns (address base, address quote);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.