Source / As deployed

06 / 06

The contracts,
as deployed.

The pool and the reader, in the source that was compiled for this deployment. The same source is verified on the explorer. Publishing it is not an audit: nobody outside the project has reviewed it.

01Compiler
solc 0.8.39
02Optimizer
200 runs, via IR
03EVM
cancun
04Audit
None

CoverPool.sol

contracts/src/CoverPool.sol

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.24;
3
4import {IERC20} from "./interfaces/IERC20.sol";
5import {IHyperCoreReader} from "./interfaces/IHyperCoreReader.sol";
6import {IReportSink} from "./interfaces/IReportSink.sol";
7
8/// @title CoverPool
9/// @notice Gap cover for Hyperliquid perp stops. A trader pays a premium; if the
10/// mark price reaches the stop and the book can only fill the position at a worse
11/// price, the pool pays the difference, up to a cap.
12///
13/// The cover is parametric: it settles on the HyperCore book at the moment of the
14/// trigger, not on the trader's own fill, so it needs read access only.
15///
16/// Three rules keep the pool solvent and hard to game:
17/// 1. Every cover reserves its maximum payout, and reserves never exceed
18/// `maxUtilizationBps` of pool assets. Underwriters cannot withdraw below that.
19/// 2. Open cover per market side is capped at a fraction of the resting depth
20/// inside the covered gap, so emptying the book to fake a gap costs more than
21/// the covers can pay.
22/// 3. The slippage the book already showed at purchase is a deductible, so
23/// ordinary slippage on a large order is never paid out.
24///
25/// Buying takes two transactions. The trader requests a cover and the pool holds
26/// the most they are willing to pay; then anyone starts it against a mark price
27/// no older than the request. The trader commits before the price that decides
28/// the premium exists, so a cover cannot be bought against a price that is
29/// already out of date.
30///
31/// The payout is measured against the stop price, so it grows if the price runs
32/// on before anyone calls `trigger`. Underwriters depend on a keeper that calls
33/// it at the first cross.
34contract CoverPool {
35 uint256 internal constant BPS = 10_000;
36 uint256 internal constant PPM = 1_000_000;
37 /// size (8 dec) * price (8 dec) / NOTIONAL_SCALE = quote token (6 dec)
38 uint256 internal constant NOTIONAL_SCALE = 1e10;
39 uint256 internal constant MIN_PROXIMITY_BPS = 2_500;
40 uint256 internal constant MAX_PROXIMITY_BPS = 40_000;
41 /// Shares are minted as if the pool already held this many shares for one
42 /// unit of USDC, so the first depositor cannot inflate the share price and
43 /// round later deposits down to nothing.
44 uint256 internal constant VIRTUAL_SHARES = 1e6;
45 uint256 internal constant VIRTUAL_ASSETS = 1;
46
47 enum Status {
48 None,
49 Requested,
50 Active,
51 Settled,
52 Expired,
53 Cancelled
54 }
55
56 struct Market {
57 bool enabled;
58 /// Premium per day at the reference stop distance and zero utilization.
59 uint32 baseRatePpmPerDay;
60 /// Largest gap beyond the stop the pool pays for.
61 uint16 maxGapBps;
62 uint16 minStopDistanceBps;
63 /// Covers whose size already moves the book more than this are refused.
64 uint16 maxImpactAtBuyBps;
65 /// Share of resting depth inside `maxGapBps` that may be covered per side.
66 uint16 depthFactorBps;
67 }
68
69 struct Cover {
70 address holder;
71 uint32 asset;
72 bool isLong;
73 Status status;
74 /// Zero until the cover starts.
75 uint64 expiry;
76 uint16 deductibleBps;
77 uint64 requestedAt;
78 uint32 duration;
79 uint256 size;
80 uint256 stopPx;
81 uint256 notional;
82 uint256 maxPayout;
83 /// While requested: the most the holder will pay, held by the pool.
84 /// Once started: the premium that was charged.
85 uint256 premium;
86 /// What the cover paid when it settled.
87 uint256 payout;
88 }
89
90 struct Quote {
91 uint256 premium;
92 uint256 maxPayout;
93 uint256 notional;
94 uint16 deductibleBps;
95 }
96
97 IERC20 public immutable quoteToken;
98 uint256 public immutable maxUtilizationBps;
99 uint256 public immutable protocolFeeBps;
100 /// Extra premium multiplier at full utilization, in bps (30_000 = +3x).
101 uint256 public immutable utilizationSlopeBps;
102 uint256 public immutable refDistanceBps;
103 /// Oldest mark price a cover may be priced and started against, in seconds.
104 uint256 public immutable maxMarkAge;
105 /// Oldest mark price a cover may be settled against, in seconds.
106 uint256 public immutable maxTriggerAge;
107 /// How long a request can be started. After that it can only be cancelled.
108 uint256 public immutable requestTtl;
109 uint256 public immutable withdrawCooldown;
110 uint256 public immutable minDuration;
111 uint256 public immutable maxDuration;
112
113 address public owner;
114 address public pendingOwner;
115 address public treasury;
116 IHyperCoreReader public reader;
117
118 /// Deposits that would take `totalAssets` above this are refused.
119 uint256 public depositCap;
120 /// Stops new deposits and new covers. Withdrawals, cancellations, triggers
121 /// and expiries stay open.
122 bool public paused;
123
124 uint256 public totalAssets;
125 uint256 public totalShares;
126 uint256 public reserved;
127 uint256 public nextCoverId = 1;
128
129 mapping(address => uint256) public sharesOf;
130 mapping(address => uint256) public lastDepositAt;
131 mapping(uint32 => Market) public markets;
132 mapping(uint256 => Cover) public covers;
133 /// asset => isLong => open covered notional
134 mapping(uint32 => mapping(bool => uint256)) public openNotional;
135 mapping(address => uint256[]) internal coverIds;
136
137 uint256 private locked = 1;
138
139 event Deposited(address indexed underwriter, uint256 assets, uint256 shares);
140 event Withdrawn(address indexed underwriter, uint256 assets, uint256 shares);
141 event MarketSet(uint32 indexed asset, Market market);
142 event ReaderSet(address reader);
143 event TreasurySet(address treasury);
144 event DepositCapSet(uint256 cap);
145 event PausedSet(bool paused);
146 event OwnershipTransferStarted(address indexed owner, address indexed pendingOwner);
147 event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
148 event CoverRequested(
149 uint256 indexed id,
150 address indexed holder,
151 uint32 indexed asset,
152 bool isLong,
153 uint256 size,
154 uint256 stopPx,
155 uint256 duration,
156 uint256 maxPremium
157 );
158 event CoverStarted(uint256 indexed id, uint64 expiry, uint256 premium, uint256 maxPayout, uint16 deductibleBps);
159 event RequestCancelled(uint256 indexed id);
160 event CoverSettled(uint256 indexed id, uint256 markPx, uint256 execPx, bool fullyFilled, uint256 payout);
161 event CoverExpired(uint256 indexed id);
162
163 error NotOwner();
164 error Reentrancy();
165 error ZeroAmount();
166 error TransferFailed();
167 error CooldownActive();
168 error ReserveLocked();
169 error Paused();
170 error DepositCapReached();
171 error MarketDisabled();
172 error BadDuration();
173 error StaleMark();
174 error StopOnWrongSide();
175 error StopTooClose();
176 error BookTooThin();
177 error NoPosition();
178 error PoolCapacity();
179 error DepthCapacity();
180 error PremiumTooHigh();
181 error NotRequested();
182 error RequestLapsed();
183 error MarkBeforeRequest();
184 error NotHolder();
185 error NotActive();
186 error CoverExpiredAlready();
187 error StopNotReached();
188 error NotExpired();
189 error BadConfig();
190
191 modifier onlyOwner() {
192 if (msg.sender != owner) revert NotOwner();
193 _;
194 }
195
196 modifier nonReentrant() {
197 if (locked != 1) revert Reentrancy();
198 locked = 2;
199 _;
200 locked = 1;
201 }
202
203 struct Params {
204 uint256 maxUtilizationBps;
205 uint256 protocolFeeBps;
206 uint256 utilizationSlopeBps;
207 uint256 refDistanceBps;
208 uint256 maxMarkAge;
209 uint256 maxTriggerAge;
210 uint256 requestTtl;
211 uint256 withdrawCooldown;
212 uint256 minDuration;
213 uint256 maxDuration;
214 uint256 depositCap;
215 }
216
217 constructor(IERC20 quoteToken_, IHyperCoreReader reader_, address treasury_, Params memory p) {
218 if (
219 p.maxUtilizationBps == 0 || p.maxUtilizationBps > BPS || p.protocolFeeBps > BPS / 2 || p.refDistanceBps == 0
220 || p.maxMarkAge == 0 || p.maxTriggerAge == 0 || p.requestTtl == 0 || p.minDuration == 0
221 || p.maxDuration < p.minDuration || p.maxDuration > type(uint32).max || treasury_ == address(0)
222 ) revert BadConfig();
223 quoteToken = quoteToken_;
224 reader = reader_;
225 treasury = treasury_;
226 owner = msg.sender;
227 maxUtilizationBps = p.maxUtilizationBps;
228 protocolFeeBps = p.protocolFeeBps;
229 utilizationSlopeBps = p.utilizationSlopeBps;
230 refDistanceBps = p.refDistanceBps;
231 maxMarkAge = p.maxMarkAge;
232 maxTriggerAge = p.maxTriggerAge;
233 requestTtl = p.requestTtl;
234 withdrawCooldown = p.withdrawCooldown;
235 minDuration = p.minDuration;
236 maxDuration = p.maxDuration;
237 depositCap = p.depositCap;
238 emit OwnershipTransferred(address(0), msg.sender);
239 }
240
241 // ---------------------------------------------------------------- admin
242
243 function setMarket(uint32 asset, Market calldata m) external onlyOwner {
244 if (m.maxGapBps == 0 || m.maxGapBps >= BPS || m.depthFactorBps > BPS) revert BadConfig();
245 markets[asset] = m;
246 emit MarketSet(asset, m);
247 }
248
249 /// @dev Swaps the HyperCore adapter, e.g. from the mock to the precompile
250 /// adapter. Whoever holds `owner` can point the pool at a dishonest reader.
251 function setReader(IHyperCoreReader reader_) external onlyOwner {
252 reader = reader_;
253 emit ReaderSet(address(reader_));
254 }
255
256 function setTreasury(address treasury_) external onlyOwner {
257 if (treasury_ == address(0)) revert BadConfig();
258 treasury = treasury_;
259 emit TreasurySet(treasury_);
260 }
261
262 function setDepositCap(uint256 cap) external onlyOwner {
263 depositCap = cap;
264 emit DepositCapSet(cap);
265 }
266
267 function setPaused(bool paused_) external onlyOwner {
268 paused = paused_;
269 emit PausedSet(paused_);
270 }
271
272 /// @dev Two steps, so ownership cannot be sent to an address nobody controls.
273 function transferOwnership(address newOwner) external onlyOwner {
274 pendingOwner = newOwner;
275 emit OwnershipTransferStarted(owner, newOwner);
276 }
277
278 function acceptOwnership() external {
279 if (msg.sender != pendingOwner) revert NotOwner();
280 emit OwnershipTransferred(owner, msg.sender);
281 owner = msg.sender;
282 pendingOwner = address(0);
283 }
284
285 // ------------------------------------------------------------- delivery
286
287 /// @notice Run several of this contract's calls in one transaction, as the
288 /// caller. A reader that takes signed reports needs its report delivered in
289 /// the same transaction as the call that reads it.
290 function multicall(bytes[] calldata calls) external returns (bytes[] memory results) {
291 results = new bytes[](calls.length);
292 for (uint256 i; i < calls.length; ++i) {
293 (bool ok, bytes memory result) = address(this).delegatecall(calls[i]);
294 if (!ok) {
295 assembly ("memory-safe") {
296 revert(add(result, 0x20), mload(result))
297 }
298 }
299 results[i] = result;
300 }
301 }
302
303 /// @notice Hand a signed HyperCore report to the reader. The reader checks
304 /// the signature; this only forwards it.
305 function submitReport(bytes calldata report, bytes calldata signature) external {
306 IReportSink(address(reader)).submit(report, signature);
307 }
308
309 // --------------------------------------------------------- underwriting
310
311 function deposit(uint256 assets) external nonReentrant returns (uint256 shares) {
312 if (paused) revert Paused();
313 if (assets == 0) revert ZeroAmount();
314 if (totalAssets + assets > depositCap) revert DepositCapReached();
315 shares = assets * (totalShares + VIRTUAL_SHARES) / (totalAssets + VIRTUAL_ASSETS);
316 if (shares == 0) revert ZeroAmount();
317 totalAssets += assets;
318 totalShares += shares;
319 sharesOf[msg.sender] += shares;
320 lastDepositAt[msg.sender] = block.timestamp;
321 _pull(msg.sender, assets);
322 emit Deposited(msg.sender, assets, shares);
323 }
324
325 function withdraw(uint256 shares) external nonReentrant returns (uint256 assets) {
326 if (shares == 0) revert ZeroAmount();
327 if (block.timestamp < lastDepositAt[msg.sender] + withdrawCooldown) revert CooldownActive();
328 assets = shares * (totalAssets + VIRTUAL_ASSETS) / (totalShares + VIRTUAL_SHARES);
329 uint256 remaining = totalAssets - assets;
330 if (reserved * BPS > remaining * maxUtilizationBps) revert ReserveLocked();
331 sharesOf[msg.sender] -= shares;
332 totalShares -= shares;
333 totalAssets = remaining;
334 _push(msg.sender, assets);
335 emit Withdrawn(msg.sender, assets, shares);
336 }
337
338 /// @notice What `shares` would be paid on withdrawal right now, in USDC.
339 function previewWithdraw(uint256 shares) external view returns (uint256) {
340 return shares * (totalAssets + VIRTUAL_ASSETS) / (totalShares + VIRTUAL_SHARES);
341 }
342
343 /// @notice Pool assets that can still back new covers.
344 function freeCapacity() public view returns (uint256) {
345 uint256 cap = totalAssets * maxUtilizationBps / BPS;
346 return cap > reserved ? cap - reserved : 0;
347 }
348
349 // ---------------------------------------------------------------- cover
350
351 /// @notice Price a cover for `holder` against the current mark and book.
352 /// Reverts with the same error `startCover` would.
353 function quote(address holder, uint32 asset, bool isLong, uint256 size, uint256 stopPx, uint256 duration)
354 public
355 view
356 returns (Quote memory q)
357 {
358 Market memory m = markets[asset];
359 if (!m.enabled) revert MarketDisabled();
360 if (duration < minDuration || duration > maxDuration) revert BadDuration();
361 if (size == 0 || stopPx == 0) revert ZeroAmount();
362
363 (uint256 mark,) = _freshMark(asset, maxMarkAge);
364 if (isLong ? stopPx >= mark : stopPx <= mark) revert StopOnWrongSide();
365 uint256 distanceBps = (isLong ? mark - stopPx : stopPx - mark) * BPS / mark;
366 if (distanceBps < m.minStopDistanceBps || distanceBps == 0) revert StopTooClose();
367
368 (uint256 execPx, bool filled) = reader.impactPx(asset, isLong, size);
369 if (!filled) revert BookTooThin();
370 uint256 impactBps = _adverseMove(isLong, mark, execPx) * BPS / mark;
371 if (impactBps > m.maxImpactAtBuyBps) revert BookTooThin();
372
373 int256 position = reader.positionSize(holder, asset);
374 if (isLong ? position < int256(size) : position > -int256(size)) revert NoPosition();
375
376 q.notional = size * stopPx / NOTIONAL_SCALE;
377 q.maxPayout = q.notional * m.maxGapBps / BPS;
378 q.deductibleBps = uint16(impactBps);
379 if (q.maxPayout == 0) revert ZeroAmount();
380
381 if (q.maxPayout > freeCapacity()) revert PoolCapacity();
382 uint256 depth = reader.depthWithinBps(asset, isLong, m.maxGapBps);
383 if (openNotional[asset][isLong] + q.notional > depth * m.depthFactorBps / BPS) revert DepthCapacity();
384
385 uint256 utilBps = (reserved + q.maxPayout) * BPS / totalAssets;
386 uint256 proximityBps = refDistanceBps * BPS / distanceBps;
387 if (proximityBps < MIN_PROXIMITY_BPS) proximityBps = MIN_PROXIMITY_BPS;
388 if (proximityBps > MAX_PROXIMITY_BPS) proximityBps = MAX_PROXIMITY_BPS;
389 uint256 utilMultBps = BPS + utilizationSlopeBps * utilBps * utilBps / (BPS * BPS);
390
391 uint256 ratePpm = uint256(m.baseRatePpmPerDay) * duration * proximityBps * utilMultBps / (1 days * BPS * BPS);
392 q.premium = q.notional * ratePpm / PPM;
393 if (q.premium == 0) revert ZeroAmount();
394 }
395
396 /// @notice Ask for a cover. The pool holds `maxPremium` until the cover
397 /// starts or the request is cancelled; nothing is covered yet.
398 function requestCover(uint32 asset, bool isLong, uint256 size, uint256 stopPx, uint256 duration, uint256 maxPremium)
399 external
400 nonReentrant
401 returns (uint256 id)
402 {
403 if (paused) revert Paused();
404 if (!markets[asset].enabled) revert MarketDisabled();
405 if (duration < minDuration || duration > maxDuration) revert BadDuration();
406 if (size == 0 || stopPx == 0 || maxPremium == 0) revert ZeroAmount();
407
408 id = nextCoverId++;
409 Cover storage c = covers[id];
410 c.holder = msg.sender;
411 c.asset = asset;
412 c.isLong = isLong;
413 c.status = Status.Requested;
414 c.requestedAt = uint64(block.timestamp);
415 c.duration = uint32(duration);
416 c.size = size;
417 c.stopPx = stopPx;
418 c.premium = maxPremium;
419 coverIds[msg.sender].push(id);
420
421 _pull(msg.sender, maxPremium);
422 emit CoverRequested(id, msg.sender, asset, isLong, size, stopPx, duration, maxPremium);
423 }
424
425 /// @notice Price a requested cover against the current mark and book, charge
426 /// the premium and put the cover in force. Anyone can call it. The mark must
427 /// be at least as new as the request, so the holder committed before it existed.
428 function startCover(uint256 id) external nonReentrant returns (uint256 premium) {
429 if (paused) revert Paused();
430 Cover storage c = covers[id];
431 if (c.status != Status.Requested) revert NotRequested();
432 if (block.timestamp > c.requestedAt + requestTtl) revert RequestLapsed();
433 (, uint64 markTime) = _freshMark(c.asset, maxMarkAge);
434 if (markTime < c.requestedAt) revert MarkBeforeRequest();
435
436 Quote memory q = quote(c.holder, c.asset, c.isLong, c.size, c.stopPx, c.duration);
437 uint256 held = c.premium;
438 premium = q.premium;
439 if (premium > held) revert PremiumTooHigh();
440
441 uint64 expiry = uint64(block.timestamp + c.duration);
442 c.status = Status.Active;
443 c.expiry = expiry;
444 c.deductibleBps = q.deductibleBps;
445 c.notional = q.notional;
446 c.maxPayout = q.maxPayout;
447 c.premium = premium;
448 reserved += q.maxPayout;
449 openNotional[c.asset][c.isLong] += q.notional;
450
451 uint256 fee = premium * protocolFeeBps / BPS;
452 totalAssets += premium - fee;
453 if (fee > 0) _push(treasury, fee);
454 if (held > premium) _push(c.holder, held - premium);
455
456 emit CoverStarted(id, expiry, premium, q.maxPayout, q.deductibleBps);
457 }
458
459 /// @notice Drop a request and return what the pool held for it. The holder
460 /// can cancel at any time; anyone can once the request has lapsed.
461 function cancelRequest(uint256 id) external nonReentrant {
462 Cover storage c = covers[id];
463 if (c.status != Status.Requested) revert NotRequested();
464 if (msg.sender != c.holder && block.timestamp <= c.requestedAt + requestTtl) revert NotHolder();
465 uint256 held = c.premium;
466 c.status = Status.Cancelled;
467 c.premium = 0;
468 _push(c.holder, held);
469 emit RequestCancelled(id);
470 }
471
472 /// @notice Settle a cover once the mark price has reached its stop. Anyone
473 /// can call it; underwriters want it called at the first cross, because the
474 /// payout is measured against the stop price and grows if the price runs on.
475 function trigger(uint256 id) external nonReentrant returns (uint256 payout) {
476 Cover storage c = covers[id];
477 if (c.status != Status.Active) revert NotActive();
478 if (block.timestamp > c.expiry) revert CoverExpiredAlready();
479
480 (uint256 mark,) = _freshMark(c.asset, maxTriggerAge);
481 if (c.isLong ? mark > c.stopPx : mark < c.stopPx) revert StopNotReached();
482
483 (uint256 execPx, bool filled) = reader.impactPx(c.asset, c.isLong, c.size);
484 if (filled) {
485 uint256 gross = c.size * _adverseMove(c.isLong, c.stopPx, execPx) / NOTIONAL_SCALE;
486 uint256 deductible = c.notional * c.deductibleBps / BPS;
487 payout = gross > deductible ? gross - deductible : 0;
488 if (payout > c.maxPayout) payout = c.maxPayout;
489 } else {
490 payout = c.maxPayout;
491 }
492
493 c.status = Status.Settled;
494 c.payout = payout;
495 _release(c);
496 if (payout > 0) {
497 totalAssets -= payout;
498 _push(c.holder, payout);
499 }
500 emit CoverSettled(id, mark, execPx, filled, payout);
501 }
502
503 function expire(uint256 id) external {
504 Cover storage c = covers[id];
505 if (c.status != Status.Active) revert NotActive();
506 if (block.timestamp <= c.expiry) revert NotExpired();
507 c.status = Status.Expired;
508 _release(c);
509 emit CoverExpired(id);
510 }
511
512 /// @notice Every cover `holder` has requested, oldest first, whatever its status.
513 function coverIdsOf(address holder) external view returns (uint256[] memory) {
514 return coverIds[holder];
515 }
516
517 // ------------------------------------------------------------- internal
518
519 function _release(Cover storage c) internal {
520 reserved -= c.maxPayout;
521 openNotional[c.asset][c.isLong] -= c.notional;
522 }
523
524 function _freshMark(uint32 asset, uint256 maxAge) internal view returns (uint256 mark, uint64 time) {
525 (mark, time) = reader.markPx(asset);
526 if (mark == 0 || time + maxAge < block.timestamp) revert StaleMark();
527 }
528
529 /// @dev How far `px` is on the losing side of `ref` for a closing order:
530 /// below it when selling out of a long, above it when buying back a short.
531 function _adverseMove(bool isLong, uint256 ref, uint256 px) internal pure returns (uint256) {
532 if (isLong) return px < ref ? ref - px : 0;
533 return px > ref ? px - ref : 0;
534 }
535
536 function _pull(address from, uint256 amount) internal {
537 (bool ok, bytes memory data) =
538 address(quoteToken).call(abi.encodeCall(IERC20.transferFrom, (from, address(this), amount)));
539 if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
540 }
541
542 function _push(address to, uint256 amount) internal {
543 (bool ok, bytes memory data) = address(quoteToken).call(abi.encodeCall(IERC20.transfer, (to, amount)));
544 if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
545 }
546}

