// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {AgentRegistry} from "../AgentRegistry.sol"; import {VenueLock} from "../VenueLock.sol"; import {HyperCoreAdapter} from "./HyperCoreAdapter.sol"; /// @title HlOrderAdapter — `hl_order(asset, isBuy, limitPx, sz, tif)`: V's own opening and limit orders on Hyperliquid. /// /// docs/design/HYPERLIQUID_ONCHAIN_ORDERS.md §2 (the decision) and §9 (OA-1..OA-5, /// owner, 2026-10-25); kanban T-1419. It overturns HL2 of /// docs/HYPERLIQUID_VENUE_PLAN.md: entries and limit orders go on chain, as a /// step V's account performs, not as bytes G signs. /// /// WHAT IT DOES. As V, it queues CoreWriter action 1 with `reduceOnly = /// false` written into the encoder (`_actOrder`) and one of Hyperliquid's three /// TIFs (H3: 1 Alo, 2 Gtc, 3 Ioc; OA-4 allows resting Gtc orders). It moves no /// token and makes no other call: the only writes are V's CoreWriter action and /// this adapter's `spent` record. /// /// THE ORDER ID IS THE CONTRACT'S. `cloid = cloidFor(account, taskId)` = /// uint128(keccak256(adapter, account, taskId)), as `hl_exit` derives it; the /// adapter address is in the hash, so an `hl_order` and an `hl_exit` cloid for /// one (account, taskId) differ. `HlOrderQueued` carries it, and the backend /// tracks the order by it (`orderStatus(V, cloid)`), as CoW tracks an orderUid. /// /// NO REPLAY. Every order spends its `taskId` in `_consume` (v1), or under v2 /// the task the gate opened for the proved step, whose nullifier the gate /// spends. HyperCore gets an action FROM V's contract, never signed bytes that /// anyone could resubmit. /// /// NOT ARMING-CLASS. The owner's VenueLock is the authorisation (as for /// `hl_deposit`): A signed the bounds, and every order is held to them here, /// on chain, in this order: /// /// lock `venueLock.lockOf(V, keccak256("hyperliquid"))`: no lock, or a /// lock set by an owner V no longer names (`lockOf` answers the /// empty lock), refuses; a lock VenueLock cannot read reverts in /// `lockOf`, a refusal too. A CLOSED lock (`cap == 0` or /// `products == 0`, VenueLock's "refuse") refuses. /// product the asset's bit must be set in `lock.limits.products` (bit i = /// Hyperliquid perp asset id i). Ids ≥ 256 cannot be named in a /// 256-bit set, so they are refused. /// leverage from precompile 0x800 (`Position.leverage`, `.isIsolated`), the /// asset's CURRENT setting, which a CoreWriter open takes (U8: /// cross 20x unless G set it first): `leverage == 0` refuses (an /// unknown or unset reading; the most restrictive one), more than /// `lock.limits.maxLeverage` refuses, and cross margin refuses /// unless `lock.limits.crossMargin`. OPEN ITEM (T-1423, funded-run /// item 2): what 0x800 answers for an asset V is FLAT in is not /// verified. If it answers zeros, a first open refuses here until /// it is measured; that is the safe side. /// size `sz > 0` and a whole number of lots: lot = 10^(8 − szDecimals) /// in 1e8 units (the unit `hl_exit` builds its sizes in). An /// off-lot size is REFUSED, never rounded. /// price the intent's `limitPx` (human × 1e8) is rounded to the tick /// TOWARD V (a buy's down, a sell's up) with `roundToTick`, the /// same algorithm as `hl_exit`'s, and the price SENT is then held to /// the owner's band around the 0x806 mark read in this transaction: /// buy: px ≤ mark · (10000 + bandBps) / 10000 /// sell: px ≥ mark · (10000 − bandBps) / 10000 /// where mark = 0x806 · 10^(2 + szDecimals). A price better for V /// passes however far it is (the CoW rule). `bandBps` is the /// LOCK's (OA-3): `0` refuses every order (a closed band), and /// above `MAX_BAND_BPS` refuses, whatever A signed. A zero mark /// refuses. /// /// WHAT IT DOES NOT ENFORCE, AND WHO DOES. /// - Margin and notional: HyperCore's own margin checks at execution. There /// is no per-order notional ceiling on chain (OA-5); exposure is bounded by /// the lock's cap (on the deposit path) times its leverage ceiling. /// - Leverage and margin MODE are read, not set: CoreWriter has no action /// for them (H2). G sets them (OA-2) before the order; a wrong or skipped /// setup is a refused order here, not an over-leveraged position. /// - Timing: CoreWriter orders are delayed on chain for a few seconds (H4, /// Hyperliquid's anti-latency rule; OA-1 accepts it). The mark checked /// here is this block's, not the one the order meets. /// - Success: CoreWriter validates nothing and cannot revert on content /// (U3). A queued order and an order HyperCore rejects have the same /// receipt, so the reconciler reads it back by cloid (OT-4, T-1422). /// /// EXITS NEVER READ THE LOCK and are not here: `hl_exit` (reduce-only IOC, /// fixed 200 bps band), `hl_cancel` and `hl_withdraw` stay as they are. /// /// READINGS TAKEN WHERE THE DESIGN LEFT A GAP (most restrictive; listed in /// the T-1419 report): /// - `MAX_BAND_BPS` is 1000 (10%): five times the exits' fixed band (HL9), /// wide enough for a resting limit, and a bound on a lock signed carelessly. /// - szDecimals above 6 is refused (a perp's price decimals are 6 − szDecimals), /// as in `hl_exit`. /// - Perp assets only (id ≤ 9999), on the first perp dex (HL8); the product /// bit narrows that further to ids below 256. contract HlOrderAdapter is HyperCoreAdapter { bytes32 public constant OP_ORDER = "hl_order"; /// The protocol ceiling on a lock's `bandBps`: 10%. A lock signed with a /// wider band opens nothing until A signs a narrower one (or tightens). uint256 public constant MAX_BAND_BPS = 1_000; uint256 internal constant BPS = 10_000; uint256 internal constant SIG_FIGS = 5; uint8 internal constant MAX_SZ_DECIMALS = 6; /// Product bits are a uint256: ids at or above this cannot be named. uint256 internal constant PRODUCT_BITS = 256; bytes32 internal constant ORDER_TYPEHASH = keccak256( "HlOrder(address account,address owner,bytes32 taskId,uint256 deadline,uint32 asset,bool isBuy,uint64 limitPx,uint64 sz,uint8 tif)" ); struct Order { address account; /// WHOSE account. Checked against what the account itself says. address owner; bytes32 taskId; uint256 deadline; /// Hyperliquid perp asset id. uint32 asset; bool isBuy; /// Human × 1e8, before rounding to tick. uint64 limitPx; /// Human × 1e8; a whole number of the asset's lots. uint64 sz; /// 1 Alo, 2 Gtc, 3 Ioc (H3). No reduce-only flag: an order here is /// never reduce-only, and an exit is `hl_exit`'s. uint8 tif; } /// The owner's lock (T-773). READ only: V never calls it from here. VenueLock public immutable venueLock; /// The order exactly as queued: `limitPx` is the rounded price SENT. event HlOrderQueued( address indexed account, bytes32 indexed taskId, uint32 indexed asset, bool isBuy, uint64 limitPx, uint64 sz, uint8 tif, uint128 cloid ); error BadVenueLock(address venueLock); error NoHyperliquidLock(address account); error LockClosed(address account); error ProductNotInLock(uint32 asset, uint256 products); /// 0x800 answered leverage 0 (unknown or unset): refused, not guessed. error LeverageUnknown(address account, uint32 asset); error OverLockLeverage(uint32 leverage, uint16 maxLeverage); error CrossMarginNotAllowed(address account, uint32 asset); error ZeroSize(); error OffLot(uint64 sz, uint256 lot); error BadSzDecimals(uint8 szDecimals); error ZeroLimitPrice(); error NoMarkPrice(uint32 asset); /// The lock's band is 0 (closed) or above `MAX_BAND_BPS`. error BadBand(uint16 bandBps); error OutsideBand(bool isBuy, uint256 limitPx, uint256 markScaled, uint16 bandBps); constructor(AgentRegistry registry_, VenueLock venueLock_) HyperCoreAdapter(registry_) { address l = address(venueLock_); // The deposit adapter's guard: a real contract, and never one of the // addresses an `hl_*` adapter makes V call. if (l.code.length == 0 || l == CORE_WRITER || l == CDW_HYPEREVM || l == USDC_HYPEREVM) { revert BadVenueLock(l); } venueLock = venueLock_; } function _domainNameAndVersion() internal pure override returns (string memory, string memory) { return ("DeFiLoopsHlOrderAdapter", "1"); } function orderDigest(Order calldata o) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode( ORDER_TYPEHASH, o.account, o.owner, o.taskId, o.deadline, o.asset, o.isBuy, o.limitPx, o.sz, o.tif ) ) ); } /// `hl_order`. function order(Order calldata o, bytes calldata signature) external { _consume(o.account, o.owner, o.taskId, o.deadline, orderDigest(o), signature); _requireOperation(o.account, OP_ORDER); _requirePerp(o.asset); uint16 bandBps = _requireInsideLock(o.account, o.asset); uint8 szDec = _szDecimals(o.asset); if (szDec > MAX_SZ_DECIMALS) revert BadSzDecimals(szDec); _requireWholeLots(o.sz, szDec); uint64 px = _bandedPrice(o.asset, o.limitPx, o.isBuy, szDec, bandBps); uint128 cloid = cloidFor(o.account, o.taskId); _actOrder(o.account, o.taskId, o.asset, o.isBuy, px, o.sz, o.tif, cloid); emit HlOrderQueued(o.account, o.taskId, o.asset, o.isBuy, px, o.sz, o.tif, cloid); } /// The cloid `order` 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)))); } /// The lock checks (see the header): live, open, the product allowed, and /// the asset's current leverage and margin mode inside it. Returns the /// lock's band for the price check. function _requireInsideLock(address account, uint32 asset) internal view returns (uint16) { VenueLock.Lock memory lock = venueLock.lockOf(account, HYPERLIQUID); if (lock.owner == address(0)) revert NoHyperliquidLock(account); VenueLock.Limits memory l = lock.limits; if (l.cap == 0 || l.products == 0) revert LockClosed(account); if (asset >= PRODUCT_BITS || ((l.products >> asset) & 1) == 0) { revert ProductNotInLock(asset, l.products); } Position memory p = _position(account, asset); if (p.leverage == 0) revert LeverageUnknown(account, asset); if (p.leverage > l.maxLeverage) revert OverLockLeverage(p.leverage, l.maxLeverage); if (!p.isIsolated && !l.crossMargin) revert CrossMarginNotAllowed(account, asset); return l.bandBps; } /// A non-zero whole number of lots, 10^(8 − szDecimals) each in 1e8 units. function _requireWholeLots(uint64 sz, uint8 szDec) internal pure { if (sz == 0) revert ZeroSize(); uint256 lot = 10 ** (8 - uint256(szDec)); if (sz % lot != 0) revert OffLot(sz, lot); } /// The intent's limit, rounded to tick toward V, then held to the lock's /// band around this block's mark. function _bandedPrice(uint32 asset, uint64 limitPx, bool isBuy, uint8 szDec, uint16 bandBps) internal view returns (uint64) { if (bandBps == 0 || bandBps > MAX_BAND_BPS) revert BadBand(bandBps); if (limitPx == 0) revert ZeroLimitPrice(); uint64 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 + bandBps)) { revert OutsideBand(isBuy, rounded, markScaled, bandBps); } } else if (rounded * BPS < markScaled * (BPS - bandBps)) { revert OutsideBand(isBuy, rounded, markScaled, bandBps); } return _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). The same algorithm /// as `HlExitAdapter.roundToTick`, line for line; HlOrder.t.sol fuzzes the /// two equal. 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; } }