// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; import {KibblePool} from "./libraries/KibblePool.sol"; import {PriceMath} from "./libraries/PriceMath.sol"; import {ChainBlock} from "./libraries/ChainBlock.sol"; import {KibbleConstants as K} from "./libraries/KibbleConstants.sol"; /// @title Oracle /// @notice TWAP of the HYPE / KIBBLE pool over 10,000 blocks (docs §2, §4, §11, §13). /// @dev The pool has no hook, so v4 keeps no price history. This contract keeps a block-weighted cumulative of the /// spot price (HYPE per KIBBLE, 1e18 scaled): on every `update()` the price recorded at the previous update is /// weighted by the blocks elapsed since, then the new spot is read from PoolManager slot0. /// `update()` is called by Miner, Zapper and Burner on every interaction and can be called by anyone. /// Snapshots of the cumulative are stored in a ring buffer at most every OBS_INTERVAL blocks, so 128 slots /// always cover more than 10,000 blocks. TWAP = (cumNow - cumAtOrBefore(now - 10,000)) / elapsed. /// Before 10,000 blocks of history, the oldest snapshot (block 0, genesis price) is used. contract Oracle { using PoolIdLibrary for PoolKey; using StateLibrary for IPoolManager; error NotGenesis(); error AlreadyInitialized(); struct Observation { uint256 blockNumber; uint256 cumulative; } uint256 public constant OBS_INTERVAL = 100; uint256 public constant CARDINALITY = 128; IPoolManager public immutable poolManager; address public immutable kibble; address public immutable genesis; PoolId public immutable poolId; bool public initialized; /// @notice Sum of price × blocks since initialization (at `lastBlock`). uint256 public cumulative; /// @notice Block of the last update. uint256 public lastBlock; /// @notice Spot price read at the last update, weighted until the next one. uint256 public lastPrice; Observation[CARDINALITY] internal _obs; /// @notice Number of observations written (capped at CARDINALITY). uint256 public observationCount; /// @notice Index of the newest observation. uint256 public observationIndex; constructor(IPoolManager poolManager_, address kibble_, address genesis_) { poolManager = poolManager_; kibble = kibble_; genesis = genesis_; poolId = KibblePool.key(kibble_).toId(); } /// @notice Starts the accumulator at block 0, after the pool is seeded. Only `Genesis`. function initialize() external { if (msg.sender != genesis) revert NotGenesis(); if (initialized) revert AlreadyInitialized(); initialized = true; uint256 nowBlock = ChainBlock.number(); lastBlock = nowBlock; lastPrice = spotPrice(); _obs[0] = Observation(nowBlock, 0); observationCount = 1; } /// @notice Pokes the accumulator (docs §4 TWAP). Anyone can call. No-op before block 0. function update() public { if (!initialized) return; uint256 nowBlock = ChainBlock.number(); uint256 last = lastBlock; if (nowBlock > last) { uint256 cum = cumulative + lastPrice * (nowBlock - last); cumulative = cum; lastBlock = nowBlock; Observation storage newest = _obs[observationIndex]; if (nowBlock >= newest.blockNumber + OBS_INTERVAL) { uint256 idx = (observationIndex + 1) % CARDINALITY; _obs[idx] = Observation(nowBlock, cum); observationIndex = idx; if (observationCount < CARDINALITY) observationCount += 1; } } lastPrice = spotPrice(); } /// @notice Pool spot price, HYPE per KIBBLE, 1e18 scaled. 0 if the pool is not initialized. function spotPrice() public view returns (uint256) { (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId); return PriceMath.priceFromSqrt(sqrtPriceX96); } /// @notice Cumulative price extrapolated to the current block. function cumulativeNow() public view returns (uint256) { return cumulative + lastPrice * (ChainBlock.number() - lastBlock); } /// @notice TWAP over the last 10,000 blocks, HYPE per KIBBLE, 1e18 scaled (docs §2). 0 before block 0. /// Uses the newest snapshot at or before now - 10,000, or the oldest snapshot if history is shorter. function twap() public view returns (uint256) { if (!initialized) return 0; uint256 nowBlock = ChainBlock.number(); Observation memory o = _observationAtOrBefore(nowBlock >= K.TWAP_WINDOW ? nowBlock - K.TWAP_WINDOW : 0); uint256 elapsed = nowBlock - o.blockNumber; if (elapsed == 0) return lastPrice; return (cumulativeNow() - o.cumulative) / elapsed; } /// @notice Observation by logical position (0 = oldest). function observation(uint256 i) public view returns (uint256 blockNumber, uint256 cum) { Observation memory o = _obs[_physical(i)]; return (o.blockNumber, o.cumulative); } function _physical(uint256 i) internal view returns (uint256) { uint256 n = observationCount; uint256 oldest = n < CARDINALITY ? 0 : (observationIndex + 1) % CARDINALITY; return (oldest + i) % CARDINALITY; } /// @dev Binary search over the chronologically ordered ring buffer. function _observationAtOrBefore(uint256 target) internal view returns (Observation memory) { uint256 n = observationCount; Observation memory oldest = _obs[_physical(0)]; if (oldest.blockNumber >= target) return oldest; uint256 lo = 0; uint256 hi = n - 1; while (lo < hi) { uint256 mid = (lo + hi + 1) / 2; if (_obs[_physical(mid)].blockNumber <= target) lo = mid; else hi = mid - 1; } return _obs[_physical(lo)]; } }