SignedReader.sol

contracts/src/readers/SignedReader.sol

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.24;
3
4import {IHyperCoreReader} from "../interfaces/IHyperCoreReader.sol";
5import {IReportSink} from "../interfaces/IReportSink.sol";
6
7/// @title SignedReader
8/// @notice Answers the pool's four HyperCore questions from a report signed by
9/// one reporter key. It stands in for Elysium's read precompile until that
10/// ships, and it is exactly as honest as whoever holds the key: a reporter that
11/// signs a false book can make the pool pay.
12///
13/// A report lives in transient storage, so it exists only inside the
14/// transaction that delivers it. Nothing can be priced or settled against a
15/// report left over from an earlier transaction, and a call that arrives
16/// without one finds no mark price and is refused by the pool.
17contract SignedReader is IHyperCoreReader, IReportSink {
18 struct Report {
19 uint32 asset;
20 /// Unix seconds at which HyperCore produced the book in this report.
21 uint64 time;
22 /// Mark price, 8 decimals.
23 uint128 markPx;
24 /// The account whose position is attested, or zero for none.
25 address user;
26 /// That account's signed perp position in `asset`, 8 decimals.
27 int128 position;
28 /// Levels packed as `(price << 128) | size`, both 8 decimals, best first.
29 uint256[] bids;
30 uint256[] asks;
31 }
32
33 bytes32 public constant DOMAIN = keccak256("CoverPool HyperCore report v1");
34 uint256 public constant MAX_LEVELS = 128;
35 /// A report may be stamped this many seconds ahead of the block, to allow
36 /// for the two chains' clocks disagreeing.
37 uint256 public constant MAX_AHEAD = 3;
38 uint256 internal constant SIZE_MASK = type(uint128).max;
39 uint256 internal constant HALF_ORDER = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
40
41 /// Transient slots. Levels sit at `BIDS + i` and `ASKS + i`.
42 uint256 internal constant T_TIME = 1;
43 uint256 internal constant T_ASSET = 2;
44 uint256 internal constant T_MARK = 3;
45 uint256 internal constant T_USER = 4;
46 uint256 internal constant T_POSITION = 5;
47 uint256 internal constant T_BID_COUNT = 6;
48 uint256 internal constant T_ASK_COUNT = 7;
49 uint256 internal constant BIDS = 0x1000;
50 uint256 internal constant ASKS = 0x2000;
51
52 address public immutable reporter;
53 /// Reports older than this many seconds are refused.
54 uint256 public immutable maxAge;
55
56 error BadConfig();
57 error BadSignature();
58 error ReportTooOld();
59 error ReportFromTheFuture();
60 error BadReport();
61 error NoReport();
62
63 constructor(address reporter_, uint256 maxAge_) {
64 if (reporter_ == address(0) || maxAge_ == 0) revert BadConfig();
65 reporter = reporter_;
66 maxAge = maxAge_;
67 }
68
69 /// @notice The hash the reporter signs, as an Ethereum signed message.
70 /// It binds a report to this chain and this contract.
71 function digest(bytes calldata report) public view returns (bytes32) {
72 return keccak256(abi.encode(DOMAIN, block.chainid, address(this), keccak256(report)));
73 }
74
75 /// @inheritdoc IReportSink
76 function submit(bytes calldata report, bytes calldata signature) external {
77 if (_recover(digest(report), signature) != reporter) revert BadSignature();
78
79 Report memory r = abi.decode(report, (Report));
80 if (r.time > block.timestamp + MAX_AHEAD) revert ReportFromTheFuture();
81 if (r.time + maxAge < block.timestamp) revert ReportTooOld();
82 if (r.markPx == 0 || r.bids.length > MAX_LEVELS || r.asks.length > MAX_LEVELS) revert BadReport();
83
84 _store(T_TIME, r.time);
85 _store(T_ASSET, r.asset);
86 _store(T_MARK, r.markPx);
87 _store(T_USER, uint256(uint160(r.user)));
88 _store(T_POSITION, uint256(int256(r.position)));
89 _storeSide(BIDS, T_BID_COUNT, r.bids, true);
90 _storeSide(ASKS, T_ASK_COUNT, r.asks, false);
91 }
92
93 // ---------------------------------------------------------------- reads
94
95 /// @dev Returns zeroes when this transaction carries no report for `asset`,
96 /// which the pool treats as a stale mark.
97 function markPx(uint32 asset) external view returns (uint256 px, uint64 timestamp) {
98 if (!_holds(asset)) return (0, 0);
99 return (_load(T_MARK), uint64(_load(T_TIME)));
100 }
101
102 function impactPx(uint32 asset, bool isSell, uint256 size) external view returns (uint256 avgPx, bool fullyFilled) {
103 if (!_holds(asset)) revert NoReport();
104 (uint256 base, uint256 count) = isSell ? (BIDS, _load(T_BID_COUNT)) : (ASKS, _load(T_ASK_COUNT));
105 uint256 remaining = size;
106 uint256 cost;
107 for (uint256 i; i < count && remaining > 0; ++i) {
108 uint256 level = _load(base + i);
109 uint256 levelSize = level & SIZE_MASK;
110 uint256 take = levelSize < remaining ? levelSize : remaining;
111 cost += take * (level >> 128);
112 remaining -= take;
113 }
114 uint256 filled = size - remaining;
115 if (filled == 0) return (0, false);
116 return (cost / filled, remaining == 0);
117 }
118
119 function depthWithinBps(uint32 asset, bool bidSide, uint256 bps) external view returns (uint256 notional) {
120 if (!_holds(asset)) revert NoReport();
121 uint256 bidCount = _load(T_BID_COUNT);
122 uint256 askCount = _load(T_ASK_COUNT);
123 if (bidCount == 0 || askCount == 0) return 0;
124 uint256 mid = ((_load(BIDS) >> 128) + (_load(ASKS) >> 128)) / 2;
125 uint256 limit = bidSide ? mid - mid * bps / 10_000 : mid + mid * bps / 10_000;
126 (uint256 base, uint256 count) = bidSide ? (BIDS, bidCount) : (ASKS, askCount);
127 for (uint256 i; i < count; ++i) {
128 uint256 level = _load(base + i);
129 uint256 px = level >> 128;
130 if (bidSide ? px < limit : px > limit) break;
131 notional += (level & SIZE_MASK) * px / 1e10;
132 }
133 }
134
135 /// @dev Zero for any account other than the one the report attests.
136 function positionSize(address user, uint32 asset) external view returns (int256 size) {
137 if (!_holds(asset)) revert NoReport();
138 if (user == address(0) || uint256(uint160(user)) != _load(T_USER)) return 0;
139 return int256(_load(T_POSITION));
140 }
141
142 // ------------------------------------------------------------- internal
143
144 function _holds(uint32 asset) internal view returns (bool) {
145 return _load(T_TIME) != 0 && _load(T_ASSET) == asset;
146 }
147
148 /// @dev Levels must be non-empty and strictly ordered away from mid,
149 /// because walking the book assumes the best price comes first.
150 function _storeSide(uint256 base, uint256 countSlot, uint256[] memory levels, bool descending) internal {
151 uint256 previous;
152 for (uint256 i; i < levels.length; ++i) {
153 uint256 px = levels[i] >> 128;
154 if (px == 0 || levels[i] & SIZE_MASK == 0) revert BadReport();
155 if (i > 0 && (descending ? px >= previous : px <= previous)) revert BadReport();
156 previous = px;
157 _store(base + i, levels[i]);
158 }
159 _store(countSlot, levels.length);
160 }
161
162 function _store(uint256 slot, uint256 value) internal {
163 assembly ("memory-safe") {
164 tstore(slot, value)
165 }
166 }
167
168 function _load(uint256 slot) internal view returns (uint256 value) {
169 assembly ("memory-safe") {
170 value := tload(slot)
171 }
172 }
173
174 function _recover(bytes32 hash, bytes calldata signature) internal pure returns (address) {
175 if (signature.length != 65) return address(0);
176 bytes32 r = bytes32(signature[0:32]);
177 bytes32 s = bytes32(signature[32:64]);
178 uint8 v = uint8(signature[64]);
179 if (uint256(s) > HALF_ORDER || (v != 27 && v != 28)) return address(0);
180 return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s);
181 }
182}

