// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {EIP712} from "solady/utils/EIP712.sol"; import {ECDSA} from "solady/utils/ECDSA.sol"; import {IKernelRoot, IOwnedValidator} from "./BaseAdapter.sol"; import {RootOwner} from "./RootOwner.sol"; /// @title VenueLock — the owner's one-time lock on what an account may do at a venue. /// /// LAYER 2 OF THE VENUE POLICY ENGINE (docs/ASTER_VENUE_PLAN.md §2 A2 and §5; /// docs/HYPERLIQUID_VENUE_PLAN.md §5 and HL4). Owner A sets it once per venue /// connect, for one account V and one venue. It says three things and nothing /// else: /// /// 1. WHICH KEY the venue knows V by: an agent address (Hyperliquid's G), an /// API public key at an index (Lighter), or the venue account wallet M /// (Aster). The key was born in the venue enclave. /// 2. THE BOUNDS: the cap on money at the venue, the allowed products, the /// leverage ceiling, whether cross margin is allowed at all, and the price /// band an opening order must sit in around the mark (`bandBps`, OA-3). /// 3. WHO SAID SO: A, read from the account at the moment of setting. /// /// It moves nothing and calls nothing that writes. The deposit adapter (T-800) /// reads it and enforces it; the venue enclave reads it and enforces it. EXITS /// NEVER READ IT: cancels, reduce-only closes and withdrawals to V are always /// allowed (owner rule: limit orders and exits must survive), so no exit path /// may depend on a lock existing, being live, or being readable. /// /// IT ALSO KEEPS THE ACCOUNT'S OWN TWO RECORDS PER VENUE, WRITTEN ONLY BY THE /// ACCOUNT (audit 2026-10-25, findings 1, 3 and 4). `sentOf` is the net money /// V sent to the venue under its current lock; `keyUsed` is every key an /// adapter ever registered for V at the venue. Both live here, keyed by /// (account, venue), so every adapter instance — today's, a replacement still /// whitelisted beside it, the next deploy — reads and writes the SAME record. /// Per-adapter storage was what let two deposit adapters each pass the cap. /// /// - WHY `msg.sender == account` IS THE AUTHORITY. Every write is made BY V: /// an adapter makes V call `noteDeposit` / `noteReturn` / `useKey` through /// `_exec`, with the calldata written in the adapter's code. That is the /// authority `tighten` already accepts ("A, or V itself"): V calling is A /// driving its own account, or an adapter A's account executes for. No /// registry, no role, no adapter list is consulted, and a stranger can only /// ever write its own records. /// - THE CAP IS `max(sentOf + amount, atVenue + inFlight + amount) ≤ cap` /// (`noteDeposit`). `sent` never falls with a loss at the venue — only an /// `hl_withdraw` home (`noteReturn`) lowers it — so losing the money does /// not free room to send more; a deposit still in flight counts at once, /// in `sent` AND in the live term (`inFlight`), in the block it leaves; /// and a GAIN at the venue still counts, through the live value the /// adapter reads (`atVenue`). The cap bounds what can be lost per signed /// lock, not only what is exposed at one moment. /// - ONE SETTLE WINDOW, BOTH DIRECTIONS (audit re-run 2026-10-25, findings /// 1, 4, 5, 6). The venue's state the adapter reads is fixed for the whole /// EVM block and moves only when HyperCore runs the queued action, a /// moment later (testnet ~0.4 s, mainnet orders "a few seconds"). So /// VenueLock keeps what it was told and the venue cannot show yet: /// `inFlight`, the deposits noted inside the window, and `pendingReturn`, /// the returns credited inside it. Each resets only when /// `block.timestamp ≥ last note + SETTLE_SECONDS` (60 s): two notes closer /// than the window always share it, however many blocks apart. A deposit /// that already landed and is still in `inFlight` counts twice, which is /// the safe side. /// - THE LOSS BUDGET IS PER SIGNED LOCK. A `set` (A's fresh signature) /// starts `sentOf` again at zero; live money at the venue still counts /// through `atVenue`, and money still in flight through `inFlight`, which /// `set` never clears. `tighten` resets nothing. /// - A KEY IS REGISTERED ONCE ("G is rotated, never reused", HL5). /// `useKey` refuses a key it has seen for (account, venue) before, and the /// record is never cleared, by `set` or anything else: once revoked or /// pruned, the venue may let old signed actions of that key replay, so it /// must never be the account's agent again. Renewing means a re-arm that /// binds a NEW key. A closed lock (zero cap or no products) registers none. /// - `noteReturn` never reads the lock and never reverts: it is on the /// withdraw path, an exit. It credits only money the adapter saw FREE in /// the venue account it sends from, less what earlier returns in the /// window already claimed (see `noteReturn`). /// /// SET BY A'S SIGNATURE, SUBMITTED BY ANYONE. `set` takes an EIP-712 statement /// signed by A and may be relayed by anybody, so A needs no gas token on the /// lock's chain (HL4: no HYPE). The domain carries the chain id and this /// contract's address, each statement carries the account's current nonce for /// that venue and a deadline: no replay, no reuse on another chain or another /// deployment, no stale relay. /// /// TIGHTENING IS IMMEDIATE, LOOSENING NEEDS A AGAIN. `tighten` lowers the cap, /// narrows the products, lowers the ceiling, narrows the band or turns cross /// margin off, with no new signature, called by A or by V itself. It can never /// change the key and never widen anything. Everything else, including any loosening and any /// change of key (rotation, HL5), is a fresh `set` A signs. A tighten also /// bumps the nonce, so an older loosening A signed but nobody relayed yet /// cannot undo it. /// /// A KEY IS BOUND ONLY WITH THE ENCLAVE'S RECEIPT (decision V5 in /// docs/VENUE_ENCLAVE_PLAN.md). Every `set` also carries a receipt signed by /// the venue enclave's pinned identity key, over (owner, account, venue, key). /// A's signature alone is not enough: a compromised prod could show A a key it /// made itself, and A would sign. With the receipt, the only keys that can be /// bound are ones the measured enclave says it holds, for this owner, this /// account and this venue. /// /// THE OWNER IS READ FROM THE ACCOUNT, NEVER TAKEN FROM INPUT. `ownerOf` asks /// V's root validator, the same question `BaseAdapter.ownerOf` asks through the /// same `RootOwner` library. The lock records that owner, and a lock whose /// recorded owner is no longer the account's owner is INERT: every read /// returns the empty lock, so a root rotation never leaves the old owner's /// bounds standing for the new one. /// /// ECDSA ROOTS ONLY IN v1 (D10, docs/security/ENCLAVE_AUTHORISATION_DESIGN.md). /// A Safe (ERC1271RootValidator) or a passkey (WebAuthnRootValidator) root is /// refused with `OwnerNotEcdsa`, by name, rather than failing a signature /// check by accident. Their owners sign through ERC-1271 or a passkey, which /// this contract does not verify yet; that is a later change, and a new /// deployment. /// /// GENERIC ACROSS VENUES. A venue is a bytes32 id the reader agrees with (for /// example keccak256("hyperliquid")); a product is a bit the venue's reader /// defines; the cap is in the unit the venue's deposit adapter counts. No venue /// logic lives here. /// /// NO PROXY, NO ADMIN, NO ROLES. The enclave identity is a constructor /// immutable. A new identity key is a new deployment and every owner /// re-signing, which is the most restrictive reading of "pinned". /// /// READINGS CHOSEN WHERE THE SOURCES LEFT A GAP (most restrictive each time; /// open questions for the owner, listed in the T-773 report): /// - Margin mode: the task names cap, products and leverage; the Hyperliquid /// plan's layer 2 adds margin mode. Included, as `crossMargin` (false = /// isolated only), and only tightenable from true to false. /// - Who may tighten without a new signature: A itself, or V calling (A /// driving its own account). Nobody else: not prod, not the keeper. /// - The receipt names the owner as well as the account, the venue and the /// key, matching the venue enclave's seal context {owner, account, venue, /// role}. A new owner of V needs a new receipt. /// - The receipt is required on EVERY `set`, not only when the key changes. /// - Products are a 256-bit set: enough for one product class per bit (Aster /// spot/perps) or the low Hyperliquid perp asset ids (BTC 0, ETH 1). Ids at /// or above 256 cannot be named, so they cannot be allowed. /// - The enclave identity is a secp256k1 address (the only signature this /// chain verifies natively). V5 does not name the key type. /// - This contract does not ask whether V is a genuine account: the reader /// (the deposit adapter) already does, through `_requireGenuine`, and a /// lock set on a costume account binds nothing any genuine account reads. contract VenueLock is EIP712 { // ----------------------------------------------------------------------- // Key kinds // ----------------------------------------------------------------------- /// An agent address the venue lets trade for the account (Hyperliquid G). /// `key` is the address, left-padded; `index` is zero. uint8 public constant KEY_AGENT = 1; /// An API public key at an index (Lighter-style). `key` is the 32-byte /// public key, or its keccak256 when longer; `index` is the venue's slot. uint8 public constant KEY_API = 2; /// The venue account wallet M (Aster). `key` is the address, left-padded; /// `index` is zero. uint8 public constant KEY_ACCOUNT_WALLET = 3; /// Kernel's validation type byte for "this is a validator module". bytes1 internal constant VALIDATION_TYPE_VALIDATOR = 0x01; /// How long a note stays unsettled: a deposit counts in `inFlight` and a /// credited return in `pendingReturn` until this long after the LATEST /// note of its kind. Testnet runs every CoreWriter action ~0.4 s after it /// is queued (U4), mainnet delays orders "a few seconds" (H4); 60 s is a /// wide margin, and a longer window only makes both checks stricter. uint256 public constant SETTLE_SECONDS = 60; uint256 internal constant MAX128 = type(uint128).max; // ----------------------------------------------------------------------- // Types // ----------------------------------------------------------------------- /// Which key the venue knows the account by. struct Binding { uint8 kind; uint64 index; bytes32 key; } /// What the account may do at the venue. struct Limits { /// Most money allowed at the venue, in the unit the venue's deposit /// adapter counts (USDC base units for Hyperliquid and Aster). uint128 cap; /// Most leverage allowed, whole times (5 = 5x). uint16 maxLeverage; /// False: isolated margin only. bool crossMargin; /// Bit i set: venue product i allowed. uint256 products; /// The price band an OPENING order must sit in around the venue's mark, /// in basis points (OA-3, docs/design/HYPERLIQUID_ONCHAIN_ORDERS.md §9): /// a buy at most mark · (1 + band), a sell at least mark · (1 − band). /// Zero: no opening order passes (a closed band). The reader keeps its /// own protocol ceiling on it (`hl_order`: `MAX_BAND_BPS`). Exits never /// read it. uint16 bandBps; } struct Lock { /// A, as the account named its owner when A signed. Zero: no lock. address owner; Binding binding; Limits limits; } /// What the account noted and the venue cannot show yet (one settle /// window, `SETTLE_SECONDS`, from the latest note of each kind). Read /// through `inFlightOf` / `pendingReturnOf`, which apply the window. struct Unsettled { /// Deposits noted inside the window, in the cap's unit. uint128 inFlight; /// When the latest deposit was noted. uint64 depositAt; /// Returns credited inside the window plus the venue fee each send /// keeps, in the cap's unit. uint128 pendingReturn; /// When the latest return was noted. uint64 returnAt; } bytes32 internal constant BINDING_TYPEHASH = keccak256("Binding(uint8 kind,uint64 index,bytes32 key)"); bytes32 internal constant LIMITS_TYPEHASH = keccak256("Limits(uint128 cap,uint16 maxLeverage,bool crossMargin,uint256 products,uint16 bandBps)"); /// What A signs. Referenced types follow, sorted, as EIP-712 requires. bytes32 internal constant SET_LOCK_TYPEHASH = keccak256( "SetLock(address account,bytes32 venue,Binding binding,Limits limits,uint256 nonce," "uint256 deadline)Binding(uint8 kind,uint64 index,bytes32 key)" "Limits(uint128 cap,uint16 maxLeverage,bool crossMargin,uint256 products,uint16 bandBps)" ); /// What the venue enclave's identity key signs when a key is born. bytes32 internal constant KEY_RECEIPT_TYPEHASH = keccak256( "KeyReceipt(address owner,address account,bytes32 venue,Binding binding)" "Binding(uint8 kind,uint64 index,bytes32 key)" ); // ----------------------------------------------------------------------- // State // ----------------------------------------------------------------------- /// The venue enclave's pinned identity key (V5). Immutable: no admin can /// repoint it. address public immutable enclaveIdentity; mapping(address account => mapping(bytes32 venue => Lock)) internal _locks; /// The nonce A's next `set` for (account, venue) must carry. Bumped by /// every `set` and every `tighten`. mapping(address account => mapping(bytes32 venue => uint256)) public nonceOf; /// Net money the account sent to the venue under its current lock, in the /// cap's unit: deposits added by `noteDeposit`, withdrawals home taken off /// by `noteReturn` as far as it credits them (never below zero). Never /// lowered by a loss at the venue. Reset to zero by `set` only. Written /// only by the account. mapping(address account => mapping(bytes32 venue => uint256)) public sentOf; /// Deposits in flight and returns pending, per (account, venue). Written /// only by the account (`noteDeposit`, `noteReturn`); never cleared by /// `set` or `tighten`, only by the window running out. mapping(address account => mapping(bytes32 venue => Unsettled)) internal _unsettled; /// Every key an adapter registered for (account, venue). Never cleared. /// Written only by the account, through `useKey`. mapping(address account => mapping(bytes32 venue => mapping(bytes32 key => bool))) public keyUsed; // ----------------------------------------------------------------------- // Events and errors // ----------------------------------------------------------------------- event LockSet( address indexed account, bytes32 indexed venue, address indexed owner, uint256 nonce, Binding binding, Limits limits ); event LockTightened( address indexed account, bytes32 indexed venue, address indexed by, uint256 nonce, Limits limits ); /// The account sent `amount` to the venue; `sent` is its net total after, /// `atVenue` the live value the adapter read, `cap` the bound it passed. event VenueSent( address indexed account, bytes32 indexed venue, uint256 amount, uint256 atVenue, uint256 sent, uint128 cap ); /// The account queued a send home of `amount`; `credited` is what /// VenueLock took off its net sent (clamped to the free balance the /// adapter read, less returns still pending), `sent` its net total after. event VenueReturned( address indexed account, bytes32 indexed venue, uint256 amount, uint256 credited, uint256 sent ); event KeyRegistered(address indexed account, bytes32 indexed venue, bytes32 indexed key); error ZeroIdentity(); error CannotEstablishOwner(address account); /// A Safe or passkey root: not verified in v1 (D10). error OwnerNotEcdsa(address account, address validator); error NoVenue(); error BadBinding(uint8 kind); error SignatureExpired(uint256 deadline); error StaleNonce(uint256 expected, uint256 got); error WrongSigner(address recovered, address owner); error ReceiptNotFromEnclave(address recovered, address identity); error NoLock(address account, bytes32 venue); error NotOwnerAuthority(address caller, address account); /// `field` is the one that would widen: "cap", "maxLeverage", /// "crossMargin", "products" or "bandBps". error Loosens(bytes32 field); error NotAnAddressKey(uint8 kind); /// `max(sent + amount, atVenue + inFlight + amount)` would exceed the /// lock's cap. error OverVenueCap(uint256 exposure, uint128 cap); /// Zero cap or no products: a closed lock registers no key and takes no /// deposit. error LockClosed(address account, bytes32 venue); error KeyNotBound(bytes32 key, bytes32 bound); /// This key was registered for (account, venue) before (HL5). error KeyReused(address account, bytes32 venue, bytes32 key); constructor(address enclaveIdentity_) { if (enclaveIdentity_ == address(0)) revert ZeroIdentity(); enclaveIdentity = enclaveIdentity_; } function _domainNameAndVersion() internal pure override returns (string memory, string memory) { return ("DeFiLoopsVenueLock", "1"); } // ----------------------------------------------------------------------- // Owner // ----------------------------------------------------------------------- /// Who owns this account, according to the account, when that owner signs /// with a plain ECDSA key. /// /// The same read as `BaseAdapter.ownerOf` (root validator, then /// `RootOwner.ownerFrom`), plus one more question: does the root answer /// in the ECDSA dialect with that same owner? `GatedECDSAValidator` and /// Kernel's `ECDSAValidator` do; `ERC1271RootValidator` and /// `WebAuthnRootValidator` do not, and are refused by name. function ownerOf(address account) public view returns (address owner) { bytes21 root = IKernelRoot(account).rootValidator(); if (bytes1(root) != VALIDATION_TYPE_VALIDATOR) revert CannotEstablishOwner(account); address validator = address(uint160(uint168(root))); owner = RootOwner.ownerFrom(validator, account); if (owner == address(0)) revert CannotEstablishOwner(account); try IOwnedValidator(validator).ecdsaValidatorStorage(account) returns (address ecdsa) { if (ecdsa != owner) revert OwnerNotEcdsa(account, validator); } catch { revert OwnerNotEcdsa(account, validator); } } // ----------------------------------------------------------------------- // Digests (public, so a wallet's prompt and an enclave's receipt can be // checked against the chain rather than trusted from whoever built them) // ----------------------------------------------------------------------- function setDigest( address account, bytes32 venue, Binding calldata binding, Limits calldata limits, uint256 nonce, uint256 deadline ) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode( SET_LOCK_TYPEHASH, account, venue, _hashBinding(binding), _hashLimits(limits), nonce, deadline ) ) ); } function receiptDigest(address owner, address account, bytes32 venue, Binding calldata binding) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode(KEY_RECEIPT_TYPEHASH, owner, account, venue, _hashBinding(binding)) ) ); } function _hashBinding(Binding calldata b) internal pure returns (bytes32) { return keccak256(abi.encode(BINDING_TYPEHASH, b.kind, b.index, b.key)); } function _hashLimits(Limits calldata l) internal pure returns (bytes32) { return keccak256( abi.encode( LIMITS_TYPEHASH, l.cap, l.maxLeverage, l.crossMargin, l.products, l.bandBps ) ); } // ----------------------------------------------------------------------- // Writes // ----------------------------------------------------------------------- /// Set (or replace) the lock A signed. Anyone may submit it. /// /// Order: cheapest refusal first, then A, then the enclave. Nothing is /// written until both signatures verified. function set( address account, bytes32 venue, Binding calldata binding, Limits calldata limits, uint256 nonce, uint256 deadline, bytes calldata ownerSignature, bytes calldata receipt ) external { if (venue == bytes32(0)) revert NoVenue(); _requireWellFormed(binding); if (block.timestamp > deadline) revert SignatureExpired(deadline); if (nonce != nonceOf[account][venue]) revert StaleNonce(nonceOf[account][venue], nonce); address owner = ownerOf(account); _requireSigned( owner, setDigest(account, venue, binding, limits, nonce, deadline), ownerSignature ); _requireReceipt(receiptDigest(owner, account, venue, binding), receipt); nonceOf[account][venue] = nonce + 1; _locks[account][venue] = Lock({owner: owner, binding: binding, limits: limits}); // A new owner-signed lock is a new loss budget. Money still at the // venue keeps counting through the live value `noteDeposit` is given, // and money still in flight through `inFlight`, which is NOT reset // (a deposit queued just before this `set` is in neither `atVenue` // nor, after the reset, `sentOf`). `keyUsed` is NOT reset either: a // key is never registered twice. sentOf[account][venue] = 0; emit LockSet(account, venue, owner, nonce, binding, limits); } /// Narrow a live lock at once, with no new signature. A, or V itself. /// /// Every field must be no wider than it is now; equal is allowed, so a /// tighten that changes nothing is how A cancels a `set` it signed and /// has not seen relayed (the nonce moves either way). function tighten(address account, bytes32 venue, Limits calldata limits) external { address owner = ownerOf(account); if (msg.sender != owner && msg.sender != account) { revert NotOwnerAuthority(msg.sender, account); } Lock storage lock = _locks[account][venue]; if (lock.owner != owner) revert NoLock(account, venue); Limits memory old = lock.limits; if (limits.cap > old.cap) revert Loosens("cap"); if (limits.maxLeverage > old.maxLeverage) revert Loosens("maxLeverage"); if (limits.crossMargin && !old.crossMargin) revert Loosens("crossMargin"); if (limits.products & ~old.products != 0) revert Loosens("products"); if (limits.bandBps > old.bandBps) revert Loosens("bandBps"); lock.limits = limits; uint256 nonce = nonceOf[account][venue]++; emit LockTightened(account, venue, msg.sender, nonce, limits); } // ----------------------------------------------------------------------- // The account's own records. msg.sender IS the account: an adapter makes // V call these through `_exec`, with calldata fixed in its code. // ----------------------------------------------------------------------- /// The cap check, and the record of the money sent. Called by V before any /// money moves; `atVenue` is the live value V holds at the venue now (the /// adapter reads it), `amount` what is about to leave. /// /// sent = sentOf + amount /// live = atVenue + inFlight + amount /// exposure = max(sent, live) ≤ lock.cap /// /// A loss at the venue never frees room (`sent` does not fall with it), a /// deposit in flight counts at once in both terms, and a gain still /// counts via `atVenue`. `inFlight` is the deposits noted inside the /// settle window: `atVenue` is read from state fixed for the block and /// the venue credits a deposit only after it (H7), so several deposits /// in one block, or a `set` between two of them, would otherwise each be /// checked against the same old balance. Refuses with no live lock, and /// with a closed one (zero cap or no products, as `useKey` and `hl_order` /// read it). function noteDeposit(bytes32 venue, uint256 amount, uint256 atVenue) external returns (uint256 sent) { address account = msg.sender; Lock memory lock = lockOf(account, venue); if (lock.owner == address(0)) revert NoLock(account, venue); if (lock.limits.cap == 0 || lock.limits.products == 0) revert LockClosed(account, venue); Unsettled storage u = _unsettled[account][venue]; uint256 flying = _unsettledAmount(u.inFlight, u.depositAt) + amount; sent = sentOf[account][venue] + amount; uint256 live = atVenue + flying; uint256 exposure = sent > live ? sent : live; if (exposure > lock.limits.cap) revert OverVenueCap(exposure, lock.limits.cap); sentOf[account][venue] = sent; // flying ≤ live ≤ cap, a uint128: the casts cannot truncate. u.inFlight = uint128(flying); u.depositAt = uint64(block.timestamp); emit VenueSent(account, venue, amount, atVenue, sent, lock.limits.cap); } /// A send home of `amount` was queued at the venue: lower the account's /// net sent by what can actually come home, never below zero. /// /// THE RULE. A return is credited only out of money that was already FREE /// in the venue account the send leaves from, at the read, less what the /// returns still pending in the window claim: /// /// room = homeable − pendingReturn (floor 0) /// credited = min(amount, room − fee) (floor 0) /// pendingReturn += credited + fee; sentOf −= credited (floor 0) /// /// `homeable` is that free balance as the adapter read it (state fixed for /// the block, H5), in the cap's unit; `fee` is what the venue keeps from /// it per send and never pays home (`hl_withdraw`: its fee reserve). N /// sends in one block, or a few blocks apart inside the window, are /// credited at most what the balance they all read can pay, fees /// included: a send the venue then rejects for want of money is one /// VenueLock never credited. /// /// THE ASSUMPTIONS (Hyperliquid): classic account mode; spot USDC moves /// only by the account's own actions (the `hl_withdraw` send, and its /// perp → spot top-up, which only adds); G cannot move spot ↔ perp /// (usdClassTransfer is user-signed) and does not trade spot; a queued /// send runs, or is rejected, inside `SETTLE_SECONDS`. /// /// ON AN EXIT PATH (withdraw): it never reads the lock, has nothing to /// refuse and NEVER reverts, whatever the inputs; every sum saturates. function noteReturn(bytes32 venue, uint256 amount, uint256 homeable, uint256 fee) external returns (uint256 credited) { address account = msg.sender; Unsettled storage u = _unsettled[account][venue]; uint256 pending = _unsettledAmount(u.pendingReturn, u.returnAt); uint256 room = homeable > pending ? homeable - pending : 0; if (room > fee) credited = amount < room - fee ? amount : room - fee; // credited + fee ≤ room when credited > 0; otherwise it is just fee. uint256 debit = credited + fee; u.pendingReturn = uint128(debit >= MAX128 - pending ? MAX128 : pending + debit); u.returnAt = uint64(block.timestamp); uint256 sent = sentOf[account][venue]; sent = sent > credited ? sent - credited : 0; sentOf[account][venue] = sent; emit VenueReturned(account, venue, amount, credited, sent); } /// Register `key` for the account at the venue, once ever. The lock must /// be live and open (a zero cap or no products is VenueLock's "refuse"), /// the key must be the one it binds, and it must never have been /// registered for (account, venue) before (HL5: rotated, never reused). function useKey(bytes32 venue, bytes32 key) external { address account = msg.sender; Lock memory lock = lockOf(account, venue); if (lock.owner == address(0)) revert NoLock(account, venue); if (lock.limits.cap == 0 || lock.limits.products == 0) revert LockClosed(account, venue); if (key != lock.binding.key) revert KeyNotBound(key, lock.binding.key); if (keyUsed[account][venue][key]) revert KeyReused(account, venue, key); keyUsed[account][venue][key] = true; emit KeyRegistered(account, venue, key); } // ----------------------------------------------------------------------- // Reads (what the deposit adapter and the venue enclave ask) // ----------------------------------------------------------------------- /// The live lock for (account, venue), or the all-zero lock when there is /// none or it was set by an owner the account no longer names. A zero cap /// and no products is the empty lock's answer to every bound: refuse. /// /// A stored lock on an account whose owner this contract can no longer /// read (its root moved to a Safe or a passkey) reverts `OwnerNotEcdsa` / /// `CannotEstablishOwner`: a refusal either way. Exit paths must not call /// it. function lockOf(address account, bytes32 venue) public view returns (Lock memory lock) { lock = _locks[account][venue]; if (lock.owner == address(0) || lock.owner != ownerOf(account)) { delete lock; } } /// Deposits noted for (account, venue) inside the settle window: money /// that left the account and the venue may not show yet. function inFlightOf(address account, bytes32 venue) external view returns (uint256) { Unsettled storage u = _unsettled[account][venue]; return _unsettledAmount(u.inFlight, u.depositAt); } /// Returns credited for (account, venue) inside the settle window, with /// the venue fee of each send: spot the venue may still show but has /// already been claimed. Never reads the lock: `hl_withdraw` reads it. function pendingReturnOf(address account, bytes32 venue) external view returns (uint256) { Unsettled storage u = _unsettled[account][venue]; return _unsettledAmount(u.pendingReturn, u.returnAt); } /// The bound key as an address, for venues that name one (an agent, or the /// account wallet). `aster_deposit` takes `forAddress` from here and /// `hl_agent` takes the agent from here, never from an intent. function boundAddress(address account, bytes32 venue) external view returns (address) { Lock memory lock = lockOf(account, venue); if (lock.owner == address(0)) revert NoLock(account, venue); uint8 kind = lock.binding.kind; if (kind != KEY_AGENT && kind != KEY_ACCOUNT_WALLET) revert NotAnAddressKey(kind); return address(uint160(uint256(lock.binding.key))); } // ----------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------- /// `amount` while the window since `at` is open, else zero. function _unsettledAmount(uint128 amount, uint64 at) internal view returns (uint256) { return block.timestamp >= uint256(at) + SETTLE_SECONDS ? 0 : amount; } /// A signed exactly this. Split out of `set` for the stack, not for reuse. function _requireSigned(address owner, bytes32 digest, bytes calldata signature) internal view { address signer = ECDSA.tryRecoverCalldata(digest, signature); if (signer != owner) revert WrongSigner(signer, owner); } /// The venue enclave's pinned identity key attested exactly this binding. function _requireReceipt(bytes32 digest, bytes calldata receipt) internal view { address attester = ECDSA.tryRecoverCalldata(digest, receipt); if (attester != enclaveIdentity) revert ReceiptNotFromEnclave(attester, enclaveIdentity); } /// A known kind, a non-zero key, and for an address kind a real address and /// no index. function _requireWellFormed(Binding calldata b) internal pure { if (b.key == bytes32(0)) revert BadBinding(b.kind); if (b.kind == KEY_API) return; if (b.kind != KEY_AGENT && b.kind != KEY_ACCOUNT_WALLET) revert BadBinding(b.kind); if (uint256(b.key) >> 160 != 0 || b.index != 0) revert BadBinding(b.kind); } }