@qntx/wallet-engine 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/controller-DpNVHVsj.d.mts +2295 -0
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -362
- package/dist/gateway-contract.mjs +1531 -81
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -515
- package/dist/index.mjs +22314 -4901
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +94 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/errors-DpkJneDe.d.mts +0 -1696
- package/dist/registry-Deo5WQe1.d.mts +0 -25
- package/dist/registry-wYrcuFNc.mjs +0 -99
- package/dist/registry-wYrcuFNc.mjs.map +0 -1
- package/dist/webln-DzsI7jVb.mjs +0 -3629
- package/dist/webln-DzsI7jVb.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apps-hyperliquid.mjs","names":["cloidOf","isRecord","subL2Book","subTrades","subCandle","subClearinghouse","subSpotState","subOpenOrders","subUserFills"],"sources":["../src/apps/hyperliquid/errors.ts","../src/apps/hyperliquid/enable.ts","../src/apps/hyperliquid/account.ts","../src/apps/hyperliquid/numbers.ts","../src/apps/hyperliquid/actions.ts","../src/apps/hyperliquid/agents.ts","../src/apps/hyperliquid/clock.ts","../src/apps/hyperliquid/exchange.ts","../src/apps/hyperliquid/socket.ts","../src/apps/hyperliquid/live.ts","../src/apps/hyperliquid/markets.ts","../src/apps/hyperliquid/trade.ts","../src/apps/hyperliquid/transport.ts","../src/apps/hyperliquid/user-signed.ts","../src/apps/hyperliquid/provider.ts","../src/apps/hyperliquid/state.ts","../src/apps/hyperliquid/app.ts"],"sourcesContent":["/** Hyperliquid provider error categories — never carry request payloads or secrets. */\nexport type HyperliquidErrorCategory =\n | \"network\"\n /** The request may have reached the server; an /exchange post's outcome is unknown. */\n | \"timeout\"\n /** The server answered with a non-2xx status. */\n | \"unavailable\"\n /** The device clock disagrees with the server beyond the bound — signing would be refused. */\n | \"clock-skew\"\n /** A price, size or other caller input fails the tick/lot/canonical rules. */\n | \"invalid-input\"\n /** Hyperliquid rejected the signed action itself (a `status: \"err\"` exchange answer). */\n | \"rejected\"\n /** The vault is locked — the kernel refused to sign; nothing was posted. */\n | \"unlock-required\"\n /** The enabled agent expired, was rejected by Hyperliquid, or is gone — re-enable is required. */\n | \"reauthorization-required\"\n /** The kernel session is closed since the last lock — `reopen` must verify the user again. */\n | \"reopen-required\"\n /** The vault has a device factor — the app lock must be on for a value-moving session. */\n | \"app-lock-required\"\n /** The action exceeds the agent's approved limits — the kernel refused to sign it. */\n | \"limit-exceeded\"\n /** The account has no enabled, owner-verified agent on this network. */\n | \"not-enabled\"\n /** The account has no Hyperliquid presence yet — a deposit must land before enabling. */\n | \"deposit-required\"\n /** The user refused, or the approval request expired or was invalidated. */\n | \"approval-rejected\"\n /** An enablement flow is already running for the group — wait or cancel it. */\n | \"busy\";\n\nexport class HyperliquidError extends Error {\n readonly category: HyperliquidErrorCategory;\n\n constructor(category: HyperliquidErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"HyperliquidError\";\n this.category = category;\n }\n}\n\n/* Kernel `WalletError` codes a session sign/open surfaces, mapped to the app's typed answer.\n `exchange.ts` handles `not-found`/`invalid-input` itself — they need the agent's validUntil\n and a markRejected side-effect — and looks up only the uniform entries. */\nconst reauthorization = [\"reauthorization-required\", \"the agent is gone\"] as const;\nexport const SESSION_ERRORS: Readonly<Record<string, readonly [HyperliquidErrorCategory, string]>> =\n {\n \"app-lock-required\": [\"app-lock-required\", \"app lock off\"],\n \"approval-required\": [\"reopen-required\", \"re-approve\"],\n \"invalid-input\": reauthorization,\n \"limit-exceeded\": [\"limit-exceeded\", \"over the agent's limits\"],\n locked: [\"unlock-required\", \"vault locked\"],\n \"not-found\": reauthorization,\n };\n","/**\n * The Hyperliquid `AppProvider`: enable/renew/disable/reconcile as one resumable state machine.\n * Every step writes state through the flow the controller hands in, so a lock or a crash can pick\n * the flow back up; a bumped generation makes the flow stale and its writes are dropped.\n *\n * The flow never holds secrets: the agent private key stays in the kernel, the user-signed\n * approvals go through the request pipeline.\n */\nimport type { VerifyFactor, Wallet } from \"@qntx/wallet\";\nimport type {\n HyperliquidAgentLimits,\n HyperliquidNetwork,\n SessionInfo,\n} from \"@qntx/wallet/protocol\";\nimport { sessions } from \"@qntx/wallet/sessions\";\n\nimport type {\n AppAuthority,\n AppFlow,\n AppGroup,\n AppProvider,\n AppRequests,\n EngineLogger,\n SetTimer,\n} from \"../spi.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\nimport type { HyperliquidErrorCategory } from \"./errors.ts\";\nimport type { HyperliquidProvider, HyperliquidProviderInternals } from \"./provider.ts\";\nimport type { HyperliquidDetail, HyperliquidFlow, HyperliquidHints } from \"./state.ts\";\nimport type { HyperliquidUserSigned } from \"./user-signed.ts\";\n\n/** Hyperliquid's own bound is 180 days; 179 keeps a day of slack inside it (research §Agents). */\nconst AGENT_VALID_MS = 179 * 24 * 60 * 60 * 1000;\n/** A disabled-with-revoke throwaway only exists to deregister; 10 minutes is enough. */\nconst REVOKE_VALID_MS = 10 * 60 * 1000;\n/** ExtraAgents/maxBuilderFee converge within seconds; poll 1 s for up to 30 s. */\nconst VERIFY_POLL_MS = 1000;\nconst VERIFY_TIMEOUT_MS = 30_000;\n/** A kernel agent not yet listed on HL this long after creation is an orphan, not an in-flight one. */\nconst ORPHAN_AGE_MS = 10 * 60 * 1000;\n/** The host surfaces a renew prompt when less than this remains. */\nconst RENEWAL_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;\n\n/**\n * What the host passes to `enable`/`renew`: the limits the kernel shows in its approval prompt and\n * binds into the agent's record, and the factor that proves the approval. `enable` takes the same\n * shape — every call may reach the create step, including a resume that lost its agent.\n */\nexport type HyperliquidEnableInput = {\n readonly limits: HyperliquidAgentLimits;\n readonly verify: VerifyFactor;\n};\n\n/**\n * The limits of a revoke throwaway: it lives ten minutes and never trades — the smallest legal\n * budgets are the honest statement of that. The throwaway stays because Hyperliquid has no revoke\n * action without a new agent — nonces-and-api-wallets §API wallet pruning.\n */\nconst REVOKE_LIMITS: HyperliquidAgentLimits = {\n notional: \"0.00000001\",\n maxLeverage: 1,\n assets: [{ asset: 0, size: \"0.00000001\" }],\n};\n\n/* `sessions.create` treats `limits` as an opaque protocol value — the scheme's grammar runs\n inside the kernel, which answers `invalid-input` the same way, and the facade resolves the\n factor. Here only the facade shape needs checking so a malformed input fails with the app's\n own typed error before any flow writes or kernel call. */\nconst record = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isVerifyFactor = (value: unknown): value is VerifyFactor =>\n record(value) &&\n (value[\"kind\"] === \"hardware\" ||\n value[\"kind\"] === \"passkey\" ||\n (value[\"kind\"] === \"password\" && typeof value[\"password\"] === \"string\"));\n\nconst isLimits = (value: unknown): value is HyperliquidAgentLimits =>\n record(value) &&\n typeof value[\"notional\"] === \"string\" &&\n Number.isInteger(value[\"maxLeverage\"]) &&\n Array.isArray(value[\"assets\"]) &&\n value[\"assets\"].every(\n (entry) =>\n record(entry) && Number.isInteger(entry[\"asset\"]) && typeof entry[\"size\"] === \"string\",\n );\n\nconst requireEnableInput = (input: unknown): HyperliquidEnableInput => {\n if (!record(input) || !isLimits(input[\"limits\"]) || !isVerifyFactor(input[\"verify\"])) {\n throw new HyperliquidError(\"invalid-input\", \"bad input\");\n }\n return { limits: input[\"limits\"], verify: input[\"verify\"] };\n};\n\n/**\n * Canonical percent string for `maxFeeRate` — `feeRateTenthsBps` hundredths of a percent\n * thousandth: f=10 → \"0.01%\", f=1 → \"0.001%\", f=100 → \"0.1%\" (perps cap).\n */\nconst feeRate = (tenthsBps: number): string => {\n const whole = Math.floor(tenthsBps / 1000);\n const frac = String(tenthsBps % 1000)\n .padStart(3, \"0\")\n .replace(/0+$/, \"\");\n return `${whole}${frac === \"\" ? \"\" : `.${frac}`}%`;\n};\n\nexport type HyperliquidEnableOptions = {\n readonly wallet: Wallet;\n readonly provider: Omit<HyperliquidProvider, \"approveBuilder\"> & HyperliquidProviderInternals;\n readonly userSigned: HyperliquidUserSigned;\n readonly requests: Pick<AppRequests, \"reject\">;\n readonly network: HyperliquidNetwork;\n /** The agent name — `^[A-Za-z0-9._-]{1,16}$`, validated by `createApps`. */\n readonly agentName: string;\n /** Optional builder the trades attach once `maxBuilderFee` confirms `feeRateTenthsBps`. */\n readonly builder?: { readonly address: string; readonly feeRateTenthsBps: number };\n readonly now: () => number;\n readonly setTimer: SetTimer;\n readonly logger: EngineLogger;\n /** The persisted enablement hints every entry point wraps its flow with. */\n readonly hints: HyperliquidHints;\n};\n\nconst errorOf = (error: unknown): { category: string; message: string } =>\n error instanceof HyperliquidError\n ? { category: error.category, message: error.message }\n : {\n category: \"unavailable\",\n message: error instanceof Error ? error.message : String(error),\n };\n\n/* A function declaration, not a const arrow: only the former narrows never-returning calls for\n the control-flow analysis at the call sites below. */\nfunction fail(\n flow: AppFlow<HyperliquidDetail>,\n category: HyperliquidErrorCategory,\n message: string,\n): never {\n flow.write({ error: { category, message } });\n throw new HyperliquidError(category, message);\n}\n\n/** Run `body`; a stale flow stops writing but a thrown error still surfaces to the caller. */\nconst guard = async (\n flow: AppFlow<HyperliquidDetail>,\n body: () => Promise<void>,\n): Promise<void> => {\n try {\n await body();\n } catch (error) {\n if (!flow.stale() && flow.current().status === \"enabling\") {\n flow.write({ error: errorOf(error), requestId: undefined });\n }\n throw error;\n }\n};\n\nexport function createHyperliquidEnable(options: HyperliquidEnableOptions): {\n readonly provider: AppProvider<HyperliquidDetail>;\n /** Ask an enabled group for the builder fee approval it declined or never gave. */\n readonly approveBuilder: (group: AppGroup, flow: AppFlow<HyperliquidDetail>) => Promise<void>;\n} {\n const { provider, userSigned } = options;\n const wallet = (): ReturnType<typeof sessions> => sessions(options.wallet);\n const sleep = async (ms: number): Promise<void> =>\n new Promise((resolve) => {\n options.setTimer(ms, resolve);\n });\n\n /** The group's kernel agents on this network, owner-verified (the registry's own read). */\n const kernelAgents = async (group: AppGroup): Promise<ReadonlyArray<SessionInfo>> => {\n const listed = await wallet().list();\n const owner = await provider.agents.owner(group);\n return listed.filter(\n (agent) =>\n agent.scheme === \"hyperliquid-l1-agent\" &&\n agent.scope === options.network &&\n agent.walletId === group.walletId &&\n agent.groupIndex === group.groupIndex &&\n agent.owner.toLowerCase() === owner,\n );\n };\n\n const deleteAgent = async (address: string): Promise<void> => {\n try {\n await wallet().delete(address);\n } catch (error) {\n options.logger.warn(`hyperliquid agent ${address} delete failed`, error);\n }\n };\n\n /** Poll `extraAgents` until the agent address is listed or the verify window lapses. */\n const waitListed = async (owner: string, address: string): Promise<boolean> => {\n const deadline = options.now() + VERIFY_TIMEOUT_MS;\n while (options.now() <= deadline) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n const agents = await provider.account.extraAgents(owner);\n if (agents.some((a) => a.address.toLowerCase() === address)) {\n return true;\n }\n if (options.now() <= deadline) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n await sleep(VERIFY_POLL_MS);\n }\n }\n return false;\n };\n\n const waitBuilderFee = async (owner: string, builder: string, f: number): Promise<boolean> => {\n const deadline = options.now() + VERIFY_TIMEOUT_MS;\n while (options.now() <= deadline) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n const approved = await provider.account.maxBuilderFee(owner, builder);\n if (approved >= f) {\n return true;\n }\n if (options.now() <= deadline) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n await sleep(VERIFY_POLL_MS);\n }\n }\n return false;\n };\n\n /**\n * Preconditions shared by enable and renew: clock gate, then `userRole` — only a funded master\n * account (\"user\") may approve agents (research §Roles).\n */\n const preconditions = async (\n group: AppGroup,\n flow: AppFlow<HyperliquidDetail>,\n ): Promise<string> => {\n if (!flow.current().termsAcknowledged) {\n fail(flow, \"invalid-input\", \"terms not acknowledged\");\n }\n if (provider.clock.skew() === undefined) {\n await provider.markets.mids();\n }\n provider.clock.assertSkew();\n const owner = await provider.agents.owner(group);\n const { role } = await provider.account.role(owner);\n if (role === \"missing\") {\n fail(flow, \"deposit-required\", \"deposit to Hyperliquid\");\n }\n if (role !== \"user\") {\n fail(flow, \"invalid-input\", `a ${role} account cannot approve agents`);\n }\n return owner;\n };\n\n /** Approve the agent on Hyperliquid, then verify it is listed — resumable through `verify`. */\n const approveAgent = async (\n group: AppGroup,\n flow: AppFlow<HyperliquidDetail>,\n owner: string,\n agent: SessionInfo,\n ): Promise<void> => {\n if (flow.current().step !== \"verify\" && flow.current().step !== \"approve-builder\") {\n flow.write({ step: \"approve-agent\" });\n /* The kernel binds validity by signing `\"<name> valid_until <ms>\"` in agentName — the\n exchange reads the suffix, not a separate field (docs §Approve an API wallet). The\n `valid_until` always comes from the kernel record, never a fresh clock read. */\n const pending = await userSigned.approveAgent(group, {\n agentAddress: agent.address,\n agentName: `${options.agentName} valid_until ${agent.validUntil}`,\n });\n flow.write({ requestId: pending.requestId });\n try {\n const outcome = await pending.outcome;\n flow.write({ requestId: undefined });\n /* A lost approve POST means the action may have committed — go to verify instead of\n treating it as a failure; the agent is kept while it may be live. */\n if (outcome.kind === \"unknown\") {\n options.logger.warn(\"hyperliquid approveAgent outcome unknown — verifying by listing\");\n }\n } catch (error) {\n /* Refusal and `status:\"err\"` are definitive — the agent never commits: delete the\n orphan and leave the group disabled. Only `unknown` is uncertain. */\n flow.write({ requestId: undefined });\n if (\n error instanceof HyperliquidError &&\n (error.category === \"approval-rejected\" || error.category === \"rejected\")\n ) {\n await deleteAgent(agent.address);\n flow.write({\n status: \"disabled\",\n agent: undefined,\n step: undefined,\n error: errorOf(error),\n });\n }\n throw error;\n }\n }\n flow.write({ step: \"verify\" });\n if (!(await waitListed(owner, agent.address.toLowerCase()))) {\n flow.write({ status: \"disabled\", step: undefined });\n await deleteAgent(agent.address);\n fail(flow, \"unavailable\", \"the agent never appeared on Hyperliquid\");\n }\n };\n\n /** The builder step: request approveBuilderFee when HL has not confirmed `f` yet. */\n const approveBuilderStep = async (\n group: AppGroup,\n flow: HyperliquidFlow,\n owner: string,\n ): Promise<\"approved\" | \"declined\"> => {\n const { builder } = options;\n if (builder === undefined || flow.current().builder === \"approved\") {\n return \"approved\";\n }\n const fee = builder.feeRateTenthsBps;\n if ((await provider.account.maxBuilderFee(owner, builder.address.toLowerCase())) >= fee) {\n return \"approved\";\n }\n /* A decline persists until an approval replaces it: renew and re-enable finish without a\n builder instead of re-asking; only the explicit approveBuilder flow asks again. */\n if (flow.wasBuilderDeclined() || flow.current().builder === \"declined\") {\n return \"declined\";\n }\n flow.write({ step: \"approve-builder\" });\n const pending = await userSigned.approveBuilderFee(group, {\n builder: builder.address,\n maxFeeRate: feeRate(fee),\n });\n flow.write({ requestId: pending.requestId });\n try {\n await pending.outcome;\n } catch (error) {\n flow.write({ requestId: undefined });\n if (error instanceof HyperliquidError && error.category === \"approval-rejected\") {\n /* A user refusal is not a failure: enable without the builder and record the\n decline so reconcile never re-asks. */\n return \"declined\";\n }\n throw error;\n }\n flow.write({ requestId: undefined });\n if (!(await waitBuilderFee(owner, builder.address.toLowerCase(), fee))) {\n /* The agent is live on Hyperliquid — keep it; the next enable resumes at this step. */\n fail(flow, \"unavailable\", \"the builder fee approval never confirmed\");\n }\n return \"approved\";\n };\n\n /**\n * The enable state machine — every step writes; a failure leaves a resumable state. `input`\n * supplies the kernel ceremony: the limits the approval prompt binds into the record and the\n * factor that proves it. A resume past `create-agent` never reaches them again.\n */\n const enableFlow = async (\n group: AppGroup,\n flow: HyperliquidFlow,\n input: HyperliquidEnableInput,\n ): Promise<void> => {\n const now = options.now();\n if (flow.current().status !== \"enabling\") {\n flow.write({ status: \"enabling\", step: \"create-agent\", error: undefined });\n }\n const owner = await preconditions(group, flow);\n let agents = await kernelAgents(group);\n /* Resume: the step already has an agent; create only when none exists or the recorded one is\n gone from the kernel. */\n let agent =\n flow.current().agent === undefined\n ? undefined\n : agents.find(\n (a) => a.address.toLowerCase() === flow.current().agent?.address.toLowerCase(),\n );\n if (agent === undefined) {\n const address = await wallet().create({\n scheme: \"hyperliquid-l1-agent\",\n owner: group,\n scope: options.network,\n name: options.agentName,\n validUntil: now + AGENT_VALID_MS,\n limits: input.limits,\n verify: input.verify,\n });\n agents = await kernelAgents(group);\n agent = agents.find((a) => a.address.toLowerCase() === address.toLowerCase());\n }\n if (agent === undefined) {\n return fail(flow, \"unavailable\", \"the kernel created no agent\");\n }\n flow.write({\n agent: {\n address: agent.address,\n name: agent.name,\n validUntil: agent.validUntil,\n network: agent.scope,\n },\n });\n await approveAgent(group, flow, owner, agent);\n const builderState = await approveBuilderStep(group, flow, owner);\n /* `require` filters the verified list — the agent created above is only kernel-known until a\n refresh lands it there; without this, trading right after enable threw not-enabled. */\n await provider.agents.refresh();\n provider.agents.markEnabled(agent.address);\n flow.write({\n status: \"enabled\",\n step: undefined,\n requestId: undefined,\n builder: builderState,\n renewalDue: agent.validUntil - options.now() < RENEWAL_WINDOW_MS,\n error: undefined,\n });\n };\n\n const enableProvider: AppProvider<HyperliquidDetail> = {\n error: (category, message) => new HyperliquidError(category, message),\n groups: async () => {\n const listed = await wallet().list();\n const seen = new Map<string, AppGroup>();\n for (const agent of listed) {\n if (agent.scheme === \"hyperliquid-l1-agent\" && agent.scope === options.network) {\n seen.set(`${agent.walletId}/${agent.groupIndex}`, {\n walletId: agent.walletId,\n groupIndex: agent.groupIndex,\n });\n }\n }\n return [...seen.values()];\n },\n enable: async (group, raw, input) => {\n const parsed = requireEnableInput(input);\n const flow = await options.hints.track(group, raw);\n await guard(flow, async () => {\n await enableFlow(group, flow, parsed);\n });\n },\n renew: async (group, raw, input) => {\n const parsed = requireEnableInput(input);\n const flow = await options.hints.track(group, raw);\n const before = await kernelAgents(group);\n try {\n /* Same name ⇒ Hyperliquid deregisters the old agent when the new one is approved. The\n old kernel agent stays usable until the new one is enabled. */\n flow.write({\n status: \"enabling\",\n step: \"create-agent\",\n agent: undefined,\n error: undefined,\n });\n await enableFlow(group, flow, parsed);\n for (const old of before) {\n if (old.address.toLowerCase() !== flow.current().agent?.address.toLowerCase()) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- deletes are sequential cleanup.\n await deleteAgent(old.address);\n }\n }\n } catch (error) {\n /* The failed flow deleted its unenabled agent (approveAgent); restore the old agent's\n enabled state — it kept trading through the whole attempt. */\n const remaining = await kernelAgents(group);\n const old = remaining.find(\n (a) =>\n a.address.toLowerCase() !== flow.current().agent?.address.toLowerCase() &&\n a.validUntil > options.now(),\n );\n flow.write(\n old === undefined\n ? {\n status: \"needs-reauthorization\",\n step: undefined,\n requestId: undefined,\n error: errorOf(error),\n }\n : {\n status: \"enabled\",\n agent: {\n address: old.address,\n name: old.name,\n validUntil: old.validUntil,\n network: old.scope,\n },\n step: undefined,\n requestId: undefined,\n renewalDue: old.validUntil - options.now() < RENEWAL_WINDOW_MS,\n error: errorOf(error),\n },\n );\n throw error;\n }\n },\n disable: async (group, { revoke, verify }, raw) => {\n const flow = await options.hints.track(group, raw);\n await guard(flow, async () => {\n await provider.agents.refresh();\n const agents = await kernelAgents(group);\n /* Trading stops first: every kernel agent of the group on this network is deleted\n before the optional revoke runs. */\n for (const agent of agents) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- deletes are sequential cleanup.\n await deleteAgent(agent.address);\n }\n flow.write({ status: \"disabled\", agent: undefined, builder: undefined, error: undefined });\n if (revoke) {\n flow.write({ step: \"revoke\" });\n /* No revoke action exists: a same-name approval deregisters the old agent. A\n throwaway valid for ten minutes does it, and is deleted in every outcome. Creating it\n is the value-moving scheme's approval ceremony — degenerate limits, user-verified. */\n if (!isVerifyFactor(verify)) {\n fail(flow, \"invalid-input\", \"needs a verify factor\");\n }\n let throwaway: string | undefined;\n try {\n const address = await wallet().create({\n scheme: \"hyperliquid-l1-agent\",\n owner: group,\n scope: options.network,\n name: options.agentName,\n validUntil: options.now() + REVOKE_VALID_MS,\n limits: REVOKE_LIMITS,\n verify,\n });\n throwaway = address;\n /* The kernel binding needs the record's own validUntil — a second clock read here\n could drift a millisecond and fail the check. */\n const records = await kernelAgents(group);\n const record = records.find((a) => a.address.toLowerCase() === address.toLowerCase());\n if (record === undefined) {\n throw new HyperliquidError(\"unavailable\", \"the kernel created no agent\");\n }\n const pending = await userSigned.approveAgent(group, {\n agentAddress: address,\n agentName: `${options.agentName} valid_until ${record.validUntil}`,\n });\n flow.write({ requestId: pending.requestId });\n await pending.outcome;\n flow.write({ requestId: undefined, step: undefined });\n } catch (error) {\n flow.write({\n step: \"revoke\",\n requestId: undefined,\n error: errorOf(error),\n });\n throw error;\n } finally {\n if (throwaway !== undefined) {\n await deleteAgent(throwaway);\n }\n }\n }\n });\n },\n cancel: async (group, raw) => {\n /* The checks and the request rejection write nothing — they run on `raw` first so the\n pending request ends in the same tick the host called `cancel`. */\n const state = raw.current();\n if (state.status !== \"enabling\") {\n throw new HyperliquidError(\"invalid-input\", \"no enablement flow is running\");\n }\n if (state.agent !== undefined && provider.agents.enabled(state.agent.address)) {\n throw new HyperliquidError(\"invalid-input\", \"the recorded agent is already enabled\");\n }\n if (state.requestId !== undefined) {\n /* A request the flow opened but the host never approved just ends. */\n options.requests.reject(state.requestId);\n }\n const flow = await options.hints.track(group, raw);\n const agents = await kernelAgents(group);\n for (const agent of agents) {\n /* Only the flow's own unenabled agent is an orphan — during a renew the old enabled\n agent names another address and is never touched. */\n if (\n agent.address.toLowerCase() === state.agent?.address.toLowerCase() &&\n !provider.agents.enabled(agent.address)\n ) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one delete.\n await deleteAgent(agent.address);\n }\n }\n /* Restore what remains: a renew's old agent is still live and enabled — a fresh enable\n leaves nothing and the group goes disabled. */\n const [restored] = agents\n .filter(\n (a) =>\n a.address.toLowerCase() !== state.agent?.address.toLowerCase() &&\n a.validUntil > options.now(),\n )\n .sort((a, b) => b.validUntil - a.validUntil);\n if (restored === undefined) {\n flow.write({\n status: \"disabled\",\n step: undefined,\n requestId: undefined,\n agent: undefined,\n error: undefined,\n });\n } else {\n provider.agents.markEnabled(restored.address);\n flow.write({\n status: \"enabled\",\n agent: {\n address: restored.address,\n name: restored.name,\n validUntil: restored.validUntil,\n network: restored.scope,\n },\n step: undefined,\n requestId: undefined,\n renewalDue: restored.validUntil - options.now() < RENEWAL_WINDOW_MS,\n error: undefined,\n });\n }\n },\n reconcile: async (group, raw) => {\n const flow = await options.hints.track(group, raw);\n const now = options.now();\n const owner = await provider.agents.owner(group);\n const agents = await kernelAgents(group);\n const listed = await provider.account.extraAgents(owner);\n const onHl = new Set(listed.map((a) => a.address.toLowerCase()));\n const live = agents\n .filter((a) => a.validUntil > now)\n .sort((a, b) => b.validUntil - a.validUntil);\n const [newest] = live;\n if (newest === undefined) {\n /* Every kernel agent expired or none exist: a group whose persisted record names an\n enabled agent needs reauthorization; a group that never enabled is disabled. */\n for (const agent of agents) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- orphan cleanup is sequential.\n await deleteAgent(agent.address);\n }\n flow.write({\n status: flow.wasEnabledAgent() === undefined ? \"disabled\" : \"needs-reauthorization\",\n agent: undefined,\n builder: undefined,\n });\n return;\n }\n if (!onHl.has(newest.address.toLowerCase())) {\n /* Kernel agent Hyperliquid does not know: fresh → resume approve-agent; old → orphan. */\n if (now - newest.createdAt < ORPHAN_AGE_MS) {\n flow.write({\n status: \"enabling\",\n step: \"approve-agent\",\n agent: {\n address: newest.address,\n name: newest.name,\n validUntil: newest.validUntil,\n network: newest.scope,\n },\n });\n } else {\n await deleteAgent(newest.address);\n flow.write({\n status: flow.wasEnabledAgent() === undefined ? \"disabled\" : \"needs-reauthorization\",\n agent: undefined,\n builder: undefined,\n });\n }\n return;\n }\n /* The newest live agent is listed: it is the enabled one; every other agent is an\n orphan and is deleted. */\n for (const agent of agents) {\n if (agent.address.toLowerCase() !== newest.address.toLowerCase()) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- orphan cleanup is sequential.\n await deleteAgent(agent.address);\n }\n }\n if (provider.agents.rejected(newest.address)) {\n /* Latched by the exchange path: Hyperliquid refuses this agent — renew, never reuse. */\n flow.write({ status: \"needs-reauthorization\", step: undefined, requestId: undefined });\n return;\n }\n const { builder } = options;\n const builderConfirmed =\n builder !== undefined &&\n (await provider.account.maxBuilderFee(owner, builder.address.toLowerCase())) >=\n builder.feeRateTenthsBps;\n if (builder !== undefined && !builderConfirmed) {\n if (flow.wasBuilderDeclined()) {\n /* The user already refused the approval — enabled without it, no new request. */\n await provider.agents.refresh();\n provider.agents.markEnabled(newest.address);\n flow.write({\n status: \"enabled\",\n step: undefined,\n agent: {\n address: newest.address,\n name: newest.name,\n validUntil: newest.validUntil,\n network: newest.scope,\n },\n builder: \"declined\",\n renewalDue: newest.validUntil - now < RENEWAL_WINDOW_MS,\n error: undefined,\n });\n return;\n }\n flow.write({\n status: \"enabling\",\n step: \"approve-builder\",\n agent: {\n address: newest.address,\n name: newest.name,\n validUntil: newest.validUntil,\n network: newest.scope,\n },\n });\n return;\n }\n /* Same rule as the flow: the registry's verified list must see the agent before\n markEnabled, or `require` reports not-enabled for an enabled group. */\n await provider.agents.refresh();\n provider.agents.markEnabled(newest.address);\n flow.write({\n status: \"enabled\",\n step: undefined,\n agent: {\n address: newest.address,\n name: newest.name,\n validUntil: newest.validUntil,\n network: newest.scope,\n },\n ...(builder === undefined || builderConfirmed ? { builder: \"approved\" as const } : {}),\n renewalDue: newest.validUntil - now < RENEWAL_WINDOW_MS,\n error: undefined,\n });\n },\n authorities: async (group): Promise<ReadonlyArray<AppAuthority>> => {\n const { builder } = options;\n if (builder === undefined) {\n return [];\n }\n const owner = await provider.agents.owner(group);\n const approved = await provider.account.maxBuilderFee(owner, builder.address.toLowerCase());\n if (approved <= 0) {\n return [];\n }\n /* `disable({ revoke: true })` only clears the agent — the builder-fee approval stays on\n HyperCore until an `approveBuilderFee` to zero, which no engine surface reaches. */\n return [\n {\n kind: \"builder-fee\",\n network: options.network,\n account: owner,\n holder: builder.address,\n limit: approved.toString(),\n revoke: \"none\",\n },\n ];\n },\n };\n return {\n provider: enableProvider,\n approveBuilder: async (group, raw) => {\n const flow = await options.hints.track(group, raw);\n /* The group must be trading before a late consent is even asked — the check the\n controller used to run before the provider's own `no builder` guard. */\n if (flow.current().status !== \"enabled\") {\n throw new HyperliquidError(\"invalid-input\", \"the group is not enabled\");\n }\n const { builder } = options;\n if (builder === undefined) {\n throw new HyperliquidError(\"invalid-input\", \"no builder is configured\");\n }\n const fee = builder.feeRateTenthsBps;\n const owner = await provider.agents.owner(group);\n if ((await provider.account.maxBuilderFee(owner, builder.address.toLowerCase())) >= fee) {\n flow.write({ builder: \"approved\" });\n return;\n }\n const pending = await userSigned.approveBuilderFee(group, {\n builder: builder.address,\n maxFeeRate: feeRate(fee),\n });\n flow.write({ requestId: pending.requestId });\n try {\n await pending.outcome;\n } catch (error) {\n flow.write({ requestId: undefined });\n if (error instanceof HyperliquidError && error.category === \"approval-rejected\") {\n flow.write({ builder: \"declined\" });\n return;\n }\n throw error;\n }\n flow.write({ requestId: undefined });\n if (!(await waitBuilderFee(owner, builder.address.toLowerCase(), fee))) {\n fail(flow, \"unavailable\", \"the builder fee approval never confirmed\");\n }\n flow.write({ builder: \"approved\" });\n },\n };\n}\n","import {\n clearinghouseState,\n extraAgents,\n frontendOpenOrders,\n maxBuilderFee,\n orderStatus,\n portfolio,\n spotClearinghouseState,\n userFees,\n userFills,\n userFunding,\n userRateLimit,\n userRole,\n} from \"@nktkas/hyperliquid/api/info\";\nimport type {\n ClearinghouseStateParameters,\n ClearinghouseStateResponse,\n ExtraAgentsResponse,\n FrontendOpenOrdersParameters,\n FrontendOpenOrdersResponse,\n InfoConfig,\n MaxBuilderFeeResponse,\n OrderStatusParameters,\n OrderStatusResponse,\n PortfolioResponse,\n SpotClearinghouseStateParameters,\n SpotClearinghouseStateResponse,\n UserFeesResponse,\n UserFillsParameters,\n UserFillsResponse,\n UserFundingParameters,\n UserFundingResponse,\n UserRateLimitResponse,\n UserRoleResponse,\n} from \"@nktkas/hyperliquid/api/info\";\n\n/** Every account read addresses the master account — agents query it lowercased. */\nconst master = (user: string): `0x${string}` => `0x${user.toLowerCase().replace(/^0x/, \"\")}`;\n\n/**\n * Account reads over the injected transport — thin pass-throughs to the SDK request functions with\n * the user always spelled as the lowercase master address.\n */\nexport type HyperliquidAccount = {\n /** Perpetual margin summary and open positions. */\n readonly state: (params: ClearinghouseStateParameters) => Promise<ClearinghouseStateResponse>;\n /** Spot balances. */\n readonly spot: (\n params: SpotClearinghouseStateParameters,\n ) => Promise<SpotClearinghouseStateResponse>;\n /** Open orders with frontend display fields (triggers, TP/SL info). */\n readonly openOrders: (\n params: FrontendOpenOrdersParameters,\n ) => Promise<FrontendOpenOrdersResponse>;\n /** The account's fills, optionally aggregated by time. */\n readonly fills: (params: UserFillsParameters) => Promise<UserFillsResponse>;\n /** Funding payments and non-funding ledger updates over `[startTime, endTime)`. */\n readonly funding: (params: UserFundingParameters) => Promise<UserFundingResponse>;\n /** The account's portfolio breakdown over the standard windows. */\n readonly portfolio: (user: string) => Promise<PortfolioResponse>;\n /** The account's REST rate-limit standing. */\n readonly rateLimit: (user: string) => Promise<UserRateLimitResponse>;\n /** Fee schedule and discounts for the account. */\n readonly fees: (user: string) => Promise<UserFeesResponse>;\n /** Order status by oid or cloid — `{status:\"order\"}` or `{status:\"unknownOid\"}`. */\n readonly orderStatus: (params: OrderStatusParameters) => Promise<OrderStatusResponse>;\n /** Named API wallets (agents) the account has approved. */\n readonly extraAgents: (user: string) => Promise<ExtraAgentsResponse>;\n /** The builder fee the account approved for `builder`, in tenths of a bp. */\n readonly maxBuilderFee: (user: string, builder: string) => Promise<MaxBuilderFeeResponse>;\n /** `missing`/`user`/`agent`/`vault`/`subAccount` — gates enabling an agent. */\n readonly role: (user: string) => Promise<UserRoleResponse>;\n};\n\nexport type {\n ClearinghouseStateResponse,\n ExtraAgentsResponse,\n FrontendOpenOrdersResponse,\n MaxBuilderFeeResponse,\n OrderStatusResponse,\n PortfolioResponse,\n SpotClearinghouseStateResponse,\n UserFeesResponse,\n UserFillsResponse,\n UserFundingResponse,\n UserRateLimitResponse,\n UserRoleResponse,\n} from \"@nktkas/hyperliquid/api/info\";\n\nexport function createHyperliquidAccount(config: InfoConfig): HyperliquidAccount {\n return {\n state: async (params) => clearinghouseState(config, { ...params, user: master(params.user) }),\n spot: async (params) =>\n spotClearinghouseState(config, { ...params, user: master(params.user) }),\n openOrders: async (params) =>\n frontendOpenOrders(config, { ...params, user: master(params.user) }),\n fills: async (params) => userFills(config, { ...params, user: master(params.user) }),\n funding: async (params) => userFunding(config, { ...params, user: master(params.user) }),\n portfolio: async (user) => portfolio(config, { user: master(user) }),\n rateLimit: async (user) => userRateLimit(config, { user: master(user) }),\n fees: async (user) => userFees(config, { user: master(user) }),\n orderStatus: async (params) => orderStatus(config, { ...params, user: master(params.user) }),\n extraAgents: async (user) => extraAgents(config, { user: master(user) }),\n maxBuilderFee: async (user, builder) =>\n maxBuilderFee(config, { user: master(user), builder: master(builder) }),\n role: async (user) => userRole(config, { user: master(user) }),\n };\n}\n","import { formatDecimal, parseDecimal } from \"../spi.ts\";\nimport type { Decimal } from \"../spi.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\n\n/**\n * Exact decimal arithmetic for Hyperliquid tick and lot rules — bigint units only, no float ever\n * touches a price or size. Prices admit at most 5 significant figures unless they are integers, and\n * at most 6 (perp) or 8 (spot) − `szDecimals` fractional decimals; sizes admit at most `szDecimals`\n * decimals. Rounded output is always the kernel's canonical decimal form.\n */\nexport type HyperliquidMarket = \"perp\" | \"spot\";\nexport type OrderSide = \"buy\" | \"sell\";\nexport type RoundDirection = \"down\" | \"up\";\n\nconst DECIMAL = /^[0-9]+(?:\\.[0-9]+)?$/;\nconst MAX_SIG_FIGS = 4; // grid exponent = leading position − (5 − 1)\n\nconst pow10 = (exponent: number): bigint => 10n ** BigInt(exponent);\n\nconst parsePositive = (text: string, field: string): Decimal => {\n if (!DECIMAL.test(text)) {\n throw new HyperliquidError(\"invalid-input\", `${field} is not a decimal: ${text}`);\n }\n const value = parseDecimal(text);\n if (value.units <= 0n) {\n throw new HyperliquidError(\"invalid-input\", `${field} must be positive: ${text}`);\n }\n return value;\n};\n\nconst isInteger = (value: Decimal): boolean =>\n value.scale <= 0 || value.units % pow10(value.scale) === 0n;\n\n/** `formatDecimal` needs a non-negative scale — fold a negative one into the units. */\nconst canonical = (value: Decimal): Decimal =>\n value.scale < 0 ? { units: value.units * pow10(-value.scale), scale: 0 } : value;\n\nconst format = (value: Decimal): string => formatDecimal(canonical(value));\n\n/** The exponent of the value's most significant decimal digit. */\nconst leadingPosition = (value: Decimal): number => String(value.units).length - value.scale - 1;\n\nconst lessThan = (a: Decimal, b: Decimal): boolean => {\n // Cross-multiply to a common denominator, shifted so neither exponent goes negative.\n const shift = Math.min(a.scale, b.scale, 0);\n return a.units * pow10(b.scale - shift) < b.units * pow10(a.scale - shift);\n};\n\n/** Round to `scale` fractional decimals — a negative `scale` rounds to powers of ten. */\nconst roundToScale = (value: Decimal, scale: number, direction: RoundDirection): Decimal => {\n const drop = value.scale - scale;\n if (drop <= 0) {\n return value;\n }\n const quantum = pow10(drop);\n const units =\n direction === \"down\" ? value.units / quantum : (value.units + quantum - 1n) / quantum;\n return { units, scale };\n};\n\nconst maxDecimals = (market: HyperliquidMarket, szDecimals: number): number =>\n Math.max((market === \"perp\" ? 6 : 8) - szDecimals, 0);\n\nconst checkSzDecimals = (szDecimals: number): void => {\n if (!Number.isInteger(szDecimals) || szDecimals < 0) {\n throw new HyperliquidError(\"invalid-input\", `szDecimals ${szDecimals} is not an integer ≥ 0`);\n }\n};\n\n/**\n * \"down\" mirrors the SDK's `formatPrice` — decimal places first, then significant figures — so\n * property tests can use it as the oracle. \"up\" returns the smallest valid price ≥ the input: the\n * minimum of the 5-significant-figure ceiling and the always-valid integer ceiling.\n */\nconst round = (\n value: Decimal,\n szDecimals: number,\n market: HyperliquidMarket,\n direction: RoundDirection,\n): Decimal => {\n const limit = maxDecimals(market, szDecimals);\n if (direction === \"down\") {\n const decimals = roundToScale(value, limit, \"down\");\n if (decimals.units === 0n) {\n throw new HyperliquidError(\"invalid-input\", \"price rounds to 0\");\n }\n if (isInteger(decimals)) {\n return decimals;\n }\n return roundToScale(decimals, MAX_SIG_FIGS - leadingPosition(decimals), \"down\");\n }\n const integer = roundToScale(value, 0, \"up\");\n const grid = Math.min(MAX_SIG_FIGS - leadingPosition(value), limit);\n const significant = roundToScale(value, grid, \"up\");\n return lessThan(integer, significant) ? integer : significant;\n};\n\n/** `price` rounded to the tick rules for `market` in `direction`; 0 is an error. */\nexport const roundPrice = (\n price: string,\n szDecimals: number,\n market: HyperliquidMarket,\n direction: RoundDirection,\n): string => {\n checkSzDecimals(szDecimals);\n return format(round(parsePositive(price, \"price\"), szDecimals, market, direction));\n};\n\n/** `size` rounded down to `szDecimals` decimals — the lot size; 0 is an error. */\nexport const roundSize = (size: string, szDecimals: number): string => {\n checkSzDecimals(szDecimals);\n const value = parsePositive(size, \"size\");\n const result = roundToScale(value, szDecimals, \"down\");\n if (result.units === 0n) {\n throw new HyperliquidError(\"invalid-input\", \"size rounds to 0\");\n }\n return format(result);\n};\n\n/** A limit price never worse than the user's: buys round down, sells round up. */\nexport const limitPrice = (\n price: string,\n side: OrderSide,\n szDecimals: number,\n market: HyperliquidMarket,\n): string => roundPrice(price, szDecimals, market, side === \"buy\" ? \"down\" : \"up\");\n\n/**\n * The slippage-bounded price for a marketable (IOC) order: `reference` moved `slippageBps` basis\n * points against the order — buy: ×(1 + bps/10⁴), sell: ×(1 − bps/10⁴) — then rounded the way\n * {@link limitPrice} rounds. `slippageBps` is an integer: 1..10000 for a buy, 1..9999 for a sell (0\n * or 100% is no market order).\n */\nexport const slippagePrice = (\n reference: string,\n side: OrderSide,\n slippageBps: number,\n szDecimals: number,\n market: HyperliquidMarket,\n): string => {\n checkSzDecimals(szDecimals);\n const bound = side === \"buy\" ? 10_000 : 9999;\n if (!Number.isInteger(slippageBps) || slippageBps < 1 || slippageBps > bound) {\n throw new HyperliquidError(\n \"invalid-input\",\n `slippageBps ${slippageBps} out of range for a ${side}`,\n );\n }\n const value = parsePositive(reference, \"reference\");\n const factor = BigInt(side === \"buy\" ? 10_000 + slippageBps : 10_000 - slippageBps);\n const scaled: Decimal = { units: value.units * factor, scale: value.scale + 4 };\n return format(round(scaled, szDecimals, market, side === \"buy\" ? \"down\" : \"up\"));\n};\n\n/** `price` × `size` exactly, as a canonical decimal string. */\nexport const notional = (price: string, size: string): string => {\n const px = parsePositive(price, \"price\");\n const sz = parsePositive(size, \"size\");\n return format({ units: px.units * sz.units, scale: px.scale + sz.scale });\n};\n\n/** Hyperliquid's minimum order value: notional ≥ 10 quote units (USDC perps, quote token spot). */\nexport const meetsMinimum = (price: string, size: string): boolean => {\n const px = parsePositive(price, \"price\");\n const sz = parsePositive(size, \"size\");\n return px.units * sz.units >= pow10(px.scale + sz.scale + 1);\n};\n","import type { HyperliquidL1Action, HyperliquidL1Order } from \"@qntx/wallet/protocol\";\n\nimport { parseDecimal } from \"../spi.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\nimport type {\n HyperliquidMarkets,\n MetaAndAssetCtxsResponse,\n SpotMetaAndAssetCtxsResponse,\n} from \"./markets.ts\";\nimport { limitPrice, meetsMinimum, roundSize, slippagePrice } from \"./numbers.ts\";\nimport type { HyperliquidMarket, OrderSide } from \"./numbers.ts\";\n\n/** An asset the main DEX can trade — the wire `a` plus the market's rounding context. */\nexport type HyperliquidAsset = {\n readonly asset: number;\n readonly szDecimals: number;\n readonly market: HyperliquidMarket;\n readonly maxLeverage?: number;\n};\n\n/** TP/SL parameters shared by attached children and standalone trigger orders. */\nexport type HyperliquidTriggerParams = {\n readonly triggerPx: string;\n /** `true` (default): a market trigger — the fill cap is the slippage price. */\n readonly market?: boolean;\n /** The cap `p` on the wire. Optional for market triggers; required for limit triggers. */\n readonly price?: string;\n /** Cap distance for market triggers without an explicit `price` — required then. */\n readonly slippageBps?: number;\n};\n\n/** What kind of order `place` builds. `market` is an IOC limit at a slippage cap. */\nexport type HyperliquidOrderKind =\n | {\n readonly kind: \"limit\";\n readonly price: string;\n readonly tif?: \"Gtc\" | \"Ioc\" | \"Alo\";\n }\n | { readonly kind: \"market\"; readonly slippageBps: number }\n | ({ readonly kind: \"trigger\"; readonly tpsl: \"tp\" | \"sl\" } & HyperliquidTriggerParams);\n\n/** One order to place — the entry; `takeProfit`/`stopLoss` attach reduce-only children. */\nexport type HyperliquidOrderParams = {\n readonly coin: string;\n readonly side: OrderSide;\n readonly size: string;\n readonly reduceOnly?: boolean;\n readonly order: HyperliquidOrderKind;\n readonly takeProfit?: HyperliquidTriggerParams;\n readonly stopLoss?: HyperliquidTriggerParams;\n /** Position TP/SL: the trigger sizes to the whole position (`positionTpsl` grouping). */\n readonly positionTpsl?: boolean;\n};\n\n/** `modify`/`batchModify` change a resting order — no attached children, no grouping. */\nexport type HyperliquidModifyParams = {\n readonly coin: string;\n readonly side: OrderSide;\n readonly size: string;\n readonly reduceOnly?: boolean;\n readonly order: HyperliquidOrderKind;\n};\n\n/** `place` reports the built entry so the caller can show the cap it will post. */\nexport type HyperliquidPlacedAction = {\n readonly action: HyperliquidL1Action;\n /** The entry order's wire price — for a market order, the slippage cap. */\n readonly price: string;\n};\n\n/** Kernel caps action arrays at 64 entries (packages/wallet/src/protocol/apps.ts `arr(.., 64)`). */\nconst BATCH_CAP = 64;\n\nexport const deepFreeze = <T>(value: T): T => {\n if (typeof value === \"object\" && value !== null && !Object.isFrozen(value)) {\n for (const item of Object.values(value)) {\n deepFreeze(item);\n }\n Object.freeze(value);\n }\n return value;\n};\n\nconst cloidOf = (random: (length: number) => Uint8Array): string =>\n `0x${Array.from(random(16), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n\nconst isCloid = (value: string): boolean => /^0x[0-9a-f]{32}$/.test(value);\n\nconst flip = (side: OrderSide): OrderSide => (side === \"buy\" ? \"sell\" : \"buy\");\n\n/** One wire order: the key order is the kernel schema's (`a,b,p,s,r,t,c`) — hashing order. */\nconst wireOrder = (order: {\n readonly asset: number;\n readonly side: OrderSide;\n readonly price: string;\n readonly size: string;\n readonly reduceOnly: boolean;\n readonly type: HyperliquidL1Order[\"t\"];\n readonly cloid?: string;\n}): HyperliquidL1Order => ({\n a: order.asset,\n b: order.side === \"buy\",\n p: order.price,\n s: order.size,\n r: order.reduceOnly,\n t: order.type,\n ...(order.cloid === undefined ? {} : { c: order.cloid }),\n});\n\nexport type HyperliquidActions = {\n /** Coin → wire asset; refreshes meta once on a miss; `{dex}:{coin}` names are out of scope. */\n readonly resolve: (coin: string) => Promise<HyperliquidAsset>;\n readonly place: (params: HyperliquidOrderParams) => Promise<HyperliquidPlacedAction>;\n readonly modify: (\n params: { readonly oid: number | string } & HyperliquidModifyParams,\n ) => Promise<HyperliquidL1Action>;\n readonly batchModify: (\n modifies: ReadonlyArray<{ readonly oid: number | string } & HyperliquidModifyParams>,\n ) => Promise<HyperliquidL1Action>;\n readonly cancel: (\n cancels: ReadonlyArray<{ readonly coin: string; readonly oid: number }>,\n ) => Promise<HyperliquidL1Action>;\n readonly cancelByCloid: (\n cancels: ReadonlyArray<{ readonly coin: string; readonly cloid: string }>,\n ) => Promise<HyperliquidL1Action>;\n /** Pure `cancel` chunks of ≤ 64 entries — `cancelAll` posts one per chunk. */\n readonly cancelBatches: (\n entries: ReadonlyArray<{ readonly a: number; readonly o: number }>,\n ) => ReadonlyArray<HyperliquidL1Action>;\n /* There is no `twap` order builder: a TWAP's slices carry no price the kernel could meter\n against the session's approved budget, so the scheme's validator refuses the action — the\n engine offers only the cancel. */\n readonly twapCancel: (params: {\n readonly coin: string;\n readonly twapId: number;\n }) => Promise<HyperliquidL1Action>;\n readonly setLeverage: (params: {\n readonly coin: string;\n readonly leverage: number;\n readonly marginMode: \"cross\" | \"isolated\";\n }) => Promise<HyperliquidL1Action>;\n readonly adjustMargin: (params: {\n readonly coin: string;\n readonly amount: string;\n }) => Promise<HyperliquidL1Action>;\n};\n\n/** Orders below the venue's minimum notional are rejected outright — check before signing. */\nconst checkMinimum = (p: string, s: string): void => {\n if (!meetsMinimum(p, s)) {\n throw new HyperliquidError(\"invalid-input\", \"order value is below the 10-quote minimum\");\n }\n};\n\n/** The wire `t`/`p` for a trigger spec — shared by standalone triggers and TP/SL children. */\nconst triggerOrder = (\n spec: { readonly tpsl: \"tp\" | \"sl\" } & HyperliquidTriggerParams,\n side: OrderSide,\n asset: HyperliquidAsset,\n): { readonly p: string; readonly t: HyperliquidL1Order[\"t\"] } => {\n const triggerPx = limitPrice(spec.triggerPx, side, asset.szDecimals, asset.market);\n const isMarket = spec.market !== false;\n let p: string;\n if (spec.price !== undefined) {\n p = limitPrice(spec.price, side, asset.szDecimals, asset.market);\n } else if (isMarket) {\n // Market triggers still cap the fill at triggerPx ± slippage, like the Python SDK's\n // _slippage_price (hyperliquid/exchange.py:112-137, market_close) and MetaMask's TP/SL\n // children (hyperLiquidValidation.ts positionTpsl → trigger × (1 ± slippage)).\n if (spec.slippageBps === undefined) {\n throw new HyperliquidError(\n \"invalid-input\",\n \"a market trigger needs slippageBps or an explicit price\",\n );\n }\n p = slippagePrice(triggerPx, side, spec.slippageBps, asset.szDecimals, asset.market);\n } else {\n throw new HyperliquidError(\"invalid-input\", \"a limit trigger needs an explicit price\");\n }\n return { p, t: { trigger: { isMarket, triggerPx, tpsl: spec.tpsl } } };\n};\n\nexport function createHyperliquidActions(options: {\n readonly markets: HyperliquidMarkets;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n}): HyperliquidActions {\n let meta: MetaAndAssetCtxsResponse[0] | undefined;\n let spotMeta: SpotMetaAndAssetCtxsResponse[0] | undefined;\n\n const refreshMeta = async (): Promise<void> => {\n const [perp, spot] = await Promise.all([options.markets.perps(), options.markets.spot()]);\n [meta] = perp;\n [spotMeta] = spot;\n };\n\n const lookup = (coin: string): HyperliquidAsset | undefined => {\n const perpIndex = meta?.universe.findIndex((entry) => entry.name === coin) ?? -1;\n const perp = perpIndex < 0 ? undefined : meta?.universe[perpIndex];\n if (perp !== undefined) {\n return {\n asset: perpIndex,\n szDecimals: perp.szDecimals,\n market: \"perp\",\n maxLeverage: perp.maxLeverage,\n };\n }\n const pair = spotMeta?.universe.find((entry) => entry.name === coin);\n const base = pair === undefined ? undefined : spotMeta?.tokens[pair.tokens[0] ?? -1];\n if (pair !== undefined && base !== undefined) {\n // Asset IDs: spot = 10000 + spotInfo[\"index\"], perps = the meta universe index\n // (docs for-developers/api/asset-ids).\n return { asset: 10_000 + pair.index, szDecimals: base.szDecimals, market: \"spot\" };\n }\n return undefined;\n };\n\n const resolve = async (coin: string): Promise<HyperliquidAsset> => {\n // Builder-deployed DEXes (\"dex:coin\") and outcome markets are out of scope (asset-ids doc).\n if (coin.includes(\":\") || coin.startsWith(\"#\")) {\n throw new HyperliquidError(\"invalid-input\", `${coin} is not a main-DEX market`);\n }\n if (meta === undefined || spotMeta === undefined) {\n await refreshMeta();\n }\n let found = lookup(coin);\n if (found === undefined) {\n await refreshMeta();\n found = lookup(coin);\n }\n if (found === undefined) {\n throw new HyperliquidError(\"invalid-input\", `unknown market ${coin}`);\n }\n return found;\n };\n\n const mid = async (coin: string): Promise<string> => {\n const mids = await options.markets.mids();\n const price = mids[coin];\n if (price === undefined) {\n throw new HyperliquidError(\"unavailable\", `no mid price for ${coin}`);\n }\n return price;\n };\n\n /** The wire `t`/`p` for an order kind — market orders price off a fresh mid. */\n const orderType = async (\n coin: string,\n kind: HyperliquidOrderKind,\n side: OrderSide,\n asset: HyperliquidAsset,\n ): Promise<{ readonly p: string; readonly t: HyperliquidL1Order[\"t\"] }> => {\n if (kind.kind === \"trigger\") {\n return triggerOrder(kind, side, asset);\n }\n if (kind.kind === \"market\") {\n return {\n p: slippagePrice(await mid(coin), side, kind.slippageBps, asset.szDecimals, asset.market),\n t: { limit: { tif: \"Ioc\" } },\n };\n }\n return {\n p: limitPrice(kind.price, side, asset.szDecimals, asset.market),\n t: { limit: { tif: kind.tif ?? \"Gtc\" } },\n };\n };\n\n const buildOrder = async (\n params: HyperliquidOrderParams,\n tpsl?: \"tp\" | \"sl\",\n spec?: HyperliquidTriggerParams,\n child?: { readonly side: OrderSide; readonly size: string },\n ): Promise<{ readonly order: HyperliquidL1Order; readonly price: string }> => {\n const asset = await resolve(params.coin);\n const side = child?.side ?? params.side;\n const size = roundSize(child?.size ?? params.size, asset.szDecimals);\n const { p, t } =\n spec !== undefined && tpsl !== undefined\n ? triggerOrder({ ...spec, tpsl }, side, asset)\n : await orderType(params.coin, params.order, side, asset);\n checkMinimum(p, size);\n return {\n order: wireOrder({\n asset: asset.asset,\n side,\n price: p,\n size,\n reduceOnly: child !== undefined || params.reduceOnly === true,\n type: t,\n cloid: cloidOf(options.random),\n }),\n price: p,\n };\n };\n\n /** Like {@link buildOrder} for modify/batchModify: the same wire order, no fresh cloid. */\n const buildModifiedOrder = async (\n params: HyperliquidModifyParams,\n ): Promise<HyperliquidL1Order> => {\n const asset = await resolve(params.coin);\n const size = roundSize(params.size, asset.szDecimals);\n const { p, t } = await orderType(params.coin, params.order, params.side, asset);\n checkMinimum(p, size);\n return wireOrder({\n asset: asset.asset,\n side: params.side,\n price: p,\n size,\n reduceOnly: params.reduceOnly === true,\n type: t,\n });\n };\n\n return {\n resolve,\n place: async (params) => {\n const attached = params.takeProfit !== undefined || params.stopLoss !== undefined;\n if (params.positionTpsl === true && params.order.kind !== \"trigger\") {\n throw new HyperliquidError(\"invalid-input\", \"positionTpsl orders must be trigger orders\");\n }\n if (attached && (params.order.kind === \"trigger\" || params.positionTpsl === true)) {\n throw new HyperliquidError(\n \"invalid-input\",\n \"only an entry order takes attached TP/SL children\",\n );\n }\n const entry = await buildOrder(params);\n const orders: HyperliquidL1Order[] = [entry.order];\n if (params.takeProfit !== undefined) {\n const tp = await buildOrder(params, \"tp\", params.takeProfit, {\n side: flip(params.side),\n size: entry.order.s,\n });\n orders.push(tp.order);\n }\n if (params.stopLoss !== undefined) {\n const sl = await buildOrder(params, \"sl\", params.stopLoss, {\n side: flip(params.side),\n size: entry.order.s,\n });\n orders.push(sl.order);\n }\n const grouping = attached\n ? \"normalTpsl\"\n : params.positionTpsl === true\n ? \"positionTpsl\"\n : \"na\";\n return { action: deepFreeze({ type: \"order\", orders, grouping }), price: entry.price };\n },\n modify: async (params) =>\n deepFreeze({\n type: \"modify\",\n oid: params.oid,\n order: await buildModifiedOrder(params),\n }),\n batchModify: async (modifies) => {\n const entries = [];\n for (const item of modifies) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- meta resolves from cache after the first.\n entries.push({ oid: item.oid, order: await buildModifiedOrder(item) });\n }\n return deepFreeze({ type: \"batchModify\", modifies: entries });\n },\n cancel: async (cancels) => {\n const entries = [];\n for (const item of cancels) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- meta resolves from cache after the first.\n const asset = await resolve(item.coin);\n entries.push({ a: asset.asset, o: item.oid });\n }\n return deepFreeze({ type: \"cancel\", cancels: entries });\n },\n cancelByCloid: async (cancels) => {\n const entries = [];\n for (const item of cancels) {\n if (!isCloid(item.cloid)) {\n throw new HyperliquidError(\"invalid-input\", \"not a cloid\");\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- meta resolves from cache after the first.\n const asset = await resolve(item.coin);\n entries.push({ asset: asset.asset, cloid: item.cloid });\n }\n return deepFreeze({ type: \"cancelByCloid\", cancels: entries });\n },\n cancelBatches: (entries) => {\n const batches: HyperliquidL1Action[] = [];\n for (let i = 0; i < entries.length; i += BATCH_CAP) {\n batches.push(deepFreeze({ type: \"cancel\", cancels: entries.slice(i, i + BATCH_CAP) }));\n }\n return batches;\n },\n twapCancel: async (params) => {\n const asset = await resolve(params.coin);\n return deepFreeze({\n type: \"twapCancel\",\n a: asset.asset,\n t: params.twapId,\n });\n },\n setLeverage: async (params) => {\n const asset = await resolve(params.coin);\n if (asset.market !== \"perp\" || asset.maxLeverage === undefined) {\n throw new HyperliquidError(\"invalid-input\", `${params.coin} has no leverage`);\n }\n if (\n !Number.isInteger(params.leverage) ||\n params.leverage < 1 ||\n params.leverage > asset.maxLeverage\n ) {\n throw new HyperliquidError(\n \"invalid-input\",\n `leverage must be an integer in 1..${asset.maxLeverage}`,\n );\n }\n return deepFreeze({\n type: \"updateLeverage\",\n asset: asset.asset,\n isCross: params.marginMode === \"cross\",\n leverage: params.leverage,\n });\n },\n adjustMargin: async (params) => {\n const asset = await resolve(params.coin);\n if (asset.market !== \"perp\") {\n throw new HyperliquidError(\"invalid-input\", \"isolated margin applies to perps\");\n }\n // ntli is USD × 10⁶ exactly — float_to_usd_int (utils/signing.py:489); isBuy is always\n // true on the wire (exchange.py:411 update_isolated_margin).\n const amount = parseDecimal(params.amount);\n if (amount.scale > 6) {\n throw new HyperliquidError(\"invalid-input\", \"margin adjustments allow 6 decimals\");\n }\n const ntli = Number(amount.units * 10n ** BigInt(6 - amount.scale));\n if (!Number.isSafeInteger(ntli) || ntli === 0) {\n throw new HyperliquidError(\"invalid-input\", \"not a valid margin adjustment\");\n }\n return deepFreeze({ type: \"updateIsolatedMargin\", asset: asset.asset, isBuy: true, ntli });\n },\n };\n}\n","import type { HyperliquidNetwork, SessionInfo } from \"@qntx/wallet/protocol\";\n\nimport type { EngineLogger } from \"../spi.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\n\n/** The account identity every trade method takes first — a wallet group, nothing more. */\nexport type HyperliquidGroup = {\n readonly walletId: string;\n readonly groupIndex: number;\n};\n\n/** The agent `require` hands to the signer: the kernel-held agent address and its owner. */\nexport type HyperliquidAgent = {\n readonly address: string;\n readonly owner: string;\n readonly validUntil: number;\n};\n\nexport type HyperliquidAgentRegistry = {\n /**\n * Reload kernel-listed sessions, keep only this scheme's on this network, and verify each agent's\n * `owner` against the group's `evm.bip44` address. Mismatched agents are logged and never usable\n * — they are not deleted, only excluded.\n */\n readonly refresh: () => Promise<void>;\n /** Mark a listed agent enabled — layer 3's enable flow calls this after HL confirmation. */\n readonly markEnabled: (address: string) => void;\n /** Mark an agent rejected by Hyperliquid (revoked / account unfunded) — fail fast next time. */\n readonly markRejected: (address: string) => void;\n /**\n * The single enabled, owner-verified, unexpired, unrejected agent of exactly this group — the one\n * with the latest `validUntil` when several qualify. Never falls back to another group's agent.\n * Throws `not-enabled` (no agent or none enabled) or `reauthorization-required` (expired or\n * rejected).\n */\n readonly require: (group: HyperliquidGroup) => HyperliquidAgent;\n /** The group's `evm.bip44` address on the signature chain, lowercased — derived once. */\n readonly owner: (group: HyperliquidGroup) => Promise<string>;\n /** True when the exchange path latched the agent as rejected — enablement must renew it. */\n readonly rejected: (address: string) => boolean;\n /** True when an enable flow marked the agent enabled this session. */\n readonly enabled: (address: string) => boolean;\n /** A lock clears the session marks and verified list — the next unlock re-derives them. */\n readonly reset: () => void;\n};\n\nconst keyOf = (group: HyperliquidGroup): string => `${group.walletId}:${group.groupIndex}`;\n\nexport function createHyperliquidAgentRegistry(options: {\n /** `sessions(wallet)` — the kernel session list. */\n readonly agents: {\n readonly list: () => Promise<ReadonlyArray<SessionInfo>>;\n };\n /** The group's `evm.bip44` address on the signature chain — the apps account seam. */\n readonly evmAddress: (group: HyperliquidGroup) => Promise<string>;\n readonly network: HyperliquidNetwork;\n readonly now: () => number;\n readonly logger: EngineLogger;\n}): HyperliquidAgentRegistry {\n /** Group key → the lowercase evm.bip44 address, derived once per group. */\n const owners = new Map<string, string>();\n /** Kernel-listed, scheme- and network-matched, owner-verified agents. */\n let verified: ReadonlyArray<SessionInfo> = [];\n const enabled = new Set<string>();\n const rejected = new Set<string>();\n\n const ownerOf = async (group: HyperliquidGroup): Promise<string> => {\n const key = keyOf(group);\n let owner = owners.get(key);\n if (owner === undefined) {\n const address = await options.evmAddress(group);\n owner = address.toLowerCase();\n owners.set(key, owner);\n }\n return owner;\n };\n\n return {\n owner: ownerOf,\n refresh: async () => {\n const listed = await options.agents.list();\n const next: SessionInfo[] = [];\n for (const agent of listed) {\n if (agent.scheme !== \"hyperliquid-l1-agent\" || agent.scope !== options.network) {\n continue;\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- one owner lookup per distinct group.\n const owner = await ownerOf(agent);\n if (agent.owner.toLowerCase() !== owner) {\n options.logger.warn(\n `hyperliquid agent ${agent.address} skipped: owner ${agent.owner} is not the group account`,\n );\n continue;\n }\n next.push(agent);\n }\n verified = next;\n },\n markEnabled: (address) => {\n enabled.add(address.toLowerCase());\n },\n markRejected: (address) => {\n rejected.add(address.toLowerCase());\n },\n rejected: (address) => rejected.has(address.toLowerCase()),\n enabled: (address) => enabled.has(address.toLowerCase()),\n reset: () => {\n owners.clear();\n verified = [];\n enabled.clear();\n rejected.clear();\n },\n require: (group) => {\n const own = verified.filter(\n (agent) => agent.walletId === group.walletId && agent.groupIndex === group.groupIndex,\n );\n if (own.length === 0) {\n throw new HyperliquidError(\"not-enabled\", \"the account has no Hyperliquid agent\");\n }\n const marked = own.filter((agent) => enabled.has(agent.address.toLowerCase()));\n const usable = marked.filter(\n (agent) => !rejected.has(agent.address.toLowerCase()) && agent.validUntil > options.now(),\n );\n let agent: SessionInfo | undefined;\n for (const candidate of usable) {\n if (agent === undefined || candidate.validUntil > agent.validUntil) {\n agent = candidate;\n }\n }\n if (agent === undefined) {\n throw new HyperliquidError(\n marked.length > 0 ? \"reauthorization-required\" : \"not-enabled\",\n marked.length > 0\n ? \"the enabled Hyperliquid agent expired or was rejected\"\n : \"the account has no enabled Hyperliquid agent\",\n );\n }\n return {\n address: agent.address,\n owner: agent.owner.toLowerCase(),\n validUntil: agent.validUntil,\n };\n },\n };\n}\n","import { HyperliquidError } from \"./errors.ts\";\n\n/** |skew| beyond this refuses to sign: the 15 s expiresAfter window needs ≥ 10 s of slack. */\nexport const MAX_SKEW_MS = 5000;\n\n/**\n * The device/server clock agreement: one estimate per response, computed from the HTTP `Date`\n * header (1 s resolution, so +500 centres it) against the midpoint of the request — the same\n * single-sample estimate Cristian's algorithm gives. Nonces are device milliseconds, strictly\n * increasing per signer; the estimate never adjusts them — it only gates.\n */\nexport type HyperliquidClock = {\n /** Feed one response's server time (ms) and the local request bounds (ms). */\n readonly record: (serverMs: number, requestStart: number, responseEnd: number) => void;\n /** The latest skew estimate in ms — positive when the server is ahead — or `undefined`. */\n readonly skew: () => number | undefined;\n /** Throws `clock-skew` once an estimate shows |skew| > {@link MAX_SKEW_MS}. */\n readonly assertSkew: () => void;\n /** The next nonce for `signer` (lowercased address): `max(now, last + 1)`. */\n readonly nextNonce: (signer: string) => number;\n};\n\nexport function createHyperliquidClock(now: () => number): HyperliquidClock {\n let estimate: number | undefined;\n const lastNonce = new Map<string, number>();\n return {\n record: (serverMs, requestStart, responseEnd) => {\n estimate = serverMs + 500 - (requestStart + responseEnd) / 2;\n },\n skew: () => estimate,\n assertSkew: () => {\n if (estimate !== undefined && Math.abs(estimate) > MAX_SKEW_MS) {\n throw new HyperliquidError(\"clock-skew\", `device clock off by ${estimate} ms`);\n }\n },\n nextNonce: (signer) => {\n const next = Math.max(now(), (lastNonce.get(signer) ?? 0) + 1);\n lastNonce.set(signer, next);\n return next;\n },\n };\n}\n","import type { IRequestTransport } from \"@nktkas/hyperliquid\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport type { HyperliquidL1Action } from \"@qntx/wallet/protocol\";\nimport { sessions } from \"@qntx/wallet/sessions\";\n\nimport { formatDecimal, parseDecimal } from \"../spi.ts\";\nimport type { SetTimer } from \"../spi.ts\";\nimport type { HyperliquidAccount } from \"./account.ts\";\nimport type { HyperliquidAgent, HyperliquidAgentRegistry, HyperliquidGroup } from \"./agents.ts\";\nimport { MAX_SKEW_MS } from \"./clock.ts\";\nimport type { HyperliquidClock } from \"./clock.ts\";\nimport { HyperliquidError, SESSION_ERRORS } from \"./errors.ts\";\nimport type { HyperliquidMarkets } from \"./markets.ts\";\n\n/** Why Hyperliquid refused an order — the docs error table plus the wire status names. */\nexport type HyperliquidRejectReason =\n | \"tick\"\n | \"min-notional\"\n | \"margin\"\n | \"reduce-only\"\n | \"post-only-would-match\"\n | \"ioc-no-match\"\n | \"bad-trigger\"\n | \"no-liquidity\"\n | \"open-interest-cap\"\n | \"insufficient-spot-balance\"\n | \"oracle\"\n | \"max-position\"\n | \"other\";\n\n/** What happened to one order of an order action, on the wire or after reconciliation. */\nexport type HyperliquidOrderOutcome =\n | {\n readonly kind: \"resting\";\n /** Absent for `waitingForFill`/`waitingForTrigger` statuses, which carry no oid. */\n readonly oid?: number | undefined;\n readonly cloid?: string | undefined;\n /** Size already filled while still resting — only from `orderStatus` reconciliation. */\n readonly filledSz?: string | undefined;\n }\n | {\n readonly kind: \"filled\";\n readonly oid?: number | undefined;\n readonly cloid?: string | undefined;\n readonly totalSz: string;\n /** `orderStatus` carries no fill price — absent on reconciled fills, never fabricated. */\n readonly avgPx?: string | undefined;\n }\n | {\n readonly kind: \"rejected\";\n readonly cloid?: string | undefined;\n readonly reason: HyperliquidRejectReason;\n readonly message: string;\n }\n | { readonly kind: \"unknown\"; readonly cloid?: string | undefined };\n\n/**\n * An `unknown` order outcome proven later — by the late reconciler or by a live user-view frame\n * that saw the cloid. `unknown` can never be proven \"not placed\": Hyperliquid documents no\n * consistency between an info read and L1 state, so only a definite later answer counts.\n */\nexport type HyperliquidOutcomeCorrection = {\n readonly group: HyperliquidGroup;\n readonly cloid: string;\n readonly outcome: HyperliquidOrderOutcome;\n};\n\n/** What happened to one entry of a cancel action. */\nexport type HyperliquidCancelOutcome =\n | { readonly kind: \"cancelled\" }\n | { readonly kind: \"rejected\"; readonly message: string }\n | { readonly kind: \"unknown\" };\n\n/** What happened to an action without per-element statuses; `twapId` when a TWAP started. */\nexport type HyperliquidActionOutcome =\n | { readonly kind: \"ok\"; readonly twapId?: number }\n | { readonly kind: \"unknown\" };\n\n/** The official app's action horizon: 15 s (research §Endpoints). */\nconst EXPIRES_AFTER_MS = 15_000;\n\n/** Poll cadence for cloid reconciliation — orderStatus is weight 2, the deadline is seconds away. */\nconst RECONCILE_POLL_MS = 1000;\n\n/**\n * Late reconciliation cadence for `unknown` cloids — orderStatus is weight 2, so a 10 s cadence\n * over {@link MAX_UNRESOLVED} entries stays far under the 1200 weight/min limit.\n */\nconst RECONCILE_LATE_POLL_MS = 10_000;\n\n/**\n * Endpoint catch-up budget: past ten minutes a pending cloid is dropped from the set silently — its\n * outcome stays `unknown`, it is simply no longer re-asked.\n */\nconst RECONCILE_LATE_WINDOW_MS = 600_000;\n\n/** Outstanding cloids cannot grow without bound — past the cap the oldest entry is evicted. */\nconst MAX_UNRESOLVED = 64;\n\n/** After `expiresAfter` plus the skew bound the action can no longer commit; +2 s of slack. */\nconst reconcileDeadline = (expiresAfter: number): number => expiresAfter + MAX_SKEW_MS + 2000;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst stringOf = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined;\n\nconst numberOf = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\n/** Order statuses the docs list as `*Rejected` — mapped to reasons by name. */\nconst statusReason = (status: string): HyperliquidRejectReason => {\n if (status.includes(\"OpenInterest\")) {\n return \"open-interest-cap\";\n }\n switch (status) {\n case \"tickRejected\":\n return \"tick\";\n case \"minTradeNtlRejected\":\n return \"min-notional\";\n case \"perpMarginRejected\":\n return \"margin\";\n case \"reduceOnlyRejected\":\n return \"reduce-only\";\n case \"badAloPxRejected\":\n return \"post-only-would-match\";\n case \"iocCancelRejected\":\n return \"ioc-no-match\";\n case \"badTriggerPxRejected\":\n return \"bad-trigger\";\n case \"marketOrderNoLiquidityRejected\":\n return \"no-liquidity\";\n case \"insufficientSpotBalanceRejected\":\n return \"insufficient-spot-balance\";\n case \"oracleRejected\":\n return \"oracle\";\n case \"perpMaxPositionRejected\":\n return \"max-position\";\n default:\n return \"other\";\n }\n};\n\n/** The same classes for the `error` strings in order-statuses (docs error-responses table). */\nconst messageReason = (message: string): HyperliquidRejectReason => {\n if (message.includes(\"divisible by tick size\")) {\n return \"tick\";\n }\n if (message.includes(\"minimum value\")) {\n return \"min-notional\";\n }\n if (message.includes(\"Insufficient margin\")) {\n return \"margin\";\n }\n if (message.includes(\"Reduce only order\")) {\n return \"reduce-only\";\n }\n if (message.includes(\"Post only order\")) {\n return \"post-only-would-match\";\n }\n if (message.includes(\"could not immediately match\")) {\n return \"ioc-no-match\";\n }\n if (message.includes(\"Invalid TP/SL price\")) {\n return \"bad-trigger\";\n }\n if (message.includes(\"No liquidity available for market order\")) {\n return \"no-liquidity\";\n }\n if (message.includes(\"open interest\")) {\n return \"open-interest-cap\";\n }\n if (message.includes(\"insufficient spot balance\")) {\n return \"insufficient-spot-balance\";\n }\n if (message.includes(\"too far from oracle\")) {\n return \"oracle\";\n }\n if (message.includes(\"margin tier limit\")) {\n return \"max-position\";\n }\n return \"other\";\n};\n\n/** `status: \"err\"` strings that mean the agent is unusable — never retried with another key. */\nconst AGENT_REJECTION =\n /User or API Wallet 0x[0-9a-fA-F]+ does not exist|Must deposit before performing actions/;\n\nconst cloidOf = (entry: Record<string, unknown>): string | undefined => stringOf(entry[\"cloid\"]);\n\n/* Pending keys normalize case: a checksummed owner or an upper-case cloid in a WebSocket frame\n is the same pending order — the map must still match it. */\nconst pendingKey = (master: string, cloid: string): string => `${master}|${cloid}`.toLowerCase();\n\n/**\n * An answered order status — strict on the documented shapes: anything else means the response was\n * misread, and a misread \"rejected\" is how duplicate orders happen. `undefined` → reconcile.\n */\nconst orderStatusOutcome = (\n entry: unknown,\n cloid?: string,\n): HyperliquidOrderOutcome | undefined => {\n if (entry === \"waitingForFill\" || entry === \"waitingForTrigger\") {\n // Accepted without an oid yet — resting without one.\n return { kind: \"resting\", cloid };\n }\n if (isRecord(entry) && isRecord(entry[\"resting\"])) {\n const oid = numberOf(entry[\"resting\"][\"oid\"]);\n return oid === undefined\n ? undefined\n : { kind: \"resting\", oid, cloid: cloidOf(entry[\"resting\"]) ?? cloid };\n }\n if (isRecord(entry) && isRecord(entry[\"filled\"])) {\n const totalSz = stringOf(entry[\"filled\"][\"totalSz\"]);\n const avgPx = stringOf(entry[\"filled\"][\"avgPx\"]);\n return totalSz === undefined || avgPx === undefined\n ? undefined\n : {\n kind: \"filled\",\n oid: numberOf(entry[\"filled\"][\"oid\"]),\n cloid: cloidOf(entry[\"filled\"]) ?? cloid,\n totalSz,\n avgPx,\n };\n }\n const message = isRecord(entry) ? stringOf(entry[\"error\"]) : undefined;\n return message === undefined\n ? undefined\n : { kind: \"rejected\", cloid, reason: messageReason(message), message };\n};\n\nconst cancelStatusOutcome = (entry: unknown): HyperliquidCancelOutcome => {\n if (entry === \"success\") {\n return { kind: \"cancelled\" };\n }\n const message = isRecord(entry) ? stringOf(entry[\"error\"]) : undefined;\n return message === undefined ? { kind: \"unknown\" } : { kind: \"rejected\", message };\n};\n\n/**\n * The docs warn that a pre-validation failure returns ONE error for the whole batch; a single\n * `{error}` status among n orders applies to every entry (error-responses doc).\n */\nconst broadcast = (statuses: ReadonlyArray<unknown>, count: number): ReadonlyArray<unknown> => {\n const [only] = statuses;\n if (statuses.length === 1 && count > 1 && isRecord(only) && typeof only[\"error\"] === \"string\") {\n return Array.from({ length: count }, () => only);\n }\n return statuses;\n};\n\nconst statusesOf = (body: unknown): ReadonlyArray<unknown> | undefined => {\n if (!isRecord(body) || body[\"status\"] !== \"ok\" || !isRecord(body[\"response\"])) {\n return undefined;\n }\n const { data } = body[\"response\"];\n if (!isRecord(data) || !Array.isArray(data[\"statuses\"])) {\n return undefined;\n }\n return data[\"statuses\"] as ReadonlyArray<unknown>;\n};\n\n/** `origSz − sz` exactly — the filled part of an order, canonical, or undefined when unreadable. */\nconst filledSize = (order: Record<string, unknown>): string | undefined => {\n const orig = stringOf(order[\"origSz\"]);\n const open = stringOf(order[\"sz\"]);\n if (orig === undefined || open === undefined) {\n return undefined;\n }\n const a = parseDecimal(orig);\n const b = parseDecimal(open);\n const scale = Math.max(a.scale, b.scale);\n const diff = a.units * 10n ** BigInt(scale - a.scale) - b.units * 10n ** BigInt(scale - b.scale);\n return formatDecimal({ units: diff < 0n ? 0n : diff, scale });\n};\n\nconst positive = (size: string | undefined): size is string =>\n size !== undefined && parseDecimal(size).units > 0n;\n\n/**\n * `orderStatus` → the outcome for one cloid, or `undefined` to keep polling (unknownOid and\n * malformed answers both keep polling — a misread is never a verdict).\n */\nconst statusOutcome = (result: unknown, cloid?: string): HyperliquidOrderOutcome | undefined => {\n if (!isRecord(result) || result[\"status\"] !== \"order\" || !isRecord(result[\"order\"])) {\n return undefined;\n }\n const detail = result[\"order\"];\n const order = isRecord(detail[\"order\"]) ? detail[\"order\"] : {};\n const status = stringOf(detail[\"status\"]) ?? \"\";\n const oid = numberOf(order[\"oid\"]);\n const filled = filledSize(order);\n if (status === \"open\" || status === \"triggered\") {\n return positive(filled)\n ? { kind: \"resting\", oid, cloid, filledSz: filled }\n : { kind: \"resting\", oid, cloid };\n }\n if (status === \"filled\") {\n return {\n kind: \"filled\",\n oid,\n cloid,\n // orderStatus carries no fill price — avgPx stays absent, never fabricated.\n totalSz: filled ?? stringOf(order[\"origSz\"]) ?? \"0\",\n };\n }\n if (status === \"\") {\n return undefined;\n }\n // Every *Rejected/*Canceled terminal status — a partial IOC fill still committed its filled part.\n return positive(filled)\n ? { kind: \"filled\", oid, cloid, totalSz: filled }\n : { kind: \"rejected\", cloid, reason: statusReason(status), message: status };\n};\n\nconst cloids = (action: HyperliquidL1Action): ReadonlyArray<string | undefined> =>\n action.type === \"order\" || action.type === \"batchModify\"\n ? action.type === \"order\"\n ? action.orders.map((order) => order.c)\n : action.modifies.map((item) => item.order.c)\n : [];\n\n/** `data.status` of single-status responses like twapOrder: `{running:{twapId}} | {error}`. */\nconst singleStatus = (body: unknown): HyperliquidActionOutcome | undefined => {\n const data =\n isRecord(body) && isRecord(body[\"response\"]) && isRecord(body[\"response\"][\"data\"])\n ? body[\"response\"][\"data\"]\n : undefined;\n const status = isRecord(data?.[\"status\"]) ? data?.[\"status\"] : undefined;\n if (status === undefined) {\n return undefined;\n }\n const message = stringOf(status[\"error\"]);\n if (message !== undefined) {\n throw new HyperliquidError(\"rejected\", message);\n }\n if (isRecord(status[\"running\"])) {\n const twapId = numberOf(status[\"running\"][\"twapId\"]);\n return twapId === undefined ? { kind: \"ok\" } : { kind: \"ok\", twapId };\n }\n return undefined;\n};\n\nexport type HyperliquidExchange = {\n /** Sign and post an order action; reconcile each cloid if the POST's outcome is unknown. */\n readonly order: (\n group: HyperliquidGroup,\n action: HyperliquidL1Action,\n ) => Promise<ReadonlyArray<HyperliquidOrderOutcome>>;\n /** Sign and post a cancel/cancelByCloid action. */\n readonly cancel: (\n group: HyperliquidGroup,\n action: HyperliquidL1Action,\n ) => Promise<ReadonlyArray<HyperliquidCancelOutcome>>;\n /** Sign and post any other action — `{kind:\"ok\"}` or `{kind:\"unknown\"}` on a lost POST. */\n readonly action: (\n group: HyperliquidGroup,\n action: HyperliquidL1Action,\n ) => Promise<HyperliquidActionOutcome>;\n /**\n * Corrections for outcomes returned `unknown`: the late reconciler re-asks pending cloids for\n * {@link RECONCILE_LATE_WINDOW_MS} and live user-view frames prove or re-ask them too. Nothing is\n * ever re-sent.\n */\n readonly corrections: {\n readonly subscribe: (\n listener: (correction: HyperliquidOutcomeCorrection) => void,\n ) => () => void;\n };\n /** A live user-view frame for `user` — proves or re-asks pending cloids it carries. */\n readonly sighted: (user: string, entry: unknown) => void;\n};\n\nexport function createHyperliquidExchange(options: {\n readonly wallet: Wallet;\n readonly transport: IRequestTransport;\n readonly clock: HyperliquidClock;\n readonly markets: HyperliquidMarkets;\n readonly account: HyperliquidAccount;\n readonly registry: HyperliquidAgentRegistry;\n readonly now: () => number;\n readonly setTimer: SetTimer;\n}): HyperliquidExchange {\n const sleep = async (ms: number): Promise<void> =>\n new Promise((resolve) => {\n options.setTimer(ms, resolve);\n });\n\n /** One cheap info call when no skew estimate exists yet — any Date-bearing response works. */\n const assertClock = async (): Promise<void> => {\n if (options.clock.skew() === undefined) {\n await options.markets.mids();\n }\n options.clock.assertSkew();\n };\n\n const listeners = new Set<(correction: HyperliquidOutcomeCorrection) => void>();\n const emit = (correction: HyperliquidOutcomeCorrection): void => {\n for (const listener of listeners) {\n listener(correction);\n }\n };\n\n type Pending = {\n readonly group: HyperliquidGroup;\n readonly master: string;\n readonly cloid: string;\n readonly since: number;\n };\n /* C-loids returned `unknown`, awaiting a provable outcome — keyed `master|cloid`, insertion\n order is eviction order. */\n const pending = new Map<string, Pending>();\n let pollCancel: (() => void) | undefined;\n let lockWatch: (() => void) | undefined;\n /* Bumped by every lock — a cloid signed in one unlocked session is never registered in a later\n one, even when its in-call reconcile outlives a lock and an unlock. */\n let session = 0;\n\n /* The vault is the boundary: a lock drops every pending cloid and stops the poll — the\n corrections a new session earns are its own. Subscribed lazily, on the first signed action, so\n a reads-only provider never needs the wallet's subscription channel. */\n const watchLock = (): void => {\n lockWatch ??= options.wallet.subscribe(() => {\n if (options.wallet.getSnapshot().vault !== \"unlocked\") {\n session += 1;\n pending.clear();\n pollCancel?.();\n pollCancel = undefined;\n }\n });\n };\n\n /** One orderStatus read for a pending cloid — a definite answer corrects and drops it. */\n const probe = async (entry: Pending): Promise<void> => {\n let outcome: HyperliquidOrderOutcome | undefined;\n try {\n outcome = statusOutcome(\n await options.account.orderStatus({ user: entry.master, oid: entry.cloid }),\n entry.cloid,\n );\n } catch {\n return; // a failed late read stays pending — the timer re-asks\n }\n if (outcome !== undefined && pending.get(pendingKey(entry.master, entry.cloid)) === entry) {\n pending.delete(pendingKey(entry.master, entry.cloid));\n emit({ group: entry.group, cloid: entry.cloid, outcome });\n }\n };\n\n const schedulePoll = (): void => {\n if (pollCancel === undefined && pending.size > 0) {\n pollCancel = options.setTimer(RECONCILE_LATE_POLL_MS, () => {\n pollCancel = undefined;\n void (async (): Promise<void> => {\n for (const entry of pending.values()) {\n if (options.now() - entry.since >= RECONCILE_LATE_WINDOW_MS) {\n pending.delete(pendingKey(entry.master, entry.cloid)); // expired: stays unknown\n } else {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls keep the weight bounded.\n await probe(entry);\n }\n }\n schedulePoll();\n })();\n });\n }\n };\n\n const registerPending = (\n group: HyperliquidGroup,\n master: string,\n cloid: string,\n signedIn: number,\n ): void => {\n if (signedIn !== session || options.wallet.getSnapshot().vault !== \"unlocked\") {\n return; // a locked session drops its pending cloids — nothing account-bound survives it\n }\n const key = pendingKey(master, cloid);\n if (!pending.has(key) && pending.size >= MAX_UNRESOLVED) {\n const [oldest] = pending.keys();\n if (oldest !== undefined) {\n pending.delete(oldest);\n }\n }\n pending.set(key, { group, master, cloid, since: options.now() });\n schedulePoll();\n };\n\n /* A live user-view frame is a second proof channel: `openOrders` carrying a pending cloid is\n the order resting; `userFills` carrying it only means a fill exists — re-ask orderStatus. */\n const sighted = (user: string, entry: unknown): void => {\n if (!isRecord(entry) || pending.size === 0) {\n return;\n }\n const { orders } = entry;\n if (Array.isArray(orders)) {\n for (const order of orders) {\n const cloid = isRecord(order) ? stringOf(order[\"cloid\"]) : undefined;\n const oid = isRecord(order) ? numberOf(order[\"oid\"]) : undefined;\n if (cloid === undefined || oid === undefined) {\n continue;\n }\n const hit = pending.get(pendingKey(user, cloid));\n if (hit !== undefined) {\n pending.delete(pendingKey(user, cloid));\n emit({ group: hit.group, cloid, outcome: { kind: \"resting\", oid, cloid } });\n }\n }\n }\n const { fills } = entry;\n if (Array.isArray(fills)) {\n for (const fill of fills) {\n const cloid = isRecord(fill) ? stringOf(fill[\"cloid\"]) : undefined;\n const hit = cloid === undefined ? undefined : pending.get(pendingKey(user, cloid));\n if (hit !== undefined) {\n void probe(hit);\n }\n }\n }\n };\n\n /**\n * The POST's outcome is unknown — the action may have committed. Poll orderStatus by cloid every\n * second; never re-POST. Deadline: `expiresAfter + MAX_SKEW + 2 s` — past it the action cannot be\n * accepted anymore.\n */\n const reconcile = async (\n group: HyperliquidGroup,\n master: string,\n cloid: string | undefined,\n expiresAfter: number,\n signedIn: number,\n ): Promise<HyperliquidOrderOutcome> => {\n if (cloid === undefined) {\n return { kind: \"unknown\" };\n }\n const deadline = reconcileDeadline(expiresAfter);\n while (options.now() <= deadline) {\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n const result = await options.account.orderStatus({ user: master, oid: cloid });\n const outcome = statusOutcome(result, cloid);\n if (outcome !== undefined) {\n return outcome;\n }\n } catch {\n // A failed read is not an answer — keep polling until the deadline.\n }\n if (options.now() <= deadline) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential polls are the protocol.\n await sleep(RECONCILE_POLL_MS);\n }\n }\n /* Every answer was unknownOid or a failed read — \"not placed\" cannot be proven: no\n documented consistency between an info read and L1 state, nor which server answered the\n polls. The cloid stays pending for late reconciliation instead. */\n registerPending(group, master, cloid, signedIn);\n return { kind: \"unknown\", cloid };\n };\n\n const sign = async (\n agent: HyperliquidAgent,\n action: HyperliquidL1Action,\n nonce: number,\n expiresAfter: number,\n ): Promise<{ readonly r: string; readonly s: string; readonly v: number }> => {\n let signature: Uint8Array;\n try {\n signature = await sessions(options.wallet).sign({\n scheme: \"hyperliquid-l1-agent\",\n address: agent.address,\n params: { action, nonce, expiresAfter },\n });\n } catch (error) {\n if (error instanceof WalletError) {\n if (\n error.code === \"not-found\" ||\n (error.code === \"invalid-input\" && options.now() >= agent.validUntil)\n ) {\n options.registry.markRejected(agent.address);\n throw new HyperliquidError(\"reauthorization-required\", \"the agent is gone\", error);\n }\n /* `invalid-input` while the agent still looks valid is a nonce-window or malformed-action\n rejection — a clock fault or a builder bug, never an agent fault worth latching. */\n if (error.code === \"invalid-input\") {\n throw new HyperliquidError(\"invalid-input\", \"kernel rejected\", error);\n }\n /* `approval-required` means the lock cleared the opened mark — the host re-approves\n with `reopen`, never by re-enabling. */\n const mapped = SESSION_ERRORS[error.code];\n if (mapped) {\n throw new HyperliquidError(mapped[0], mapped[1], error);\n }\n }\n throw new HyperliquidError(\"unavailable\", \"the wallet failed to sign\", error);\n }\n if (signature.length !== 65) {\n throw new HyperliquidError(\"unavailable\", \"the kernel returned a malformed signature\");\n }\n const hex = Array.from(signature, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n // r‖s‖v with v already 27/28 — Signature.toBytes emits 27 + yParity (evm/sign.ts:40).\n return { r: `0x${hex.slice(0, 64)}`, s: `0x${hex.slice(64, 128)}`, v: signature[64] ?? 27 };\n };\n\n /**\n * Gate → require → nonce → sign → POST the exact frozen action. A transport failure after signing\n * means the action may have committed: the caller maps that to a reconciliation, never a retry.\n */\n const execute = async <T>(\n group: HyperliquidGroup,\n action: HyperliquidL1Action,\n onOk: (body: unknown, master: string, expiresAfter: number, signedIn: number) => T | Promise<T>,\n onLost: (master: string, expiresAfter: number, signedIn: number) => T | Promise<T>,\n ): Promise<T> => {\n const agent = options.registry.require(group);\n await assertClock();\n const nonce = options.clock.nextNonce(agent.address);\n const expiresAfter = options.now() + EXPIRES_AFTER_MS;\n watchLock();\n const signedIn = session;\n const signature = await sign(agent, action, nonce, expiresAfter);\n const body = { action, nonce, signature, expiresAfter };\n let response: unknown;\n try {\n response = await options.transport.request(\"exchange\", body);\n } catch (error) {\n // The transport throws only network/timeout/unavailable HyperliquidErrors — each means\n // the POST may have landed.\n if (error instanceof HyperliquidError) {\n return onLost(agent.owner, expiresAfter, signedIn);\n }\n throw error;\n }\n if (isRecord(response) && response[\"status\"] === \"err\") {\n const message = stringOf(response[\"response\"]) ?? \"rejected\";\n if (AGENT_REJECTION.test(message)) {\n options.registry.markRejected(agent.address);\n throw new HyperliquidError(\"reauthorization-required\", message);\n }\n throw new HyperliquidError(\"rejected\", message);\n }\n return onOk(response, agent.owner, expiresAfter, signedIn);\n };\n\n return {\n order: async (group, action) =>\n execute(\n group,\n action,\n async (body, master, expiresAfter, signedIn) => {\n const count =\n action.type === \"order\"\n ? action.orders.length\n : action.type === \"batchModify\"\n ? action.modifies.length\n : 1;\n const known = cloids(action);\n const raw = statusesOf(body);\n const entries = raw === undefined ? undefined : broadcast(raw, count);\n /* A malformed/short answered response is as unknown as a lost POST — reconcile the\n cloids it could not account for instead of fabricating rejections. */\n if (entries === undefined || entries.length !== count) {\n return Promise.all(\n known.map(async (cloid) => reconcile(group, master, cloid, expiresAfter, signedIn)),\n );\n }\n return Promise.all(\n entries.map(async (entry, index) => {\n const outcome = orderStatusOutcome(entry, known[index]);\n return outcome ?? reconcile(group, master, known[index], expiresAfter, signedIn);\n }),\n );\n },\n async (master, expiresAfter, signedIn) => {\n const known = cloids(action);\n if (known.length === 0) {\n return [{ kind: \"unknown\" }];\n }\n return Promise.all(\n known.map(async (cloid) => reconcile(group, master, cloid, expiresAfter, signedIn)),\n );\n },\n ),\n cancel: async (group, action) => {\n const count =\n action.type === \"cancel\" || action.type === \"cancelByCloid\" ? action.cancels.length : 1;\n return execute(\n group,\n action,\n (body) => {\n const raw = statusesOf(body);\n const entries = raw === undefined ? undefined : broadcast(raw, count);\n return entries === undefined || entries.length !== count\n ? Array.from({ length: count }, () => ({ kind: \"unknown\" as const }))\n : entries.map(cancelStatusOutcome);\n },\n () => Array.from({ length: count }, () => ({ kind: \"unknown\" as const })),\n );\n },\n action: async (group, action) =>\n execute(\n group,\n action,\n (body) => singleStatus(body) ?? { kind: \"ok\" },\n () => ({ kind: \"unknown\" }),\n ),\n corrections: {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n },\n sighted,\n };\n}\n","/**\n * An `ISubscriptionTransport` over the shared apps socket core (`../socket.ts`): subscribe/\n * unsubscribe frames, confirmation matching by \"payload ⊆ echo\" (most specific pending wins),\n * `{\"method\":\"ping\"}` heartbeats answered by `{channel:\"pong\"}`, and the server-side limits\n * enforced client-side. Matching mirrors `@nktkas/hyperliquid` `transport/websocket/_id.js`\n * (`isSubset`/`specificity`/`requestToId`) and `transport/websocket/_dispatcher.js` (queue +\n * response handling); the SDK's subscription functions consume `{ detail }` events only\n * (`api/subscription/_methods/l2Book.js` etc.).\n */\nimport { TransportError } from \"@nktkas/hyperliquid\";\nimport type { ISubscription, ISubscriptionTransport } from \"@nktkas/hyperliquid\";\n\nimport type { HyperliquidNetwork } from \"@qntx/wallet/protocol\";\n\nimport { createAppSocketCore } from \"../spi.ts\";\nimport type { AppSocket, AppSocketStatus, SetTimer } from \"../spi.ts\";\n\n/* AppSocket moved to the shared core — re-exported for the paths tests and apps/index.ts import. */\nexport type { AppSocket } from \"../spi.ts\";\n\nexport type HyperliquidSocketOptions = {\n readonly network: HyperliquidNetwork;\n /** The socket factory, e.g. `(url) => new WebSocket(url)`. */\n readonly socket: (url: string) => AppSocket;\n readonly setTimer: SetTimer;\n /** Jitter source — one byte scaled to [0,1) of the backoff. */\n readonly random: (length: number) => Uint8Array;\n};\n\nexport type HyperliquidSocketStatus = AppSocketStatus;\n\nexport type HyperliquidSocket = ISubscriptionTransport & {\n readonly isTestnet: boolean;\n /** Current connection status. */\n readonly status: () => HyperliquidSocketStatus;\n /** Subscribe to status transitions; returns an unsubscribe. */\n readonly onStatus: (listener: (status: HyperliquidSocketStatus) => void) => () => void;\n /**\n * Per-subscription `confirmed` transitions — initial AND every re-confirmation after a reconnect.\n * The listener gets the channel and the subscribed payload.\n */\n readonly onConfirmed: (listener: (channel: string, payload: unknown) => void) => () => void;\n /** Ends every subscription and prevents reconnects. */\n readonly close: () => void;\n};\n\nexport const HYPERLIQUID_WS: Record<HyperliquidNetwork, string> = {\n Mainnet: \"wss://api.hyperliquid.xyz/ws\",\n Testnet: \"wss://api.hyperliquid-testnet.xyz/ws\",\n};\n\nconst OPEN = 1;\nconst PING_MS = 30_000;\nconst PONG_MS = 10_000;\nconst CONFIRM_MS = 10_000;\nconst MAX_SUBSCRIPTIONS = 1000;\nconst MAX_USERS = 10;\n\nconst HEX = /^0x[0-9a-f]+$/i;\n\nconst normalize = (value: unknown): unknown => {\n if (typeof value === \"string\" && HEX.test(value)) {\n return value.toLowerCase();\n }\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n if (typeof value === \"object\" && value !== null) {\n /* `Object.fromEntries` makes a `__proto__` key an own property — assigning it\n (`out[key] = …`) would set the output's prototype and drop the key from the canonical\n JSON, collapsing distinct payloads onto one subscription id. */\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => (a < b ? -1 : 1))\n .map(([key, item]) => [key, normalize(item)]),\n );\n }\n return value;\n};\n\nconst idOf = (value: unknown): string => JSON.stringify(normalize(value));\n\nconst specificity = (value: unknown): number =>\n typeof value === \"object\" && value !== null\n ? Object.values(value).reduce<number>((sum: number, item) => sum + specificity(item), 0)\n : 1;\n\nconst isSubset = (subset: unknown, superset: unknown): boolean => {\n if (typeof subset === \"string\" && typeof superset === \"string\") {\n return HEX.test(subset) && HEX.test(superset)\n ? subset.toLowerCase() === superset.toLowerCase()\n : subset === superset;\n }\n if (\n typeof subset !== \"object\" ||\n typeof superset !== \"object\" ||\n subset === null ||\n superset === null\n ) {\n return subset === superset;\n }\n if (Array.isArray(subset)) {\n return (\n Array.isArray(superset) &&\n subset.length === superset.length &&\n subset.every((item, i) => isSubset(item, (superset as unknown[])[i]))\n );\n }\n const sup = new Map<string, unknown>(Object.entries(superset));\n return Object.entries(subset).every(([key, item]) => isSubset(item, sup.get(key)));\n};\n\n/**\n * `subset ⊆ superset` with hex strings compared case-insensitively — the same rule the confirmation\n * matching uses; the live layer matches `onConfirmed` payloads with it.\n */\nexport const payloadContains: (subset: unknown, superset: unknown) => boolean = isSubset;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst userOf = (payload: unknown): string | undefined => {\n const user = isRecord(payload) ? payload[\"user\"] : undefined;\n return typeof user === \"string\" ? user.toLowerCase() : undefined;\n};\n\n/** `{channel:\"pong\"}` answers `{\"method\":\"ping\"}` — checked before the dispatcher sees the frame. */\nconst isPong = (raw: string): boolean => {\n try {\n const frame: unknown = JSON.parse(raw);\n return isRecord(frame) && frame[\"channel\"] === \"pong\";\n } catch {\n return false;\n }\n};\n\n/* `CustomEvent<never>` params accept every `CustomEvent<T>` listener — the SDK's subscription\n functions only ever read `e.detail` — so listener storage needs no cast. */\ntype Listener = (event: CustomEvent<never>) => void;\n\ntype Entry = {\n readonly channel: string;\n readonly payload: unknown;\n readonly listeners: Set<Listener>;\n resolve: (subscription: ISubscription) => void;\n reject: (error: Error) => void;\n readonly onError?: (error: TransportError) => void;\n /** Gates dispatch — cleared on resubscribe until the echo returns. */\n confirmed: boolean;\n /** Whether the subscribe promise already resolved — decides `reject` vs `onError` on fail. */\n resolved: boolean;\n timer?: (() => void) | undefined;\n};\n\nexport function createHyperliquidSocket(options: HyperliquidSocketOptions): HyperliquidSocket {\n const entries = new Map<string, Entry>();\n const confirmedListeners = new Set<(channel: string, payload: unknown) => void>();\n\n const send = (method: \"subscribe\" | \"unsubscribe\", payload: unknown): void => {\n core.send(JSON.stringify({ method, subscription: payload }));\n };\n\n /** Each caller's unsubscribe drops its own listener; the wire frame goes when the last leaves. */\n const unsubscribe = (id: string, listener: Listener): ISubscription => ({\n unsubscribe: async () => {\n const entry = entries.get(id);\n entry?.listeners.delete(listener);\n if (\n entry !== undefined &&\n entry.listeners.size === 0 &&\n entries.delete(id) &&\n core.readyState() === OPEN\n ) {\n send(\"unsubscribe\", entry.payload);\n }\n await Promise.resolve();\n },\n });\n\n const fail = (id: string, error: TransportError): void => {\n const entry = entries.get(id);\n if (entry === undefined) {\n return;\n }\n entry.timer?.();\n entries.delete(id);\n if (entry.resolved) {\n entry.onError?.(error);\n } else {\n entry.reject(error);\n }\n };\n\n const resubscribe = (): void => {\n for (const entry of entries.values()) {\n entry.confirmed = false;\n send(\"subscribe\", entry.payload);\n }\n };\n\n const onMessage = (raw: string): void => {\n let frame: unknown;\n try {\n frame = JSON.parse(raw);\n } catch {\n return;\n }\n if (!isRecord(frame)) {\n return;\n }\n const { channel } = frame;\n const { data } = frame;\n if (channel === \"subscriptionResponse\") {\n /* The echo names the subscription; the most specific pending payload contained in it\n wins (mirrors _dispatcher.js). */\n const echo = isRecord(data) ? data[\"subscription\"] : undefined;\n const [winner] = [...entries.entries()]\n .filter(([, entry]) => !entry.confirmed && isSubset(entry.payload, echo))\n .sort(([, a], [, b]) => specificity(b.payload) - specificity(a.payload));\n if (winner !== undefined) {\n const [id, entry] = winner;\n entry.timer?.();\n entry.timer = undefined;\n entry.confirmed = true;\n entry.resolved = true;\n const [first] = entry.listeners;\n entry.resolve(unsubscribe(id, first ?? (() => undefined)));\n for (const listener of confirmedListeners) {\n listener(entry.channel, entry.payload);\n }\n }\n return;\n }\n if (channel === \"error\") {\n const text = typeof data === \"string\" ? data : JSON.stringify(data);\n const [target] =\n [...entries.entries()].find(\n ([id, entry]) =>\n !entry.confirmed &&\n (text.includes(\"Already subscribed\") ||\n text.includes(\"Invalid subscription\") ||\n text.includes(idOf(entry.payload)) ||\n text.includes(id)),\n ) ?? [];\n if (target !== undefined) {\n fail(target, new TransportError(text));\n }\n return;\n }\n /* Data frames carry the subscription's channel name; several payloads can share one\n channel (the SDK's listeners filter, e.g. `e.detail.coin === coin`). */\n for (const entry of entries.values()) {\n if (entry.channel === channel && entry.confirmed) {\n // The SDK's listeners only read `e.detail` (api/subscription/_methods) — a plain\n // object stands in for the DOM CustomEvent class the type names.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const event = { detail: data } as CustomEvent<never>;\n for (const listener of entry.listeners) {\n listener(event);\n }\n }\n }\n };\n\n const core = createAppSocketCore({\n url: HYPERLIQUID_WS[options.network],\n socket: options.socket,\n setTimer: options.setTimer,\n random: options.random,\n heartbeat: {\n intervalMs: PING_MS,\n pongTimeoutMs: PONG_MS,\n ping: JSON.stringify({ method: \"ping\" }),\n isPong,\n },\n onOpen: resubscribe,\n onMessage,\n onUserClose: () => {\n for (const id of entries.keys()) {\n fail(id, new TransportError(\"the socket was closed\"));\n }\n },\n });\n\n return {\n isTestnet: options.network === \"Testnet\",\n status: core.status,\n onStatus: core.onStatus,\n onConfirmed: (listener) => {\n confirmedListeners.add(listener);\n return () => {\n confirmedListeners.delete(listener);\n };\n },\n subscribe: async <T>(\n channel: string,\n payload: unknown,\n listener: (data: CustomEvent<T>) => void,\n callOptions?: { signal?: AbortSignal; onError?: (error: TransportError) => void },\n ): Promise<ISubscription> => {\n if (core.closedByUser()) {\n throw new TransportError(\"the socket is closed\");\n }\n const id = `${channel}:${idOf(payload)}`;\n const existing = entries.get(id);\n if (existing !== undefined) {\n /* Identical payloads share one server subscription — the listener rides along and\n resolves (or rejects) with the same pending request. */\n const own: Listener = listener;\n existing.listeners.add(own);\n if (existing.confirmed) {\n return unsubscribe(id, own);\n }\n return new Promise<ISubscription>((resolve, reject) => {\n const { resolve: outerResolve, reject: outerReject } = existing;\n existing.resolve = (sub) => {\n outerResolve(sub);\n resolve(unsubscribe(id, own));\n };\n existing.reject = (error) => {\n outerReject(error);\n reject(error);\n };\n });\n }\n /* Client-side limits: ≤ 1000 subscriptions, ≤ 10 distinct users (docs rate-limits). */\n const users = new Set(\n [...entries.values()]\n .map((entry) => userOf(entry.payload))\n .filter((user): user is string => user !== undefined),\n );\n const user = userOf(payload);\n if (user !== undefined) {\n users.add(user);\n }\n if (entries.size >= MAX_SUBSCRIPTIONS) {\n throw new TransportError(\"the 1000-subscription limit is reached\");\n }\n if (users.size > MAX_USERS) {\n throw new TransportError(\"the 10-user subscription limit is reached\");\n }\n const entry: Entry = {\n channel,\n payload,\n listeners: new Set<Listener>([listener]),\n resolve: () => undefined,\n reject: () => undefined,\n ...(callOptions?.onError === undefined ? {} : { onError: callOptions.onError }),\n confirmed: false,\n resolved: false,\n };\n const promise = new Promise<ISubscription>((resolve, reject) => {\n entry.resolve = resolve;\n entry.reject = reject;\n });\n entry.timer = options.setTimer(CONFIRM_MS, () => {\n fail(id, new TransportError(\"the subscription was not confirmed within 10 s\"));\n });\n callOptions?.signal?.addEventListener(\"abort\", () => {\n fail(id, new TransportError(\"the subscription was aborted\"));\n });\n entries.set(id, entry);\n core.connect();\n if (core.readyState() === OPEN) {\n send(\"subscribe\", payload);\n }\n return promise;\n },\n close: core.close,\n };\n}\n","import type { ISubscription, TransportError } from \"@nktkas/hyperliquid\";\nimport { candleSnapshot, recentTrades } from \"@nktkas/hyperliquid/api/info\";\nimport type { CandleSnapshotResponse, RecentTradesResponse } from \"@nktkas/hyperliquid/api/info\";\n/**\n * Live Hyperliquid views over the reconnecting `HyperliquidSocket` — market reads need no unlocked\n * wallet; user views resolve the group to its owner and follow the wallet lock (a lock closes\n * them). Every view reports `LiveState`: `connecting` until the subscription confirms AND the first\n * post-confirmation snapshot is applied, `live` while streaming, `stale` on any disconnect — data\n * is kept, never presented as live. A reconnect re-confirms the subscription (the socket\n * resubscribes and fires `onConfirmed`) and the view only goes `live` again on a fresh snapshot —\n * delta channels re-fetch over HTTP, snapshot channels wait for the server's first frame.\n *\n * Message shapes follow the SDK's subscription functions (`@nktkas/hyperliquid/api/subscription`,\n * docs for-developers/api/websocket/subscriptions): `l2Book` frames are full books (`{coin, time,\n * levels:[bids,asks]}`), `trades` frames are delta arrays, `candle` frames are single candles\n * upserted by open time `t`, `clearinghouseState`/`openOrders` frames are full state, `userFills`\n * frames are `{user, fills, isSnapshot?}` — `isSnapshot` replaces, deltas append deduplicated by\n * `tid`.\n */\nimport {\n candle as subCandle,\n clearinghouseState as subClearinghouse,\n spotState as subSpotState,\n l2Book as subL2Book,\n openOrders as subOpenOrders,\n trades as subTrades,\n userFills as subUserFills,\n} from \"@nktkas/hyperliquid/api/subscription\";\nimport type {\n CandleEvent,\n L2BookEvent,\n OpenOrdersEvent,\n SpotStateEvent,\n UserFillsEvent,\n ClearinghouseStateEvent,\n CandleParameters,\n} from \"@nktkas/hyperliquid/api/subscription\";\n\nimport type { Wallet } from \"@qntx/wallet\";\n\nimport type { SetTimer } from \"../spi.ts\";\nimport type { HyperliquidGroup } from \"./agents.ts\";\nimport type { HyperliquidSocket } from \"./socket.ts\";\nimport { payloadContains } from \"./socket.ts\";\nimport type { createHyperliquidTransport } from \"./transport.ts\";\n\n/** What a live view reports — `data` is kept while `stale`, never while absent. */\nexport type LiveState<T> = {\n readonly status: \"connecting\" | \"live\" | \"stale\";\n readonly data: T | undefined;\n readonly updatedAt: number | undefined;\n};\n\nexport type LiveView<T> = {\n readonly getState: () => LiveState<T>;\n /** Listener on every state change; returns an unsubscribe. */\n readonly subscribe: (listener: (state: LiveState<T>) => void) => () => void;\n /**\n * Drops the subscription and never updates again. Market views keep their last state; account\n * views (`account`, `spotState`, `openOrders`, `fills`) report `stale` with no data.\n */\n readonly close: () => Promise<void>;\n};\n\nexport type HyperliquidLive = {\n /** Full L2 book — every `l2Book` frame is a complete snapshot and replaces `data`. */\n readonly book: (\n coin: string,\n // oxlint-disable-next-line typescript/no-restricted-types -- the SDK's parameter type is `| null`\n params?: { readonly nSigFigs?: 2 | 3 | 4 | 5 | null },\n ) => LiveView<L2BookEvent>;\n /**\n * Trades — deltas over an HTTP `recentTrades` snapshot; deltas arriving before the snapshot\n * buffer, merge/dedupe by `tid`, newest first, capped at {@link TRADES_CAP}.\n */\n readonly trades: (coin: string) => LiveView<RecentTradesResponse>;\n /** Candles — `candle` frames upserted by `t` over an HTTP `candleSnapshot` window. */\n readonly candles: (\n coin: string,\n interval: CandleParameters[\"interval\"],\n ) => LiveView<CandleSnapshotResponse>;\n /** Full margin state — every `clearinghouseState` frame replaces `data`. */\n readonly account: (group: HyperliquidGroup) => LiveView<ClearinghouseStateEvent>;\n /** Full spot state — every `spotState` frame replaces `data`. */\n readonly spotState: (group: HyperliquidGroup) => LiveView<SpotStateEvent>;\n /** Full open-orders state — every `openOrders` frame replaces `data`. */\n readonly openOrders: (group: HyperliquidGroup) => LiveView<OpenOrdersEvent>;\n /**\n * Fills — the first `userFills` frame of a (re)subscription carries `isSnapshot: true` and\n * replaces `data`; later frames append deduplicated by `tid`.\n */\n readonly fills: (group: HyperliquidGroup) => LiveView<UserFillsEvent[\"fills\"]>;\n};\n\ntype HttpTransport = ReturnType<typeof createHyperliquidTransport>;\n\nexport type HyperliquidLiveOptions = {\n readonly socket: HyperliquidSocket;\n readonly transport: HttpTransport;\n /** Resolves a group to the owner's master address. */\n readonly ownerOf: (group: HyperliquidGroup) => Promise<string>;\n readonly now: () => number;\n /** Snapshot retries run on the injected timer — a dead HTTP fetch must not stall a view. */\n readonly setTimer: SetTimer;\n /** Jitter source for the snapshot retry backoff. */\n readonly random: (length: number) => Uint8Array;\n /** Lock-following: a vault that is not `unlocked` closes every user view. */\n readonly wallet: Wallet;\n /**\n * Every `openOrders`/`userFills` frame is reported to the exchange — a pending unknown cloid the\n * frame carries is proven (resting) or re-asked (a fill cannot prove a full fill).\n */\n readonly sighted?: (user: string, entry: OpenOrdersEvent | UserFillsEvent) => void;\n};\n\nconst TRADES_CAP = 100;\nconst CANDLES_WINDOW = 200;\n/* Snapshot retry backoff — the socket's shape: 500 ms·2ⁿ capped at 30 s plus equal jitter. */\nconst SNAPSHOT_BACKOFF_MIN_MS = 500;\nconst SNAPSHOT_BACKOFF_MAX_MS = 30_000;\n\n/** Milliseconds per candle interval — the snapshot window is CANDLES_WINDOW intervals deep. */\nconst INTERVAL_MS: Record<CandleParameters[\"interval\"], number> = {\n \"1m\": 60_000,\n \"3m\": 180_000,\n \"5m\": 300_000,\n \"15m\": 900_000,\n \"30m\": 1_800_000,\n \"1h\": 3_600_000,\n \"2h\": 7_200_000,\n \"4h\": 14_400_000,\n \"8h\": 28_800_000,\n \"12h\": 43_200_000,\n \"1d\": 86_400_000,\n \"3d\": 259_200_000,\n \"1w\": 604_800_000,\n \"1M\": 2_592_000_000,\n};\n\nconst dedupeByTid = <T extends { readonly tid: number }>(list: ReadonlyArray<T>): T[] => {\n const seen = new Set<number>();\n const out: T[] = [];\n for (const item of list) {\n if (!seen.has(item.tid)) {\n seen.add(item.tid);\n out.push(item);\n }\n }\n return out;\n};\n\n/** `channel` and the subscribed-payload subset a view waits to see re-confirmed. */\nconst match =\n (channel: string, expected: unknown) =>\n (ch: string, payload: unknown): boolean =>\n ch === channel && payloadContains(expected, payload);\n\n/* A view wrapper for starts that need an async step first (owner resolution). */\nconst liveFromPromise = <T>(build: () => Promise<LiveView<T>>): LiveView<T> => {\n const listeners = new Set<(state: LiveState<T>) => void>();\n let inner: LiveView<T> | undefined;\n let innerOff: (() => void) | undefined;\n let current: LiveState<T> = { status: \"connecting\", data: undefined, updatedAt: undefined };\n let closed = false;\n const emit = (next: LiveState<T>): void => {\n current = next;\n for (const listener of listeners) {\n listener(next);\n }\n };\n const ready = (async (): Promise<void> => {\n try {\n const built = await build();\n inner = built;\n if (closed) {\n void built.close();\n return;\n }\n innerOff = built.subscribe(emit);\n emit(built.getState());\n } catch {\n emit({ status: \"stale\", data: undefined, updatedAt: undefined });\n }\n })();\n return {\n getState: () => inner?.getState() ?? current,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n close: async () => {\n if (closed) {\n return;\n }\n closed = true;\n await ready;\n innerOff?.();\n await inner?.close();\n /* A user view serves account data — once closed nothing stays readable, even while the\n inner view was still being built. */\n emit({ status: \"stale\", data: undefined, updatedAt: undefined });\n },\n };\n};\n\nexport function createHyperliquidLive(options: HyperliquidLiveOptions): HyperliquidLive {\n const { socket, transport, ownerOf, now, setTimer, random, wallet } = options;\n const jittered = (ms: number): number => ms + Math.floor(((random(1)[0] ?? 0) / 256) * ms);\n const config = { transport: socket };\n const http = { transport };\n /* Open user views — a vault lock closes them all; market views ignore it. */\n const userViews = new Set<{ close: () => Promise<void> }>();\n let walletUnsubscribe: (() => void) | undefined;\n\n const watchLock = (view: { close: () => Promise<void> }): void => {\n userViews.add(view);\n if (wallet.getSnapshot().vault !== \"unlocked\") {\n void view.close();\n }\n walletUnsubscribe ??= wallet.subscribe(() => {\n if (wallet.getSnapshot().vault !== \"unlocked\") {\n /* `close` removes the view from the set — iterate a copy. */\n // oxlint-disable-next-line unicorn/no-useless-spread -- the copy is the point.\n for (const v of [...userViews]) {\n void v.close();\n }\n }\n });\n };\n\n type SnapshotSource<T> = () => Promise<T>;\n\n /**\n * The shared skeleton: status bookkeeping, confirmed/status wiring, delta buffering while a\n * snapshot is in flight, and `close` teardown. `subscribeSocket` is the SDK call (its validation +\n * event filtering stay active); `matches` names the payload this view waits to see confirmed;\n * `snapshot` (delta channels only) fetches the window each confirmation opens.\n */\n const view = <M, T>(args: {\n readonly matches: (channel: string, payload: unknown) => boolean;\n readonly start: (\n listener: (message: M) => void,\n onError: (error: TransportError) => void,\n ) => Promise<ISubscription>;\n /** First-frame → data for snapshot channels; undefined for delta channels. */\n readonly snapshot?: SnapshotSource<T>;\n /** Merge one delta into the current data. */\n readonly delta?: (current: T | undefined, message: M) => T;\n /**\n * Push-channel reducer: returns the new data, or `undefined` to keep waiting (e.g. a\n * `userFills` frame before its `isSnapshot`).\n */\n readonly frame?: (current: T | undefined, message: M) => T | undefined;\n /** Account data: `close` clears it — a locked vault leaves nothing account-readable. */\n readonly accountData?: boolean;\n }): LiveView<T> => {\n const listeners = new Set<(state: LiveState<T>) => void>();\n let data: T | undefined;\n let updatedAt: number | undefined;\n let status: LiveState<T>[\"status\"] = \"connecting\";\n let closed = false;\n let ready = false;\n let generation = 0;\n let subscription: ISubscription | undefined;\n const buffered: M[] = [];\n\n const state = (): LiveState<T> => ({ status, data, updatedAt });\n const emit = (): void => {\n const current = state();\n for (const listener of listeners) {\n listener(current);\n }\n };\n const set = (patch: Partial<LiveState<T>>): void => {\n status = patch.status ?? status;\n if (\"data\" in patch) {\n ({ data } = patch);\n }\n if (\"updatedAt\" in patch) {\n ({ updatedAt } = patch);\n }\n emit();\n };\n\n /* Post-confirmation: a delta view fetches its window; a snapshot view waits for the first\n frame. Either way `ready` only flips when fresh data is applied. */\n const onConfirmed = async (): Promise<void> => {\n const gen = ++generation;\n ready = false;\n buffered.length = 0;\n set({ status: \"connecting\" });\n if (args.snapshot === undefined) {\n return;\n }\n /* A failed fetch must not stall the view until the next reconnect — retry on the\n injected timer with the socket's backoff shape, generation-checked. */\n let snap: T | undefined;\n /* oxlint-disable eslint/no-await-in-loop -- retries are sequential by design. */\n for (let attempt = 0; snap === undefined; attempt += 1) {\n try {\n snap = await args.snapshot();\n } catch {\n if (closed || gen !== generation) {\n return;\n }\n const backoff = Math.min(SNAPSHOT_BACKOFF_MAX_MS, SNAPSHOT_BACKOFF_MIN_MS * 2 ** attempt);\n await new Promise<void>((resolve) => {\n setTimer(jittered(backoff), resolve);\n });\n }\n if (closed || gen !== generation) {\n return;\n }\n }\n if (closed || gen !== generation) {\n return;\n }\n let acc: T = snap;\n for (const message of buffered.splice(0)) {\n if (args.delta !== undefined) {\n acc = args.delta(acc, message);\n }\n }\n ready = true;\n set({ status: \"live\", data: acc, updatedAt: now() });\n };\n\n const onMessage = (message: M): void => {\n if (closed) {\n return;\n }\n if (args.snapshot !== undefined) {\n if (!ready) {\n buffered.push(message);\n return;\n }\n if (args.delta !== undefined) {\n set({ data: args.delta(data, message), updatedAt: now() });\n }\n return;\n }\n if (args.frame === undefined) {\n return;\n }\n const next = args.frame(data, message);\n if (next !== undefined) {\n ready = true;\n set({ status: \"live\", data: next, updatedAt: now() });\n }\n };\n\n const offConfirmed = socket.onConfirmed((channel, payload) => {\n if (!closed && args.matches(channel, payload)) {\n void onConfirmed();\n }\n });\n const offStatus = socket.onStatus((next) => {\n if (closed) {\n return;\n }\n if (next === \"closed\") {\n ready = false;\n set({ status: \"stale\" });\n }\n });\n const onError = (): void => {\n ready = false;\n set({ status: \"stale\" });\n };\n const started = (async (): Promise<void> => {\n try {\n subscription = await args.start(onMessage, onError);\n } catch {\n ready = false;\n set({ status: \"stale\" });\n }\n })();\n\n return {\n getState: state,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n close: async () => {\n if (closed) {\n return;\n }\n closed = true;\n offConfirmed();\n offStatus();\n await started;\n await subscription?.unsubscribe();\n if (args.accountData === true) {\n set({ status: \"stale\", data: undefined, updatedAt: undefined });\n } else if (status !== \"stale\") {\n set({ status: \"stale\" });\n }\n },\n };\n };\n\n const userView = <T>(\n build: (user: string) => LiveView<T>,\n group: HyperliquidGroup,\n ): LiveView<T> => {\n /* The group resolves to its owner before subscribing; the view follows the lock. */\n const inner = liveFromPromise<T>(async () => build(await ownerOf(group)));\n const view: LiveView<T> = {\n getState: () => inner.getState(),\n subscribe: (listener) => inner.subscribe(listener),\n /* A closed user view leaves the lock set — a later lock has nothing left to close. */\n close: async () => {\n userViews.delete(view);\n await inner.close();\n },\n };\n watchLock(view);\n return view;\n };\n\n return {\n book: (coin, params) =>\n view<L2BookEvent, L2BookEvent>({\n matches: match(\"l2Book\", {\n type: \"l2Book\",\n coin,\n ...(params?.nSigFigs === undefined ? {} : { nSigFigs: params.nSigFigs }),\n }),\n start: async (listener, onError) =>\n subL2Book(\n config,\n { coin, ...(params?.nSigFigs === undefined ? {} : { nSigFigs: params.nSigFigs }) },\n listener,\n { onError },\n ),\n frame: (_current, message) => message,\n }),\n trades: (coin) =>\n view<RecentTradesResponse[number], RecentTradesResponse>({\n matches: match(\"trades\", { type: \"trades\", coin }),\n start: async (listener, onError) =>\n subTrades(\n config,\n { coin },\n (tradesEvent) => {\n for (const trade of tradesEvent) {\n listener(trade);\n }\n },\n { onError },\n ),\n snapshot: async () => dedupeByTid(await recentTrades(http, { coin })).slice(0, TRADES_CAP),\n delta: (current, message) =>\n dedupeByTid([message, ...(current ?? [])]).slice(0, TRADES_CAP),\n }),\n candles: (coin, interval) =>\n view<CandleEvent, CandleSnapshotResponse>({\n matches: match(\"candle\", { type: \"candle\", coin, interval }),\n start: async (listener, onError) =>\n subCandle(config, { coin, interval }, listener, { onError }),\n snapshot: async () => {\n const endTime = now();\n return candleSnapshot(http, {\n coin,\n interval,\n startTime: Math.max(0, endTime - INTERVAL_MS[interval] * CANDLES_WINDOW),\n endTime,\n });\n },\n delta: (current, message) => {\n const rest = (current ?? []).filter((c) => c.t !== message.t);\n return [...rest, message].sort((a, b) => a.t - b.t);\n },\n }),\n account: (group) =>\n userView(\n (user) =>\n view<ClearinghouseStateEvent, ClearinghouseStateEvent>({\n matches: match(\"clearinghouseState\", { type: \"clearinghouseState\", user }),\n start: async (listener, onError) =>\n subClearinghouse(config, { user }, listener, { onError }),\n frame: (_current, message) => message,\n accountData: true,\n }),\n group,\n ),\n spotState: (group) =>\n userView(\n (user) =>\n view<SpotStateEvent, SpotStateEvent>({\n matches: match(\"spotState\", { type: \"spotState\", user }),\n start: async (listener, onError) =>\n subSpotState(config, { user }, listener, { onError }),\n frame: (_current, message) => message,\n accountData: true,\n }),\n group,\n ),\n openOrders: (group) =>\n userView(\n (user) =>\n view<OpenOrdersEvent, OpenOrdersEvent>({\n matches: match(\"openOrders\", { type: \"openOrders\", user }),\n start: async (listener, onError) =>\n subOpenOrders(config, { user }, listener, { onError }),\n frame: (_current, message) => {\n options.sighted?.(user, message);\n return message;\n },\n accountData: true,\n }),\n group,\n ),\n fills: (group) =>\n userView(\n (user) =>\n view<UserFillsEvent, UserFillsEvent[\"fills\"]>({\n matches: match(\"userFills\", { type: \"userFills\", user }),\n start: async (listener, onError) =>\n subUserFills(config, { user }, listener, { onError }),\n frame: (current, message) => {\n options.sighted?.(user, message);\n /* The server re-sends `isSnapshot` on resubscribe — it replaces. */\n if (message.isSnapshot === true) {\n return dedupeByTid(message.fills);\n }\n if (current === undefined) {\n return undefined; // keep waiting for the snapshot frame\n }\n return dedupeByTid([...message.fills, ...current]);\n },\n accountData: true,\n }),\n group,\n ),\n };\n}\n","import {\n allMids,\n candleSnapshot,\n fundingHistory,\n l2Book,\n metaAndAssetCtxs,\n predictedFundings,\n recentTrades,\n spotMetaAndAssetCtxs,\n} from \"@nktkas/hyperliquid/api/info\";\nimport type {\n AllMidsParameters,\n AllMidsResponse,\n CandleSnapshotParameters,\n CandleSnapshotResponse,\n FundingHistoryParameters,\n FundingHistoryResponse,\n InfoConfig,\n L2BookParameters,\n L2BookResponse,\n MetaAndAssetCtxsParameters,\n MetaAndAssetCtxsResponse,\n PredictedFundingsResponse,\n RecentTradesParameters,\n RecentTradesResponse,\n SpotMetaAndAssetCtxsResponse,\n} from \"@nktkas/hyperliquid/api/info\";\n\n/**\n * Market data reads over the injected transport — thin pass-throughs to the SDK request functions\n * so response validation, parameter schemas and return types stay the SDK's.\n */\nexport type HyperliquidMarkets = {\n /** Perpetual universe and per-asset contexts (mark price, funding, open interest). */\n readonly perps: (params?: MetaAndAssetCtxsParameters) => Promise<MetaAndAssetCtxsResponse>;\n /** Spot universe and per-token contexts. */\n readonly spot: () => Promise<SpotMetaAndAssetCtxsResponse>;\n /** The level-2 book snapshot for one coin. */\n readonly book: (params: L2BookParameters) => Promise<L2BookResponse>;\n /** Candles for one coin and interval over `[startTime, endTime)`. */\n readonly candles: (params: CandleSnapshotParameters) => Promise<CandleSnapshotResponse>;\n /** The most recent trades for one coin. */\n readonly trades: (params: RecentTradesParameters) => Promise<RecentTradesResponse>;\n /** Historical funding rates for one coin over `[startTime, endTime)`. */\n readonly fundingHistory: (params: FundingHistoryParameters) => Promise<FundingHistoryResponse>;\n /** Predicted funding for the next interval across all coins. */\n readonly predictedFundings: () => Promise<PredictedFundingsResponse>;\n /** All mid prices, optionally for one DEX. */\n readonly mids: (params?: AllMidsParameters) => Promise<AllMidsResponse>;\n};\n\nexport type {\n AllMidsResponse,\n CandleSnapshotResponse,\n FundingHistoryResponse,\n L2BookResponse,\n MetaAndAssetCtxsResponse,\n PredictedFundingsResponse,\n RecentTradesResponse,\n SpotMetaAndAssetCtxsResponse,\n} from \"@nktkas/hyperliquid/api/info\";\n\nexport function createHyperliquidMarkets(config: InfoConfig): HyperliquidMarkets {\n return {\n perps: async (params) => metaAndAssetCtxs(config, params ?? {}),\n spot: async () => spotMetaAndAssetCtxs(config),\n book: async (params) => l2Book(config, params),\n candles: async (params) => candleSnapshot(config, params),\n trades: async (params) => recentTrades(config, params),\n fundingHistory: async (params) => fundingHistory(config, params),\n predictedFundings: async () => predictedFundings(config),\n mids: async (params) => allMids(config, params ?? {}),\n };\n}\n","import { parseDecimal } from \"../spi.ts\";\nimport type { HyperliquidAccount } from \"./account.ts\";\nimport { deepFreeze } from \"./actions.ts\";\nimport type {\n HyperliquidActions,\n HyperliquidModifyParams,\n HyperliquidOrderParams,\n} from \"./actions.ts\";\nimport type { HyperliquidGroup, HyperliquidAgentRegistry } from \"./agents.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\nimport type {\n HyperliquidActionOutcome,\n HyperliquidCancelOutcome,\n HyperliquidExchange,\n HyperliquidOrderOutcome,\n HyperliquidOutcomeCorrection,\n} from \"./exchange.ts\";\n\n/** `place`/`close` results: the order outcomes plus the entry cap to show the user. */\nexport type HyperliquidPlaceResult = {\n readonly outcomes: ReadonlyArray<HyperliquidOrderOutcome>;\n /** The entry order's wire price — for a market order or close, the slippage cap. */\n readonly price: string;\n};\n\nexport type HyperliquidTrade = {\n /** Place one order — entry plus optional attached TP/SL children. */\n readonly place: (\n group: HyperliquidGroup,\n params: HyperliquidOrderParams,\n ) => Promise<HyperliquidPlaceResult>;\n /** Replace a resting order by oid or cloid. */\n readonly modify: (\n group: HyperliquidGroup,\n params: { readonly oid: number | string } & HyperliquidModifyParams,\n ) => Promise<HyperliquidActionOutcome>;\n /** Replace many resting orders in one signed action. */\n readonly batchModify: (\n group: HyperliquidGroup,\n modifies: ReadonlyArray<{ readonly oid: number | string } & HyperliquidModifyParams>,\n ) => Promise<ReadonlyArray<HyperliquidOrderOutcome>>;\n /** Cancel open orders by oid. */\n readonly cancel: (\n group: HyperliquidGroup,\n cancels: ReadonlyArray<{ readonly coin: string; readonly oid: number }>,\n ) => Promise<ReadonlyArray<HyperliquidCancelOutcome>>;\n /** Cancel open orders by cloid. */\n readonly cancelByCloid: (\n group: HyperliquidGroup,\n cancels: ReadonlyArray<{ readonly coin: string; readonly cloid: string }>,\n ) => Promise<ReadonlyArray<HyperliquidCancelOutcome>>;\n /** Cancel every open order of the account — one batch action per ≤64-order chunk. */\n readonly cancelAll: (group: HyperliquidGroup) => Promise<ReadonlyArray<HyperliquidCancelOutcome>>;\n /**\n * Stop a running TWAP — starting one needs no price-less action the kernel could not meter, so it\n * is not offered.\n */\n readonly twapCancel: (\n group: HyperliquidGroup,\n params: { readonly coin: string; readonly twapId: number },\n ) => Promise<HyperliquidActionOutcome>;\n /** Set cross or isolated leverage within the market's maximum. */\n readonly setLeverage: (\n group: HyperliquidGroup,\n params: {\n readonly coin: string;\n readonly leverage: number;\n readonly marginMode: \"cross\" | \"isolated\";\n },\n ) => Promise<HyperliquidActionOutcome>;\n /** Add to (positive) or remove from (negative) an isolated position's margin, in USD. */\n readonly adjustMargin: (\n group: HyperliquidGroup,\n params: { readonly coin: string; readonly amount: string },\n ) => Promise<HyperliquidActionOutcome>;\n /** Market-close the whole position of `coin` — reduce-only IOC at the slippage cap. */\n readonly close: (\n group: HyperliquidGroup,\n params: { readonly coin: string; readonly slippageBps: number },\n ) => Promise<HyperliquidPlaceResult>;\n /**\n * Corrections for orders whose outcome was `unknown`: the exchange re-asks them by cloid for ten\n * minutes after the call returned and learns others from live user-view frames. Nothing is ever\n * re-sent.\n */\n readonly corrections: {\n readonly subscribe: (\n listener: (correction: HyperliquidOutcomeCorrection) => void,\n ) => () => void;\n };\n};\n\nexport function createHyperliquidTrade(options: {\n readonly actions: HyperliquidActions;\n readonly exchange: HyperliquidExchange;\n readonly account: HyperliquidAccount;\n readonly registry: HyperliquidAgentRegistry;\n /**\n * The builder the controller confirmed for this group — `order` actions carry `builder: {b, f}`\n * only while this returns one; never above the confirmed maximum.\n */\n readonly builderFor?: (\n group: HyperliquidGroup,\n ) => { readonly address: string; readonly feeRateTenthsBps: number } | undefined;\n}): HyperliquidTrade {\n const place = async (\n group: HyperliquidGroup,\n params: HyperliquidOrderParams,\n ): Promise<HyperliquidPlaceResult> => {\n const built = await options.actions.place(params);\n const builder = options.builderFor?.(group);\n const action =\n builder === undefined\n ? built.action\n : deepFreeze({\n ...built.action,\n builder: { b: builder.address.toLowerCase(), f: builder.feeRateTenthsBps },\n });\n return {\n outcomes: await options.exchange.order(group, action),\n price: built.price,\n };\n };\n\n return {\n place,\n modify: async (group, params) =>\n options.exchange.action(group, await options.actions.modify(params)),\n batchModify: async (group, modifies) =>\n options.exchange.order(group, await options.actions.batchModify(modifies)),\n cancel: async (group, cancels) =>\n options.exchange.cancel(group, await options.actions.cancel(cancels)),\n cancelByCloid: async (group, cancels) =>\n options.exchange.cancel(group, await options.actions.cancelByCloid(cancels)),\n cancelAll: async (group) => {\n const { owner } = options.registry.require(group);\n const open = await options.account.openOrders({ user: owner });\n const entries = [];\n for (const order of open) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- meta resolves from cache after the first.\n const asset = await options.actions.resolve(order.coin);\n entries.push({ a: asset.asset, o: order.oid });\n }\n const outcomes: HyperliquidCancelOutcome[] = [];\n for (const batch of options.actions.cancelBatches(entries)) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential posts keep nonce order simple.\n outcomes.push(...(await options.exchange.cancel(group, batch)));\n }\n return outcomes;\n },\n twapCancel: async (group, params) =>\n options.exchange.action(group, await options.actions.twapCancel(params)),\n setLeverage: async (group, params) =>\n options.exchange.action(group, await options.actions.setLeverage(params)),\n adjustMargin: async (group, params) =>\n options.exchange.action(group, await options.actions.adjustMargin(params)),\n close: async (group, params) => {\n const { owner } = options.registry.require(group);\n const state = await options.account.state({ user: owner });\n const position = state.assetPositions.find((entry) => entry.position.coin === params.coin);\n const szi = position === undefined ? undefined : position.position.szi;\n if (szi === undefined || parseDecimal(szi).units === 0n) {\n throw new HyperliquidError(\"invalid-input\", `no open position in ${params.coin}`);\n }\n return place(group, {\n coin: params.coin,\n side: szi.startsWith(\"-\") ? \"buy\" : \"sell\",\n size: szi.replace(/^-/, \"\"),\n reduceOnly: true,\n order: { kind: \"market\", slippageBps: params.slippageBps },\n });\n },\n corrections: options.exchange.corrections,\n };\n}\n","import type { IRequestTransport } from \"@nktkas/hyperliquid\";\n\nimport type { HyperliquidNetwork } from \"@qntx/wallet/protocol\";\n\nimport { timeoutSignal } from \"../spi.ts\";\nimport type { SetTimer } from \"../spi.ts\";\nimport type { HyperliquidClock } from \"./clock.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\n\nexport const REQUEST_TIMEOUT_MS = 10_000;\n\nconst BASE_URL: Readonly<Record<HyperliquidNetwork, string>> = {\n Mainnet: \"https://api.hyperliquid.xyz\",\n Testnet: \"https://api.hyperliquid-testnet.xyz\",\n};\n\nexport type HyperliquidTransportOptions = {\n readonly network: HyperliquidNetwork;\n readonly fetch: typeof globalThis.fetch;\n readonly setTimer: SetTimer;\n readonly now: () => number;\n readonly clock: HyperliquidClock;\n readonly timeoutMs?: number;\n};\n\n/**\n * The SDK `IRequestTransport` over the injected `fetch` — never the global one — with a timeout on\n * the injected timer. Every response's `Date` header feeds the clock. A deadline miss surfaces as\n * `HyperliquidError(\"timeout\")`, never a generic network error: an /exchange post that timed out\n * may still have committed.\n */\nexport function createHyperliquidTransport(\n options: HyperliquidTransportOptions,\n): IRequestTransport {\n const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;\n const base = BASE_URL[options.network];\n return {\n isTestnet: options.network === \"Testnet\",\n request: async <T>(endpoint: \"info\" | \"exchange\", payload: unknown, signal?: AbortSignal) => {\n const requestStart = options.now();\n const bound = timeoutSignal(timeoutMs, options.setTimer);\n let callerAborted = false;\n const onAbort = (): void => {\n callerAborted = true;\n bound.abort();\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const response = await options.fetch(`${base}/${endpoint}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(payload),\n signal: bound.signal,\n });\n const date = response.headers.get(\"date\");\n if (date !== null) {\n const serverMs = Date.parse(date);\n if (!Number.isNaN(serverMs)) {\n options.clock.record(serverMs, requestStart, options.now());\n }\n }\n if (!response.ok) {\n throw new HyperliquidError(\n \"unavailable\",\n `POST /${endpoint} answered ${response.status}`,\n );\n }\n try {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- IRequestTransport<T> delegates validation to the SDK caller's schema\n return (await response.json()) as T;\n } catch (error) {\n throw new HyperliquidError(\"network\", `POST /${endpoint} answered non-JSON`, error);\n }\n } catch (error) {\n if (error instanceof HyperliquidError) {\n throw error;\n }\n if (bound.signal.aborted && !callerAborted) {\n throw new HyperliquidError(\"timeout\", `POST /${endpoint} timed out`, error);\n }\n throw new HyperliquidError(\"network\", `POST /${endpoint} failed`, error);\n } finally {\n bound.cancel();\n signal?.removeEventListener(\"abort\", onAbort);\n }\n },\n };\n}\n","import type { IRequestTransport } from \"@nktkas/hyperliquid\";\n/**\n * Hyperliquid user-signed actions: EIP-712 documents the account owner signs itself (no agent key)\n * under the `HyperliquidSignTransaction` domain. The typed-data shape is exact — the kernel's\n * recognizer (`wallet-chains/evm/hyperliquid.ts`) describes each document only when the type field\n * list is verbatim, so the approval UI shows the real action instead of a blind payload.\n *\n * The EIP-712 field lists come from the SDK's own `…Types` constants — if the SDK's list changes,\n * the import resolves but the recognizer's `sameFields` check fails, surfacing as a blind payload\n * instead of a wrong signature.\n */\nimport {\n ApproveAgentTypes,\n ApproveBuilderFeeTypes,\n SpotSendTypes,\n UsdClassTransferTypes,\n UsdSendTypes,\n Withdraw3Types,\n} from \"@nktkas/hyperliquid/api/exchange\";\n\nimport type { HyperliquidNetwork } from \"@qntx/wallet/protocol\";\n\nimport { RequestEndedError } from \"../spi.ts\";\nimport type { AppRequests, SignatureResult } from \"../spi.ts\";\nimport type { HyperliquidAccount } from \"./account.ts\";\nimport type { HyperliquidGroup } from \"./agents.ts\";\nimport type { HyperliquidClock } from \"./clock.ts\";\nimport { HyperliquidError } from \"./errors.ts\";\nimport type { HyperliquidActionOutcome } from \"./exchange.ts\";\nimport type { HyperliquidMarkets } from \"./markets.ts\";\n\n/** The chain ids the user-signed domain commits to (design §2 — the signature chain). */\nconst CHAIN = {\n Mainnet: { id: 42161, caip: \"eip155:42161\", signatureChainId: \"0xa4b1\" },\n Testnet: { id: 421614, caip: \"eip155:421614\", signatureChainId: \"0x66eee\" },\n} as const satisfies Record<\n HyperliquidNetwork,\n { id: number; caip: string; signatureChainId: `0x${string}` }\n>;\n\nconst EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst ZERO_ADDRESS = \"0x0000000000000000000000000000000000000000\";\n\ntype TypedFields = ReadonlyArray<{ readonly name: string; readonly type: string }>;\n\n/** A user-signed action waiting on approval — the host presents `requestId`'s prompt. */\nexport type HyperliquidPendingAction = {\n /** The approval request the host shows; the prompt is the kernel-described typed data. */\n readonly requestId: string;\n /**\n * Resolves once the approval resolved and the signed action was posted: `ok`, or `unknown` when\n * the POST's outcome is unknowable (the action may have committed — refresh the account). Rejects\n * with `approval-rejected` when the request is refused/expired and `rejected` when Hyperliquid\n * answers `status: \"err\"`.\n */\n readonly outcome: Promise<HyperliquidActionOutcome>;\n};\n\nexport type HyperliquidUserSigned = {\n /**\n * Register an agent key under `agentName` — the kernel binds validity by signing `\"<name>\n * valid_until <ms>\"` in the `agentName` field (docs §Approve an API wallet). `agentName` here is\n * that full signed string.\n */\n readonly approveAgent: (\n group: HyperliquidGroup,\n params: { readonly agentAddress: string; readonly agentName: string },\n ) => Promise<HyperliquidPendingAction>;\n /** Approve a builder's fee rate — `maxFeeRate` is the canonical percent string (\"0.01%\"). */\n readonly approveBuilderFee: (\n group: HyperliquidGroup,\n params: { readonly builder: string; readonly maxFeeRate: string },\n ) => Promise<HyperliquidPendingAction>;\n /** Move quote balance between the perp and spot accounts of the same owner. */\n readonly usdClassTransfer: (\n group: HyperliquidGroup,\n params: { readonly amount: string; readonly toPerp: boolean },\n ) => Promise<HyperliquidPendingAction>;\n /** Send perp-account USDC to another address (`destination` lowercased). */\n readonly usdSend: (\n group: HyperliquidGroup,\n params: { readonly destination: string; readonly amount: string },\n ) => Promise<HyperliquidPendingAction>;\n /** Send a spot balance — `token` is the `\"NAME:0x<id>\"` pair id (docs §Send Asset). */\n readonly spotSend: (\n group: HyperliquidGroup,\n params: { readonly destination: string; readonly token: string; readonly amount: string },\n ) => Promise<HyperliquidPendingAction>;\n /** Withdraw USDC to the owner's Arbitrum address — the 1 USDC fee applies at the bridge. */\n readonly withdraw: (\n group: HyperliquidGroup,\n params: { readonly destination: string; readonly amount: string },\n ) => Promise<HyperliquidPendingAction>;\n};\n\nexport type HyperliquidUserSignedOptions = {\n readonly requests: AppRequests;\n readonly transport: IRequestTransport;\n readonly clock: HyperliquidClock;\n readonly markets: HyperliquidMarkets;\n readonly account: HyperliquidAccount;\n /** The owner's lowercase address — needed for the per-signer nonce counter. */\n readonly ownerOf: (group: HyperliquidGroup) => Promise<string>;\n readonly network: HyperliquidNetwork;\n readonly now: () => number;\n};\n\nconst accountRef = (group: HyperliquidGroup) => ({\n kind: \"hd\" as const,\n walletId: group.walletId,\n groupIndex: group.groupIndex,\n template: \"evm.bip44\" as const,\n});\n\n/** The kernel's 65-byte r‖s‖v → Hyperliquid's `{r, s, v}` (v already 27/28). */\nconst signatureOf = (result: SignatureResult): { r: string; s: string; v: number } => {\n const bytes = result.signature;\n if (bytes.length !== 65) {\n throw new HyperliquidError(\"unavailable\", \"the kernel returned a malformed signature\");\n }\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return { r: `0x${hex.slice(0, 64)}`, s: `0x${hex.slice(64, 128)}`, v: bytes[64] ?? 27 };\n};\n\n/** The `/exchange` envelope's `status`/`response` fields without asserting the body. */\nconst fieldOf = (body: unknown, field: \"status\" | \"response\"): unknown => {\n if (typeof body !== \"object\" || body === null) {\n return undefined;\n }\n return field === \"status\"\n ? \"status\" in body\n ? body.status\n : undefined\n : \"response\" in body\n ? body.response\n : undefined;\n};\n\nexport function createHyperliquidUserSigned(\n options: HyperliquidUserSignedOptions,\n): HyperliquidUserSigned {\n const chain = CHAIN[options.network];\n\n const assertClock = async (): Promise<void> => {\n if (options.clock.skew() === undefined) {\n await options.markets.mids();\n }\n options.clock.assertSkew();\n };\n\n /**\n * Build the document, open the request, and return `{requestId, outcome}` — the outcome waits for\n * the approval, posts the action, and maps the answer. A lost POST is `unknown`: user-signed\n * actions have no cloid to reconcile by and are never re-posted.\n */\n const send = async (\n group: HyperliquidGroup,\n doc: {\n readonly type: string;\n readonly types: TypedFields;\n readonly primaryType: string;\n readonly fields: Record<string, unknown>;\n readonly nonceField: \"nonce\" | \"time\";\n },\n ): Promise<HyperliquidPendingAction> => {\n await assertClock();\n const owner = await options.ownerOf(group);\n const nonce = options.clock.nextNonce(owner);\n const message = {\n hyperliquidChain: options.network,\n ...doc.fields,\n [doc.nonceField]: nonce,\n };\n const typedData = JSON.stringify({\n types: { EIP712Domain: EIP712_DOMAIN, [doc.primaryType]: doc.types },\n primaryType: doc.primaryType,\n domain: {\n name: \"HyperliquidSignTransaction\",\n version: \"1\",\n chainId: chain.id,\n verifyingContract: ZERO_ADDRESS,\n },\n message,\n });\n const pending = await options.requests.prepare({\n method: \"evm-sign\",\n account: accountRef(group),\n network: chain.caip,\n request: {\n kind: \"evm.typed-data\",\n network: chain.caip,\n account: accountRef(group),\n typedData,\n },\n });\n const action = {\n type: doc.type,\n signatureChainId: chain.signatureChainId,\n hyperliquidChain: options.network,\n ...doc.fields,\n [doc.nonceField]: nonce,\n };\n const outcome = (async (): Promise<HyperliquidActionOutcome> => {\n /* Pre-POST failures are real errors: a refused/expired request is `approval-rejected`, a\n malformed result is `unavailable`. Only what the POST leaves behind is `unknown`. */\n let signature: ReturnType<typeof signatureOf>;\n try {\n const result = await options.requests.outcome(pending.id);\n if (\n !(\"kind\" in result) ||\n (result.kind !== \"evm.typed-data\" && result.kind !== \"evm.personal-message\")\n ) {\n throw new HyperliquidError(\"unavailable\", \"the request resolved without a signature\");\n }\n signature = signatureOf(result);\n } catch (error) {\n if (error instanceof RequestEndedError) {\n throw new HyperliquidError(\"approval-rejected\", `the request was ${error.stage}`, error);\n }\n throw error;\n }\n try {\n // The envelope nonce equals the action's nonce/time — the docs require they match.\n const body = await options.transport.request(\"exchange\", { action, nonce, signature });\n const status = fieldOf(body, \"status\");\n if (status === \"ok\") {\n return { kind: \"ok\" };\n }\n if (status === \"err\") {\n const response = fieldOf(body, \"response\");\n throw new HyperliquidError(\n \"rejected\",\n typeof response === \"string\" ? response : \"Hyperliquid rejected the action\",\n );\n }\n /* A malformed answer may have committed — unknown, never rejected. */\n return { kind: \"unknown\" };\n } catch (error) {\n /* A non-2xx, a network error or a timeout may have committed; `rejected` is the only\n outcome that definitively failed. */\n if (error instanceof HyperliquidError && error.category === \"rejected\") {\n throw error;\n }\n return { kind: \"unknown\" };\n }\n })();\n /* The flow awaits `outcome` after `send` returns — mark it handled so a rejection that\n lands in between is not an unhandled rejection. */\n void (async () => {\n try {\n await outcome;\n } catch {\n // The consumer's own await still sees the rejection — this only marks it handled.\n }\n })();\n return { requestId: pending.id, outcome };\n };\n\n return {\n approveAgent: async (group, { agentAddress, agentName }) =>\n send(group, {\n type: \"approveAgent\",\n types: ApproveAgentTypes[\"HyperliquidTransaction:ApproveAgent\"],\n primaryType: \"HyperliquidTransaction:ApproveAgent\",\n fields: { agentAddress: agentAddress.toLowerCase(), agentName },\n nonceField: \"nonce\",\n }),\n approveBuilderFee: async (group, { builder, maxFeeRate }) =>\n send(group, {\n type: \"approveBuilderFee\",\n types: ApproveBuilderFeeTypes[\"HyperliquidTransaction:ApproveBuilderFee\"],\n primaryType: \"HyperliquidTransaction:ApproveBuilderFee\",\n fields: { maxFeeRate, builder: builder.toLowerCase() },\n nonceField: \"nonce\",\n }),\n usdClassTransfer: async (group, { amount, toPerp }) =>\n send(group, {\n type: \"usdClassTransfer\",\n types: UsdClassTransferTypes[\"HyperliquidTransaction:UsdClassTransfer\"],\n primaryType: \"HyperliquidTransaction:UsdClassTransfer\",\n fields: { amount, toPerp },\n nonceField: \"nonce\",\n }),\n usdSend: async (group, { destination, amount }) =>\n send(group, {\n type: \"usdSend\",\n types: UsdSendTypes[\"HyperliquidTransaction:UsdSend\"],\n primaryType: \"HyperliquidTransaction:UsdSend\",\n fields: { destination: destination.toLowerCase(), amount },\n nonceField: \"time\",\n }),\n spotSend: async (group, { destination, token, amount }) =>\n send(group, {\n type: \"spotSend\",\n types: SpotSendTypes[\"HyperliquidTransaction:SpotSend\"],\n primaryType: \"HyperliquidTransaction:SpotSend\",\n fields: { destination: destination.toLowerCase(), token, amount },\n nonceField: \"time\",\n }),\n withdraw: async (group, { destination, amount }) =>\n send(group, {\n type: \"withdraw3\",\n types: Withdraw3Types[\"HyperliquidTransaction:Withdraw\"],\n primaryType: \"HyperliquidTransaction:Withdraw\",\n fields: { destination: destination.toLowerCase(), amount },\n nonceField: \"time\",\n }),\n };\n}\n","import type { PublicClient } from \"viem\";\n\nimport { WalletError } from \"@qntx/wallet\";\nimport type { VerifyFactor, Wallet } from \"@qntx/wallet\";\nimport type { ChainsApi } from \"@qntx/wallet/chains\";\nimport { sessions } from \"@qntx/wallet/sessions\";\n\nimport { RequestEndedError } from \"../spi.ts\";\nimport type { AppRequests, EngineLogger, EvmFeeTier } from \"../spi.ts\";\nimport { createHyperliquidAccount } from \"./account.ts\";\nimport type { HyperliquidAccount } from \"./account.ts\";\nimport { createHyperliquidActions } from \"./actions.ts\";\nimport { createHyperliquidAgentRegistry } from \"./agents.ts\";\nimport type { HyperliquidAgentRegistry, HyperliquidGroup } from \"./agents.ts\";\nimport { createHyperliquidClock } from \"./clock.ts\";\nimport type { HyperliquidClock } from \"./clock.ts\";\nimport { HyperliquidError, SESSION_ERRORS } from \"./errors.ts\";\nimport { createHyperliquidExchange } from \"./exchange.ts\";\nimport { createHyperliquidLive } from \"./live.ts\";\nimport type { HyperliquidLive } from \"./live.ts\";\nimport { createHyperliquidMarkets } from \"./markets.ts\";\nimport type { HyperliquidMarkets } from \"./markets.ts\";\nimport { limitPrice, meetsMinimum, notional, roundSize, slippagePrice } from \"./numbers.ts\";\nimport type { HyperliquidMarket, OrderSide } from \"./numbers.ts\";\nimport type { HyperliquidSocket } from \"./socket.ts\";\nimport { createHyperliquidTrade } from \"./trade.ts\";\nimport type { HyperliquidTrade } from \"./trade.ts\";\nimport { createHyperliquidTransport } from \"./transport.ts\";\nimport type { HyperliquidTransportOptions } from \"./transport.ts\";\nimport { createHyperliquidUserSigned } from \"./user-signed.ts\";\nimport type { HyperliquidPendingAction, HyperliquidUserSigned } from \"./user-signed.ts\";\n\n/** What a quote preview shows the interface: the wire-ready order and its value checks. */\nexport type HyperliquidQuotePreview = {\n /** The rounded price that would go on the wire (for a market order, the slippage cap). */\n readonly price: string;\n /** The rounded size that would go on the wire. */\n readonly size: string;\n /** `price` × `size` exactly. */\n readonly notional: string;\n /** Whether the order clears Hyperliquid's 10-quote minimum. */\n readonly meetsMinimum: boolean;\n};\n\n/** Pure order preview helpers — no I/O, safe to call on every render. */\nexport type HyperliquidQuote = {\n /** Preview a limit order: price rounded the user's way (buy down, sell up). */\n readonly limit: (params: {\n readonly price: string;\n readonly size: string;\n readonly side: OrderSide;\n readonly szDecimals: number;\n readonly market: HyperliquidMarket;\n }) => HyperliquidQuotePreview;\n /** Preview a market order: the IOC cap at `slippageBps` from `reference`. */\n readonly market: (params: {\n readonly reference: string;\n readonly size: string;\n readonly side: OrderSide;\n readonly slippageBps: number;\n readonly szDecimals: number;\n readonly market: HyperliquidMarket;\n }) => HyperliquidQuotePreview;\n};\n\nexport type HyperliquidProvider = {\n readonly markets: HyperliquidMarkets;\n readonly account: HyperliquidAccount;\n readonly quote: HyperliquidQuote;\n /** The skew/nonce clock the transport feeds — exposed so callers can gate signing on it. */\n readonly clock: HyperliquidClock;\n /**\n * Ask an enabled group for the builder fee approval it declined or never gave — `invalid-input`\n * while the group is not `enabled` or no builder is configured.\n */\n readonly approveBuilder: (group: HyperliquidGroup) => Promise<void>;\n /**\n * Re-approves the group's enabled agent in the kernel after a lock: the kernel shows the\n * session's limits and remaining budget in its verification prompt and the session signs again\n * until the next lock. Trading answers `reopen-required` while the session is unopened.\n */\n readonly reopen: (group: HyperliquidGroup, verify: VerifyFactor) => Promise<void>;\n /**\n * L1 trading: every method signs the exact action it posts through `sessions(wallet).sign` with\n * the group's enabled, owner-verified agent, and reconciles an unknown order outcome by cloid.\n */\n readonly trade: HyperliquidTrade;\n /** Funding moves on the signature chain: the CCTP deposit into Hyperliquid. */\n readonly fund: HyperliquidFund;\n /**\n * Move balances the user-signed way — every method opens an approval request and posts the action\n * once the signature resolves.\n */\n readonly transfer: {\n /** Perp-account USDC → spot account of the same owner. */\n readonly toSpot: (group: HyperliquidGroup, amount: string) => Promise<HyperliquidPendingAction>;\n /** Spot-account USDC → perp account of the same owner. */\n readonly toPerp: (group: HyperliquidGroup, amount: string) => Promise<HyperliquidPendingAction>;\n /** Perp-account USDC to another address (`destination` lowercased). */\n readonly usdSend: (\n group: HyperliquidGroup,\n params: { readonly destination: string; readonly amount: string },\n ) => Promise<HyperliquidPendingAction>;\n /** A spot balance to another address — `token` is the `\"NAME:0x<id>\"` pair id. */\n readonly spotSend: (\n group: HyperliquidGroup,\n params: {\n readonly destination: string;\n readonly token: string;\n readonly amount: string;\n },\n ) => Promise<HyperliquidPendingAction>;\n /** Withdraw USDC to the owner's Arbitrum address — the bridge fee applies at the bridge. */\n readonly withdraw: (\n group: HyperliquidGroup,\n params: { readonly destination: string; readonly amount: string },\n ) => Promise<HyperliquidPendingAction>;\n };\n /**\n * Streaming views over the WebSocket transport — present only when the provider was built with a\n * `socket` (createApps always wires one). Market views need no unlocked wallet; user views\n * resolve the group to its owner and close on lock.\n */\n readonly live?: HyperliquidLive;\n};\n\n/**\n * The CCTP deposit: a `depositForBurnWithHook` on this chain's TokenMessengerV2 burns USDC and\n * Circle's CctpForwarder on HyperEVM (destination domain 19) mints it into the Hyperliquid account\n * — the legacy Bridge2 route is deprecated (docs §Deposits; research §H-1). Sources:\n *\n * - TokenMessengerV2 — https://developers.circle.com/cctp/references/contract-addresses\n * - USDC — https://developers.circle.com/stablecoins/usdc-contract-addresses\n * - CctpForwarder — https://developers.circle.com/cctp/references/hypercore-contract-addresses\n */\nexport type HyperliquidDepositInfo = {\n /** The CCTP TokenMessengerV2 the deposit burns USDC through. */\n readonly tokenMessenger: string;\n /** The USDC contract the deposit spends. */\n readonly usdc: string;\n /** Circle's CctpForwarder on HyperEVM — mint recipient and destination caller. */\n readonly forwarder: string;\n /** The signature chain, CAIP-2. */\n readonly network: string;\n /** The Hyperliquid CCTP destination domain. */\n readonly destinationDomain: number;\n /** The confirmed-finality threshold the deposit requests (Circle's Fast Transfer 1000). */\n readonly minFinalityThreshold: number;\n /** The hook's dex selector for the account the deposit funds. */\n readonly dex: \"perps\" | \"spot\";\n};\n\nexport const HYPERLIQUID_DEPOSIT: Record<\"Mainnet\" | \"Testnet\", HyperliquidDepositInfo> = {\n Mainnet: {\n tokenMessenger: \"0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d\",\n usdc: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\",\n forwarder: \"0xb21D281DEdb17AE5B501F6AA8256fe38C4e45757\",\n network: \"eip155:42161\",\n destinationDomain: 19,\n minFinalityThreshold: 1000,\n dex: \"perps\",\n },\n Testnet: {\n tokenMessenger: \"0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA\",\n usdc: \"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d\",\n forwarder: \"0x02e39ECb8368b41bF68FF99ff351aC9864e5E2a2\",\n network: \"eip155:421614\",\n destinationDomain: 19,\n minFinalityThreshold: 1000,\n dex: \"perps\",\n },\n};\n\n/** The Iris fee API host per network — the finality-1000 forward fee row feeds `maxFee`. */\nconst IRIS_FEES_URL: Record<\"Mainnet\" | \"Testnet\", string> = {\n Mainnet: \"https://iris-api.circle.com/v2/burn/USDC/fees/3/19?forward=true&hyperCoreDeposit=true\",\n Testnet:\n \"https://iris-api-sandbox.circle.com/v2/burn/USDC/fees/3/19?forward=true&hyperCoreDeposit=true\",\n};\n\n/** The eth_call selectors the deposit reads: localMinter(), burnLimitsPerMessage, allowance. */\nconst SEL_LOCAL_MINTER = \"0xcb75c11c\";\nconst SEL_BURN_LIMIT = \"0xa56ec632\";\nconst SEL_ALLOWANCE = \"0xdd62ed3e\";\n\nconst ethCallWord = async (client: PublicClient, to: string, data: string): Promise<string> => {\n const result: unknown = await client.transport.request({\n method: \"eth_call\",\n params: [{ to, data }, \"latest\"],\n });\n if (typeof result !== \"string\" || !/^0x[0-9a-fA-F]{64}$/.test(result)) {\n throw new HyperliquidError(\"unavailable\", \"the CCTP chain read answered malformed\");\n }\n return result;\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst word = (v: string): string => v.slice(2).toLowerCase().padStart(64, \"0\");\n\n/**\n * The two-call CCTP deposit flow. When the messenger's USDC allowance is short, only the\n * exact-amount approve opens — the deposit call cannot be prepared yet (`eth_estimateGas` would\n * revert on-chain while the approval is unmined), so the host approves it and calls `deposit` again\n * once the approval confirmed; the re-read allowance then covers the amount and only the burn\n * request opens.\n */\nexport type HyperliquidDeposit =\n | {\n readonly kind: \"approval-required\";\n /** The exact-amount USDC approve for the TokenMessengerV2. */\n readonly approval: HyperliquidPendingAction;\n }\n | {\n readonly kind: \"deposit\";\n /** The `depositForBurnWithHook` transaction. */\n readonly deposit: HyperliquidPendingAction;\n };\n\n/** What the Iris forward-fee endpoint contributes: flat fee + the burn's bps minimum. */\nconst fetchMaxFee = async (\n fetcher: typeof globalThis.fetch,\n url: string,\n amount: bigint,\n): Promise<bigint> => {\n let body: unknown;\n try {\n const res = await fetcher(url);\n body = res.ok ? await res.json() : undefined;\n } catch {\n body = undefined;\n }\n const rows = Array.isArray(body) ? body.filter(isObject) : [];\n const row = rows.find(\n (r): r is Record<string, unknown> & { minimumFee: number; forwardFee: { high: number } } =>\n r[\"finalityThreshold\"] === 1000 &&\n typeof r[\"minimumFee\"] === \"number\" &&\n isObject(r[\"forwardFee\"]) &&\n typeof r[\"forwardFee\"][\"high\"] === \"number\",\n );\n if (\n row === undefined ||\n !Number.isInteger(row.minimumFee) ||\n row.minimumFee < 0 ||\n !Number.isInteger(row.forwardFee.high) ||\n row.forwardFee.high < 0\n ) {\n throw new HyperliquidError(\"unavailable\", \"the Circle fee endpoint answered malformed\");\n }\n return BigInt(row.forwardFee.high) + (amount * BigInt(row.minimumFee) + 9999n) / 10_000n;\n};\n\n/** The per-message burn limit for this route's USDC — `localMinter` → `burnLimitsPerMessage`. */\nconst readBurnLimit = async (\n client: PublicClient,\n messenger: string,\n usdc: string,\n): Promise<bigint> => {\n const minterWord = await ethCallWord(client, messenger, SEL_LOCAL_MINTER);\n const minter = minterWord.slice(26);\n if (!/^[0-9a-fA-F]{40}$/.test(minter)) {\n throw new HyperliquidError(\"unavailable\", \"the messenger answered no local minter\");\n }\n return BigInt(await ethCallWord(client, `0x${minter}`, `${SEL_BURN_LIMIT}${word(usdc)}`));\n};\n\n/** `allowance(owner, spender)` on the route's USDC. */\nconst readAllowance = async (\n client: PublicClient,\n usdc: string,\n owner: string,\n spender: string,\n): Promise<bigint> =>\n BigInt(await ethCallWord(client, usdc, `${SEL_ALLOWANCE}${word(owner)}${word(spender)}`));\n\nexport type HyperliquidFund = {\n /** The CCTP route constants for the provider's network. */\n readonly depositInfo: HyperliquidDepositInfo;\n /**\n * Fund the Hyperliquid account from the group's Arbitrum USDC through Circle's CCTP: an\n * exact-amount `approve` to the TokenMessengerV2 when the allowance is short, then a\n * `depositForBurnWithHook` routed to the CctpForwarder (domain 19, finality 1000). `amount` is\n * USDC base units (6 decimals); it must exceed the Circle fee and fit the per-message burn limit.\n * Both request outcomes are reported.\n */\n readonly deposit: (\n group: HyperliquidGroup,\n params: {\n readonly amount: bigint;\n readonly fee: EvmFeeTier;\n /** Which Hyperliquid account the deposit funds — `depositInfo.dex` when omitted. */\n readonly dex?: \"perps\" | \"spot\";\n },\n ) => Promise<HyperliquidDeposit>;\n};\n\n/**\n * Internal seams `createHyperliquidProvider` returns next to the public surface — the\n * `AppsController`'s enable flow needs them; they are deliberately off the `apps` entry's exports.\n */\nexport type HyperliquidProviderInternals = {\n /**\n * The kernel-agent registry `trade` uses — the controller drives `refresh`, `markEnabled`,\n * `reset`, and sees `markRejected` latch rejections from the exchange path.\n */\n readonly agents: HyperliquidAgentRegistry;\n /**\n * Owner-signed actions (approvals, transfers, withdrawals) — the request pipeline signs the typed\n * data; `{requestId, outcome}` lets the host show the approval prompt.\n */\n readonly userSigned: HyperliquidUserSigned;\n};\n\nexport type HyperliquidProviderOptions = Pick<\n HyperliquidTransportOptions,\n \"network\" | \"fetch\" | \"setTimer\" | \"now\" | \"timeoutMs\"\n> & {\n /** The wallet the kernel signs L1 actions for — `sessions(wallet)`. */\n readonly wallet: Wallet;\n /**\n * The group's `evm.bip44` account on the signature chain — the apps context's account seam;\n * absent on a reads-only provider, whose enable/sign paths throw `not-enabled` first.\n */\n readonly account?: ChainsApi[\"account\"];\n /** Randomness for cloids — the engine's injected source. */\n readonly random: (length: number) => Uint8Array;\n /** Owner mismatches and other anomalies are reported here, never secrets. */\n readonly logger: EngineLogger;\n /**\n * The request pipeline user-signed actions and the CCTP deposit go through — absent on a\n * reads-only provider, whose `transfer`/`fund`/`userSigned` throw `not-enabled`.\n */\n readonly requests?: AppRequests;\n /**\n * The chain clients `deposit` reads allowance and the CCTP burn limit through — absent on a\n * reads-only provider.\n */\n readonly networks?: { readonly client: (network: string) => PublicClient };\n /**\n * The builder the AppsController confirmed for this group — `order` actions carry `builder: {b,\n * f}` only while this returns one; never above the confirmed maximum.\n */\n readonly builderFor?: (\n group: HyperliquidGroup,\n ) => { readonly address: string; readonly feeRateTenthsBps: number } | undefined;\n /** The injected WebSocket transport live views stream over — absent on reads-only rigs. */\n readonly socket?: HyperliquidSocket;\n};\n\nconst preview = (price: string, size: string, szDecimals: number): HyperliquidQuotePreview => {\n const roundedSize = roundSize(size, szDecimals);\n return {\n price,\n size: roundedSize,\n notional: notional(price, roundedSize),\n meetsMinimum: meetsMinimum(price, roundedSize),\n };\n};\n\nconst accountOf = (options: HyperliquidProviderOptions): ChainsApi[\"account\"] => {\n if (options.account === undefined) {\n throw new HyperliquidError(\"not-enabled\", \"this provider has no account api\");\n }\n return options.account;\n};\n\nexport function createHyperliquidProvider(\n options: HyperliquidProviderOptions,\n): Omit<HyperliquidProvider, \"approveBuilder\"> & HyperliquidProviderInternals {\n const clock = createHyperliquidClock(options.now);\n const transport = createHyperliquidTransport({ ...options, clock });\n const config = { transport };\n const markets = createHyperliquidMarkets(config);\n const account = createHyperliquidAccount(config);\n const agents = createHyperliquidAgentRegistry({\n /* Deferred so a provider built for reads only does not need a live wallet object — the\n first agent or signing call resolves it. */\n agents: {\n list: async () => sessions(options.wallet).list(),\n },\n evmAddress: async (group) => {\n // The signature chain names the group account: Arbitrum One / Sepolia (design §2).\n const account = await accountOf(options)({\n walletId: group.walletId,\n groupIndex: group.groupIndex,\n template: \"evm.bip44\",\n network: options.network === \"Mainnet\" ? \"eip155:42161\" : \"eip155:421614\",\n });\n if (!(\"address\" in account)) {\n throw new HyperliquidError(\"unavailable\", \"the group has no EVM address\");\n }\n return account.address;\n },\n network: options.network,\n now: options.now,\n logger: options.logger,\n });\n const actions = createHyperliquidActions({\n markets,\n random: options.random,\n now: options.now,\n });\n const { requests } = options;\n const userSigned = createHyperliquidUserSigned({\n requests: requests ?? {\n prepare: () => {\n throw new HyperliquidError(\"not-enabled\", \"this provider has no request pipeline\");\n },\n outcome: () => {\n throw new HyperliquidError(\"not-enabled\", \"this provider has no request pipeline\");\n },\n reject: () => undefined,\n },\n transport,\n clock,\n markets,\n account,\n ownerOf: async (group) => agents.owner(group),\n network: options.network,\n now: options.now,\n });\n const exchange = createHyperliquidExchange({\n wallet: options.wallet,\n transport,\n clock,\n markets,\n account,\n registry: agents,\n now: options.now,\n setTimer: options.setTimer,\n });\n return {\n markets,\n account,\n quote: {\n limit: ({ price, size, side, szDecimals, market }) =>\n preview(limitPrice(price, side, szDecimals, market), size, szDecimals),\n market: ({ reference, size, side, slippageBps, szDecimals, market }) =>\n preview(slippagePrice(reference, side, slippageBps, szDecimals, market), size, szDecimals),\n },\n clock,\n trade: createHyperliquidTrade({\n actions,\n exchange,\n account,\n registry: agents,\n ...(options.builderFor === undefined ? {} : { builderFor: options.builderFor }),\n }),\n agents,\n reopen: async (group, verify) => {\n /* The registry already enforces owner-verified, enabled, unexpired — the kernel re-checks\n the rest: app lock on, limits intact, the factor verified against the recorded budget. */\n const agent = agents.require(group);\n try {\n await sessions(options.wallet).open(agent.address, verify);\n } catch (error) {\n const mapped = error instanceof WalletError ? SESSION_ERRORS[error.code] : undefined;\n throw new HyperliquidError(...(mapped ?? ([\"unavailable\", \"open failed\"] as const)), error);\n }\n },\n userSigned,\n ...(options.socket === undefined\n ? {}\n : {\n live: createHyperliquidLive({\n socket: options.socket,\n transport,\n ownerOf: async (group) => agents.owner(group),\n now: options.now,\n setTimer: options.setTimer,\n random: options.random,\n wallet: options.wallet,\n sighted: exchange.sighted,\n }),\n }),\n transfer: {\n toSpot: async (group, amount) =>\n userSigned.usdClassTransfer(group, { amount, toPerp: false }),\n toPerp: async (group, amount) => userSigned.usdClassTransfer(group, { amount, toPerp: true }),\n usdSend: async (group, params) => userSigned.usdSend(group, params),\n spotSend: async (group, params) => userSigned.spotSend(group, params),\n withdraw: async (group, params) => userSigned.withdraw(group, params),\n },\n fund: {\n depositInfo: HYPERLIQUID_DEPOSIT[options.network],\n deposit: async (group, { amount, fee, dex }) => {\n const route = HYPERLIQUID_DEPOSIT[options.network];\n if (requests === undefined || options.networks === undefined) {\n throw new HyperliquidError(\"not-enabled\", \"this provider has no request pipeline\");\n }\n const client = options.networks.client(route.network);\n const owner = await agents.owner(group);\n /* The Circle fee bound is read before any request is opened: a deposit it would\n consume, or a fee answer we cannot parse, is refused with no prompt shown. */\n const maxFee = await fetchMaxFee(options.fetch, IRIS_FEES_URL[options.network], amount);\n if (amount <= maxFee) {\n throw new HyperliquidError(\n \"invalid-input\",\n \"the Circle fee would consume the whole deposit\",\n );\n }\n const limit = await readBurnLimit(client, route.tokenMessenger, route.usdc);\n if (amount > limit) {\n throw new HyperliquidError(\n \"invalid-input\",\n \"the deposit exceeds the per-message burn limit\",\n );\n }\n const account = {\n kind: \"hd\" as const,\n walletId: group.walletId,\n groupIndex: group.groupIndex,\n template: \"evm.bip44\" as const,\n };\n const track = (pending: { readonly id: string }): HyperliquidPendingAction => ({\n requestId: pending.id,\n outcome: (async (): Promise<{ readonly kind: \"ok\" }> => {\n try {\n const result = await requests.outcome(pending.id);\n if (!(\"family\" in result)) {\n throw new HyperliquidError(\n \"unavailable\",\n \"the deposit request resolved without a transaction\",\n );\n }\n return { kind: \"ok\" };\n } catch (error) {\n if (error instanceof RequestEndedError) {\n throw new HyperliquidError(\n \"approval-rejected\",\n `the request was ${error.stage}`,\n error,\n );\n }\n throw error;\n }\n })(),\n });\n /* An exact-amount approve only when the allowance is short — the pipeline itself\n refuses an overwrite of a nonzero allowance, so the read must come first. The deposit\n request is not prepared here: its estimateGas reverts on a real chain while the\n approval is unmined. The host calls `deposit` again after the approval confirmed. */\n const allowance = await readAllowance(client, route.usdc, owner, route.tokenMessenger);\n if (allowance < amount) {\n return {\n kind: \"approval-required\",\n approval: track(\n await requests.prepare({\n method: \"evm-approve\",\n account,\n network: route.network,\n token: route.usdc,\n spender: route.tokenMessenger,\n amount,\n fee,\n }),\n ),\n };\n }\n return {\n kind: \"deposit\",\n deposit: track(\n await requests.prepare({\n method: \"evm-cctp\",\n account,\n network: route.network,\n amount,\n dex: dex ?? route.dex,\n maxFee,\n fee,\n }),\n ),\n };\n },\n },\n };\n}\n","/**\n * Hyperliquid's own group-state fields and the enablement hints the flows persist between sessions:\n * the last agent that reached `enabled` (reconcile's needs-reauthorization signal) and the builder\n * approval the user declined (so renew and re-enable never re-ask). Both live in one `enablement`\n * record in collection `apps.hyperliquid` under `<walletId>/<groupIndex>` — strict parse, a\n * malformed record reads as empty.\n */\nimport { readJson } from \"../spi.ts\";\nimport type { AppFlow, AppGroup, AppGroupState, AppStorage, EngineLogger } from \"../spi.ts\";\n\n/** The resumable enablement step a group is in; absent when `status` is terminal. */\nexport type HyperliquidStep =\n | \"create-agent\"\n | \"approve-agent\"\n | \"approve-builder\"\n | \"verify\"\n | \"revoke\";\n\nexport type HyperliquidGroupAgent = {\n readonly address: string;\n readonly name: string;\n readonly validUntil: number;\n readonly network: string;\n};\n\n/** Hyperliquid's own group-state fields on top of the controller's base. */\nexport type HyperliquidDetail = {\n /** The agent the group is enabling or enabled with. */\n readonly agent?: HyperliquidGroupAgent;\n /** The step an `enabling` flow is at — `verify` also marks a lost-POST re-check. */\n readonly step?: HyperliquidStep;\n /** `validUntil - now < 14 days` — the host surfaces a renew prompt. */\n readonly renewalDue?: boolean;\n /**\n * `approved` once `maxBuilderFee(owner, builder) >= f` was confirmed on Hyperliquid; `declined`\n * when the user refused the approval — trades go out without a builder either way the fee is\n * unconfirmed.\n */\n readonly builder?: \"approved\" | \"declined\";\n};\n\n/** One wallet group's Hyperliquid app state. */\nexport type HyperliquidGroupState = AppGroupState<HyperliquidDetail>;\n\n/**\n * The flow the enable machine runs on: the controller's `AppFlow` plus the session's enablement\n * hints — `wasEnabledAgent` is reconcile's needs-reauthorization signal, `wasBuilderDeclined` the\n * persisted decline that keeps a renew or re-enable from re-asking.\n */\nexport type HyperliquidFlow = AppFlow<HyperliquidDetail> & {\n /** The address of the last agent a previous session enabled, when the record persisted one. */\n readonly wasEnabledAgent: () => string | undefined;\n /** Whether the persisted record saw the builder approval declined. */\n readonly wasBuilderDeclined: () => boolean;\n};\n\n/** The `enablement` record's fields — both hints in one record. */\ntype Hints = {\n /** The last agent that reached `enabled` — reconcile's status hint. */\n enabledAgent?: string;\n /** The user declined the builder approval — persisted while `builder` is `declined`. */\n builderDeclined?: true;\n};\n\nexport type HyperliquidHints = {\n /**\n * Load the group's hints once per session and wrap `flow` so its writes keep them current —\n * `wasEnabledAgent`/`wasBuilderDeclined` read the live hints, and every status/agent/builder\n * write derives and persists the change.\n */\n readonly track: (group: AppGroup, flow: AppFlow<HyperliquidDetail>) => Promise<HyperliquidFlow>;\n /** Drop the session cache — the app calls this on lock, with its other session marks. */\n readonly reset: () => void;\n};\n\n/** Exact keys only — a record with anything else reads as absent (logged by the caller). */\nconst parseHints = (raw: Uint8Array): Hints | undefined => {\n const value: unknown = readJson(raw);\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n if (Object.keys(value).some((k) => k !== \"enabledAgent\" && k !== \"builderDeclined\")) {\n return undefined;\n }\n if (\n \"enabledAgent\" in value &&\n (typeof value.enabledAgent !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(value.enabledAgent))\n ) {\n return undefined;\n }\n if (\"builderDeclined\" in value && value.builderDeclined !== true) {\n return undefined;\n }\n const hints: Hints = {};\n if (\"enabledAgent\" in value && typeof value.enabledAgent === \"string\") {\n hints.enabledAgent = value.enabledAgent;\n }\n if (\"builderDeclined\" in value && value.builderDeclined === true) {\n hints.builderDeclined = true;\n }\n return hints;\n};\n\nexport function createHyperliquidHints(options: {\n readonly storage: AppStorage;\n readonly logger: EngineLogger;\n}): HyperliquidHints {\n const name = \"enablement\";\n /* One load per group per session — the hints object lives in the cache and the tracked flow's\n writes mutate it, so `was*` always reads the freshest derivation. */\n const loaded = new Map<string, Promise<Hints>>();\n const loadOne = async (group: AppGroup): Promise<Hints> => {\n const raw = await options.storage.get(group, name);\n if (raw === undefined) {\n return {};\n }\n const hints = parseHints(raw);\n if (hints === undefined) {\n options.logger.warn(\n `hyperliquid ${name} ${group.walletId}/${group.groupIndex} skipped: malformed`,\n );\n return {};\n }\n return hints;\n };\n const load = async (group: AppGroup): Promise<Hints> => {\n const key = `${group.walletId}/${group.groupIndex}`;\n let pending = loaded.get(key);\n if (pending === undefined) {\n pending = loadOne(group);\n loaded.set(key, pending);\n }\n return pending;\n };\n /* Fire-and-forget like the controller's own record writes — a failed persist only means the\n next session re-derives from a staler hint. */\n const persist = (group: AppGroup, hints: Hints): void => {\n const key = `${group.walletId}/${group.groupIndex}`;\n const bytes = new TextEncoder().encode(JSON.stringify(hints));\n const put = async (): Promise<void> => {\n try {\n await options.storage.put(group, name, bytes);\n } catch (error) {\n options.logger.warn(`hyperliquid ${name} ${key} write failed`, error);\n }\n };\n void put();\n };\n return {\n track: async (group, flow) => {\n const hints = await load(group);\n return {\n current: flow.current,\n stale: flow.stale,\n wasEnabledAgent: () => hints.enabledAgent,\n wasBuilderDeclined: () => hints.builderDeclined === true,\n write: (patch) => {\n if (flow.stale()) {\n return;\n }\n flow.write(patch);\n /* Derive the hints from the state the write landed: `enabled` with an agent records\n its address; `disabled`/`unavailable` drops it; the decline survives `enabling`\n rewrites until an approval replaces it. */\n const state = flow.current();\n let changed = false;\n if (state.status === \"enabled\" && state.agent !== undefined) {\n if (hints.enabledAgent !== state.agent.address) {\n hints.enabledAgent = state.agent.address;\n changed = true;\n }\n } else if (\n (state.status === \"disabled\" || state.status === \"unavailable\") &&\n hints.enabledAgent !== undefined\n ) {\n delete hints.enabledAgent;\n changed = true;\n }\n if (state.builder === \"declined\") {\n if (hints.builderDeclined !== true) {\n hints.builderDeclined = true;\n changed = true;\n }\n } else if (state.builder === \"approved\" && hints.builderDeclined === true) {\n delete hints.builderDeclined;\n changed = true;\n }\n if (changed) {\n persist(group, hints);\n }\n },\n };\n },\n reset: () => loaded.clear(),\n };\n}\n","/**\n * The Hyperliquid app definition: `hyperliquid(config)` validates the config synchronously and\n * returns the `AppDefinition` `createApps` builds over the shared `AppContext` — the socket,\n * provider and enable state machine wired exactly as the monolithic composition built them, with\n * the lifecycle hooks (`unlock` = agents refresh, `lock` = agents reset, `close` = shared socket\n * close) that keep the controller's lock semantics byte-for-byte.\n */\nimport type { HyperliquidNetwork } from \"@qntx/wallet/protocol\";\n\nimport type { AppContext, AppDefinition } from \"../spi.ts\";\nimport { createHyperliquidEnable } from \"./enable.ts\";\nimport { createHyperliquidProvider } from \"./provider.ts\";\nimport type { HyperliquidProvider } from \"./provider.ts\";\nimport { createHyperliquidSocket } from \"./socket.ts\";\nimport { createHyperliquidHints } from \"./state.ts\";\nimport type { HyperliquidDetail } from \"./state.ts\";\n\nexport type AppsBuilderConfig = {\n /** The builder address the trades attach once `maxBuilderFee` confirms `feeRateTenthsBps`. */\n readonly address: string;\n /** Tenths of a basis point: 1..100 (the perps cap is 0.1 %). */\n readonly feeRateTenthsBps: number;\n};\n\nexport type AppsHyperliquidConfig = {\n readonly network: HyperliquidNetwork;\n /** The agent name — `^[A-Za-z0-9._-]{1,16}$`, the exchange's limit. */\n readonly agentName: string;\n readonly builder?: AppsBuilderConfig;\n};\n\nexport function hyperliquid(\n config: AppsHyperliquidConfig,\n): AppDefinition<\"hyperliquid\", HyperliquidProvider, HyperliquidDetail> {\n const { network, agentName, builder } = config;\n if (!/^[A-Za-z0-9._-]{1,16}$/.test(agentName)) {\n throw new Error(\"hyperliquid agentName must match ^[A-Za-z0-9._-]{1,16}$\");\n }\n if (builder !== undefined) {\n if (!/^0x[0-9a-fA-F]{40}$/.test(builder.address)) {\n throw new Error(\"hyperliquid builder.address must be a 20-byte hex address\");\n }\n if (\n !Number.isInteger(builder.feeRateTenthsBps) ||\n builder.feeRateTenthsBps < 1 ||\n builder.feeRateTenthsBps > 100\n ) {\n throw new Error(\"hyperliquid builder.feeRateTenthsBps must be an integer in 1..100\");\n }\n }\n\n return {\n id: \"hyperliquid\",\n enableWhen: [\"available\"],\n create: (context: AppContext<HyperliquidDetail>) => {\n const socket = createHyperliquidSocket({\n network,\n socket: context.socket,\n setTimer: context.setTimer,\n random: context.random,\n });\n const hints = createHyperliquidHints({\n storage: context.storage,\n logger: context.logger,\n });\n const provider = createHyperliquidProvider({\n wallet: context.wallet,\n account: context.account,\n network,\n fetch: context.fetch,\n setTimer: context.setTimer,\n now: context.now,\n random: context.random,\n logger: context.logger,\n requests: context.requests,\n networks: context.networks,\n socket,\n builderFor: (group) => {\n /* Trades carry the builder only while the group state confirms the fee — a lock or a\n stale approval makes it return undefined and the field is omitted. */\n if (builder === undefined) {\n return undefined;\n }\n return context.groupState(group)?.builder === \"approved\" ? builder : undefined;\n },\n });\n const enable = createHyperliquidEnable({\n wallet: context.wallet,\n provider,\n userSigned: provider.userSigned,\n requests: context.requests,\n network,\n agentName,\n ...(builder === undefined ? {} : { builder }),\n now: context.now,\n setTimer: context.setTimer,\n logger: context.logger,\n hints,\n });\n const api: HyperliquidProvider = {\n ...provider,\n approveBuilder: async (group) =>\n context.flow(group, async (flow) => enable.approveBuilder(group, flow)),\n };\n return {\n api,\n provider: enable.provider,\n unlock: provider.agents.refresh,\n lock: () => {\n provider.agents.reset();\n hints.reset();\n },\n close: () => socket.close(),\n };\n },\n };\n}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