IHyperCoreReader.sol

contracts/src/interfaces/IHyperCoreReader.sol

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.24;
3
4/// @notice The HyperCore state Gapless needs, behind one adapter.
5/// @dev Elysium's HyperCore read precompile is not live yet and its ABI is not
6/// published, so the pool talks to this interface instead of the precompile.
7/// Until it ships, `SignedReader` answers these four calls from reports signed
8/// by one reporter key. Once it ships, a thin adapter maps it onto them.
9///
10/// Fixed-point conventions used everywhere in Gapless:
11/// - prices: USD per unit, 8 decimals
12/// - sizes: asset units, 8 decimals
13/// - notionals and payouts: quote token, 6 decimals
14interface IHyperCoreReader {
15 /// @return px Mark price, and the unix time (seconds) HyperCore produced it.
16 function markPx(uint32 asset) external view returns (uint256 px, uint64 timestamp);
17
18 /// @notice Average price a market order of `size` gets by walking the book now.
19 /// @param isSell True to walk the bids (closing a long), false to walk the asks.
20 /// @return avgPx Size-weighted fill price of the part the book can absorb.
21 /// @return fullyFilled False when the book is too thin to absorb `size`.
22 function impactPx(uint32 asset, bool isSell, uint256 size) external view returns (uint256 avgPx, bool fullyFilled);
23
24 /// @notice Resting notional within `bps` of mid on one side of the book.
25 /// @param bidSide True for bids, false for asks.
26 function depthWithinBps(uint32 asset, bool bidSide, uint256 bps) external view returns (uint256 notional);
27
28 /// @notice Signed perp position of `user`: positive long, negative short.
29 function positionSize(address user, uint32 asset) external view returns (int256 size);
30}

IReportSink.sol

contracts/src/interfaces/IReportSink.sol

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.24;
3
4/// @notice A reader that is fed signed reports instead of reading the chain.
5interface IReportSink {
6 /// @notice Check `signature` over `report` and hold the report for the rest
7 /// of the transaction.
8 function submit(bytes calldata report, bytes calldata signature) external;
9}

IERC20.sol

contracts/src/interfaces/IERC20.sol

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.24;
3
4interface IERC20 {
5 function balanceOf(address account) external view returns (uint256);
6 function transfer(address to, uint256 amount) external returns (bool);
7 function transferFrom(address from, address to, uint256 amount) external returns (bool);
8 function approve(address spender, uint256 amount) external returns (bool);
9}