CoverPool.sol
contracts/src/CoverPool.sol
| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity ^0.8.24; |
| 3 | |
| 4 | import {IERC20} from "./interfaces/IERC20.sol"; |
| 5 | import {IHyperCoreReader} from "./interfaces/IHyperCoreReader.sol"; |
| 6 | import {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. |
| 34 | contract 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 | } |