// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {BaseAdapter} from "../BaseAdapter.sol"; import {AgentRegistry} from "../AgentRegistry.sol"; /// HyperEVM's system contract for acting on HyperCore. `msg.sender` is the /// HyperCore account the action is for, so every call here is made BY the /// account (V), through `_exec`, never by the adapter. interface ICoreWriter { function sendRawAction(bytes calldata data) external; } /// @title HyperCoreAdapter — the shared half of the five `hl_*` adapters (T-800, T-1419). /// /// docs/HYPERLIQUID_VENUE_PLAN.md §7. Five adapters live on HyperEVM and act on /// HyperCore through CoreWriter: `hl_deposit`, `hl_agent` / `hl_agent_revoke`, /// `hl_exit` / `hl_cancel`, `hl_withdraw`, and `hl_order` /// (docs/design/HYPERLIQUID_ONCHAIN_ORDERS.md). This file is what they share /// and, more to the point, what NONE of them can do. /// /// THE WHOLE CoreWriter SURFACE IS THE SEVEN TYPED ENCODERS BELOW. There is no /// function anywhere in the five adapters that takes an action id or raw /// action bytes: `_sendAction` is PRIVATE, and the only callers are the seven /// `_act*` functions, each with its action id and every constant field /// written in. So the CoreWriter actions reachable at all are exactly /// /// 1 limit order, reduce-only and IOC (`_actReduceOnlyIoc`, the exits), or /// NOT reduce-only with an Alo, Gtc or Ioc TIF (`_actOrder`, `hl_order` /// only, which holds it to the owner's VenueLock first); /// 6 spot send, ONLY USDC (token 0) and ONLY to 0x2000…0000, which credits /// the SENDER, V, on HyperEVM (`_actSpotSendHome`, H6); /// 7 USD class transfer, ONLY perp → spot (`_actPerpToSpot`); /// 9 add API wallet, ONLY with the name "" (`_actSetAgent`); /// 10 cancel by oid; 11 cancel by cloid. /// /// Never 2 (vault transfer), 3-5 (staking), 8, 12 (builder fee, §7.6a item 8), /// 13 (send asset anywhere), 15, 16, 17. An unused internal function is not /// compiled into an adapter that does not reach it, so each adapter's /// bytecode carries only the encoders its own entry points call. /// /// A QUEUED ACTION IS NOT A DONE ACTION (U3). CoreWriter validates nothing /// and cannot revert on content: an executed and a rejected action have the /// same receipt. So every entry point here emits the pre-state it read, and /// the reconciler (§8, off chain, not in this contract) reads the precompiles /// and `/info` a block later and compares. /// /// THE CoreWriter IS NAMED, AND PINNED. It is resolved by name from what the /// guardian curated for this adapter (`_venueOf`, the same default-off gate /// every adapter has: an adapter not whitelisted with the name reaches /// nothing), AND the answer must be the system address. A curation that /// pointed the name anywhere else would otherwise have V call that contract /// with `sendRawAction` calldata; it is refused instead. /// /// UNITS (U6). Order price and size are human × 1e8. The mark price /// precompile answers human × 10^(6 − szDecimals). USDC is 6 dp on HyperEVM, /// 8 dp in HyperCore spot (`wei`, actions 6 and 13) and 6 dp for perp `ntl` /// (action 7) and for the margin and withdrawable precompiles. abstract contract HyperCoreAdapter is BaseAdapter { // ----------------------------------------------------------------------- // System addresses (H1, H5, H6). Fixed by HyperEVM, not configured. // ----------------------------------------------------------------------- address internal constant CORE_WRITER = 0x3333333333333333333333333333333333333333; address internal constant PRECOMPILE_POSITION = 0x0000000000000000000000000000000000000800; address internal constant PRECOMPILE_SPOT_BALANCE = 0x0000000000000000000000000000000000000801; address internal constant PRECOMPILE_WITHDRAWABLE = 0x0000000000000000000000000000000000000803; address internal constant PRECOMPILE_MARK_PX = 0x0000000000000000000000000000000000000806; address internal constant PRECOMPILE_PERP_ASSET_INFO = 0x000000000000000000000000000000000000080a; address internal constant PRECOMPILE_MARGIN_SUMMARY = 0x000000000000000000000000000000000000080F; /// Circle's CoreDepositWallet and USDC on HyperEVM mainnet (H7). Pinned in /// bytecode; `hl_deposit` calls both, and no adapter's VenueLock may be /// either. address internal constant CDW_HYPEREVM = 0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24; address internal constant USDC_HYPEREVM = 0xb88339CB7199b77E23DB6E890353E22632Ba630f; /// USDC's system address: a spot send of USDC here credits THE SENDER on /// HyperEVM (H6). The only destination action 6 is ever given. address internal constant USDC_SYSTEM = 0x2000000000000000000000000000000000000000; /// USDC's HyperCore token index. uint64 internal constant USDC_TOKEN = 0; /// The venue name the guardian curates CoreWriter under. bytes32 public constant VENUE_CORE_WRITER = "hl_core_writer"; /// VenueLock's id for this venue (VenueLock's header: "for example /// keccak256("hyperliquid")"). bytes32 public constant HYPERLIQUID = keccak256("hyperliquid"); /// VenueLock's `KEY_AGENT` (a constant of another contract cannot be read /// by name; HlAdapters.t.sol pins the two equal). uint8 internal constant LOCK_KEY_AGENT = 1; uint8 internal constant ACTION_VERSION = 1; uint24 internal constant ACTION_LIMIT_ORDER = 1; uint24 internal constant ACTION_SPOT_SEND = 6; uint24 internal constant ACTION_USD_CLASS_TRANSFER = 7; uint24 internal constant ACTION_ADD_API_WALLET = 9; uint24 internal constant ACTION_CANCEL_BY_OID = 10; uint24 internal constant ACTION_CANCEL_BY_CLOID = 11; /// Hyperliquid's TIF codes (H3): add-liquidity-only (post-only), /// good-til-cancelled, immediate-or-cancel. uint8 internal constant TIF_ALO = 1; uint8 internal constant TIF_GTC = 2; uint8 internal constant TIF_IOC = 3; /// A perp asset id. Spot assets are 10000 + index and HIP-3 dexes higher /// still; v1 trades neither (HL8), and the position precompile reads only /// the first perp dex. uint32 internal constant MAX_PERP_ASSET = 9_999; /// Perp field layouts, as the precompiles return them ([hl-lib] L1Read). struct Position { int64 szi; uint64 entryNtl; int64 isolatedRawUsd; uint32 leverage; bool isIsolated; } struct SpotBalance { uint64 total; uint64 hold; uint64 entryNtl; } struct PerpAssetInfo { string coin; uint32 marginTableId; uint8 szDecimals; uint8 maxLeverage; bool onlyIsolated; } struct AccountMarginSummary { int64 accountValue; uint64 marginUsed; uint64 ntlPos; int64 rawUsd; } /// Every action this family queues, in the exact bytes CoreWriter got. /// The reconciler's join key with the `RawAction` log CoreWriter emits. event HyperCoreActionQueued(address indexed account, bytes32 indexed taskId, uint24 indexed action); error PrecompileFailed(address precompile); /// The curated name resolved to something other than the system contract. error NotCoreWriter(address resolved); error NotAPerpAsset(uint32 asset); error ValueTooLarge(uint256 value); /// Not one of Hyperliquid's three TIF codes (H3). error BadTif(uint8 tif); constructor(AgentRegistry registry_) BaseAdapter(registry_) {} // ----------------------------------------------------------------------- // The seven encoders. The ONLY way to CoreWriter. // ----------------------------------------------------------------------- /// Action 1, reduce-only, IOC: the exits' only order shape. function _actReduceOnlyIoc( address account, bytes32 taskId, uint32 asset, bool isBuy, uint64 limitPx, uint64 sz, uint128 cloid ) internal { _sendAction( account, taskId, ACTION_LIMIT_ORDER, abi.encode(asset, isBuy, limitPx, sz, true, TIF_IOC, cloid) ); } /// Action 1, NOT reduce-only, with one of the three TIFs: an opening or /// limit order (`hl_order`). `reduceOnly` is written in as false; a TIF /// outside Alo / Gtc / Ioc is refused here, so no other code reaches the /// venue whatever the caller passes. The caller holds the order to the /// owner's lock BEFORE calling this: this encoder checks only the shape. function _actOrder( address account, bytes32 taskId, uint32 asset, bool isBuy, uint64 limitPx, uint64 sz, uint8 tif, uint128 cloid ) internal { if (tif != TIF_ALO && tif != TIF_GTC && tif != TIF_IOC) revert BadTif(tif); _sendAction( account, taskId, ACTION_LIMIT_ORDER, abi.encode(asset, isBuy, limitPx, sz, false, tif, cloid) ); } /// Action 6: USDC, to its system address, so it lands on the SENDER (V). function _actSpotSendHome(address account, bytes32 taskId, uint64 wei_) internal { _sendAction(account, taskId, ACTION_SPOT_SEND, abi.encode(USDC_SYSTEM, USDC_TOKEN, wei_)); } /// Action 7, perp → spot only. function _actPerpToSpot(address account, bytes32 taskId, uint64 ntl) internal { _sendAction(account, taskId, ACTION_USD_CLASS_TRANSFER, abi.encode(ntl, false)); } /// Action 9 into the unnamed slot. `agent == address(0)` is the revoke /// (U2). function _actSetAgent(address account, bytes32 taskId, address agent) internal { _sendAction(account, taskId, ACTION_ADD_API_WALLET, abi.encode(agent, "")); } /// Action 10. function _actCancelByOid(address account, bytes32 taskId, uint32 asset, uint64 oid) internal { _sendAction(account, taskId, ACTION_CANCEL_BY_OID, abi.encode(asset, oid)); } /// Action 11. function _actCancelByCloid(address account, bytes32 taskId, uint32 asset, uint128 cloid) internal { _sendAction(account, taskId, ACTION_CANCEL_BY_CLOID, abi.encode(asset, cloid)); } /// Version 1, a 3-byte big-endian action id, then the ABI params (H1). /// PRIVATE: no adapter can name an action id. function _sendAction(address account, bytes32 taskId, uint24 action, bytes memory params) private { address writer = _venueOf(account, VENUE_CORE_WRITER); if (writer != CORE_WRITER) revert NotCoreWriter(writer); _exec( account, CORE_WRITER, 0, abi.encodeCall( ICoreWriter.sendRawAction, (abi.encodePacked(ACTION_VERSION, action, params)) ) ); emit HyperCoreActionQueued(account, taskId, action); } // ----------------------------------------------------------------------- // Precompile reads. Values are HyperCore's state when this EVM block was // built (H5), so nothing in this transaction can move them. // ----------------------------------------------------------------------- function _read(address precompile, bytes memory input) internal view returns (bytes memory out) { bool ok; (ok, out) = precompile.staticcall(input); if (!ok || out.length == 0) revert PrecompileFailed(precompile); } function _requirePerp(uint32 asset) internal pure { if (asset > MAX_PERP_ASSET) revert NotAPerpAsset(asset); } function _position(address user, uint32 asset) internal view returns (Position memory) { _requirePerp(asset); // so the uint16 below cannot truncate return abi.decode(_read(PRECOMPILE_POSITION, abi.encode(user, uint16(asset))), (Position)); } function _markPx(uint32 asset) internal view returns (uint64) { return abi.decode(_read(PRECOMPILE_MARK_PX, abi.encode(asset)), (uint64)); } function _szDecimals(uint32 asset) internal view returns (uint8) { return abi.decode(_read(PRECOMPILE_PERP_ASSET_INFO, abi.encode(asset)), (PerpAssetInfo)) .szDecimals; } function _spotUsdc(address user) internal view returns (SpotBalance memory) { return abi.decode( _read(PRECOMPILE_SPOT_BALANCE, abi.encode(user, USDC_TOKEN)), (SpotBalance) ); } /// 6 dp. function _withdrawable(address user) internal view returns (uint64) { return abi.decode(_read(PRECOMPILE_WITHDRAWABLE, abi.encode(user)), (uint64)); } /// Perp dex 0's account value, 6 dp. function _accountValue(address user) internal view returns (int64) { return abi.decode( _read(PRECOMPILE_MARGIN_SUMMARY, abi.encode(uint32(0), user)), (AccountMarginSummary) ).accountValue; } function _u64(uint256 v) internal pure returns (uint64) { if (v > type(uint64).max) revert ValueTooLarge(v); return uint64(v); } }