// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import {ECDSA} from "solady/utils/ECDSA.sol"; import {BaseAdapter, IERC20Balance} from "../BaseAdapter.sol"; import {AgentRegistry} from "../AgentRegistry.sol"; /// Lighter's L1 proxy on Ethereum (`0x3B4D…5ca7`), the functions this /// adapter reaches and nothing else. Selectors (docs/LIGHTER_VENUE_PLAN.md v1 /// F2): `deposit` 0x8a857083, `changePubKey` 0x17010c68, /// `withdrawPendingBalance` 0x2f25807e; `getPendingBalance` is read by a /// claim, `tokenToAssetIndex` once, at construction. interface ILighterProxy { /// Credits `_to`'s Lighter account (created in this same transaction if /// `_to` has none, F4). Pulls `_amount` of the asset from `msg.sender`. function deposit(address _to, uint16 _assetIndex, uint8 _routeType, uint256 _amount) external; /// Binds `_pubKey` at `_apiKeyIndex` of the CALLER's account (F3): the /// account is `validateAndGetAccountIndexFromAddress(msg.sender)`, and /// `_accountIndex = NIL` means "my master account". function changePubKey(uint48 _accountIndex, uint8 _apiKeyIndex, bytes calldata _pubKey) external; /// Pays `_owner`'s pending balance to `_owner`, whoever calls (F11). function withdrawPendingBalance(address _owner, uint16 _assetIndex, uint128 _amount) external; /// `_owner`'s claimable balance of an asset, in the asset's base units. function getPendingBalance(address _owner, uint16 _assetIndex) external view returns (uint128); function tokenToAssetIndex(address token) external view returns (uint16); } /// @title LighterAdapter — V's own money into, and back out of, V's own Lighter account. /// /// T-807 (W1), docs/LIGHTER_VENUE_PLAN.md §7 and §5a. Three operations on /// Ethereum (chain 1), catalogue ids `lighter.deposit`, `lighter.register`, /// `lighter.claim`; all three are price-neutral (no swap, no quote). /// /// lighter_deposit(amount, route) approve(proxy, amount); /// deposit(V, 3, route, amount); /// the approval cleared. /// lighter_register(index, pubkey, changePubKey(NIL, index, pubkey), only /// receipt) with a KeyReceipt from the pinned enclave. /// lighter_claim(assetIndex, withdrawPendingBalance(V, assetIndex, /// amount) min(amount, pending)), measured as V's /// balance delta; nothing pending, no call /// and no revert. Feeds no later step. /// /// THE ACCOUNT IS V (LD12). A Lighter account is an L1 address; V is it. Every /// call is V's, through `_exec`, so no token ever passes through this contract /// and there is no balance here to drain. /// /// WHAT THE INTENT CANNOT NAME. A recipient: `deposit`'s `_to` and /// `withdrawPendingBalance`'s `_owner` are written here as V, never read from /// the intent. A target: the proxy is a constant in this bytecode, and the /// curated venue `lighter` must resolve to it. An asset: deposits are USDC /// (asset index 3, checked against the proxy at construction), and a claim's /// asset index must be on this contract's fixed allow-list (USDC only in v1, /// §5a). A route other than perps (0) or spot (1). A key the enclave did not /// receipt. /// /// THE OWNER'S CAP. Every deposit is charged to the account's AgentRegistry /// per-asset daily cap on USDC (`_charge`, `CAP_EPOCH` = 1 day) before money /// moves (LD14). There is no VenueLock on Ethereum (§15): the MegaETH lock /// bounds what the keeper SIGNS at Lighter, not what reaches it. /// /// THE KEY RECEIPT (`register`). The pinned enclave identity — the keeper's K, /// the same key `VenueLock.enclaveIdentity` pins — must have signed /// /// LighterKeyReceipt(owner = ownerOf(V) READ ON CHAIN, account = V, /// venue = keccak256("lighter"), /// Binding{kind = KEY_API (2), index, key = keccak256(pubkey)}, /// deadline) /// /// in THIS contract's EIP-712 domain ("DeFiLoopsLighterAdapter", "1", chain 1, /// this address), and `register` refuses it after `deadline` (the keeper signs /// it with a short one, at most a day). Its OWN type, not VenueLock's /// `KeyReceipt` (owner, 2026-10-27): `Binding` keeps VenueLock's string, so /// the binding hash is the same, but no VenueLock receipt (no deadline, other /// domain) verifies here, nor one for another chain or adapter. The keeper issues this receipt /// only after the owner's lock reads back on MegaETH with the same binding /// (§7, T-1578 B1), so a key the owner has not locked has no chain-1 receipt. /// /// THREATS (the brief's two, worked from this code): /// /// 1. REPLAYING AN OLDER RECEIPT AFTER A ROTATION. A receipt carries no nonce, /// so until its deadline a receipt for rotation r-1's key stays a valid /// signature after rotation r. The /// brief's reasoning was: "re-registering an old key the keeper itself /// derived only denies trading (the keeper refuses to sign unless the /// registered key is the current K_L), and it needs an owner-authorized /// step". From this code, the second half does NOT hold: `register` is /// gated by `_consume`, i.e. by the account's appointed agent B, exactly /// like every adapter step — on chain it is not an act of A. And the first /// half holds only while the old key never left the enclave: a rotation /// made BECAUSE a key leaked, then undone by a replay, would hand the /// venue back to whoever holds the leaked key (trade, MintShares into a /// foreign pool, F22). So this adapter closes the replay on chain: /// `keyUsed[V][keccak256(pubkey)]` is set by the first registration and a /// second registration of the same key for the same V is refused /// (`KeyReused`, the rule VenueLock's HL5 applies to its own bindings). A /// replayed receipt of a REGISTERED key can no longer register anything. /// A receipt of a key that was receipted and NEVER registered /// (solidity-auditor, 2026-10-27, raised by 11 of 12 agents) is now /// BOUNDED BY ITS DEADLINE: this contract cannot read the MegaETH lock, /// so until then it can still land, but only at the slot it binds (LD4: /// 200), replacing the live K_L — a denial (the keeper signs only with the /// registered current K_L) unless that key also leaked. After the /// deadline it registers nothing (`ReceiptExpired`). The keeper issues it /// only after the lock reads back (§7), for the register it sends at once, /// with a deadline of at most a day. /// Cost of the guard: a re-registration of the same key (an L2 refusal of /// a changePubKey) needs a key rotation; that is the keeper's normal path. /// `keyUsed` lives in this contract, so a replacement adapter starts /// empty: the keeper must never re-issue a receipt for a key it once /// registered. /// /// 2. THE COMBINED BOUND (§14). A bad keeper image, or a stolen B, can move /// at most the owner's AgentRegistry USDC cap per day from V on Ethereum /// into V's own Lighter account — and if the owner set NO cap on USDC, /// everything V holds on Ethereum (an uncapped asset is uncapped, by /// AgentRegistry's design). It can send it nowhere but V's Lighter account /// (`_to = V`), and bring it back nowhere but V (`_owner = V`; Lighter's /// own withdraw has no recipient, F5). At Lighter it can lose all of it /// (adverse trades, MintShares into a foreign pool): the MegaETH lock and /// the keeper's allow-list bound that, not this contract. /// /// 3. SOMEONE ELSE PAYS V FIRST (solidity-auditor, 2026-10-28, 10 of 12 /// agents). Lighter's `withdrawPendingBalance(V, asset, x)` is callable by /// anyone and always pays V (F11), and Lighter's own sweeper on mainnet /// pays pending balances out routinely. So the claim is IDEMPOTENT AND /// TOLERANT (owner, 2026-10-28): it pays out whatever is still pending, /// up to its amount, and otherwise does nothing (no call, no revert, a /// LighterClaimed of 0). It only makes sure V is paid; no money is lost /// either way, because the only possible recipient is V. And because what /// arrives in this transaction depends on who paid first, the claim /// publishes no delivered amount: a later step spends a literal, signed /// amount (catalogue `lighter.claim`, Produces false). /// /// NOT HERE (§15): no lock storage, no L1 `withdraw`, `createOrder` or /// `cancelAllOrders` (L2 txs the keeper signs; the L1 forms are the owner's own /// exit), no non-USDC deposit, no sub-account, no fast withdraw. contract LighterAdapter is BaseAdapter { bytes32 public constant OP_DEPOSIT = "lighter_deposit"; bytes32 public constant OP_REGISTER = "lighter_register"; bytes32 public constant OP_CLAIM = "lighter_claim"; /// The venue name the guardian curates the proxy under. bytes32 public constant VENUE_LIGHTER = "lighter"; /// Lighter's L1 proxy on Ethereum mainnet (F1). address public constant LIGHTER_PROXY = 0x3B4D794a66304F130a4Db8F2551B0070dfCf5ca7; /// Circle's USDC on Ethereum mainnet. address public constant USDC_ETHEREUM = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; /// USDC's Lighter asset index (F4), checked against the proxy at construction. uint16 public constant ASSET_USDC = 3; /// Deposit routes (F4, F28): 0 perps (USDC only), 1 spot. uint8 public constant ROUTE_PERPS = 0; uint8 public constant ROUTE_SPOT = 1; /// "My master account" for the caller-bound L1 calls (F3): 2^48 - 1. uint48 public constant NIL = type(uint48).max; /// API key slots 0..3 are Lighter's; 4..254 are usable (F8). uint8 public constant MIN_KEY_INDEX = 4; uint8 public constant MAX_KEY_INDEX = 254; /// A Lighter public key: 40 bytes (five Goldilocks limbs, F8). uint256 public constant PUBKEY_LENGTH = 40; /// VenueLock's venue id for Lighter, and its KEY_API kind. bytes32 public constant LIGHTER = keccak256("lighter"); uint8 public constant KEY_API = 2; uint256 internal constant CHAIN_ETHEREUM = 1; /// `Binding` is VenueLock's type string, byte for byte (`VenueLock.sol` /// BINDING_TYPEHASH). The receipt is this adapter's own type, with a /// deadline (owner, 2026-10-27). bytes32 internal constant BINDING_TYPEHASH = keccak256("Binding(uint8 kind,uint64 index,bytes32 key)"); bytes32 internal constant KEY_RECEIPT_TYPEHASH = keccak256( "LighterKeyReceipt(address owner,address account,bytes32 venue,Binding binding,uint64 deadline)" "Binding(uint8 kind,uint64 index,bytes32 key)" ); bytes32 internal constant DEPOSIT_TYPEHASH = keccak256( "LighterDeposit(address account,address owner,bytes32 taskId,uint256 deadline,uint256 amount,uint8 route)" ); bytes32 internal constant REGISTER_TYPEHASH = keccak256( "LighterRegister(address account,address owner,bytes32 taskId,uint256 deadline,uint8 index,bytes pubkey,uint64 receiptDeadline,bytes receipt)" ); bytes32 internal constant CLAIM_TYPEHASH = keccak256( "LighterClaim(address account,address owner,bytes32 taskId,uint256 deadline,uint16 assetIndex,uint256 amount)" ); struct Deposit { address account; /// WHOSE account. Checked against what the account itself says. address owner; bytes32 taskId; uint256 deadline; /// USDC, 6 dp. Lighter refuses under 1 USDC (F4). uint256 amount; /// ROUTE_PERPS or ROUTE_SPOT. uint8 route; // No recipient, no asset, no venue address: all fixed here. } struct Register { address account; address owner; bytes32 taskId; uint256 deadline; /// The API key slot, 4..254 (LD4 uses 200). uint8 index; /// The 40-byte Lighter public key. bytes pubkey; /// The receipt's own deadline (unix seconds), signed by the enclave. uint64 receiptDeadline; /// The enclave identity's signature over the LighterKeyReceipt (header). bytes receipt; } struct Claim { address account; address owner; bytes32 taskId; uint256 deadline; /// A Lighter asset index on this contract's allow-list (USDC only in v1). uint16 assetIndex; /// In the asset's own base units; at most 2^128 - 1 (the proxy's type). uint256 amount; } /// The keeper's pinned identity key. Immutable: no admin can repoint it. address public immutable enclaveIdentity; /// A key once registered for V through this adapter is never registered /// again (threat 1 in the header). mapping(address account => mapping(bytes32 keyHash => bool)) public keyUsed; event LighterDeposited(address indexed account, bytes32 indexed taskId, uint8 route, uint256 amount); event LighterKeyRegistered(address indexed account, bytes32 indexed taskId, uint8 index, bytes32 keyHash); event LighterClaimed(address indexed account, bytes32 indexed taskId, uint16 assetIndex, uint256 amount); error ZeroIdentity(); error ChainNotServed(uint256 chainId); error WrongUsdcAssetIndex(uint16 got); error NotLighterProxy(address resolved); error ZeroAmount(); error BadRoute(uint8 route); error KeyIndexOutOfRange(uint8 index); error BadPubkeyLength(uint256 length); error ReceiptNotFromEnclave(address recovered, address identity); error ReceiptExpired(uint64 deadline); error KeyReused(address account, bytes32 keyHash); error AssetNotClaimable(uint16 assetIndex); error AmountTooLarge(uint256 amount); error ApproveFailed(); /// What left V is not what was authorised, in either direction. error SentOtherThanAuthorised(uint256 authorised, uint256 sent); /// What reached V is not what was claimed. error ClaimedOtherThanAsked(uint256 asked, uint256 received); constructor(AgentRegistry registry_, address enclaveIdentity_) BaseAdapter(registry_) { if (enclaveIdentity_ == address(0)) revert ZeroIdentity(); if (block.chainid != CHAIN_ETHEREUM) revert ChainNotServed(block.chainid); uint16 idx = ILighterProxy(LIGHTER_PROXY).tokenToAssetIndex(USDC_ETHEREUM); if (idx != ASSET_USDC) revert WrongUsdcAssetIndex(idx); enclaveIdentity = enclaveIdentity_; } function _domainNameAndVersion() internal pure override returns (string memory, string memory) { return ("DeFiLoopsLighterAdapter", "1"); } // ----------------------------------------------------------------------- // Digests // ----------------------------------------------------------------------- function depositDigest(Deposit calldata d) public view returns (bytes32) { return _hashTypedData( keccak256(abi.encode(DEPOSIT_TYPEHASH, d.account, d.owner, d.taskId, d.deadline, d.amount, d.route)) ); } function registerDigest(Register calldata r) public view returns (bytes32) { return _hashTypedData( keccak256( abi.encode( REGISTER_TYPEHASH, r.account, r.owner, r.taskId, r.deadline, r.index, keccak256(r.pubkey), r.receiptDeadline, keccak256(r.receipt) ) ) ); } function claimDigest(Claim calldata c) public view returns (bytes32) { return _hashTypedData( keccak256(abi.encode(CLAIM_TYPEHASH, c.account, c.owner, c.taskId, c.deadline, c.assetIndex, c.amount)) ); } /// What the enclave identity signs for (owner, account, index, pubkey, /// deadline): a LighterKeyReceipt, in this contract's domain. function receiptDigest(address owner, address account, uint8 index, bytes calldata pubkey, uint64 deadline) public view returns (bytes32) { bytes32 binding = keccak256(abi.encode(BINDING_TYPEHASH, KEY_API, uint64(index), keccak256(pubkey))); return _hashTypedData( keccak256(abi.encode(KEY_RECEIPT_TYPEHASH, owner, account, LIGHTER, binding, deadline)) ); } // ----------------------------------------------------------------------- // Operations // ----------------------------------------------------------------------- /// V's USDC into V's own Lighter account, perps or spot. function deposit(Deposit calldata d, bytes calldata signature) external { _consume(d.account, d.owner, d.taskId, d.deadline, depositDigest(d), signature); _requireOperation(d.account, OP_DEPOSIT); if (d.amount == 0) revert ZeroAmount(); if (d.route != ROUTE_PERPS && d.route != ROUTE_SPOT) revert BadRoute(d.route); address proxy = _proxy(d.account); // The owner's per-epoch spend cap on USDC (registry), before anything // moves. Uncapped unless the owner set one. _charge(d.account, USDC_ETHEREUM, d.amount); uint256 before = IERC20Balance(USDC_ETHEREUM).balanceOf(d.account); bytes memory ok = _exec(d.account, USDC_ETHEREUM, 0, abi.encodeWithSelector(0x095ea7b3, proxy, d.amount)); if (ok.length != 0 && !abi.decode(ok, (bool))) revert ApproveFailed(); _exec( d.account, proxy, 0, abi.encodeCall(ILighterProxy.deposit, (d.account, ASSET_USDC, d.route, d.amount)) ); _requireNoResidual(d.account, USDC_ETHEREUM, proxy); uint256 sent = before - IERC20Balance(USDC_ETHEREUM).balanceOf(d.account); if (sent != d.amount) revert SentOtherThanAuthorised(d.amount, sent); emit LighterDeposited(d.account, d.taskId, d.route, d.amount); } /// Bind an enclave-made API key to V's Lighter account. V must already /// have one (a deposit creates it); the proxy refuses an unknown caller. function register(Register calldata r, bytes calldata signature) external { _consume(r.account, r.owner, r.taskId, r.deadline, registerDigest(r), signature); _requireOperation(r.account, OP_REGISTER); if (r.index < MIN_KEY_INDEX || r.index > MAX_KEY_INDEX) revert KeyIndexOutOfRange(r.index); if (r.pubkey.length != PUBKEY_LENGTH) revert BadPubkeyLength(r.pubkey.length); if (block.timestamp > r.receiptDeadline) revert ReceiptExpired(r.receiptDeadline); address proxy = _proxy(r.account); // The owner as V says it NOW, not as the intent says. address owner = ownerOf(r.account); address attester = ECDSA.tryRecoverCalldata(receiptDigest(owner, r.account, r.index, r.pubkey, r.receiptDeadline), r.receipt); if (attester != enclaveIdentity) revert ReceiptNotFromEnclave(attester, enclaveIdentity); bytes32 keyHash = keccak256(r.pubkey); if (keyUsed[r.account][keyHash]) revert KeyReused(r.account, keyHash); keyUsed[r.account][keyHash] = true; _exec(r.account, proxy, 0, abi.encodeCall(ILighterProxy.changePubKey, (NIL, r.index, r.pubkey))); emit LighterKeyRegistered(r.account, r.taskId, r.index, keyHash); } /// Make sure V's pending Lighter balance is paid to V, up to `amount`. /// Lighter would pay V whoever called (F11); this is the agent doing it as /// a plan step, measured. /// /// IDEMPOTENT AND TOLERANT (owner, 2026-10-28: "claim never reverts when /// nothing is pending. It pays out whatever is still pending, and /// otherwise does nothing."). Anyone may pay V's pending balance to V /// first, and Lighter's sweeper does (threat 3 in the header). So the /// claim takes `min(amount, pending)`; when that is zero it makes no call, /// emits LighterClaimed with 0 and returns 0. What it does pay is checked /// exactly against V's balance delta. /// /// IT FEEDS NO LATER STEP: no delivered amount is published, since what /// arrives here depends on who paid first. The return value is what this /// call paid V, for a caller to read. function claim(Claim calldata c, bytes calldata signature) external returns (uint256) { _consume(c.account, c.owner, c.taskId, c.deadline, claimDigest(c), signature); _requireOperation(c.account, OP_CLAIM); if (c.amount == 0) revert ZeroAmount(); if (c.amount > type(uint128).max) revert AmountTooLarge(c.amount); address token = claimableToken(c.assetIndex); address proxy = _proxy(c.account); uint256 pending = ILighterProxy(proxy).getPendingBalance(c.account, c.assetIndex); uint256 amount = pending < c.amount ? pending : c.amount; if (amount == 0) { // Already paid (by anyone): nothing to do, and not a failure. emit LighterClaimed(c.account, c.taskId, c.assetIndex, 0); return 0; } uint256 before = IERC20Balance(token).balanceOf(c.account); _exec( c.account, proxy, 0, abi.encodeCall(ILighterProxy.withdrawPendingBalance, (c.account, c.assetIndex, uint128(amount))) ); uint256 received = IERC20Balance(token).balanceOf(c.account) - before; if (received != amount) revert ClaimedOtherThanAsked(amount, received); emit LighterClaimed(c.account, c.taskId, c.assetIndex, received); return received; } /// The claim allow-list: a Lighter asset index to the token V receives. /// v1 is USDC only (§5a: ETH and the listed ERC-20s once F30 is settled). function claimableToken(uint16 assetIndex) public pure returns (address) { if (assetIndex == ASSET_USDC) return USDC_ETHEREUM; revert AssetNotClaimable(assetIndex); } /// The curated venue `lighter`, which must be the pinned proxy. function _proxy(address account) internal view returns (address proxy) { proxy = _venueOf(account, VENUE_LIGHTER); if (proxy != LIGHTER_PROXY) revert NotLighterProxy(proxy); } }