Skip to content
Verified contractPartialMIT

KettoLens

Address0x0fbe7ace63b058ff6557bbe21298f0bd6e4698d8
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,329,258
Creation transaction
0x5a7e726d89…f22c7fd3c7

94 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/KettoLens.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {FullMath} from "v4-core/src/libraries/FullMath.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {Position} from "v4-core/src/libraries/Position.sol";
import {KettoKey} from "./KettoKey.sol";
import {KettoHook} from "./KettoHook.sol";
import {KettoToken} from "./KettoToken.sol";
import {KettoFactory} from "./KettoFactory.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Read-only helpers for the frontend and indexer, including pure-math price quotes.
/// @dev Every pool holds ONE liquidity position that never changes, so the pool behaves like a constant-product pool
///      with virtual reserves derived from (liquidity, sqrtPrice). Quotes use that closed form (accurate to a few wei);
///      the router enforces the real minimum output on-chain. All "pair" amounts are RAW units of the pair stock token
///      (18 decimals on most chains, 8 on Base B20); the frontend scales them by the pair's decimals.
contract KettoLens {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    uint16 private constant BPS = 10_000;
    uint256 private constant SUPPLY = 1_000_000_000 ether;
    uint160 private constant Q96 = 2 ** 96;
    int24 private constant TICK_MARGIN = 20 * 200;
    error BadPrice();


    IPoolManager public immutable poolManager;
    KettoHook public immutable hook;
    KettoFactory public immutable factory;

    constructor(IPoolManager pm_, KettoHook hook_, KettoFactory factory_) {
        poolManager = pm_;
        hook = hook_;
        factory = factory_;
    }

    struct TokenState {
        uint160 sqrtPriceX96;
        int24 tick;
        uint128 liquidity;
        uint256 reservePair; // virtual reserves (pair raw units / token wei)
        uint256 reserveToken;
        uint256 pricePairPerToken; // pair raw units per 1e18 token wei, scaled by 1e18 (keeps 8 decimal pairs precise)
        uint256 fdvPair; // fully diluted value of the local supply in pair raw units
        uint256 totalSupply; // supply on THIS chain (changes when tokens are bridged)
        address creator;
        uint16 taxBps;
        address pair;
        bytes32 pairId;
        uint256 creatorOwed;
        uint16 toPot; // share of the creator side (80% of the tax) that feeds the last-buyer pot, in bps
        uint256 potAmount; // pot standing to be won in the live round, pair raw units
        uint256 potEndsAt; // unix time the live 5 minute round ends
        address potLastBuyer; // current last buyer of the live round (address(0) if none yet)
        uint256 minBuy; // smallest buy (pair raw units) that can become the last buyer
    }

    function _reserves(address token, address pair)
        private
        view
        returns (uint160 sqrtP, int24 tick, uint128 liq, uint256 rp, uint256 rt)
    {
        (PoolKey memory key, bool pairIs0) = KettoKey.keyFor(token, pair, IHooks(address(hook)));
        PoolId id = key.toId();
        (sqrtP, tick,,) = poolManager.getSlot0(id);
        // The pool's active liquidity can be 0 while the price sits exactly on the range edge (a fresh launch), so read
        // the one locked position instead.
        int24 sp = KettoKey.TICK_SPACING;
        int24 edge = (TickMath.MIN_TICK / sp) * sp;
        int24 st = factory.startTickOf(token);
        (int24 lo, int24 hi) = pairIs0 ? (edge, st) : (st, -edge);
        liq = poolManager.getPositionLiquidity(id, Position.calculatePositionKey(address(factory), lo, hi, bytes32(0)));
        uint256 v0 = FullMath.mulDiv(liq, 2 ** 96, sqrtP); // virtual currency0
        uint256 v1 = FullMath.mulDiv(liq, sqrtP, 2 ** 96); // virtual currency1
        (rp, rt) = pairIs0 ? (v0, v1) : (v1, v0);
    }

    function tokenState(address token) external view returns (TokenState memory s) {
        (address creator, uint16 taxBps, address pair,, uint16 toPot) = hook.configs(token);
        s.toPot = toPot;
        s.creator = creator;
        s.taxBps = taxBps;
        s.pair = pair;
        s.pairId = factory.pairIdOf(token);
        (s.sqrtPriceX96, s.tick, s.liquidity, s.reservePair, s.reserveToken) = _reserves(token, pair);
        s.totalSupply = KettoToken(token).totalSupply();
        s.pricePairPerToken = s.reserveToken == 0 ? 0 : FullMath.mulDiv(s.reservePair, 1e36, s.reserveToken);
        s.fdvPair = FullMath.mulDiv(s.pricePairPerToken, s.totalSupply, 1e36);
        s.creatorOwed = hook.creatorOwed(token);
        (, s.potEndsAt, s.potAmount, s.potLastBuyer) = hook.potState(token);
        s.minBuy = hook.minBuy(pair);
    }

    /// @notice Tokens received for spending `pairIn` pair raw units (tax included) on a buy
    function quoteBuy(address token, uint256 pairIn) external view returns (uint256 tokensOut) {
        (, uint16 taxBps, address pair,,) = hook.configs(token);
        (,,, uint256 rp, uint256 rt) = _reserves(token, pair);
        uint256 net = pairIn - (pairIn * taxBps) / BPS;
        tokensOut = FullMath.mulDiv(rt, net, rp + net);
    }

    /// @notice Pair raw units received for selling `tokensIn` (tax already deducted)
    function quoteSell(address token, uint256 tokensIn) external view returns (uint256 pairOut) {
        (, uint16 taxBps, address pair,,) = hook.configs(token);
        (,,, uint256 rp, uint256 rt) = _reserves(token, pair);
        uint256 gross = FullMath.mulDiv(rp, tokensIn, rt + tokensIn);
        pairOut = gross - (gross * taxBps) / BPS;
    }

    /// @notice Pot winnings `account` can claim on `token` right now (pair raw units, a finished round included)
    function potClaimable(address token, address account) external view returns (uint256) {
        return hook.claimable(token, account);
    }

    /// @notice Creator payout waiting for `account` on `token` (in pair raw units)
    function pending(address token, address account) external view returns (uint256 creatorRewards) {
        (address creator,,,,) = hook.configs(token);
        if (creator == account) creatorRewards = hook.creatorOwed(token);
    }

    // ---------------------------------------------------------------- launch helpers (kept here to keep the factory small)

    /// @notice The token address a launch will get on THIS chain
    function predictToken(string calldata name, string calldata symbol, address creator, bytes32 salt)
        external
        view
        returns (address)
    {
        return factory.deployer().predict(name, symbol, creator, salt);
    }

    /// @notice The CANONICAL start tick for an opening fully diluted value expressed in RAW units of the pair stock token
    ///         (for example 18 decimals on most chains, 8 on Base B20). Canonical means the orientation where the pair is
    ///         currency0: price = tokens per raw pair unit = supply / fdv. When the pair sorts as currency1 the pool uses
    ///         the negated tick, and the signer and bounds still use the canonical one. Reverts with BadPrice if out of range.
    function previewStartTick(uint256 fdvRaw) external pure returns (int24 tick) {
        if (fdvRaw == 0 || fdvRaw >= 2 ** 128) revert BadPrice();
        uint256 sa = Math.sqrt(SUPPLY << 64);
        uint256 sb = Math.sqrt(fdvRaw << 64);
        uint256 sqrtP = FullMath.mulDiv(sa, Q96, sb);
        if (sqrtP <= TickMath.MIN_SQRT_PRICE || sqrtP >= TickMath.MAX_SQRT_PRICE) revert BadPrice();
        int24 raw = TickMath.getTickAtSqrtPrice(uint160(sqrtP));
        int24 sp = KettoKey.TICK_SPACING;
        int24 floored = (raw / sp) * sp;
        if (raw < 0 && raw % sp != 0) floored -= sp; // floor division for negatives
        tick = floored;
        if (tick < TickMath.MIN_TICK + TICK_MARGIN || tick > TickMath.MAX_TICK - TICK_MARGIN) revert BadPrice();
    }

    /// @notice The token address of a launch on a REMOTE chain (as configured in the registry)
    function predictRemoteToken(uint32 eid, string calldata name, string calldata symbol, address creator, bytes32 salt)
        external
        view
        returns (address)
    {
        (address rd, address rf,) = factory.remotes(eid);
        return factory.deployer().predictRemote(rd, rf, name, symbol, creator, salt);
    }

}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@layerzerolabs/oft-evm/=node_modules/@layerzerolabs/oft-evm/",
    "@layerzerolabs/oapp-evm/=node_modules/@layerzerolabs/oapp-evm/",
    "@layerzerolabs/lz-evm-protocol-v2/=node_modules/@layerzerolabs/lz-evm-protocol-v2/",
    "@layerzerolabs/lz-evm-messagelib-v2/=node_modules/@layerzerolabs/lz-evm-messagelib-v2/",
    "@layerzerolabs/test-devtools-evm-foundry/=node_modules/@layerzerolabs/test-devtools-evm-foundry/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "@layerzerolabs/lz-evm-v1-0.7/=node_modules/@layerzerolabs/lz-evm-v1-0.7/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.