Verified contractPartialBUSL-1.1
V3PositionLogic
Address0xabfabec60666a65f48957bef2b22dd282adc004d
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,423,238
- Creation transaction
- 0x719efd2534…031d086f68
- Libraries
- project/contracts/vaults/libraries/ShapeMath.sol:ShapeMath0x9b33…619edbproject/contracts/vaults/libraries/BaseLimitMath.sol:BaseLimitMath0xb120…91b7e7
26 files
- project/contracts/vaults/libraries/V3PositionLogic.solmain27.66 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol4.45 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC165.sol193 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20.sol182 B
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol13.31 KB
- npm/@openzeppelin/[email protected]/utils/Panic.sol1.97 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
- npm/@openzeppelin/[email protected]/utils/math/Math.sol32.66 KB
- npm/@openzeppelin/[email protected]/utils/math/SafeCast.sol34.94 KB
- project/contracts/interfaces/IAggregatorV3.sol424 B
- project/contracts/interfaces/IHorizonMintable.sol290 B
- project/contracts/interfaces/IUniswapV3Minimal.sol5.61 KB
- project/contracts/libraries/PoolLastGood.sol2.52 KB
- project/contracts/libraries/PoolMath.sol6.89 KB
- project/contracts/libraries/PriceOracle.sol11.89 KB
- project/contracts/libraries/TickMath.sol3.32 KB
- project/contracts/vaults/interfaces/IClearing.sol762 B
- project/contracts/vaults/interfaces/IRehypoLendingPool.sol807 B
- project/contracts/vaults/libraries/BaseLimitMath.sol5.6 KB
- project/contracts/vaults/libraries/LiquidityAmounts.sol5.15 KB
- project/contracts/vaults/libraries/PriceLib.sol4.13 KB
- project/contracts/vaults/libraries/Range.sol298 B
- project/contracts/vaults/libraries/ShapeMath.sol6.07 KB
- project/contracts/vaults/libraries/ShareHookDispatch.sol3.43 KB
- project/contracts/vaults/libraries/VaultConfigChecks.sol7.73 KB
project/contracts/vaults/libraries/V3PositionLogic.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "../../libraries/PriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../../interfaces/IUniswapV3Minimal.sol";
import "./Range.sol";
import "./LiquidityAmounts.sol";
import "./ShapeMath.sol";
import "./BaseLimitMath.sol";
import "./PriceLib.sol";
import "../interfaces/IRehypoLendingPool.sol";
import {ShareHookDispatch, IVaultHolderFeeHook} from "./ShareHookDispatch.sol";
import {VaultConfigChecks} from "./VaultConfigChecks.sol";
import "../interfaces/IClearing.sol";
/// @dev The vault's self-only mint entrypoint, kept on the vault so the mint callback guard sits with `pool.mint`.
interface IV3VaultMint {
function mintPosition(int24 tickLower, int24 tickUpper, uint128 liquidity) external;
}
/// @notice The guard's idle trigger, so the vault's swap rule and the guard's signal share one dial.
interface IGuardIdleTrigger {
function idleTriggerBps(address vault) external view returns (uint256);
}
/// @notice Vault state the idle signal reads through a self-call.
interface IVaultState {
function totalSupply() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function lendingPool() external view returns (address);
}
/// @title V3PositionLogic
/// @notice `V3Vault`'s position, deploy, swap, rehypothecation and oracle bodies, linked as an external library.
/// @dev Runs by delegatecall, so storage and `address(this)` are the vault's.
library V3PositionLogic {
using SafeERC20 for IERC20;
uint128 internal constant MAX_U128 = type(uint128).max;
/// @notice A fee-growth read failed for a position holding liquidity.
error FeeGrowthUnreadable();
/// @notice Same signature as `VaultCore.RebalancingIsPaused`.
error RebalancingIsPaused();
/// @notice During `globalPause`, reverts unless `caller` is a compounding account of this vault on `ledger`.
function requirePausedRealiser(address ledger, address caller) external view {
if (ledger == address(0) || !IVaultHolderFeeHook(ledger).isCompounding(address(this), caller)) {
revert RebalancingIsPaused();
}
}
/// @notice Poke every position (zero-liquidity burn realises its fees) and collect them.
function realiseAndCollectAll(Range[] storage ranges, address pool)
external
returns (uint256 fee0, uint256 fee1)
{
uint256 count = ranges.length;
for (uint256 i = 0; i < count; i++) {
if (_dup(ranges, i)) continue;
Range storage r = ranges[i];
// burn(0) on a never-minted position reverts "NP", so only poke live liquidity;
// `collect` has no NP check, so owed fees are still collected.
if (_liquidityOf(pool, r.tickLower, r.tickUpper) != 0) IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, 0);
(uint128 c0, uint128 c1) =
IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, MAX_U128, MAX_U128);
fee0 += c0;
fee1 += c1;
}
}
/// @notice Burn a pro-rata slice of every position plus idle, pay `to`, and report fees apart from principal.
/// @dev A touch realises all of a position's fees, so they are routed, not paid to the withdrawer.
function withdrawProRata(
Range[] storage ranges,
address pool,
IERC20 token0,
IERC20 token1,
uint256 shares,
uint256 supply,
address to
) external returns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) {
// Idle measured before burning, so this withdrawal's proceeds are not paid twice.
uint256 idle0 = Math.mulDiv(token0.balanceOf(address(this)), shares, supply);
uint256 idle1 = Math.mulDiv(token1.balanceOf(address(this)), shares, supply);
uint256 count = ranges.length;
for (uint256 i = 0; i < count; i++) {
if (_dup(ranges, i)) continue;
Range storage r = ranges[i];
uint128 liquidity = _liquidityOf(pool, r.tickLower, r.tickUpper);
uint128 outLiquidity = uint128(Math.mulDiv(liquidity, shares, supply));
// A zero slice burns nothing but still collects what the position owes.
uint256 principal0;
uint256 principal1;
if (outLiquidity != 0) {
(principal0, principal1) = IUniswapV3PoolActions(pool).burn(r.tickLower, r.tickUpper, outLiquidity);
}
(uint128 collected0, uint128 collected1) =
IUniswapV3PoolActions(pool).collect(address(this), r.tickLower, r.tickUpper, MAX_U128, MAX_U128);
fee0 += collected0 - principal0;
fee1 += collected1 - principal1;
amount0 += principal0;
amount1 += principal1;
}
amount0 += idle0;
amount1 += idle1;
// A whole-supply exit also takes the collected fees; unrouted on the paused path, they would
// otherwise go to the next depositor.
if (shares == supply) {
(amount0, amount1, fee0, fee1) = (amount0 + fee0, amount1 + fee1, 0, 0);
}
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
}
/// @notice Deploys the idle balance as floor, base and limit; the limit side is forced by the leftover inventory.
/// @dev Each leftover read after a mint is exact, since the callback has already pulled the tokens.
function deployIdleCapital(
Range[] storage ranges,
address pool,
IERC20 token0,
IERC20 token1,
int24 baseThreshold,
int24 limitThreshold,
uint32 twapWindow,
uint16 fullRangeBps
) external {
uint256 budget0 = token0.balanceOf(address(this));
uint256 budget1 = token1.balanceOf(address(this));
if (budget0 == 0 && budget1 == 0) return;
(uint160 sqrtP,,,,,,) = IUniswapV3PoolState(pool).slot0();
// The full-range floor first: `fullRangeBps` of the budget in both tokens, at `ranges[2]` when listed.
if (ranges.length >= 3 && fullRangeBps > 0) {
Range storage full = ranges[2];
uint128 fullL = LiquidityAmounts.getLiquidityForAmounts(
sqrtP, ShapeMath.sqrtRatioAtTick(full.tickLower), ShapeMath.sqrtRatioAtTick(full.tickUpper),
(budget0 * fullRangeBps) / BPS, (budget1 * fullRangeBps) / BPS
);
if (fullL > 0) {
IV3VaultMint(address(this)).mintPosition(full.tickLower, full.tickUpper, fullL);
budget0 = token0.balanceOf(address(this));
budget1 = token1.balanceOf(address(this));
}
}
Range storage base = ranges[0];
uint128 baseL = LiquidityAmounts.getLiquidityForAmounts(
sqrtP, ShapeMath.sqrtRatioAtTick(base.tickLower), ShapeMath.sqrtRatioAtTick(base.tickUpper), budget0, budget1
);
if (baseL > 0) IV3VaultMint(address(this)).mintPosition(base.tickLower, base.tickUpper, baseL);
if (ranges.length < 2) return;
Range storage limit = ranges[1];
uint256 left0 = token0.balanceOf(address(this));
uint256 left1 = token1.balanceOf(address(this));
if (_liquidityOf(pool, limit.tickLower, limit.tickUpper) > 0) {
// Top-up the existing limit side. Single-sided, so only its one relevant token is used.
uint128 addL = LiquidityAmounts.getLiquidityForAmounts(
sqrtP, ShapeMath.sqrtRatioAtTick(limit.tickLower), ShapeMath.sqrtRatioAtTick(limit.tickUpper), left0, left1
);
if (addL > 0) IV3VaultMint(address(this)).mintPosition(limit.tickLower, limit.tickUpper, addL);
return;
}
// Fresh limit: bid below both spot and TWAP, ask above both, so it never straddles spot and a spot nudge
// only pushes it away from the TWAP. A side not single-sided at spot is skipped; the larger side deploys.
(int24 spotTick, int24 twapTick, bool ok) = spotAndTwapTick(pool, twapWindow);
int24 spacing = IUniswapV3PoolState(pool).tickSpacing();
(,, int24 bidLower, int24 bidUpper,,) =
BaseLimitMath.ranges(ok && twapTick < spotTick ? twapTick : spotTick, spacing, baseThreshold, limitThreshold);
(,,,, int24 askLower, int24 askUpper) =
BaseLimitMath.ranges(ok && twapTick > spotTick ? twapTick : spotTick, spacing, baseThreshold, limitThreshold);
uint128 bidL = sqrtP >= ShapeMath.sqrtRatioAtTick(bidUpper)
? LiquidityAmounts.getLiquidityForAmount1(ShapeMath.sqrtRatioAtTick(bidLower), ShapeMath.sqrtRatioAtTick(bidUpper), left1)
: 0;
uint128 askL = sqrtP <= ShapeMath.sqrtRatioAtTick(askLower)
? LiquidityAmounts.getLiquidityForAmount0(ShapeMath.sqrtRatioAtTick(askLower), ShapeMath.sqrtRatioAtTick(askUpper), left0)
: 0;
if (bidL == 0 && askL == 0) return;
(int24 l, int24 u, uint128 lim) = bidL > askL ? (bidLower, bidUpper, bidL) : (askLower, askUpper, askL);
// Never put the limit on the base's or floor's tick pair (the pool keys positions on the pair).
if ((l == base.tickLower && u == base.tickUpper)
|| (ranges.length >= 3 && l == ranges[2].tickLower && u == ranges[2].tickUpper)) return;
limit.tickLower = l;
limit.tickUpper = u;
IV3VaultMint(address(this)).mintPosition(l, u, lim);
}
function _liquidityOf(address pool, int24 tickLower, int24 tickUpper) private view returns (uint128 liquidity) {
(liquidity,,,,) =
IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), tickLower, tickUpper)));
}
/// @notice True when `centerTick` is within one base-width (at most 100 spacings) plus a spacing of a tick bound.
/// @dev Computed in int256 so the sum cannot overflow int24.
function centerNearBound(int24 centerTick, int24 baseThreshold, int24 tickSpacing) external pure returns (bool) {
int256 spacing = int256(tickSpacing);
int256 margin = (int256(baseThreshold) < 100 * spacing ? int256(baseThreshold) : 100 * spacing) + spacing;
int256 c = int256(centerTick);
return c - margin < int256(BaseLimitMath.MIN_TICK) || c + margin > int256(BaseLimitMath.MAX_TICK);
}
/// @notice Plan shape check: 1 = two entries share a tick pair; 2 = a third entry is not the weight-0 floor.
function validateRanges(Range[] storage ranges) external view returns (uint8) {
uint256 n = ranges.length;
for (uint256 i = 1; i < n; i++) {
if (_dup(ranges, i)) return 1;
}
if (n == 3 && (ranges[2].weightBps != 0 || !BaseLimitMath.isFullBand(ranges[2].tickLower, ranges[2].tickUpper))) {
return 2;
}
return 0;
}
/// @dev True when `ranges[i]` repeats an earlier tick pair; the pool keys positions on the pair, so every walk
/// skips duplicates to avoid double counting.
function _dup(Range[] storage ranges, uint256 i) private view returns (bool) {
int24 lo = ranges[i].tickLower;
int24 hi = ranges[i].tickUpper;
for (uint256 j = 0; j < i; j++) {
if (ranges[j].tickLower == lo && ranges[j].tickUpper == hi) return true;
}
return false;
}
uint256 internal constant BPS = 10_000;
/// @dev Reported for a vault with no positions and only dust: above BPS, so the guard reads nothing idle.
uint256 internal constant NO_POSITIONS = BPS + 1;
/// @dev An adjacent limit counts as productive up to this multiple of the in-range value beside it,
/// so dust cannot make a one-sided vault read fully productive.
uint256 internal constant ADJACENT_CAP_X = 2;
/// @dev With no positions, raw and parked value under 1 bp of the supply's face value is dust.
uint256 internal constant DUST_SHARES_PER_VALUE = 1e3 * BPS;
/// @notice Everything the shares claim, with range legs valued at `sqrtPriceX96`, plus owed, idle and parked.
function totalAmountsAt(
Range[] storage ranges,
address pool,
IERC20 token0,
IERC20 token1,
address lendingPool,
uint160 sqrtPriceX96
) public view returns (uint256 amount0, uint256 amount1) {
uint256 count = ranges.length;
for (uint256 i = 0; i < count; i++) {
if (_dup(ranges, i)) continue;
Range storage r = ranges[i];
(uint128 liquidity,,, uint128 owed0, uint128 owed1) = IUniswapV3PoolActions(pool).positions(
keccak256(abi.encodePacked(address(this), r.tickLower, r.tickUpper))
);
if (liquidity > 0) {
(uint256 a0, uint256 a1) = ShapeMath.amountsForLiquidity(
sqrtPriceX96, ShapeMath.sqrtRatioAtTick(r.tickLower), ShapeMath.sqrtRatioAtTick(r.tickUpper), liquidity
);
amount0 += a0;
amount1 += a1;
}
amount0 += owed0;
amount1 += owed1;
}
amount0 += token0.balanceOf(address(this)) + _parkedOf(lendingPool, token0);
amount1 += token1.balanceOf(address(this)) + _parkedOf(lendingPool, token1);
}
/// @notice Stores the vault's value at each deposit valuation point (TWAP, block start, spot, and the spot
/// composition at TWAP and block start); returns the TWAP price and spot composition.
function depositQuote(
Range[] storage ranges,
address pool,
IERC20 token0,
IERC20 token1,
address lendingPool,
uint160 sqrtTwap
) external returns (uint256 twapPrice, uint256 existing0, uint256 existing1) {
(uint160 sqrtSpot,,,,,,) = IUniswapV3PoolState(pool).slot0();
// Block-start price from the one-second TWAP, which nothing in this block can move; a buffer that
// cannot serve it reverts (`OLD`) and refuses the deposit.
uint32[] memory ago = new uint32[](2);
ago[0] = 1;
(int56[] memory cum,) = IUniswapV3PoolState(pool).observe(ago);
uint160 sqrtStart = ShapeMath.sqrtRatioAtTick(int24(cum[1] - cum[0]));
uint160[5] memory at = [sqrtTwap, sqrtStart, sqrtSpot, sqrtTwap, sqrtStart];
// Spot third, so existing0/existing1 end as the spot composition the zap sizes against.
for (uint256 i; i < 5; ++i) {
if (i < 3) (existing0, existing1) = totalAmountsAt(ranges, pool, token0, token1, lendingPool, at[i]);
uint256 price = PriceLib.priceFromSqrt(at[i]);
if (i == 0) twapPrice = price;
PriceLib.storeQuote(i, price, PriceLib.valueInToken1(existing0, existing1, price));
}
}
/// @notice The lowest share count over the quote `depositQuote` stored.
function quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) external view returns (uint256) {
return PriceLib.quotedShares(amount0, amount1, supply, virtualAssets);
}
/// @dev Idle trigger used when the guard has no dial or none is wired.
uint256 internal constant DEFAULT_IDLE_TRIGGER_BPS = 5_000;
/// @notice Why the vault needs a recenter: 1 TWAP outside its concentrated ranges, 2 productive share under the
/// idle trigger, 0 neither. Read before the unwind, so only a vault that needed it swaps.
function recenterNeeded(Range[] storage ranges, address pool, address clearing, int24 limitThreshold, address guard)
external
view
returns (uint8)
{
if (clearing == address(0)) return 0;
int24 twapTick;
try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
twapTick = t;
} catch {
return 0;
}
int24 lo = type(int24).max;
int24 hi = type(int24).min;
for (uint256 i = 0; i < ranges.length; i++) {
Range storage r = ranges[i];
if (r.weightBps == 0 && BaseLimitMath.isFullBand(r.tickLower, r.tickUpper)) continue;
if (r.tickLower < lo) lo = r.tickLower;
if (r.tickUpper > hi) hi = r.tickUpper;
}
if (lo <= hi && (twapTick < lo || twapTick > hi)) return 1;
uint256 trigger = DEFAULT_IDLE_TRIGGER_BPS;
if (guard.code.length > 0) {
try IGuardIdleTrigger(guard).idleTriggerBps(address(this)) returns (uint256 t) {
if (t > 0) trigger = t;
} catch {}
}
return _productiveShare(ranges, pool, twapTick, limitThreshold) < trigger ? 2 : 0;
}
/// @notice Bps of concentrated value at TWAP that is in range, plus adjacent limits up to `ADJACENT_CAP_X`.
/// @dev The floor and raw balances are excluded; no clearing or a cold oracle returns BPS.
function productiveShareBps(Range[] storage ranges, address pool, address clearing, int24 limitThreshold)
external
view
returns (uint256)
{
if (clearing == address(0)) return BPS;
int24 twapTick;
try IClearing(clearing).twapTick(address(this)) returns (int24 t) {
twapTick = t;
} catch {
return BPS;
}
return _productiveShare(ranges, pool, twapTick, limitThreshold);
}
function _productiveShare(Range[] storage ranges, address pool, int24 twapTick, int24 limitThreshold)
private
view
returns (uint256)
{
uint160 sqrtTwap = ShapeMath.sqrtRatioAtTick(twapTick);
uint256 priceX = PriceLib.priceFromSqrt(sqrtTwap);
(, int24 spotTick,,,,,) = IUniswapV3PoolState(pool).slot0();
uint256 inRange;
uint256 adjacent;
uint256 total;
uint256 count = ranges.length;
for (uint256 i = 0; i < count; i++) {
if (_dup(ranges, i)) continue;
Range storage r = ranges[i];
if (r.weightBps == 0 && BaseLimitMath.isFullBand(r.tickLower, r.tickUpper)) continue; // the floor
uint128 liquidity = _liquidityOf(pool, r.tickLower, r.tickUpper);
if (liquidity == 0) continue;
(uint256 a0, uint256 a1) = ShapeMath.amountsForLiquidity(
sqrtTwap, ShapeMath.sqrtRatioAtTick(r.tickLower), ShapeMath.sqrtRatioAtTick(r.tickUpper), liquidity
);
uint256 v = PriceLib.valueInToken1(a0, a1, priceX);
total += v;
if (twapTick >= r.tickLower && twapTick < r.tickUpper) {
inRange += v;
} else if (_gap(r, twapTick) <= limitThreshold || _gap(r, spotTick) <= limitThreshold) {
adjacent += v;
}
}
if (total == 0) return _noConcentratedLiquidity(priceX);
uint256 cap = inRange * ADJACENT_CAP_X;
uint256 productive = inRange + (adjacent < cap ? adjacent : cap);
return (productive * BPS) / total;
}
/// @dev With no concentrated liquidity: `NO_POSITIONS` for no shares or only dust, else 0 (wholly idle).
function _noConcentratedLiquidity(uint256 priceX) private view returns (uint256) {
IVaultState v = IVaultState(address(this));
uint256 supply = v.totalSupply();
if (supply == 0) return NO_POSITIONS;
IERC20 t0 = IERC20(v.token0());
IERC20 t1 = IERC20(v.token1());
address lp = v.lendingPool();
uint256 raw = PriceLib.valueInToken1(
t0.balanceOf(address(this)) + _parkedOf(lp, t0), t1.balanceOf(address(this)) + _parkedOf(lp, t1), priceX
);
return raw * DUST_SHARES_PER_VALUE < supply ? NO_POSITIONS : 0;
}
/// @dev Ticks between `tick` and the nearest edge of `r`; 0 inside.
function _gap(Range storage r, int24 tick) private view returns (int24) {
if (tick < r.tickLower) return r.tickLower - tick;
if (tick >= r.tickUpper) return tick - r.tickUpper + 1;
return 0;
}
/// @dev Parked inventory for `token`; a reverting pool counts as 0.
function _parkedOf(address lendingPool, IERC20 token) private view returns (uint256) {
if (lendingPool == address(0)) return 0;
try IRehypoLendingPool(lendingPool).sTokenAddressOf(address(token)) returns (address sTok) {
if (sTok == address(0)) return 0;
} catch {
return 0;
}
try IRehypoLendingPool(lendingPool).supplyBalanceOf(address(token), address(this)) returns (uint256 bal) {
return bal;
} catch {
return 0;
}
}
/// @notice `VaultCore.setRehypo` validation; see `VaultConfigChecks`.
function checkRehypo(
address oldPool, address newPool, bool enabled, uint16 floorBps, uint16 capBps, IERC20 token0, IERC20 token1
) external view {
VaultConfigChecks.checkRehypo(oldPool, newPool, enabled, floorBps, capBps, token0, token1);
}
function checkFactories(address fm, address ledger) external view {
VaultConfigChecks.checkFactories(fm, ledger);
}
/// @notice Fees `realiseAndCollectAll` would collect now: `tokensOwed` plus fee growth since the last poke.
/// @dev `owed0`/`owed1` is the `tokensOwed` part; an unreadable fee growth reverts `FeeGrowthUnreadable`.
function unrealisedFees(Range[] storage ranges, address pool)
external
view
returns (uint256 f0, uint256 f1, uint256 owed0, uint256 owed1)
{
(bool okG, uint256 g0, uint256 g1, int24 tick) = _feeGlobals(pool);
uint256 count = ranges.length;
for (uint256 i = 0; i < count; i++) {
if (_dup(ranges, i)) continue;
int24 lo = ranges[i].tickLower;
int24 hi = ranges[i].tickUpper;
(uint128 liq, uint256 last0, uint256 last1, uint128 o0, uint128 o1) =
IUniswapV3PoolActions(pool).positions(keccak256(abi.encodePacked(address(this), lo, hi)));
owed0 += o0;
owed1 += o1;
if (liq == 0) continue;
if (!okG) revert FeeGrowthUnreadable();
(bool okL, uint256 lo0, uint256 lo1) = _feeOutside(pool, lo);
(bool okH, uint256 hi0, uint256 hi1) = _feeOutside(pool, hi);
if (!okL || !okH) revert FeeGrowthUnreadable();
unchecked {
// Uniswap V3 Tick.getFeeGrowthInside, wrapping arithmetic as in the pool.
uint256 in0 = g0 - (tick >= lo ? lo0 : g0 - lo0) - (tick < hi ? hi0 : g0 - hi0);
uint256 in1 = g1 - (tick >= lo ? lo1 : g1 - lo1) - (tick < hi ? hi1 : g1 - hi1);
f0 += Math.mulDiv(in0 - last0, liq, 1 << 128);
f1 += Math.mulDiv(in1 - last1, liq, 1 << 128);
}
}
(f0, f1) = (f0 + owed0, f1 + owed1);
}
function _feeGlobals(address pool) private view returns (bool ok, uint256 g0, uint256 g1, int24 tick) {
(bool a, bytes memory r0) = pool.staticcall(abi.encodeWithSignature("feeGrowthGlobal0X128()"));
(bool b, bytes memory r1) = pool.staticcall(abi.encodeWithSignature("feeGrowthGlobal1X128()"));
(bool c, bytes memory rs) = pool.staticcall(abi.encodeWithSignature("slot0()"));
if (!a || !b || !c || r0.length < 32 || r1.length < 32 || rs.length < 64) return (false, 0, 0, 0);
int256 t;
assembly ("memory-safe") {
g0 := mload(add(r0, 32))
g1 := mload(add(r1, 32))
t := mload(add(rs, 64))
}
return (true, g0, g1, int24(t));
}
function _feeOutside(address pool, int24 t) private view returns (bool, uint256 o0, uint256 o1) {
(bool ok, bytes memory r) = pool.staticcall(abi.encodeWithSignature("ticks(int24)", t));
if (!ok || r.length < 128) return (false, 0, 0);
assembly ("memory-safe") {
o0 := mload(add(r, 96))
o1 := mload(add(r, 128))
}
return (true, o0, o1);
}
/// @notice `VaultCore._update`'s pre-change settlement; see `ShareHookDispatch`.
function beforeShareUpdate(address accountant, address ledger, address from, address to, uint256 value) external {
if (accountant != address(0) || ledger != address(0)) ShareHookDispatch.dispatch(accountant, ledger, from, to, value);
}
/// @notice Best-effort reclaim of both legs' parked inventory; what the pool cannot pay stays parked.
function reclaimAll(address pool, IERC20 token0, IERC20 token1) external {
_reclaimOne(pool, token0);
_reclaimOne(pool, token1);
}
function _reclaimOne(address pool, IERC20 token) private {
// Defensive reads: a reverting lending pool skips this leg instead of reverting the exit.
try IRehypoLendingPool(pool).sTokenAddressOf(address(token)) returns (address sTok) {
if (sTok == address(0)) return;
} catch { return; }
uint256 parked;
try IRehypoLendingPool(pool).supplyBalanceOf(address(token), address(this)) returns (uint256 p) {
parked = p;
} catch { return; }
if (parked == 0) return;
// `max` (burns every share, no dust) when cash covers the position, else the live cash, since a
// `max` withdrawal is all-or-nothing.
uint256 cash = token.balanceOf(pool);
uint256 toReclaim = parked <= cash ? type(uint256).max : cash;
if (toReclaim == 0) return;
(bool ok, ) = pool.call(abi.encodeCall(IRehypoLendingPool.withdraw, (address(token), toReclaim)));
ok;
}
/// @notice Spot tick and trailing-TWAP tick from the pool's oracle; `ok` false on a buffer too cold for `window`.
function spotAndTwapTick(address pool, uint32 window) public view returns (int24 spot, int24 twap, bool ok) {
(, spot,,,,,) = IUniswapV3PoolState(pool).slot0();
uint32[] memory ago = new uint32[](2);
ago[0] = window;
ago[1] = 0;
try IUniswapV3PoolState(pool).observe(ago) returns (int56[] memory cum, uint160[] memory) {
int56 delta = cum[1] - cum[0];
twap = int24(delta / int56(uint56(window)));
// Round toward negative infinity, as OracleLibrary.consult does.
if (delta < 0 && delta % int56(uint56(window)) != 0) twap--;
ok = true;
} catch {
ok = false;
}
}
/// @notice Park each leg's idle above the floor buffer; a refused supply clears the approval.
function parkExcess(address pool, IERC20 token0, IERC20 token1, uint16 floorBps, uint16 capBps) external {
_parkOne(pool, token0, floorBps, capBps);
_parkOne(pool, token1, floorBps, capBps);
}
function _parkOne(address pool, IERC20 token, uint16 floorBps, uint16 capBps) private {
// Registered vaults stay within capBps of other suppliers' depth (supplied, not raw cash, so
// donations cannot inflate it); an empty reserve or unregistered vault parks nothing.
uint256 room = VaultConfigChecks.rehypoRoom(pool, token, capBps);
if (room == 0) return;
uint256 raw = token.balanceOf(address(this));
uint256 toPark = raw - (raw * floorBps) / 10_000;
if (toPark > room) toPark = room;
if (toPark == 0) return;
token.forceApprove(pool, toPark);
(bool ok, ) = pool.call(abi.encodeCall(IRehypoLendingPool.supply, (address(token), toPark)));
if (!ok) token.forceApprove(pool, 0);
}
}
npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
npm/@openzeppelin/[email protected]/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
npm/@openzeppelin/[email protected]/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
npm/@openzeppelin/[email protected]/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
npm/@openzeppelin/[email protected]/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
npm/@openzeppelin/[email protected]/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
project/contracts/interfaces/IAggregatorV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Minimal Chainlink AggregatorV3 interface: `decimals` and `latestRoundData`.
interface IAggregatorV3 {
function decimals() external view returns (uint8);
function latestRoundData() external view returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
project/contracts/interfaces/IHorizonMintable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @notice HorizonToken interface for allowlisted minters: ERC20 plus mint.
interface IHorizonMintable is IERC20 {
function mint(address to, uint256 amount) external;
}
project/contracts/interfaces/IUniswapV3Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// Minimal Uniswap SwapRouter02 interface.
/// @dev SwapRouter02 params carry no `deadline`; a SwapRouter01-shaped call has a different selector and reverts.
interface IV3SwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata) external payable returns (uint256);
/// SwapRouter02's exact-output single hop, with no deadline.
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
function exactOutputSingle(ExactOutputSingleParams calldata) external payable returns (uint256 amountIn);
}
/// Minimal Uniswap V3 factory interface.
interface IUniswapV3Factory {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}
/// Minimal Uniswap V3 pool state interface.
interface IUniswapV3PoolState {
function slot0() external view returns (
uint160 sqrtPriceX96, int24 tick, uint16, uint16, uint16, uint8, bool
);
function observe(uint32[] calldata secondsAgos) external view returns (
int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s
);
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
function tickSpacing() external view returns (int24);
/// Pool-immutable identity, read to verify a supplied pool's tokens and fee.
function token0() external view returns (address);
function token1() external view returns (address);
function fee() external view returns (uint24);
}
/// The pool's in-range liquidity.
interface IUniswapV3PoolLiquidity {
function liquidity() external view returns (uint128);
}
/// Minimal Uniswap V3 NonfungiblePositionManager interface.
interface IUniswapV3NPM {
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
function mint(MintParams calldata p)
external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
function increaseLiquidity(IncreaseLiquidityParams calldata p)
external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);
function decreaseLiquidity(DecreaseLiquidityParams calldata p)
external returns (uint256 amount0, uint256 amount1);
function collect(CollectParams calldata p)
external returns (uint256 amount0, uint256 amount1);
function positions(uint256 tokenId) external view returns (
uint96 nonce, address operator, address token0, address token1,
uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity,
uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0, uint128 tokensOwed1
);
/// @notice The Uniswap V3 factory this position manager's pools are created through.
function factory() external view returns (address);
}
/// Uniswap V3 pool liquidity actions for pool-direct positions, keyed on
/// `keccak256(abi.encodePacked(owner, tickLower, tickUpper))`.
interface IUniswapV3PoolActions {
/// Adds `amount` liquidity to the position owned by `recipient` over [tickLower, tickUpper]; the
/// caller must pay the returned owed tokens inside `uniswapV3MintCallback` before this returns.
function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data)
external returns (uint256 amount0, uint256 amount1);
/// Removes `amount` liquidity from the caller's position, crediting principal and fees to `tokensOwed`.
function burn(int24 tickLower, int24 tickUpper, uint128 amount)
external returns (uint256 amount0, uint256 amount1);
/// Transfers up to the requested amounts of the caller's position's `tokensOwed` to `recipient`.
function collect(
address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
function positions(bytes32 key) external view returns (
uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0, uint128 tokensOwed1
);
}
/// Mint callback a pool-direct minter implements to pay owed tokens; it must accept only the pool, during its own
/// mint.
interface IUniswapV3MintCallback {
function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external;
}
project/contracts/libraries/PoolLastGood.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "./PoolMath.sol";
/// @title PoolLastGood - the lending pool's own last-good liquidation price, per price feed
/// @notice Per price feed, the last healthy long-median answer a pool action read, as a liquidation fallback.
/// @dev ERC-7201 slot in the pool's storage, keyed by feed; at most one write per feed per block, newer only.
library PoolLastGood {
/// ERC-7201: keccak256(abi.encode(uint256(keccak256("horizon.pool.lastGood")) - 1)) & ~0xff.
bytes32 internal constant SLOT = 0x83530c3fafbf76ea81752cb3c03a9a31e81528eda7015e4f1f0bea8ef73b1c00;
/// The word for `feed`: `mapping(address => uint256)` rooted at SLOT.
function slotOf(address feed) internal pure returns (bytes32 s) {
assembly ("memory-safe") {
mstore(0x00, feed)
mstore(0x20, SLOT)
s := keccak256(0x00, 0x40)
}
}
/// The stored record (answer in the feed's own units and decimals, and the block time of the read); (0, 0) = none.
function load(address feed) internal view returns (uint256 answer, uint256 at) {
bytes32 s = slotOf(feed);
uint256 w;
assembly ("memory-safe") { w := sload(s) }
return (w >> 64, uint64(w));
}
/// Pack a healthy live read into an observation, or 0 when it does not qualify (see the header).
function observe(int256 answer, uint256 updatedAt) internal view returns (uint256) {
if (answer <= 0 || uint256(answer) > type(uint128).max || updatedAt != block.timestamp) return 0;
return (uint256(answer) << 64) | updatedAt;
}
/// Store `obs` for `feed` unless it is empty or no newer than what is stored (at most one write per feed per block).
function record(address feed, uint256 obs) internal {
if (obs == 0) return;
bytes32 s = slotOf(feed);
uint256 cur;
assembly ("memory-safe") { cur := sload(s) }
if (uint64(cur) >= uint64(obs)) return;
assembly ("memory-safe") { sstore(s, obs) }
}
/// Store each reserve's observation from an account walk (`obs[i]` belongs to `reservesList[i]`; 0 = none).
function recordAll(
mapping(address => PoolMath.ReserveConfig) storage reserveConfig,
address[] storage reservesList,
uint256[] memory obs
) internal {
for (uint256 i = 0; i < obs.length; i++) {
if (obs[i] != 0) record(reserveConfig[reservesList[i]].priceFeed, obs[i]);
}
}
}
project/contracts/libraries/PoolMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IHorizonMintable.sol";
/// @title PoolMath
/// @notice Internal helpers shared by HorizonLendingPool and its logic libraries: decimals, userConfig bits, payouts.
library PoolMath {
using SafeERC20 for IERC20;
error ReserveNotRegistered();
/// Mirrors HorizonLendingPool.ReserveConfig field for field; storage layout is positional, so field order and
/// sizes must match exactly and new fields are appended only.
struct ReserveConfig {
address sTokenAddress;
bool isActive;
uint16 collateralFactorBps;
uint16 liquidationThresholdBps;
uint16 liquidationBonusBps;
address priceFeed;
uint16 baseRateBps;
uint16 slope1Bps;
uint16 slope2Bps;
uint16 kinkBps;
uint16 reserveFactorBps;
uint16 liquidationFeeBps;
uint8 decimals;
uint128 supplyCap;
uint128 borrowCap;
/// Oracle freshness bounds in seconds: `priceStaleAfter` for supply/withdraw/borrow/repay, the lenient
/// `maxPriceAge` for health and liquidation; `maxPriceAge >= priceStaleAfter`.
uint32 priceStaleAfter;
uint32 maxPriceAge;
/// Upside price cap (1e18 USD), 0 = off; collateral reads use `min(feedPrice, priceCapUsd)`, debt reads uncapped.
uint128 priceCapUsd;
/// Non-zero marks the reserve as isolated collateral and is its USD debt ceiling; zero means not isolated.
uint128 isolationDebtCeilingUsd;
/// Whether this asset may be borrowed by an account in isolation mode.
bool borrowableInIsolation;
/// Extra origination fee in bps when this asset backs a borrow, on top of the pool's `borrowFeeBps`.
uint16 liquidityPremiumBps;
/// Facilitator reserve (e.g. hUSD): `payOut` mints instead of transferring, supply is refused, and
/// `borrowCap` is the mint cap.
bool isFacilitator;
/// Genesis kill switch: blocks supply, withdraw, borrow, repay and liquidation on this reserve as either leg.
bool paused;
/// Collateral-only: the asset can be supplied, used as collateral, withdrawn and seized, but not borrowed.
/// `IHorizonLendingPool` declares the same tuple, so a field order mismatch is a compile error.
bool borrowingDisabled;
/// Non-zero marks membership of that correlated group; a position opted into the same id values this collateral
/// at the constellation factors below, each at least its standard one.
uint8 constellationId;
bool constellationBorrowable;
uint16 constellationCollateralFactorBps;
uint16 constellationLiquidationThresholdBps;
uint16 constellationLiquidationBonusBps;
}
/// The opted-in constellation id lives in the top byte of `userConfig[account]` (0 = none); reserve bits stop at
/// bit 199 (`MAX_RESERVES` = 100) and `setUserBit` flips single bits, so the byte is never disturbed.
uint256 internal constant CID_SHIFT = 248;
function constellationIdOf(mapping(address => uint256) storage userConfig, address account) internal view returns (uint8) {
return uint8(userConfig[account] >> CID_SHIFT);
}
function writeConstellationId(mapping(address => uint256) storage userConfig, address account, uint8 id) internal {
userConfig[account] = (userConfig[account] & ~(uint256(0xFF) << CID_SHIFT)) | (uint256(id) << CID_SHIFT);
}
function requireRegistered(mapping(address => ReserveConfig) storage reserveConfig, address asset) internal view {
if (reserveConfig[asset].sTokenAddress == address(0)) revert ReserveNotRegistered();
}
function payOut(mapping(address => ReserveConfig) storage reserveConfig, address asset, address to, uint256 amount) internal {
if (reserveConfig[asset].isFacilitator) {
// A facilitator reserve holds no liquidity, so every payout from it is a mint.
IHorizonMintable(asset).mint(to, amount);
} else {
IERC20(asset).safeTransfer(to, amount);
}
}
/// @dev Normalizes `amount` (in `asset`'s own decimals) up to the canonical 18-decimal basis
/// every internal computation uses.
function toCanonical(mapping(address => ReserveConfig) storage reserveConfig, address asset, uint256 amount) internal view returns (uint256) {
uint8 dec = reserveConfig[asset].decimals;
return dec == 18 ? amount : amount * (10 ** (18 - dec));
}
function fromCanonical(mapping(address => ReserveConfig) storage reserveConfig, address asset, uint256 canonicalAmount) internal view returns (uint256) {
uint8 dec = reserveConfig[asset].decimals;
return dec == 18 ? canonicalAmount : canonicalAmount / (10 ** (18 - dec));
}
/// @notice Weighted collateral cost of one dollar repaid, in bps: LT x (1 + bonus), scaled by cap / uncapped price
/// when the collateral trades above `priceCapUsd`. A partial repay lowers health exactly when HF < this / BPS.
function seizeCostBps(uint256 ltBps, uint256 bonusBps, uint256 priceCapUsd, uint256 uncapped) internal pure returns (uint256 s) {
s = ((10_000 + bonusBps) * ltBps) / 10_000;
if (priceCapUsd != 0 && uncapped > priceCapUsd) s = (s * priceCapUsd) / uncapped;
}
/// @dev Canonical (18-decimal) to native for a bare `decimals`, scaling in both directions.
function canonicalToNative(uint256 canonical, uint8 dec) internal pure returns (uint256) {
if (dec == 18) return canonical;
return dec < 18 ? canonical / 10 ** (18 - dec) : canonical * 10 ** (dec - 18);
}
/// @dev Native -> canonical for a bare `decimals`, the inverse of `canonicalToNative`.
function nativeToCanonical(uint256 amount, uint8 dec) internal pure returns (uint256) {
if (dec == 18) return amount;
return dec < 18 ? amount * 10 ** (18 - dec) : amount / 10 ** (dec - 18);
}
function setUserBit(
mapping(address => uint256) storage userConfig,
mapping(address => uint256) storage reserveIndex1,
address user, address asset, uint256 offset, bool value
) internal {
uint256 id1 = reserveIndex1[asset]; // 1-indexed
uint256 bitPos = 2 * (id1 - 1) + offset;
if (value) {
userConfig[user] |= (1 << bitPos);
} else {
userConfig[user] &= ~(1 << bitPos);
}
}
/// @dev This reserve's real, currently-held ERC20 balance, in its own decimals.
function liquidBalance(address asset) internal view returns (uint256) {
return IERC20(asset).balanceOf(address(this));
}
}
project/contracts/libraries/PriceOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "../interfaces/IAggregatorV3.sol";
import "./PoolLastGood.sol";
/// @title PriceOracle
/// @notice The lending pool's price-reading logic, as an external library so it deploys outside the pool's bytecode.
/// @notice The standard feed's last-good surface (`HorizonDexPriceFeed.lastGoodRoundData`), liquidation reads only.
interface ILastGoodFeed {
function lastGoodRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
function lastGoodWindow() external view returns (uint32);
}
/// The lending pool's own last-good record (`HorizonLendingPool.lastGoodRecordOf`), for readers outside it.
interface ILastGoodPool {
function lastGoodRecordOf(address feed) external view returns (uint256 answer, uint256 recordedAt);
}
library PriceOracle {
error BadPrice();
error StalePrice();
/// The standard feed's own error (`HorizonDexPriceFeed.InsufficientGas()`), re-raised by every lenient read.
error InsufficientGas();
bytes4 internal constant INSUFFICIENT_GAS = bytes4(keccak256("InsufficientGas()"));
/// @dev Strict read: reverts on a non-positive answer or one older than `maxAge`; returns
/// `min(price, priceCapUsd)` (0 = no cap), so a fall always passes through.
function readStrict(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256) {
(, int256 answer, , uint256 updatedAt, ) = IAggregatorV3(priceFeed).latestRoundData();
if (answer <= 0) revert BadPrice();
// A future `updatedAt` raises StalePrice instead of an underflow panic.
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
uint8 dec = IAggregatorV3(priceFeed).decimals();
uint256 p = (uint256(answer) * scale) / (10 ** dec);
return (priceCapUsd != 0 && p > priceCapUsd) ? priceCapUsd : p;
}
/// @dev `readStrict` plus the raw observation (before the cap) for `PoolLastGood.observe`; same returned price.
function readStrictObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p, uint256 obs) {
(, int256 answer, , uint256 updatedAt, ) = IAggregatorV3(priceFeed).latestRoundData();
if (answer <= 0) revert BadPrice();
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
uint8 dec = IAggregatorV3(priceFeed).decimals();
p = (uint256(answer) * scale) / (10 ** dec);
if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
obs = PoolLastGood.observe(answer, updatedAt);
}
/// @dev Non-reverting read: returns 0 on a bad, stale or unreadable feed (the call is wrapped in try/catch).
function readOrZero(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256) {
(bool ok, int256 answer, uint256 updatedAt, uint256 dec) = rawRound(priceFeed);
if (!ok || answer <= 0) return 0;
// A future `updatedAt` returns 0 instead of underflowing, so this never reverts.
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return 0;
uint256 p = (uint256(answer) * scale) / (10 ** dec);
return (priceCapUsd != 0 && p > priceCapUsd) ? priceCapUsd : p; // asymmetric upside cap
}
/// @dev `readOrZero` plus the raw observation (before the cap) for `PoolLastGood.observe`; same returned price.
function readOrZeroObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p, uint256 obs) {
(bool ok, int256 answer, uint256 updatedAt, uint256 dec) = rawRound(priceFeed);
if (!ok || answer <= 0) return (0, 0);
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return (0, 0);
p = (uint256(answer) * scale) / (10 ** dec);
if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
obs = PoolLastGood.observe(answer, updatedAt);
}
/// @notice Liquidation strict read: `readStrict`, but a dark feed answers the fresher of its own and the pool's
/// last-good record inside the feed's window; pool context only, and `InsufficientGas` re-raises.
function readLiqStrict(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
(p, ) = _liqStrict(address(this), priceFeed, maxAge, scale, priceCapUsd);
}
/// @notice `readLiqStrict` for code outside the pool: the pool's record is read through `lastGoodRecordOf`.
function readLiqStrictOf(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
(p, ) = _liqStrict(pool, priceFeed, maxAge, scale, priceCapUsd);
}
/// @notice Liquidation lenient read: `readOrZero` over `readLiqStrict`'s answer; `InsufficientGas` re-raises.
function readLiqOrZero(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
(p, ) = _liqOrZero(address(this), priceFeed, maxAge, scale, priceCapUsd);
}
/// @notice `readLiqOrZero` for code outside the pool (the liquidation views).
function readLiqOrZeroOf(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd) external view returns (uint256 p) {
(p, ) = _liqOrZero(pool, priceFeed, maxAge, scale, priceCapUsd);
}
/// @notice The pool's liquidation reads plus the observation it may record (only a healthy live answer, uncapped).
/// `strict` picks `readLiqStrict` (debt) or `readLiqOrZero` (collateral).
function readLiqObs(address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd, bool strict)
external view returns (uint256 p, uint256 obs)
{
return strict ? _liqStrict(address(this), priceFeed, maxAge, scale, priceCapUsd)
: _liqOrZero(address(this), priceFeed, maxAge, scale, priceCapUsd);
}
function _liqStrict(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd)
private view returns (uint256 p, uint256 obs)
{
(bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, bytes memory err) = _liqRound(pool, priceFeed);
if (!ok) {
// No answer: the latest read's own refusal when it reverted (as with no fallback), BadPrice otherwise.
if (err.length != 0) assembly ("memory-safe") { revert(add(err, 0x20), mload(err)) }
revert BadPrice();
}
if (answer <= 0) revert BadPrice();
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) revert StalePrice();
p = (uint256(answer) * scale) / (10 ** dec);
if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
if (live) obs = PoolLastGood.observe(answer, updatedAt);
}
function _liqOrZero(address pool, address priceFeed, uint256 maxAge, uint256 scale, uint256 priceCapUsd)
private view returns (uint256 p, uint256 obs)
{
(bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, ) = _liqRound(pool, priceFeed);
if (!ok || answer <= 0) return (0, 0);
if (updatedAt > block.timestamp || block.timestamp - updatedAt > maxAge) return (0, 0);
p = (uint256(answer) * scale) / (10 ** dec);
if (priceCapUsd != 0 && p > priceCapUsd) p = priceCapUsd;
if (live) obs = PoolLastGood.observe(answer, updatedAt);
}
/// @notice `rawRound`, falling back to the fresher last-good answer when the latest round cannot be read.
/// For liquidation-side readers outside the pool; `InsufficientGas` re-raises first.
function rawRoundLiq(address feed, address pool) internal view returns (bool ok, int256 answer, uint256 updatedAt, uint256 dec) {
(ok, , answer, updatedAt, dec, ) = _liqRound(pool, feed);
}
/// @notice The liquidation-grade round shared by the reads above; reverts only on `InsufficientGas`.
/// `live`: `latestRoundData` answered; else the fresher last-good record, or `err` holding the revert data.
function _liqRound(address pool, address feed)
internal view returns (bool ok, bool live, int256 answer, uint256 updatedAt, uint256 dec, bytes memory err)
{
(bool s, bytes memory r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.latestRoundData.selector));
if (s) {
if (r.length < 160) return (false, false, 0, 0, 0, err);
(, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
ok = true;
live = true;
} else {
bubbleInsufficientGas(r);
err = r;
(s, r) = feed.staticcall(abi.encodeWithSelector(ILastGoodFeed.lastGoodRoundData.selector));
if (s && r.length >= 160) {
(, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
ok = true;
}
(bool pOk, uint256 pAnswer, uint256 pAt) = _poolRecord(pool, feed);
if (pOk && (!ok || pAt > updatedAt)) {
answer = int256(pAnswer);
updatedAt = pAt;
ok = true;
}
if (!ok) return (false, false, 0, 0, 0, err);
}
(s, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.decimals.selector));
if (!s || r.length < 32) return (false, false, 0, 0, 0, err);
dec = abi.decode(r, (uint256));
if (dec > 77) return (false, false, 0, 0, 0, err);
}
/// The pool's own record for `feed`, used only inside the feed's `lastGoodWindow()` (0 = 1 hour, max 6 hours).
function _poolRecord(address pool, address feed) private view returns (bool ok, uint256 answer, uint256 at) {
(bool s, bytes memory r) = feed.staticcall(abi.encodeWithSelector(ILastGoodFeed.lastGoodWindow.selector));
if (!s || r.length < 32) return (false, 0, 0);
uint256 w = abi.decode(r, (uint256));
if (w == 0) w = 1 hours;
else if (w > 6 hours) w = 6 hours;
if (pool == address(this)) {
(answer, at) = PoolLastGood.load(feed);
} else {
(s, r) = pool.staticcall(abi.encodeWithSelector(ILastGoodPool.lastGoodRecordOf.selector, feed));
if (!s || r.length < 64) return (false, 0, 0);
(answer, at) = abi.decode(r, (uint256, uint256));
}
if (answer == 0 || answer > type(uint128).max || at == 0 || at > block.timestamp || block.timestamp - at > w) return (false, 0, 0);
ok = true;
}
/// @notice A feed's latest answer, update time and decimals that never reverts: raw staticcalls with length checks.
/// Decimals above 77 count as unreadable.
function rawRound(address feed) internal view returns (bool ok, int256 answer, uint256 updatedAt, uint256 dec) {
bytes memory r;
(ok, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.latestRoundData.selector));
if (!ok) bubbleInsufficientGas(r);
if (!ok || r.length < 160) return (false, 0, 0, 0);
(, answer, , updatedAt, ) = abi.decode(r, (uint256, int256, uint256, uint256, uint256));
(ok, r) = feed.staticcall(abi.encodeWithSelector(IAggregatorV3.decimals.selector));
if (!ok || r.length < 32) return (false, 0, 0, 0);
dec = abi.decode(r, (uint256));
if (dec > 77) return (false, 0, 0, 0);
}
/// @notice Re-raises a standard feed's `InsufficientGas()`, so a caller cannot turn a gas limit into "no price".
function bubbleInsufficientGas(bytes memory r) internal pure {
if (r.length == 4 && bytes4(r) == INSUFFICIENT_GAS) revert InsufficientGas();
}
}
project/contracts/libraries/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.20;
/// @title Math library for computing sqrt prices from ticks
/// @dev Adapted from Uniswap v3-core libraries/TickMath.sol (GPL-2.0-or-later).
/// @notice `getSqrtRatioAtTick` only; it cannot overflow uint256 for any tick within `MAX_TICK`.
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick, exactly -MAX_TICK.
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick
int24 internal constant MAX_TICK = 887272;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 The sqrt of token1/token0 at the given tick, as a Q64.96 number
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// Divide by 1<<32 rounding up (Q128.128 to Q128.96); the result fits in 160 bits for any valid tick.
// Rounding up keeps getTickAtSqrtRatio of the output price consistent.
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
project/contracts/vaults/interfaces/IClearing.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @notice Deposit gate implemented by `ClearingV3` and `ClearingV4`.
interface IClearing {
function clearDeposit(address vault, uint256 amount0, uint256 amount1, address from) external view;
/// @notice Spot-vs-TWAP deviation check only, without the deposit range and cap checks.
function isPriceStable(address vault) external view returns (bool);
/// @notice TWAP-anchored token1 value of (amount0, amount1).
function twapValue(address vault, uint256 amount0, uint256 amount1) external view returns (uint256);
/// @notice The TWAP tick, which `VaultCore.rebalanceOptimal` centers its range plan on.
function twapTick(address vault) external view returns (int24);
}
project/contracts/vaults/interfaces/IRehypoLendingPool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @notice The HorizonLendingPool functions a vault uses to park idle inventory and reclaim it.
/// @dev A nonzero `sTokenAddressOf` marks a token as a listed reserve the vault can park in.
interface IRehypoLendingPool {
function supply(address asset, uint256 amount) external returns (uint256 sTokensOut);
function withdraw(address asset, uint256 amount) external returns (uint256 withdrawn);
function supplyBalanceOf(address asset, address user) external view returns (uint256);
/// @notice Reserve-wide accounted supplied underlying (native decimals), donation-proof.
function totalSuppliedOf(address asset) external view returns (uint256);
function sTokenAddressOf(address asset) external view returns (address);
}
project/contracts/vaults/libraries/BaseLimitMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "./Range.sol";
/// @title BaseLimitMath
/// @notice Tick math for the base + limit shape: a base around the TWAP center tick and a one-sided bid or ask limit.
/// @dev Thresholds are in ticks and must be positive multiples of `tickSpacing`.
library BaseLimitMath {
error BadThreshold();
/// Uniswap V3's absolute tick bounds; every emitted edge is clamped strictly inside the aligned band.
int256 private constant _MIN_TICK = -887272;
int256 private constant _MAX_TICK = 887272;
/// The same bounds as int24, for callers checking whether a centre can host the shape.
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = 887272;
function _clamp(int256 v, int256 lo, int256 hi) private pure returns (int24) {
if (v < lo) return int24(lo);
if (v > hi) return int24(hi);
return int24(v);
}
/// @notice The full-range floor's ticks: the usable band, aligned to `tickSpacing` and strictly interior.
function fullRange(int24 tickSpacing) internal pure returns (int24 lower, int24 upper) {
lower = int24((_MIN_TICK / int256(tickSpacing)) * int256(tickSpacing));
upper = int24((_MAX_TICK / int256(tickSpacing)) * int256(tickSpacing));
}
/// @notice True for a range spanning the whole usable band (the full-range floor).
/// @dev Fixed bounds; matches `fullRange(s)` when `887272 mod s <= 272`, which initialise enforces.
function isFullBand(int24 tickLower, int24 tickUpper) internal pure returns (bool) {
return tickLower <= -887000 && tickUpper >= 887000;
}
/// @notice Rounds `tick` down to a multiple of `tickSpacing` (toward negative infinity).
function floorTick(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
/// Base range and both candidate limits around `centerTick`: `base` two-sided, `bid` below spot (token1) and
/// `ask` above spot (token0); the vault deploys the limit side its leftover balances back with more liquidity.
function ranges(int24 centerTick, int24 tickSpacing, int24 baseThreshold, int24 limitThreshold)
public
pure
returns (
int24 baseLower,
int24 baseUpper,
int24 bidLower,
int24 bidUpper,
int24 askLower,
int24 askUpper
)
{
if (
baseThreshold <= 0 || limitThreshold <= 0 || baseThreshold % tickSpacing != 0
|| limitThreshold % tickSpacing != 0
) revert BadThreshold();
int24 tickFloor = floorTick(centerTick, tickSpacing);
int24 tickCeil = tickFloor + tickSpacing;
// Usable band, strictly interior; every edge is clamped into it, so near-extreme ticks cannot revert and a
// huge `baseThreshold` gives a full-range base.
int256 lo = (_MIN_TICK / int256(tickSpacing)) * int256(tickSpacing);
int256 hi = (_MAX_TICK / int256(tickSpacing)) * int256(tickSpacing);
// Base straddles spot: [floor - baseThreshold, ceil + baseThreshold].
baseLower = _clamp(int256(tickFloor) - int256(baseThreshold), lo, hi);
baseUpper = _clamp(int256(tickCeil) + int256(baseThreshold), lo, hi);
// Bid: entirely below spot, token1 only. Both edges clamped so a range near the minimum cannot invert.
bidLower = _clamp(int256(tickFloor) - int256(limitThreshold), lo, hi);
bidUpper = _clamp(int256(tickFloor), lo, hi);
// Ask: entirely above spot, token0 only.
askLower = _clamp(int256(tickCeil), lo, hi);
askUpper = _clamp(int256(tickCeil) + int256(limitThreshold), lo, hi);
// A range clamped onto a point at the band's edge opens one spacing inward, so lower < upper always holds.
(baseLower, baseUpper) = _widen(baseLower, baseUpper, tickSpacing, lo, hi);
(bidLower, bidUpper) = _widen(bidLower, bidUpper, tickSpacing, lo, hi);
(askLower, askUpper) = _widen(askLower, askUpper, tickSpacing, lo, hi);
}
/// @dev A range collapsed onto one edge of the band opens one spacing toward the inside.
function _widen(int24 lower, int24 upper, int24 tickSpacing, int256 lo, int256 hi)
private
pure
returns (int24, int24)
{
if (lower < upper) return (lower, upper);
if (int256(upper) + int256(tickSpacing) <= hi) return (lower, upper + tickSpacing);
return (_clamp(int256(lower) - int256(tickSpacing), lo, hi), upper);
}
/// @notice The base, provisional ask and full-range floor centred on `centerTick`; a full-range base is the floor,
/// giving two ranges. The base carries 10,000 `weightBps`.
function baseLimitRanges(int24 centerTick, int24 tickSpacing, int24 baseThreshold, int24 limitThreshold)
public
pure
returns (Range[] memory r)
{
(int24 bl, int24 bu,,, int24 al, int24 au) = ranges(centerTick, tickSpacing, baseThreshold, limitThreshold);
bool baseIsFull = isFullBand(bl, bu);
r = new Range[](baseIsFull ? 2 : 3);
r[0] = Range({tickLower: bl, tickUpper: bu, weightBps: 10_000});
r[1] = Range({tickLower: al, tickUpper: au, weightBps: 0});
if (!baseIsFull) {
(int24 fl, int24 fu) = fullRange(tickSpacing);
r[2] = Range({tickLower: fl, tickUpper: fu, weightBps: 0});
}
}
}
project/contracts/vaults/libraries/LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @title Liquidity amount functions
/// @dev Adapted from Uniswap v3-periphery libraries/LiquidityAmounts.sol (GPL-2.0-or-later).
/// @notice Computes liquidity amounts from token amounts and prices, with full-precision `Math.mulDiv`.
library LiquidityAmounts {
uint256 internal constant Q96 = 1 << 96;
uint8 internal constant RESOLUTION = 96;
/// @notice Downcasts uint256 to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = Math.mulDiv(sqrtRatioAX96, sqrtRatioBX96, Q96);
return toUint128(Math.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(Math.mulDiv(amount1, Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
// Compute each leg at full width and cast the minimum once, so the larger leg cannot overflow uint128.
uint256 liquidity0 = Math.mulDiv(amount0, Math.mulDiv(sqrtRatioX96, sqrtRatioBX96, Q96), sqrtRatioBX96 - sqrtRatioX96);
uint256 liquidity1 = Math.mulDiv(amount1, Q96, sqrtRatioX96 - sqrtRatioAX96);
liquidity = toUint128(liquidity0 < liquidity1 ? liquidity0 : liquidity1);
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
Math.mulDiv(
uint256(liquidity) << RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return Math.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Q96);
}
/// @notice Computes the token0 and token1 value for a given liquidity, current price and range bounds
/// @dev Internal, so importers need no library linking; vaults reach it through `ShapeMath.amountsForLiquidity`.
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
project/contracts/vaults/libraries/PriceLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice `sqrtPriceX96` to PRECISION-scaled token1-per-token0 conversion and value helpers for vaults and clearing.
library PriceLib {
uint256 internal constant PRECISION = 1e36;
/// @dev Transient deposit quote: (price, value) per valuation point, written by `depositQuote` and read by
/// `VaultCore._creditDeposit` in the same call. keccak256("horizon.vault.depositQuote") - 1.
uint256 internal constant QUOTE_SLOT = 0x42c10b870062e3e0d34b791d9952e4b9bb6e0cc428f91560e4f8d0b121f3fa45;
/// @dev Valuation points: range liquidity at the TWAP, block-start and spot prices, then the spot composition at
/// the TWAP and block-start prices (so a pushed spot's impermanent loss is priced).
uint256 internal constant QUOTE_POINTS = 5;
function storeQuote(uint256 i, uint256 price, uint256 value) internal {
assembly ("memory-safe") {
let s := add(QUOTE_SLOT, mul(2, i))
tstore(s, price)
tstore(add(s, 1), value)
}
}
/// @dev The lowest share count over the stored valuation points: `amount0`/`amount1` priced at each point's
/// price against the vault's value at that same price, `supply` and `virtualAssets` the vault's offsets.
function quotedShares(uint256 amount0, uint256 amount1, uint256 supply, uint256 virtualAssets) internal view returns (uint256 shares) {
shares = type(uint256).max;
for (uint256 i; i < QUOTE_POINTS; ++i) {
uint256 price;
uint256 value;
assembly ("memory-safe") {
let s := add(QUOTE_SLOT, mul(2, i))
price := tload(s)
value := tload(add(s, 1))
}
uint256 n = Math.mulDiv(valueInToken1(amount0, amount1, price), supply, value + virtualAssets);
if (n < shares) shares = n;
}
}
/// @dev Two chained `Math.mulDiv` calls, since the full product can exceed 256 bits.
function priceFromSqrt(uint160 sqrtPriceX96) internal pure returns (uint256) {
uint256 intermediate = Math.mulDiv(uint256(sqrtPriceX96), PRECISION, 1 << 96);
return Math.mulDiv(intermediate, uint256(sqrtPriceX96), 1 << 96);
}
/// @notice `amount1 + amount0 * price`: total value in token1 at a PRECISION-scaled price.
function valueInToken1(uint256 amount0, uint256 amount1, uint256 priceX) internal pure returns (uint256) {
return amount1 + Math.mulDiv(amount0, priceX, PRECISION);
}
/// @notice The share of a one-sided `amountIn` to swap: the other side's share of the target's value at `priceX`;
/// a zero-value target splits in half.
function valueWeightedSplit(bool tokenInIsToken0, uint256 amountIn, uint256 target0, uint256 target1, uint256 priceX)
internal
pure
returns (uint256 swapAmount)
{
if (target0 == 0 && target1 == 0) return amountIn / 2;
uint256 target0Value = valueInToken1(target0, 0, priceX);
// Dust token0 that values to zero with target1 zero would divide 0/0; fall back to the even split.
if (target0Value + target1 == 0) return amountIn / 2;
swapAmount = tokenInIsToken0
? Math.mulDiv(amountIn, target1, target0Value + target1)
: Math.mulDiv(amountIn, target0Value, target1 + target0Value);
}
/// @notice TWAP-anchored minimum output, net of the pool fee `feePips` (1e6 base) and `slippageBps`.
/// @dev Dynamic-fee venues pass `feePips = 0`.
function minOutNetOfFee(bool tokenInIsToken0, uint256 swapAmount, uint256 priceX, uint256 slippageBps, uint256 feePips)
internal
pure
returns (uint256 minOut)
{
uint256 expectedOut = tokenInIsToken0
? Math.mulDiv(swapAmount, priceX, PRECISION)
: Math.mulDiv(swapAmount, PRECISION, priceX);
expectedOut = Math.mulDiv(expectedOut, 1_000_000 - feePips, 1_000_000);
minOut = Math.mulDiv(expectedOut, 10_000 - slippageBps, 10_000);
}
}
project/contracts/vaults/libraries/Range.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
/// @notice One concentrated position: a tick range plus the share of deployable capital it takes.
/// @dev `weightBps` across a plan must sum to 10,000.
struct Range {
int24 tickLower;
int24 tickUpper;
uint16 weightBps;
}
project/contracts/vaults/libraries/ShapeMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import "../../libraries/TickMath.sol";
import "./LiquidityAmounts.sol";
import "./Range.sol";
import {VaultConfigChecks} from "./VaultConfigChecks.sol";
/// @title ShapeMath
/// @notice Builds a `Range` plan from a named shape: N equal-width, spacing-aligned buckets around a center tick.
/// @dev Gaussian weight tables are offline constants summing to exactly 10,000 bps; N is one of 3, 4, 5, 7, 9.
library ShapeMath {
enum Shape {
Gaussian
}
error UnsupportedShape();
error UnsupportedPositionCount();
error HalfWidthTooSmallForPositionCount();
/// @notice `VaultCore.setShapeConfig` / `setWidthConfig` geometry checks (`VaultConfigChecks.checkGeometry`).
function checkGeometry(
int24 halfWidth, uint8 count, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat, int24 spacing
) public view {
VaultConfigChecks.checkGeometry(halfWidth, count, enabled, minHW, maxHW, volWindow, volSat, spacing);
}
/// @notice `n`-bucket Gaussian weight table, bps, always summing to exactly 10,000.
/// @dev Odd counts put a bucket on the center tick; even counts straddle it symmetrically.
function gaussianWeights(uint256 n) internal pure returns (uint16[] memory bps) {
if (n == 3) {
bps = new uint16[](3);
(bps[0], bps[1], bps[2]) = (2420, 5160, 2420);
} else if (n == 4) {
bps = new uint16[](4);
(bps[0], bps[1], bps[2], bps[3]) = (1500, 3500, 3500, 1500);
} else if (n == 5) {
bps = new uint16[](5);
(bps[0], bps[1], bps[2], bps[3], bps[4]) = (856, 2427, 3434, 2427, 856);
} else if (n == 7) {
bps = new uint16[](7);
(bps[0], bps[1], bps[2], bps[3], bps[4], bps[5], bps[6]) = (366, 1113, 2167, 2708, 2167, 1113, 366);
} else if (n == 9) {
bps = new uint16[](9);
(bps[0], bps[1], bps[2], bps[3], bps[4], bps[5], bps[6], bps[7], bps[8]) =
(190, 559, 1209, 1921, 2242, 1921, 1209, 559, 190);
} else {
revert UnsupportedPositionCount();
}
}
function weightsFor(Shape shape, uint256 n) internal pure returns (uint16[] memory) {
if (shape != Shape.Gaussian) revert UnsupportedShape();
return gaussianWeights(n);
}
/// @notice Builds an `n`-bucket plan for `shape` spanning `centerTick +/- totalHalfWidth`, aligned and clamped.
/// @dev Contiguous equal-width buckets; weight carries the shape. Public, so callers must link ShapeMath.
function buildRanges(Shape shape, int24 centerTick, int24 tickSpacing, int24 totalHalfWidth, uint256 n)
public
pure
returns (Range[] memory ranges)
{
uint16[] memory weights = weightsFor(shape, n);
// Layout math in int256, narrowed to int24 only after clamping, so wide many-bucket plans cannot overflow.
int256 rawBucketWidth = (int256(totalHalfWidth) * 2) / int256(n);
int256 bucketWidth = (rawBucketWidth / int256(tickSpacing)) * int256(tickSpacing);
if (bucketWidth < int256(tickSpacing)) revert HalfWidthTooSmallForPositionCount();
int256 alignedCenter = (int256(centerTick) / int256(tickSpacing)) * int256(tickSpacing);
// Re-snap the half span to the grid: with odd `k * n` the ladder would land half a spacing off-grid,
// which the pool rejects on mint.
int256 halfSpan = ((bucketWidth * int256(n)) / 2 / int256(tickSpacing)) * int256(tickSpacing);
int256 start = alignedCenter - halfSpan;
int256 minUsableTick = (int256(TickMath.MIN_TICK) / int256(tickSpacing)) * int256(tickSpacing);
int256 maxUsableTick = (int256(TickMath.MAX_TICK) / int256(tickSpacing)) * int256(tickSpacing);
ranges = new Range[](n);
for (uint256 i = 0; i < n; i++) {
int256 lower = start + int256(i) * bucketWidth;
int256 upper = lower + bucketWidth;
if (lower < minUsableTick) lower = minUsableTick;
if (upper > maxUsableTick) upper = maxUsableTick;
// Independent clamping can invert a bucket outside the usable band; collapse it onto the boundary as a
// minimal valid range so `_setRanges` does not reject the whole plan.
if (upper <= lower) {
if (lower <= minUsableTick) {
lower = minUsableTick;
upper = minUsableTick + int256(tickSpacing);
} else {
upper = maxUsableTick;
lower = maxUsableTick - int256(tickSpacing);
}
}
ranges[i] = Range({tickLower: int24(lower), tickUpper: int24(upper), weightBps: weights[i]});
}
}
/// @notice `TickMath.getSqrtRatioAtTick` behind this library's delegatecall boundary, out of vault bytecode.
function sqrtRatioAtTick(int24 tick) public pure returns (uint160) {
return TickMath.getSqrtRatioAtTick(tick);
}
/// @notice `LiquidityAmounts.getAmountsForLiquidity` behind this library's delegatecall boundary.
function amountsForLiquidity(uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
public
pure
returns (uint256 amount0, uint256 amount1)
{
return LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
/// @notice Volatility-adaptive half-width: linear from `minHalfWidth` at zero volatility to `maxHalfWidth` at
/// saturation, clamped.
function adaptiveHalfWidth(uint256 volTicks, int24 minHalfWidth, int24 maxHalfWidth, uint32 volSaturationTicks)
public
pure
returns (int24)
{
if (volTicks >= volSaturationTicks) return maxHalfWidth;
int256 span = int256(maxHalfWidth) - int256(minHalfWidth);
return int24(int256(minHalfWidth) + (span * int256(volTicks)) / int256(uint256(volSaturationTicks)));
}
}
project/contracts/vaults/libraries/ShareHookDispatch.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @notice Emissions accountant for vault shares, called on every mint, burn and transfer before balances move.
/// @dev `from`/`to` is `address(0)` on mint/burn; the implementation skips those.
interface IShareIncentivesHook {
function handleShareMove(
address from, address to, uint256 value, uint256 totalSupplyBefore, uint256 fromBalanceBefore, uint256 toBalanceBefore
) external;
}
/// @notice Trading-fee ledger for unstaked vault shares, called on every balance change before balances move.
interface IVaultHolderFeeHook {
function onShareUpdate(
address from, uint256 fromBalanceBefore, address to, uint256 toBalanceBefore, uint256 value, bool realised
) external;
/// @notice Whether `account` is a compounding account of `vault`.
function isCompounding(address vault, address account) external view returns (bool);
}
/// @title ShareHookDispatch
/// @notice Pre-change share settlement for `VaultCore._update`: notifies the emissions accountant and fee ledger.
/// @dev Runs by delegatecall from the vault and must run before the ERC-20 balance update.
library ShareHookDispatch {
/// @dev Transient flag in the vault's storage, set when the vault realised and routed fees earlier in this tx.
bytes32 internal constant REALISED_SLOT = keccak256("horizon.vault.realisedThisTx");
function markRealised() internal {
bytes32 slot = REALISED_SLOT;
assembly { tstore(slot, 1) }
}
function realisedThisTx() internal view returns (bool r) {
bytes32 slot = REALISED_SLOT;
assembly { r := tload(slot) }
}
/// @dev Gas given to the outgoing accountant's accrual before a change of wiring.
uint256 internal constant FLUSH_GAS = 300_000;
/// @notice Thrown when too little gas is left to give the flush its full budget.
error FlushGasShort();
function dispatch(address accountant, address ledger, address from, address to, uint256 value) internal {
IERC20 self = IERC20(address(this));
// No party: the outgoing accountant accrues before a rewire; best effort, so a broken one cannot block it.
if (from == address(0) && to == address(0)) {
bytes memory data =
abi.encodeCall(IShareIncentivesHook.handleShareMove, (address(0), address(0), 0, self.totalSupply(), 0, 0));
// Requires the full budget plus the 1/64 the EVM keeps back, so the call always gets `FLUSH_GAS`.
if (gasleft() < FLUSH_GAS + FLUSH_GAS / 63 + 10_000) revert FlushGasShort();
// Gas-capped, result ignored, no returndata copied: a faulty accountant costs at most `FLUSH_GAS`.
assembly ("memory-safe") {
pop(call(FLUSH_GAS, accountant, 0, add(data, 0x20), mload(data), 0, 0))
}
return;
}
uint256 fromBal = from == address(0) ? 0 : self.balanceOf(from);
uint256 toBal = to == address(0) ? 0 : self.balanceOf(to);
if (accountant != address(0)) {
IShareIncentivesHook(accountant).handleShareMove(from, to, value, self.totalSupply(), fromBal, toBal);
}
if (ledger != address(0)) {
IVaultHolderFeeHook(ledger).onShareUpdate(from, fromBal, to, toBal, value, realisedThisTx());
}
}
}
project/contracts/vaults/libraries/VaultConfigChecks.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IRehypoLendingPool} from "../interfaces/IRehypoLendingPool.sol";
interface IFactoryPointerC {
function vaultFactory() external view returns (address);
}
/// @notice The vault's stored geometry and root key, read back by `checkGeometry`.
interface IVaultGeometryC {
function genesis() external view returns (address);
function shapeHalfWidth() external view returns (int24);
function shapePositionCount() external view returns (uint8);
function widthConfig() external view returns (bool, int24, int24, uint32, uint32);
}
/// @title VaultConfigChecks
/// @notice Validation for `VaultCore` config setters, run by delegatecall so `address(this)` is the vault.
library VaultConfigChecks {
uint256 internal constant BPS = 10_000;
error ZeroAddress();
error BadRehypoConfig();
error RehypoOldPoolNotDrained();
error RehypoVaultNotRegistered();
error BadWidthConfig();
error FactoryMismatch();
error NotGenesis();
/// @dev `VaultCore.setRehypo`'s checks.
function checkRehypo(
address oldPool, address newPool, bool enabled, uint16 floorBps, uint16 capBps, IERC20 token0, IERC20 token1
) internal view {
if (enabled) {
if (newPool == address(0)) revert ZeroAddress();
if (floorBps > BPS) revert BadRehypoConfig(); // floor can't exceed 100%
// capBps of the reserve's current liquid depth: zero with rehypo on, or above 50%, is a config error.
if (capBps == 0 || capBps > 5_000) revert BadRehypoConfig();
// Refuse while this vault's shares are a listed reserve of that pool (index-feedback loop).
if (IRehypoLendingPool(newPool).sTokenAddressOf(address(this)) != address(0)) revert BadRehypoConfig();
// Each reserve leg's emissions controller must register this vault (keeps parked sTokens out of the farm).
if (!_registeredFor(newPool, token0) || !_registeredFor(newPool, token1)) revert RehypoVaultNotRegistered();
}
// Repointing or clearing the pool must not orphan inventory still parked in the old one.
if (oldPool != address(0) && oldPool != newPool) {
if (parkedBalanceIn(oldPool, token0) != 0 || parkedBalanceIn(oldPool, token1) != 0) {
revert RehypoOldPoolNotDrained();
}
}
}
/// @dev FeeManager and the fee ledger must authenticate against the same vault registry.
function checkFactories(address fm, address ledger) internal view {
if (fm != address(0) && ledger != address(0)
&& IFactoryPointerC(fm).vaultFactory() != IFactoryPointerC(ledger).vaultFactory()) revert FactoryMismatch();
}
/// @dev True for a non-reserve leg or one whose emissions controller registers this vault.
/// A missing or unreadable controller reads as unregistered (fail closed).
function _registeredFor(address pool, IERC20 token) private view returns (bool) {
address sTok = IRehypoLendingPool(pool).sTokenAddressOf(address(token));
return sTok == address(0)
|| _registry(sTok, abi.encodeWithSignature("isRehypoVault(address,address)", sTok, address(this))) != 0;
}
/// @dev How much more of `token` this vault may park in `pool`, per the reserve's emissions controller.
/// 0 for a non-reserve leg or a missing or unreadable controller (fail closed).
function rehypoRoom(address pool, IERC20 token, uint16 capBps) internal view returns (uint256) {
address sTok = IRehypoLendingPool(pool).sTokenAddressOf(address(token));
if (sTok == address(0)) return 0;
return _registry(
sTok, abi.encodeWithSignature("rehypoRoom(address,address,uint256)", sTok, address(this), uint256(capBps))
);
}
/// @dev One-word answer of the sToken's `shareIncentives` controller to `data`; any failure reads as 0.
function _registry(address sTok, bytes memory data) private view returns (uint256) {
uint256 c = _word(sTok, abi.encodeWithSignature("shareIncentives()"));
return c == 0 || c >> 160 != 0 ? 0 : _word(address(uint160(c)), data);
}
/// @dev First word of a static call's answer; 0 for no code, a revert or a short answer.
function _word(address target, bytes memory data) private view returns (uint256 w) {
if (target.code.length == 0) return 0;
assembly ("memory-safe") {
let out := mload(0x40)
let ok := staticcall(gas(), target, add(data, 32), mload(data), out, 32)
if lt(returndatasize(), 32) { ok := 0 }
w := mul(ok, mload(out))
}
}
/// @dev Parked balance of `token` in `p`; a reverting pool reads as 0.
function parkedBalanceIn(address p, IERC20 token) internal view returns (uint256) {
if (p == address(0)) return 0;
try IRehypoLendingPool(p).sTokenAddressOf(address(token)) returns (address sTok) {
if (sTok == address(0)) return 0;
} catch {
return 0;
}
try IRehypoLendingPool(p).supplyBalanceOf(address(token), address(this)) returns (uint256 bal) {
return bal;
} catch {
return 0;
}
}
/// @dev Hard bounds on every width dial for `VaultCore.setWidthConfig`.
function checkWidth(bool enabled, int24 minHalfWidth, int24 maxHalfWidth, uint32 volWindow, uint32 volSaturationTicks)
internal
pure
{
if (!enabled) return;
if (minHalfWidth <= 0 || minHalfWidth > maxHalfWidth) revert BadWidthConfig();
if (maxHalfWidth > 400_000) revert BadWidthConfig();
if (volWindow < 60 || volWindow > 3600) revert BadWidthConfig();
if (volSaturationTicks == 0) revert BadWidthConfig();
}
/// @dev Bounds the shape (count 0 or 3/4/5/7/9, one tick spacing per bucket) and width; a non-genesis caller
/// may only widen: same count, `halfWidth` not lowered, width config per `checkWidthMonotone`.
function checkGeometry(
int24 halfWidth, uint8 count, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat, int24 spacing
) internal view {
checkWidth(enabled, minHW, maxHW, volWindow, volSat);
if (
count != 0
&& (
halfWidth <= 0 || halfWidth > 400_000 || (count != 3 && count != 4 && count != 5 && count != 7 && count != 9)
|| (int256(halfWidth) * 2) / int256(uint256(count)) < int256(spacing)
|| (enabled && (int256(minHW) * 2) / int256(uint256(count)) < int256(spacing))
)
) revert BadWidthConfig();
IVaultGeometryC v = IVaultGeometryC(address(this));
if (msg.sender == v.genesis()) return;
if (count != v.shapePositionCount() || halfWidth < v.shapeHalfWidth()) revert NotGenesis();
checkWidthMonotone(v, enabled, minHW, maxHW, volWindow, volSat);
}
/// @dev `checkGeometry`'s rule for the width config (warm key only): `enabled` and `volWindow` unchanged,
/// `minHalfWidth` and `maxHalfWidth` non-decreasing, `volSaturationTicks` non-increasing.
function checkWidthMonotone(
IVaultGeometryC v, bool enabled, int24 minHW, int24 maxHW, uint32 volWindow, uint32 volSat
) private view {
(bool oldEnabled, int24 oldMin, int24 oldMax, uint32 oldWindow, uint32 oldSat) = v.widthConfig();
if (enabled != oldEnabled || minHW < oldMin || maxHW < oldMax || volSat > oldSat || volWindow != oldWindow) {
revert NotGenesis();
}
}
}
Compiler settingsShow
{
"viaIR": true,
"libraries": {
"project/contracts/vaults/libraries/ShapeMath.sol": {
"ShapeMath": "0x9b33c66faed9ea39a8624dd3815a13ad4c619edb"
},
"project/contracts/vaults/libraries/BaseLimitMath.sol": {
"BaseLimitMath": "0xb12095ad18c517bfe1f26e357dda8006a291b7e7"
}
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"npm/@openzeppelin/[email protected]/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@uniswap/v4-core/=npm/@uniswap/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.