// 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 HlWithdrawAdapter — `hl_withdraw(amount)`: USDC from V's HyperCore account back to V on HyperEVM. /// /// docs/HYPERLIQUID_VENUE_PLAN.md §7.5, §7.6a item 5, U5-U7. /// /// ONE ACTION PER CALL, AND ONLY FREE SPOT IS SENT (audit re-run 2026-10-25, /// finding 1). Each call reads V's free spot USDC (0x801, `total − hold`) and /// the returns VenueLock still holds as pending (`pendingReturnOf`, the /// settle window), and then does exactly one of two things: /// /// - SPOT HOLDS IT: `free − pending ≥ wei + FEE_RESERVE_WEI`. Action 6 /// `(0x2000…0000, token 0, wei)` spot-sends USDC to its system address, /// which credits THE SENDER, V, on HyperEVM (H6), and V calls /// `venueLock.noteReturn(HYPERLIQUID, amount, homeable, FEE_RESERVE)` /// with `homeable` = the free spot it read (6 dp, rounded down). /// - SPOT IS SHORT: action 7 `(ntl, toPerp = false)` moves the missing part /// (plus the fee reserve, rounded up to whole `ntl`) from withdrawable /// perp margin (0x803) to V's own spot, and NOTHING is credited: /// `HlWithdrawTopUpQueued` says so. It refuses (`OverWithdrawable`) when /// withdrawable cannot cover it. The caller withdraws again, with a new /// task, in a later block, when spot shows the money; that call sends. /// /// So a withdraw out of perp margin is TWO calls (the U5 fallback the plan /// already allows, docs/HYPERLIQUID_VENUE_PLAN.md §7.5), and a send is only /// ever queued, and credited, against money already sitting in V's spot. /// /// WHY. HyperCore state is fixed for the whole EVM block (H5) and the queued /// actions run after it. Perp `withdrawable` can be spent before the 7 runs /// (an order queued earlier, a mark move, G's margin or leverage change), so /// a send credited against it may be rejected (U3) after VenueLock lowered /// V's net sent: the cap's loss budget, refilled. Free spot cannot be spent /// that way (below), and VenueLock's `pendingReturn` stops N sends in one /// block, or a few blocks apart, from each claiming the same balance. /// /// THE ASSUMPTIONS that make free spot hold: classic account mode; spot USDC /// moves only by V's own action 6 (this adapter) and action 7 (only adds); /// G cannot move spot ↔ perp (usdClassTransfer is a user-signed action) and /// does not trade spot; a queued action runs, or is rejected, within /// VenueLock's `SETTLE_SECONDS`. /// /// Destination and token are constants in the encoder; the intent carries /// `amount` only, so there is no way to name another destination, another /// token, a vault, a sub-account or a dex (actions 2 and 13 do not exist in /// this family). /// /// UNITS. `amount` is EVM USDC, 6 dp, and is what lands on V. Action 6 takes /// spot `wei`, 8 dp: `wei = amount · 100`. Action 7 takes `ntl`, 6 dp. /// /// THE CORE → EVM FEE STAYS IN SPOT (U7). The sender pays a flat fee per /// send, in spot USDC when it holds no Core HYPE, ON TOP of the amount. So /// spot must hold `wei + FEE_RESERVE_WEI` beyond what pending sends claim, /// and each send's reserve is itself counted as pending (`noteReturn`'s /// `fee`), so five sends in a window cannot each lean on the same reserve. /// A send whose fee outruns the reserve fails at the venue, visible only off /// the EVM, and moves nothing. /// /// AN EXIT: no lock is read, no grant is needed. VenueLock is read for /// `pendingReturnOf` only, which reads no lock and cannot refuse, and /// `noteReturn` reads no lock and never reverts, so the withdraw works with /// no lock, a closed lock, or a lock whose owner V no longer has. /// /// NO IN-TX DELTA. The USDC is paid out on HyperEVM by the CDW in a LATER /// block (H7), so V's balance cannot be measured here. `HlWithdrawQueued` /// carries the pre-state and the reconciler checks the Core debit and V's /// USDC credit next block (§8). /// /// READINGS TAKEN WHERE THE PLAN LEFT A GAP (listed for the owner): /// - Free spot is `total − hold`; held USDC is not counted. /// - FEE_RESERVE_WEI is 0.01 USDC: about 4× the flat fee measured on /// testnet (0.00246, U7). It stays in V's own spot. contract HlWithdrawAdapter is HyperCoreAdapter { bytes32 public constant OP_WITHDRAW = "hl_withdraw"; /// 0.01 USDC in spot wei (8 dp), left in spot for the Core → EVM fee. uint256 public constant FEE_RESERVE_WEI = 1_000_000; /// The same reserve in EVM USDC units (6 dp), as VenueLock counts it. uint256 public constant FEE_RESERVE = FEE_RESERVE_WEI / 100; bytes32 internal constant WITHDRAW_TYPEHASH = keccak256( "HlWithdraw(address account,address owner,bytes32 taskId,uint256 deadline,uint256 amount)" ); struct Withdraw { address account; address owner; bytes32 taskId; uint256 deadline; /// EVM USDC, 6 dp: what lands on V. uint256 amount; // No destination, no token: both fixed in the encoder. } /// Action 6 queued: `amount` is on its way home and VenueLock credited /// `credited` of it (equal to `amount` on this path). The pre-state it /// was checked against: spot total and hold (8 dp), and the returns /// pending in VenueLock's window before it (6 dp). event HlWithdrawQueued( address indexed account, bytes32 indexed taskId, uint256 amount, uint256 credited, uint64 spotTotalWei, uint64 spotHoldWei, uint256 pendingReturn ); /// Spot was short: only action 7 was queued, moving `ntlToSpot` of perp /// margin to V's own spot, and nothing was credited or sent. Withdraw /// again in a later block. event HlWithdrawTopUpQueued( address indexed account, bytes32 indexed taskId, uint256 amount, uint64 ntlToSpot, uint64 spotTotalWei, uint64 spotHoldWei, uint256 pendingReturn, uint64 withdrawable ); /// The shared per-(account, venue) record (VenueLock). V calls it for one /// function only, `noteReturn`, with calldata written here; this adapter /// reads `pendingReturnOf` (no lock is read). VenueLock public immutable venueLock; error ZeroAmount(); error OverWithdrawable(uint256 neededWei, uint256 freeSpotWei, uint64 withdrawable); error BadVenueLock(address venueLock); constructor(AgentRegistry registry_, VenueLock venueLock_) HyperCoreAdapter(registry_) { address l = address(venueLock_); // The same guard as `hl_deposit`'s: a real contract, and never one of // the other addresses V is made to call on this venue. 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 ("DeFiLoopsHlWithdrawAdapter", "1"); } function digest(Withdraw calldata w) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode(WITHDRAW_TYPEHASH, w.account, w.owner, w.taskId, w.deadline, w.amount) ) ); } /// `hl_withdraw`: a send home out of free spot, or, when spot is short, /// only the perp → spot top-up (see the header). function withdraw(Withdraw calldata w, bytes calldata signature) external { _consume(w.account, w.owner, w.taskId, w.deadline, digest(w), signature); _requireOperation(w.account, OP_WITHDRAW); if (w.amount == 0) revert ZeroAmount(); uint64 wei_ = _u64(w.amount * 100); uint256 neededWei = uint256(wei_) + FEE_RESERVE_WEI; SpotBalance memory spot = _spotUsdc(w.account); uint256 free = spot.total > spot.hold ? spot.total - spot.hold : 0; // Spot already claimed by sends still pending in VenueLock's window. uint256 pending = venueLock.pendingReturnOf(w.account, HYPERLIQUID); uint256 claimedWei = pending * 100; uint256 freeNow = free > claimedWei ? free - claimedWei : 0; if (freeNow < neededWei) { // Short: move the missing part to V's own spot and stop. Nothing // is sent, nothing is credited. uint64 withdrawable = _withdrawable(w.account); uint256 ntl = (neededWei - freeNow + 99) / 100; if (ntl > withdrawable) revert OverWithdrawable(neededWei, freeNow, withdrawable); _actPerpToSpot(w.account, w.taskId, uint64(ntl)); emit HlWithdrawTopUpQueued( w.account, w.taskId, w.amount, uint64(ntl), spot.total, spot.hold, pending, withdrawable ); return; } _actSpotSendHome(w.account, w.taskId, wei_); // V's net sent to the venue falls by what this send can bring home: // VenueLock clamps it to the free spot read here, less what pending // sends claim. Never reads the lock, never reverts: this is an exit. bytes memory ret = _exec( w.account, address(venueLock), 0, abi.encodeCall(VenueLock.noteReturn, (HYPERLIQUID, w.amount, free / 100, FEE_RESERVE)) ); uint256 credited = abi.decode(ret, (uint256)); emit HlWithdrawQueued( w.account, w.taskId, w.amount, credited, spot.total, spot.hold, pending ); } }