Skip to content

Reading Elysium

Mine

Oracle.sol

144 lines · sha256 0f48bfe6ba7f6cca5ece91e7cd5b399446d6abc3dc5de9e332c15dbcbee445c6 · Raw

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.26;
3
4import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
5import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
6import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
7import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
8import {KibblePool} from "./libraries/KibblePool.sol";
9import {PriceMath} from "./libraries/PriceMath.sol";
10import {ChainBlock} from "./libraries/ChainBlock.sol";
11import {KibbleConstants as K} from "./libraries/KibbleConstants.sol";
12
13/// @title Oracle
14/// @notice TWAP of the HYPE / KIBBLE pool over 10,000 blocks (docs §2, §4, §11, §13).
15/// @dev The pool has no hook, so v4 keeps no price history. This contract keeps a block-weighted cumulative of the
16/// spot price (HYPE per KIBBLE, 1e18 scaled): on every `update()` the price recorded at the previous update is
17/// weighted by the blocks elapsed since, then the new spot is read from PoolManager slot0.
18/// `update()` is called by Miner, Zapper and Burner on every interaction and can be called by anyone.
19/// Snapshots of the cumulative are stored in a ring buffer at most every OBS_INTERVAL blocks, so 128 slots
20/// always cover more than 10,000 blocks. TWAP = (cumNow - cumAtOrBefore(now - 10,000)) / elapsed.
21/// Before 10,000 blocks of history, the oldest snapshot (block 0, genesis price) is used.
22contract Oracle {
23 using PoolIdLibrary for PoolKey;
24 using StateLibrary for IPoolManager;
25
26 error NotGenesis();
27 error AlreadyInitialized();
28
29 struct Observation {
30 uint256 blockNumber;
31 uint256 cumulative;
32 }
33
34 uint256 public constant OBS_INTERVAL = 100;
35 uint256 public constant CARDINALITY = 128;
36
37 IPoolManager public immutable poolManager;
38 address public immutable kibble;
39 address public immutable genesis;
40 PoolId public immutable poolId;
41
42 bool public initialized;
43 /// @notice Sum of price × blocks since initialization (at `lastBlock`).
44 uint256 public cumulative;
45 /// @notice Block of the last update.
46 uint256 public lastBlock;
47 /// @notice Spot price read at the last update, weighted until the next one.
48 uint256 public lastPrice;
49
50 Observation[CARDINALITY] internal _obs;
51 /// @notice Number of observations written (capped at CARDINALITY).
52 uint256 public observationCount;
53 /// @notice Index of the newest observation.
54 uint256 public observationIndex;
55
56 constructor(IPoolManager poolManager_, address kibble_, address genesis_) {
57 poolManager = poolManager_;
58 kibble = kibble_;
59 genesis = genesis_;
60 poolId = KibblePool.key(kibble_).toId();
61 }
62
63 /// @notice Starts the accumulator at block 0, after the pool is seeded. Only `Genesis`.
64 function initialize() external {
65 if (msg.sender != genesis) revert NotGenesis();
66 if (initialized) revert AlreadyInitialized();
67 initialized = true;
68 uint256 nowBlock = ChainBlock.number();
69 lastBlock = nowBlock;
70 lastPrice = spotPrice();
71 _obs[0] = Observation(nowBlock, 0);
72 observationCount = 1;
73 }
74
75 /// @notice Pokes the accumulator (docs §4 TWAP). Anyone can call. No-op before block 0.
76 function update() public {
77 if (!initialized) return;
78 uint256 nowBlock = ChainBlock.number();
79 uint256 last = lastBlock;
80 if (nowBlock > last) {
81 uint256 cum = cumulative + lastPrice * (nowBlock - last);
82 cumulative = cum;
83 lastBlock = nowBlock;
84 Observation storage newest = _obs[observationIndex];
85 if (nowBlock >= newest.blockNumber + OBS_INTERVAL) {
86 uint256 idx = (observationIndex + 1) % CARDINALITY;
87 _obs[idx] = Observation(nowBlock, cum);
88 observationIndex = idx;
89 if (observationCount < CARDINALITY) observationCount += 1;
90 }
91 }
92 lastPrice = spotPrice();
93 }
94
95 /// @notice Pool spot price, HYPE per KIBBLE, 1e18 scaled. 0 if the pool is not initialized.
96 function spotPrice() public view returns (uint256) {
97 (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
98 return PriceMath.priceFromSqrt(sqrtPriceX96);
99 }
100
101 /// @notice Cumulative price extrapolated to the current block.
102 function cumulativeNow() public view returns (uint256) {
103 return cumulative + lastPrice * (ChainBlock.number() - lastBlock);
104 }
105
106 /// @notice TWAP over the last 10,000 blocks, HYPE per KIBBLE, 1e18 scaled (docs §2). 0 before block 0.
107 /// Uses the newest snapshot at or before now - 10,000, or the oldest snapshot if history is shorter.
108 function twap() public view returns (uint256) {
109 if (!initialized) return 0;
110 uint256 nowBlock = ChainBlock.number();
111 Observation memory o = _observationAtOrBefore(nowBlock >= K.TWAP_WINDOW ? nowBlock - K.TWAP_WINDOW : 0);
112 uint256 elapsed = nowBlock - o.blockNumber;
113 if (elapsed == 0) return lastPrice;
114 return (cumulativeNow() - o.cumulative) / elapsed;
115 }
116
117 /// @notice Observation by logical position (0 = oldest).
118 function observation(uint256 i) public view returns (uint256 blockNumber, uint256 cum) {
119 Observation memory o = _obs[_physical(i)];
120 return (o.blockNumber, o.cumulative);
121 }
122
123 function _physical(uint256 i) internal view returns (uint256) {
124 uint256 n = observationCount;
125 uint256 oldest = n < CARDINALITY ? 0 : (observationIndex + 1) % CARDINALITY;
126 return (oldest + i) % CARDINALITY;
127 }
128
129 /// @dev Binary search over the chronologically ordered ring buffer.
130 function _observationAtOrBefore(uint256 target) internal view returns (Observation memory) {
131 uint256 n = observationCount;
132 Observation memory oldest = _obs[_physical(0)];
133 if (oldest.blockNumber >= target) return oldest;
134 uint256 lo = 0;
135 uint256 hi = n - 1;
136 while (lo < hi) {
137 uint256 mid = (lo + hi + 1) / 2;
138 if (_obs[_physical(mid)].blockNumber <= target) lo = mid;
139 else hi = mid - 1;
140 }
141 return _obs[_physical(lo)];
142 }
143}
144