Verified contractExactMIT
PriceOracle
Address0x2ea25ebff573d27f415c444753cd3c9e1fae9e74
- Balance
0 ETH
- Transactions
17
- Compiler
solc 0.8.26
- Same code
1 more contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,978,079
- Creation transaction
- 0xd5df1d3fe3…62328b3ede
3 files
- src/PriceOracle.solmain19.82 KB
- src/libraries/LiquidityAmounts.sol5.36 KB
- src/libraries/TickMath.sol9.9 KB
src/PriceOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {TickMath} from "./libraries/TickMath.sol";
import {LiquidityAmounts} from "./libraries/LiquidityAmounts.sol";
/// @notice The Chainlink `AggregatorV3Interface`, in the two calls this contract needs.
interface IAggregatorV3 {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface IFloorTokenLite {
function floorWei() external view returns (uint256);
function TOKENS_PER_NFT() external view returns (uint256);
}
interface IUniswapV3FactoryLite {
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}
interface IUniswapV3PoolLite {
function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
function slot0()
external
view
returns (uint160 sqrtPriceX96, int24 tick, uint16, uint16, uint16, uint8, bool);
function liquidity() external view returns (uint128);
function token0() external view returns (address);
}
/// @notice What an asset is worth in dollars, from Chainlink, with the ways it can be wrong handled.
///
/// @dev Every launch that opens more than one pool depends on this. A token paired against both
/// NVDA and USDG has to open at the *same dollar price* in each pool, or the two disagree the
/// moment they exist and an arbitrageur takes the difference out of the creator's liquidity.
/// The only way to price two different assets against one number is to know what each is worth,
/// and on this chain that is Chainlink -- live from block zero, with feeds for the tokenized
/// equities as well as the crypto.
///
/// Before this, opening prices came from a tick the operator set by hand per asset. Measured
/// across the 44 curated assets those ticks implied opening valuations from $2,350 to $4,402 --
/// a 1.9x spread. For a single pool that is a launch opening a bit higher or lower than
/// intended. For seven pools it is a guaranteed arbitrage on the first block.
///
/// **What this contract refuses to do is answer when it is not sure.** A price feed can be
/// absent, stale, negative, or reporting from a round that never closed, and a launchpad that
/// treats any of those as a number opens a market at a price nobody chose. Each one reverts
/// with a distinct error so the interface can say which.
contract PriceOracle {
/// @notice A feed and how old its answer may be before this contract stops trusting it.
struct Feed {
address aggregator;
/// @dev Seconds. Zero means the asset is not configured.
uint32 maxAge;
}
/// @notice Dollar prices are reported with this many decimals, whatever the feed uses.
///
/// @dev Chainlink's USD feeds on this chain are all 8, but that is a fact about today rather
/// than a guarantee, so every answer is normalised rather than passed through.
uint8 public constant DECIMALS = 8;
/// @notice How long after the sequencer comes back a price is still refused.
///
/// @dev Robinhood Chain is an Arbitrum Orbit L2. When its sequencer has been down, feeds resume
/// with answers that were correct before the outage and have not caught up yet; the first
/// minutes after recovery are exactly when a stale price is most likely and least obvious.
uint256 public constant SEQUENCER_GRACE = 30 minutes;
address public owner;
address public pendingOwner;
/// @notice The L2 sequencer uptime feed, or zero when none is configured.
///
/// @dev Chainlink does not publish one for this chain yet. Left settable rather than omitted:
/// the check is the difference between "the chain was down" and "this price is current",
/// and it should be possible to turn on without redeploying anything.
address public sequencerUptimeFeed;
mapping(address asset => Feed) public feedOf;
/// @notice Uniswap V3, for pricing assets Chainlink does not cover.
IUniswapV3FactoryLite public immutable v3Factory;
/// @notice The chain's dollar. Every derived price is quoted against it and then converted.
address public immutable usdgHub;
/// @notice Least in-range liquidity a pool must hold before its price is used.
///
/// @dev A spot price from a pool holding nothing is not a price, it is whatever the last person
/// to touch it decided. Settable because the right floor is a fact about this chain's
/// liquidity rather than a constant.
uint128 public derivedLiquidityFloor;
/// @notice How far back a derived price averages. A spot price can be set by whoever adds the
/// deepest position for a block; holding an average this long against arbitrage costs.
uint32 public constant DERIVED_TWAP_WINDOW = 30 minutes;
event OwnerNominated(address indexed to);
event OwnerChanged(address indexed from, address indexed to);
event FeedSet(address indexed asset, address indexed aggregator, uint32 maxAge);
event SequencerFeedSet(address indexed feed);
event LiquidityFloorSet(uint128 floor);
error NotOwner();
error NotPendingOwner();
error ZeroAddress();
error NoFeed(address asset);
error StalePrice(address asset, uint256 updatedAt, uint32 maxAge);
error BadPrice(address asset, int256 answer);
error IncompleteRound(address asset);
error SequencerDown();
error SequencerRecovering(uint256 secondsLeft);
error NotPriceable(address asset);
error LengthMismatch();
error PoolTooThin(address asset, uint128 liquidity, uint128 floor);
/// @notice Floor tokens (one millionth of an NFT each): priced as their posted floor in ETH times
/// the ETH/USD feed, divided by the tokens per NFT. Registered by the owner, like feeds.
mapping(address => bool) public floorTokens;
event FloorTokenSet(address indexed asset, bool on);
function setFloorTokens(address[] calldata assets, bool on) external onlyOwner {
for (uint256 i; i < assets.length; ++i) {
floorTokens[assets[i]] = on;
emit FloorTokenSet(assets[i], on);
}
}
function _floorTokenUsd(address asset) private view returns (uint256 price, uint256 updatedAt) {
Feed memory eth = feedOf[address(0)];
if (eth.maxAge == 0) revert NoFeed(address(0));
uint256 ethUsd;
(ethUsd, updatedAt) = _feedPrice(address(0), eth);
uint256 perNft = (IFloorTokenLite(asset).floorWei() * ethUsd) / 1e18;
price = (perNft * 1e18) / IFloorTokenLite(asset).TOKENS_PER_NFT();
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
constructor(address _owner, address _v3Factory, address _usdgHub, uint128 _liquidityFloor) {
if (_owner == address(0) || _v3Factory == address(0) || _usdgHub == address(0)) {
revert ZeroAddress();
}
owner = _owner;
v3Factory = IUniswapV3FactoryLite(_v3Factory);
usdgHub = _usdgHub;
derivedLiquidityFloor = _liquidityFloor;
}
// ------------------------------------------------------------------ configuration
/// @notice Points an asset at its Chainlink feed.
///
/// @dev `maxAge` is per asset because the honest answer differs by asset class, and getting it
/// wrong in either direction is a real failure. Chainlink's feeds here have a 24-hour
/// heartbeat and update early on a 0.5% move, so a crypto price older than about a day is
/// genuinely suspect. An equity feed follows `us_equities_24/5` and simply does not update
/// while the market is shut -- on a Sunday its last answer is three days old and perfectly
/// correct, because the thing it prices has not traded either. A single bound tight enough
/// for ETH would refuse every weekend launch of a stock-paired token.
///
/// @param maxAge Seconds. Zero removes the asset.
function setFeed(address asset, address aggregator, uint32 maxAge) external onlyOwner {
_setFeed(asset, aggregator, maxAge);
}
/// @notice Points many assets at their feeds in one transaction.
///
/// @dev Twenty-six feeds is the whole Chainlink coverage of this launchpad's quote assets, and
/// an oracle configured with some of them is worse than one configured with none: the
/// assets that made it price normally and the ones that did not revert, so a basket fails
/// for reasons nobody can see. One signature, all or nothing.
function setFeeds(
address[] calldata assets,
address[] calldata aggregators,
uint32[] calldata maxAges
) external onlyOwner {
if (assets.length != aggregators.length || assets.length != maxAges.length) {
revert LengthMismatch();
}
for (uint256 i; i < assets.length; ++i) {
_setFeed(assets[i], aggregators[i], maxAges[i]);
}
}
function _setFeed(address asset, address aggregator, uint32 maxAge) private {
if (maxAge != 0 && aggregator == address(0)) revert ZeroAddress();
feedOf[asset] = Feed({aggregator: aggregator, maxAge: maxAge});
emit FeedSet(asset, aggregator, maxAge);
}
function setSequencerUptimeFeed(address feed) external onlyOwner {
sequencerUptimeFeed = feed;
emit SequencerFeedSet(feed);
}
function transferOwnership(address to) external onlyOwner {
pendingOwner = to;
emit OwnerNominated(to);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotPendingOwner();
emit OwnerChanged(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
// ------------------------------------------------------------------ reading
/// @notice What one whole unit of `asset` is worth in dollars, to 8 decimals.
///
/// @dev Reverts rather than returning zero, and with a distinct error per cause. A launch that
/// cannot be priced must not happen; a launch priced from a number this contract does not
/// stand behind is worse than one that reverted.
function usdPrice(address asset) public view returns (uint256 price, uint256 updatedAt) {
_requireSequencerUp();
if (floorTokens[asset]) return _floorTokenUsd(asset);
Feed memory feed = feedOf[asset];
// No feed is not the end of the question. Chainlink covers 26 of this launchpad's 45 quote
// assets; the rest have real markets on this chain and can be priced from them, which is how
// every launchpad here that does not use an oracle prices everything. A derived price is
// weaker -- see `_derivedUsdPrice` -- so it is only ever reached for.
if (feed.maxAge == 0) return (_derivedUsdPrice(asset), block.timestamp);
return _feedPrice(asset, feed);
}
/// @notice Whether `asset` can be priced right now, without reverting.
///
/// @dev For interfaces, which need to grey out an asset and say why rather than discover the
/// problem when somebody presses launch.
function priceable(address asset) external view returns (bool ok, uint256 price) {
try this.usdPrice(asset) returns (uint256 p, uint256) {
return (true, p);
} catch {
return (false, 0);
}
}
/// @notice How much of `asset`, in its own raw units, is worth `usdAmount` dollars.
///
/// @dev The conversion a multi-pool launch actually needs: given one opening valuation in
/// dollars, how much of each pool's quote asset does that represent. Every pool derived
/// this way opens at the same dollar price by construction, which is the entire point.
///
/// @param usdAmount Dollars, to `DECIMALS` places.
/// @param assetDecimals The asset's own decimals, which is not something a feed reports.
function quoteAmountForUsd(address asset, uint256 usdAmount, uint8 assetDecimals)
external
view
returns (uint256)
{
(uint256 price,) = usdPrice(asset);
// usdAmount and price share DECIMALS, so those cancel and the asset's own scale is applied.
return (usdAmount * (10 ** assetDecimals)) / price;
}
/// @notice Whether an asset is priced by Chainlink or by its own market, for the interface.
///
/// @dev A trader deciding what to buy should be able to tell the difference, and a creator
/// picking quote assets should know which of them rest on a spot price.
function priceSource(address asset) external view returns (bool chainlink, uint256 price) {
chainlink = feedOf[asset].maxAge != 0;
(price,) = usdPrice(asset);
}
function setLiquidityFloor(uint128 floor) external onlyOwner {
derivedLiquidityFloor = floor;
emit LiquidityFloorSet(floor);
}
// ------------------------------------------------------------------ internals
/// @notice An asset's dollar price, taken from its deepest Uniswap V3 pool against USDG.
///
/// @dev The fallback for assets Chainlink does not carry, and the same method par uses for every
/// asset: read the spot price of a real market. Anchored on USDG rather than ETH because
/// USDG is this chain's hub -- it is where the stock pools actually are -- and because it
/// is itself a Chainlink feed, so the conversion to dollars is one multiplication by a
/// price that cannot be moved in a transaction.
///
/// **This is a spot price and it can be moved.** Whoever launches can push the reference
/// pool inside their own transaction, open at a price nobody advertised, and push it back
/// afterwards, paying the pool's fees for the privilege. The liquidity floor sets what that
/// costs. It is worth being plain that this is a weaker number than a Chainlink feed, that
/// it only ever affects the launch that used it, and that a time-weighted price was the
/// alternative -- rejected because it would mean a token could not be used as a quote asset
/// until half an hour after it existed.
function _derivedUsdPrice(address asset) private view returns (uint256) {
// USDG prices itself, and its own feed is the anchor everything else converts through.
Feed memory hubFeed = feedOf[usdgHub];
if (hubFeed.maxAge == 0) revert NotPriceable(asset);
(uint256 hubUsd,) = _feedPrice(usdgHub, hubFeed);
if (asset == usdgHub) return hubUsd;
(address pool, uint128 liquidity) = _deepestUsdgPool(asset);
if (pool == address(0)) revert NotPriceable(asset);
if (liquidity < derivedLiquidityFloor) {
revert PoolTooThin(asset, liquidity, derivedLiquidityFloor);
}
// The pool's time-weighted average, never its spot. A pool without enough history to
// answer is not priceable, rather than priced off whatever it says right now.
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = DERIVED_TWAP_WINDOW;
secondsAgos[1] = 0;
int56[] memory ticks;
try IUniswapV3PoolLite(pool).observe(secondsAgos) returns (int56[] memory tc, uint160[] memory) {
ticks = tc;
} catch {
revert NotPriceable(asset);
}
int56 delta = ticks[1] - ticks[0];
int256 avgTick = int256(delta) / int256(uint256(DERIVED_TWAP_WINDOW));
if (delta < 0 && (int256(delta) % int256(uint256(DERIVED_TWAP_WINDOW))) != 0) avgTick -= 1;
if (avgTick < TickMath.MIN_TICK || avgTick > TickMath.MAX_TICK) revert NotPriceable(asset);
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(avgTick));
// How much USDG one whole unit of the asset is worth, in USDG's own raw units.
bool assetIsToken0 = IUniswapV3PoolLite(pool).token0() == asset;
uint256 assetUnit = 10 ** IAggregatorV3(asset).decimals();
uint256 usdgPerAsset = _quoteFromSqrtPrice(sqrtPriceX96, assetIsToken0, assetUnit);
uint8 hubDecimals = IAggregatorV3(usdgHub).decimals();
return (usdgPerAsset * hubUsd) / (10 ** hubDecimals);
}
/// @dev The pool holding the most in range, across the fee tiers this chain's stock pairs use.
function _deepestUsdgPool(address asset) private view returns (address best, uint128 bestLiq) {
uint24[4] memory fees = [uint24(100), 500, 3000, 10000];
for (uint256 i; i < 4; ++i) {
address pool = v3Factory.getPool(asset, usdgHub, fees[i]);
if (pool == address(0)) continue;
uint128 liq = IUniswapV3PoolLite(pool).liquidity();
if (liq > bestLiq) {
best = pool;
bestLiq = liq;
}
}
}
/// @dev `sqrtPriceX96` is sqrt(token1/token0) in Q64.96. Squaring it in two steps keeps the
/// intermediate inside 256 bits for the price ranges this chain actually has.
function _quoteFromSqrtPrice(uint160 sqrtPriceX96, bool assetIsToken0, uint256 assetUnit)
private
pure
returns (uint256)
{
uint256 p = uint256(sqrtPriceX96);
// Full-width products: a sqrt price near either end of the range squares past 256 bits.
if (assetIsToken0) {
// quote = asset * (sqrt^2 / 2^192)
uint256 ratioX96 = LiquidityAmounts.mulDiv(p, p, 1 << 96);
return LiquidityAmounts.mulDiv(ratioX96, assetUnit, 1 << 96);
}
// The asset is token1, so the ratio is inverted.
return LiquidityAmounts.mulDiv(assetUnit, 1 << 192, p) / p;
}
/// @dev The Chainlink half, factored out so both entry points ask the same questions.
function _feedPrice(address asset, Feed memory feed)
private
view
returns (uint256 price, uint256 updatedAt)
{
(uint80 roundId, int256 answer,, uint256 at, uint80 answeredIn) =
IAggregatorV3(feed.aggregator).latestRoundData();
if (answeredIn < roundId) revert IncompleteRound(asset);
if (answer <= 0) revert BadPrice(asset, answer);
if (at == 0 || block.timestamp - at > feed.maxAge) revert StalePrice(asset, at, feed.maxAge);
price = _rescale(uint256(answer), IAggregatorV3(feed.aggregator).decimals());
updatedAt = at;
}
/// @dev Normalises a feed's answer to `DECIMALS`, in whichever direction it needs.
function _rescale(uint256 answer, uint8 feedDecimals) private pure returns (uint256) {
if (feedDecimals == DECIMALS) return answer;
if (feedDecimals < DECIMALS) return answer * (10 ** (DECIMALS - feedDecimals));
return answer / (10 ** (feedDecimals - DECIMALS));
}
/// @dev The uptime feed answers 0 when the sequencer is up and 1 when it is down, and its
/// `startedAt` is when that state began -- which is what the grace period is measured from.
function _requireSequencerUp() private view {
address feed = sequencerUptimeFeed;
if (feed == address(0)) return;
(, int256 answer, uint256 startedAt,,) = IAggregatorV3(feed).latestRoundData();
if (answer != 0) revert SequencerDown();
uint256 up = block.timestamp - startedAt;
if (up < SEQUENCER_GRACE) revert SequencerRecovering(SEQUENCER_GRACE - up);
}
}
src/libraries/LiquidityAmounts.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* @notice Converting an amount of one token into the liquidity a single-sided V4 position needs.
*
* @dev V3's position manager took the amounts you had and worked out the liquidity. V4's takes the
* liquidity and works out the amounts, so this arithmetic moves from Uniswap's side of the
* call to ours.
*
* It is computed here rather than passed in by the caller on purpose. The launchpad's central
* claim is that the whole supply goes into the pool, and a caller-supplied liquidity figure
* that came in low would put part of the supply back in the creator's hands -- a pre-mine
* produced by arithmetic rather than by intent, which is no better for whoever buys it. The
* factory checks what actually landed as well, but it should not be relying on that check to
* catch its own inputs.
*
* Every launch here is single-sided: the range sits entirely on one side of the opening price,
* so exactly one of these two is ever the right one to call.
*/
library LiquidityAmounts {
error PriceOutOfOrder();
uint256 internal constant Q96 = 0x1000000000000000000000000;
/**
* @notice 512-bit multiply then divide, without losing the high bits in between.
*
* @dev Needed twice below and unavoidable: `sqrtA * sqrtB` is up to 2^320, and the product of an
* amount with that intermediate is larger still. Doing it in 256 bits would overflow on
* every realistic launch rather than a rare one.
*
* This is Remco Bloemen's full-width division, the same routine Uniswap's own periphery
* uses. It is transcribed rather than invented, and the fork tests check its output against
* real positions minted on the real position manager.
*/
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
uint256 prod0; // least significant 256 bits of the product
uint256 prod1; // most significant 256 bits
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// The product fits in 256 bits: an ordinary division is exact.
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Otherwise the result must still fit, which it only does if the denominator is larger
// than the high word.
require(denominator > prod1);
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor the powers of two out of the denominator, so what is left is odd and therefore
// invertible modulo 2^256.
uint256 twos = (0 - denominator) & denominator;
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Newton-Raphson on the modular inverse: four correct bits, doubling each round, so six
// rounds cover all 256.
uint256 inv = (3 * denominator) ^ 2;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
result = prod0 * inv;
}
}
/**
* @notice Liquidity for a position funded entirely with currency0.
*
* @dev The shape of a launch whose token sorts first: the range starts at the opening price and
* runs upward, so it holds only the token and fills with quote as the price rises.
*/
function forAmount0(uint160 sqrtA, uint160 sqrtB, uint256 amount0)
internal
pure
returns (uint128)
{
if (sqrtA > sqrtB) (sqrtA, sqrtB) = (sqrtB, sqrtA);
if (sqrtA == 0 || sqrtA == sqrtB) revert PriceOutOfOrder();
uint256 intermediate = mulDiv(sqrtA, sqrtB, Q96);
return _toUint128(mulDiv(amount0, intermediate, sqrtB - sqrtA));
}
/**
* @notice Liquidity for a position funded entirely with currency1.
*
* @dev The mirror case, for a token that sorts after its quote asset: the range runs downward
* from the opening price.
*/
function forAmount1(uint160 sqrtA, uint160 sqrtB, uint256 amount1)
internal
pure
returns (uint128)
{
if (sqrtA > sqrtB) (sqrtA, sqrtB) = (sqrtB, sqrtA);
if (sqrtA == sqrtB) revert PriceOutOfOrder();
return _toUint128(mulDiv(amount1, Q96, sqrtB - sqrtA));
}
function _toUint128(uint256 x) private pure returns (uint128 y) {
y = uint128(x);
// Silent truncation here would seed a pool with a fraction of the supply and report success.
require(y == x);
}
}
src/libraries/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;
/// @notice Uniswap V3's tick <-> sqrt-price conversion, vendored.
///
/// @dev Vendored rather than imported because the repo deliberately carries no Uniswap dependency
/// -- `src/interfaces/IUniswapV3.sol` is a hand-written slice of the surface for the same
/// reason. The arithmetic here cannot be approximated: the pool derives its opening tick by
/// running `getTickAtSqrtRatio` on whatever price `initialize` is handed, and the launch
/// depends on that tick coming back *exactly* equal to the one the position's boundary was set
/// to. Only the canonical implementation is its own exact inverse in that direction, so this is
/// a byte-for-byte port of Uniswap's, with the pre-0.8 wrapping arithmetic wrapped in
/// `unchecked` and the `require` strings turned into custom errors.
///
/// MIN_TICK / MAX_TICK here are the absolute bounds of the tick domain (+/-887272). They are
/// *not* the position bounds a launch uses: those are the same numbers floored to the fee
/// tier's spacing, and live in LaunchFactory where the spacing is known.
library TickMath {
/// @dev The tick domain: prices from 2**-128 to 2**128.
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = 887272;
/// @dev getSqrtRatioAtTick(MIN_TICK) and getSqrtRatioAtTick(MAX_TICK). The pool rejects a swap
/// price limit outside this open interval, so callers use MIN+1 / MAX-1.
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
error TickOutOfBounds();
error PriceOutOfBounds();
error RatioOutOfBounds();
/// @notice sqrt(1.0001**tick) * 2**96.
/// @dev Binary decomposition: each bit of |tick| multiplies in a precomputed Q128.128 factor,
/// so the whole range costs 20 multiplications rather than an exponentiation.
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
if (absTick > uint256(int256(MAX_TICK))) revert TickOutOfBounds();
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;
// The table is built for negative ticks; a positive tick is the reciprocal.
if (tick > 0) ratio = type(uint256).max / ratio;
// Q128.128 -> Q128.96, rounding up so that getTickAtSqrtRatio always recovers `tick`.
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice The greatest tick whose sqrt ratio is at most `sqrtPriceX96`.
/// @dev Not used by the launch path -- the pool computes this itself. It is here so scripts and
/// tests can turn a target price into the tick to configure, which is the direction an
/// operator actually thinks in.
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) {
revert PriceOutOfBounds();
}
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 logTwo = (int256(msb) - 128) << 64;
for (uint256 i; i < 14; ++i) {
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
logTwo := or(logTwo, shl(sub(63, i), f))
r := shr(f, r)
}
}
int256 logSqrt10001 = logTwo * 255738958999603826347141;
int24 tickLow = int24((logSqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((logSqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
/// @notice The tick whose price is `quoteAmount / tokenAmount`, floored to `spacing`.
///
/// @dev The operator-facing direction: "I want the whole supply to open at 12 SAMSUNG" becomes
/// `tickForRatio(12e18, 1e27, 200)`. Both amounts are in their own token's raw units, so a
/// 6-decimal quote asset needs no special handling by the caller.
///
/// Computed as `sqrt(q * 2**96 / t) << 48` rather than `sqrt(q * 2**192 / t)` so the
/// intermediate stays inside uint256. That costs roughly half the significant bits of the
/// square root, which is worth far less than one tick for any ratio a launch would use, and
/// the result is snapped to the tick spacing afterwards regardless. Ratios below 2**-96
/// floor to zero and are rejected rather than silently priced at the bottom of the domain.
///
/// Flooring is toward negative infinity (Solidity's `/` truncates toward zero, so a
/// negative tick needs the correction) because the launch price should never round *up*
/// into a higher opening valuation than was asked for.
function tickForRatio(uint256 quoteAmount, uint256 tokenAmount, int24 spacing)
internal
pure
returns (int24)
{
if (tokenAmount == 0) revert RatioOutOfBounds();
uint256 ratioX96 = (quoteAmount << 96) / tokenAmount;
if (ratioX96 == 0) revert RatioOutOfBounds();
uint160 sqrtPriceX96 = uint160(sqrt(ratioX96) << 48);
int24 tick = getTickAtSqrtRatio(sqrtPriceX96);
int24 snapped = (tick / spacing) * spacing;
if (tick < 0 && snapped != tick) snapped -= spacing;
return snapped;
}
/// @dev Babylonian, converging from above. Only ever run off-chain or in a script.
///
/// The `x < 4` guard is not an optimisation. Seeding `y` at `(x >> 1) + 1` makes the loop
/// condition `y < z` false immediately when x is 2 -- both start at 2 -- so it returns 2 as
/// the root of 2. Every other input converges correctly; 2 is the single value in the whole
/// uint256 domain where this seed does not, and floor(sqrt(x)) is 1 for all of 1, 2 and 3.
function sqrt(uint256 x) internal pure returns (uint256 z) {
if (x == 0) return 0;
if (x < 4) return 1;
z = x;
uint256 y = (x >> 1) + 1;
while (y < z) {
z = y;
y = (x / y + y) >> 1;
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.