// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {AgentRegistry} from "../AgentRegistry.sol"; import {HyperCoreAdapter} from "./HyperCoreAdapter.sol"; /// @title HlExitAdapter — `hl_exit(asset, fraction, limitPx)` and `hl_cancel(asset, oid | cloid)`. /// /// docs/HYPERLIQUID_VENUE_PLAN.md §7.4, §7.6a item 4, HL9. /// /// EXITS ONLY. Nothing here can open or grow a position (HL2: no on-chain /// open orders). `hl_exit` queues CoreWriter action 1 with `reduceOnly = /// true` and `tif = IOC` written into the encoder, and the intent has no /// field for either, nor for the side, nor for the size: /// /// side from the position's sign (0x800 `szi`): a long is sold, a short /// bought; no position, no order. /// size ⌊|szi| · fractionBps / 10000⌋ · 10^(8 − szDecimals), which is a /// valid size by construction (U6). `szi` is in 10^szDecimals units. /// price the intent's `limitPx` (human × 1e8) rounded to Hyperliquid's tick /// TOWARD V — a sell's up, a buy's down — and then held to the band /// against the mark price read in this same transaction: /// sell: px ≥ mark · (1 − 200 bps) buy: px ≤ mark · (1 + 200 bps) /// where mark = 0x806 · 10^(2 + szDecimals). The band is checked on /// the price that is SENT, after rounding. A limit better for V passes /// however far it is (the CoW rule); an IOC that cannot fill is a /// no-op at the venue. /// szDecimals from the 0x80a asset-info precompile, in this transaction, /// never from the intent. /// cloid derived from (adapter, account, taskId): the reconciliation key, /// read back with `orderStatus(V, cloid)` (U3). /// /// HyperCore state does not change inside an EVM block (H5), so nothing in /// this transaction can move the mark the band is checked against. /// /// `hl_cancel` queues action 10 (by oid) or 11 (by cloid). It moves nothing. /// /// EXITS ARE ALWAYS ALLOWED (§5): this contract has no VenueLock at all, and /// no lock, grant or product list is consulted. Any perp asset V holds a /// position in can be closed. /// /// `hl_cancel` IS ARMING-CLASS; `hl_exit` IS NOT (audit 2026-10-25, finding 5). /// A cancel can reach any resting order of V — and the keeper's own exits are /// IOC and never rest, so every order a cancel can reach is G's or the /// owner's: a stop-loss or a limit the owner's grant placed. So `hl_cancel` /// answers to the owner's own switch (`_requiresArming`), which in this repo /// is ON unless the account switched it off: by default the keeper may still /// cancel, as before. An owner who wants G's resting stops and limits safe /// from the keeper calls `registry.armOperation("hl_cancel", false)` from V, /// and cancels through V's root instead (§12). `hl_exit` stays always /// allowed: it only reduces, IOC, inside the band. CURATION LISTS `hl_exit` /// ONLY: `onInstall` refuses an install payload naming `hl_cancel` /// (`OperationNeedsArming`, H-2), so a curated op list that still named it /// would make every v1 activation skip this adapter. /// /// TICK (U6): ≤ 5 significant figures and ≤ 6 − szDecimals decimals. The /// integer-price exception Hyperliquid allows is NOT used: rounding to 5 /// significant figures always yields a valid price, and is the stricter of /// the two readings. /// /// READINGS TAKEN WHERE THE PLAN LEFT A GAP (listed for the owner): /// - `fraction` is basis points of the position, 1..10000. /// - A cancel does not require a position: a resting open order with no fill /// yet has none, and cancels must always be possible (§5, §12). /// - Perp assets only (id ≤ 9999), on the first perp dex (HL8). /// - szDecimals above 6 is refused (a perp's price decimals are 6 − szDecimals). contract HlExitAdapter is HyperCoreAdapter { bytes32 public constant OP_EXIT = "hl_exit"; bytes32 public constant OP_CANCEL = "hl_cancel"; /// HL9: the keeper's `max_slippage_bps`, on chain. uint256 public constant BAND_BPS = 200; uint256 internal constant BPS = 10_000; uint256 internal constant SIG_FIGS = 5; uint8 internal constant MAX_SZ_DECIMALS = 6; bytes32 internal constant EXIT_TYPEHASH = keccak256( "HlExit(address account,address owner,bytes32 taskId,uint256 deadline,uint32 asset,uint16 fractionBps,uint64 limitPx)" ); bytes32 internal constant CANCEL_TYPEHASH = keccak256( "HlCancel(address account,address owner,bytes32 taskId,uint256 deadline,uint32 asset,bool byCloid,uint128 id)" ); struct Exit { address account; address owner; bytes32 taskId; uint256 deadline; uint32 asset; /// How much of the position, in bps. uint16 fractionBps; /// Human × 1e8, before rounding. No side, no size, no TIF, no /// reduce-only flag: those are not the intent's to choose. uint64 limitPx; } struct Cancel { address account; address owner; bytes32 taskId; uint256 deadline; uint32 asset; /// False: `id` is an oid (must fit uint64). True: `id` is a cloid. bool byCloid; uint128 id; } /// The pre-state the order was built from, for the reconciler (§8). event HlExitQueued( address indexed account, bytes32 indexed taskId, uint32 indexed asset, bool isBuy, uint64 limitPx, uint64 sz, uint128 cloid, int64 szi, uint64 markPx, uint8 szDecimals ); event HlCancelQueued( address indexed account, bytes32 indexed taskId, uint32 indexed asset, bool byCloid, uint128 id ); error BadFraction(uint16 fractionBps); error NoPosition(address account, uint32 asset); error NothingToClose(int64 szi, uint16 fractionBps); error NoMarkPrice(uint32 asset); error BadSzDecimals(uint8 szDecimals); error ZeroLimitPrice(); error OutsideBand(bool isBuy, uint256 limitPx, uint256 markScaled); error OidTooLarge(uint128 id); constructor(AgentRegistry registry_) HyperCoreAdapter(registry_) {} function _domainNameAndVersion() internal pure override returns (string memory, string memory) { return ("DeFiLoopsHlExitAdapter", "1"); } /// `hl_cancel` only: on by default, the owner's `armOperation(OP_CANCEL, /// false)` switches it off for V (see the header). function _requiresArming(bytes32 op) internal pure override returns (bool) { return op == OP_CANCEL; } function exitDigest(Exit calldata e) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode( EXIT_TYPEHASH, e.account, e.owner, e.taskId, e.deadline, e.asset, e.fractionBps, e.limitPx ) ) ); } function cancelDigest(Cancel calldata c) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode( CANCEL_TYPEHASH, c.account, c.owner, c.taskId, c.deadline, c.asset, c.byCloid, c.id ) ) ); } /// `hl_exit`. function exit(Exit calldata e, bytes calldata signature) external { _consume(e.account, e.owner, e.taskId, e.deadline, exitDigest(e), signature); _requireOperation(e.account, OP_EXIT); // Perp-only is enforced by `_position`, the read that needs it. if (e.fractionBps == 0 || e.fractionBps > BPS) revert BadFraction(e.fractionBps); if (e.limitPx == 0) revert ZeroLimitPrice(); int64 szi = _position(e.account, e.asset).szi; if (szi == 0) revert NoPosition(e.account, e.asset); // A long is closed by selling, a short by buying. Never the other way. bool isBuy = szi < 0; uint8 szDec = _szDecimals(e.asset); if (szDec > MAX_SZ_DECIMALS) revert BadSzDecimals(szDec); uint64 sz = _closeSize(szi, e.fractionBps, szDec); (uint64 px, uint64 mark) = _bandedPrice(e.asset, e.limitPx, isBuy, szDec); uint128 cloid = cloidFor(e.account, e.taskId); _actReduceOnlyIoc(e.account, e.taskId, e.asset, isBuy, px, sz, cloid); emit HlExitQueued(e.account, e.taskId, e.asset, isBuy, px, sz, cloid, szi, mark, szDec); } /// `hl_cancel`. function cancel(Cancel calldata c, bytes calldata signature) external { _consume(c.account, c.owner, c.taskId, c.deadline, cancelDigest(c), signature); _requireOperation(c.account, OP_CANCEL); _requirePerp(c.asset); if (c.byCloid) { _actCancelByCloid(c.account, c.taskId, c.asset, c.id); } else { if (c.id > type(uint64).max) revert OidTooLarge(c.id); _actCancelByOid(c.account, c.taskId, c.asset, uint64(c.id)); } emit HlCancelQueued(c.account, c.taskId, c.asset, c.byCloid, c.id); } /// The cloid `exit` gives the order for (account, taskId). function cloidFor(address account, bytes32 taskId) public view returns (uint128) { return uint128(uint256(keccak256(abi.encode(address(this), account, taskId)))); } /// ⌊|szi| · fraction⌋ in szDecimals units, then to 1e8 units. function _closeSize(int64 szi, uint16 fractionBps, uint8 szDec) internal pure returns (uint64) { uint256 abs = szi < 0 ? uint256(-int256(szi)) : uint256(int256(szi)); uint256 lots = (abs * fractionBps) / BPS; if (lots == 0) revert NothingToClose(szi, fractionBps); return _u64(lots * 10 ** (8 - szDec)); } /// The intent's limit, rounded to tick toward V, then held to the band. function _bandedPrice(uint32 asset, uint64 limitPx, bool isBuy, uint8 szDec) internal view returns (uint64 px, uint64 mark) { mark = _markPx(asset); if (mark == 0) revert NoMarkPrice(asset); uint256 markScaled = uint256(mark) * 10 ** (2 + szDec); uint256 rounded = roundToTick(limitPx, szDec, !isBuy); if (rounded == 0) revert ZeroLimitPrice(); if (isBuy) { if (rounded * BPS > markScaled * (BPS + BAND_BPS)) { revert OutsideBand(isBuy, rounded, markScaled); } } else if (rounded * BPS < markScaled * (BPS - BAND_BPS)) { revert OutsideBand(isBuy, rounded, markScaled); } px = _u64(rounded); } /// A price in 1e8 units rounded to Hyperliquid's perp tick: at most /// `6 − szDec` decimals and at most 5 significant figures. `up` rounds /// up (a sell, toward V), else down (a buy, toward V). function roundToTick(uint256 px, uint8 szDec, bool up) public pure returns (uint256) { uint256 step = 10 ** (2 + uint256(szDec)); uint256 digits = 0; for (uint256 v = px; v != 0; v /= 10) { digits++; } if (digits > SIG_FIGS) { uint256 sig = 10 ** (digits - SIG_FIGS); if (sig > step) step = sig; } uint256 r = (px / step) * step; if (up && r < px) r += step; return r; } }