@qntx/wallet-engine 0.13.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.
Files changed (80) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/{errors-CQnlTc1i.d.mts → controller-DpNVHVsj.d.mts} +1093 -758
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -608
  30. package/dist/gateway-contract.mjs +1467 -161
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -618
  37. package/dist/index.mjs +21963 -6836
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +92 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/registry-DwguKWvt.d.mts +0 -27
  77. package/dist/registry-oorLoGtz.mjs +0 -120
  78. package/dist/registry-oorLoGtz.mjs.map +0 -1
  79. package/dist/webln-DKqCnqx1.mjs +0 -3677
  80. package/dist/webln-DKqCnqx1.mjs.map +0 -1
@@ -0,0 +1,2742 @@
1
+ import { n as formatDecimal, r as parseDecimal } from "./decimal-COJ4g8qy.mjs";
2
+ import { t as readJson } from "./json-BDwV38cj.mjs";
3
+ import { n as timeoutSignal } from "./timer-Cdk5rGM2.mjs";
4
+ import { i as RequestEndedError } from "./types-DbftVZ3I.mjs";
5
+ import { t as createAppSocketCore } from "./socket-ChG9JRT_.mjs";
6
+ import { WalletError } from "@qntx/wallet";
7
+ import { sessions } from "@qntx/wallet/sessions";
8
+ import { allMids, candleSnapshot, clearinghouseState, extraAgents, frontendOpenOrders, fundingHistory, l2Book, maxBuilderFee, metaAndAssetCtxs, orderStatus, portfolio, predictedFundings, recentTrades, spotClearinghouseState, spotMetaAndAssetCtxs, userFees, userFills, userFunding, userRateLimit, userRole } from "@nktkas/hyperliquid/api/info";
9
+ import { candle, clearinghouseState as clearinghouseState$1, l2Book as l2Book$1, openOrders, spotState, trades, userFills as userFills$1 } from "@nktkas/hyperliquid/api/subscription";
10
+ import { TransportError } from "@nktkas/hyperliquid";
11
+ import { ApproveAgentTypes, ApproveBuilderFeeTypes, SpotSendTypes, UsdClassTransferTypes, UsdSendTypes, Withdraw3Types } from "@nktkas/hyperliquid/api/exchange";
12
+ // src/apps/hyperliquid/errors.ts
13
+ var HyperliquidError = class extends Error {
14
+ category;
15
+ constructor(category, message, cause) {
16
+ super(message, { cause });
17
+ this.name = "HyperliquidError";
18
+ this.category = category;
19
+ }
20
+ };
21
+ const reauthorization = ["reauthorization-required", "the agent is gone"];
22
+ const SESSION_ERRORS = {
23
+ "app-lock-required": ["app-lock-required", "app lock off"],
24
+ "approval-required": ["reopen-required", "re-approve"],
25
+ "invalid-input": reauthorization,
26
+ "limit-exceeded": ["limit-exceeded", "over the agent's limits"],
27
+ locked: ["unlock-required", "vault locked"],
28
+ "not-found": reauthorization
29
+ };
30
+ // src/apps/hyperliquid/enable.ts
31
+ /** Hyperliquid's own bound is 180 days; 179 keeps a day of slack inside it (research §Agents). */
32
+ const AGENT_VALID_MS = 154656e5;
33
+ /** A disabled-with-revoke throwaway only exists to deregister; 10 minutes is enough. */
34
+ const REVOKE_VALID_MS = 6e5;
35
+ /** ExtraAgents/maxBuilderFee converge within seconds; poll 1 s for up to 30 s. */
36
+ const VERIFY_POLL_MS = 1e3;
37
+ const VERIFY_TIMEOUT_MS = 3e4;
38
+ /** A kernel agent not yet listed on HL this long after creation is an orphan, not an in-flight one. */
39
+ const ORPHAN_AGE_MS = 6e5;
40
+ /** The host surfaces a renew prompt when less than this remains. */
41
+ const RENEWAL_WINDOW_MS = 12096e5;
42
+ /**
43
+ * The limits of a revoke throwaway: it lives ten minutes and never trades — the smallest legal
44
+ * budgets are the honest statement of that. The throwaway stays because Hyperliquid has no revoke
45
+ * action without a new agent — nonces-and-api-wallets §API wallet pruning.
46
+ */
47
+ const REVOKE_LIMITS = {
48
+ notional: "0.00000001",
49
+ maxLeverage: 1,
50
+ assets: [{
51
+ asset: 0,
52
+ size: "0.00000001"
53
+ }]
54
+ };
55
+ const record = (value) => typeof value === "object" && value !== null;
56
+ const isVerifyFactor = (value) => record(value) && (value["kind"] === "hardware" || value["kind"] === "passkey" || value["kind"] === "password" && typeof value["password"] === "string");
57
+ const isLimits = (value) => record(value) && typeof value["notional"] === "string" && Number.isInteger(value["maxLeverage"]) && Array.isArray(value["assets"]) && value["assets"].every((entry) => record(entry) && Number.isInteger(entry["asset"]) && typeof entry["size"] === "string");
58
+ const requireEnableInput = (input) => {
59
+ if (!record(input) || !isLimits(input["limits"]) || !isVerifyFactor(input["verify"])) throw new HyperliquidError("invalid-input", "bad input");
60
+ return {
61
+ limits: input["limits"],
62
+ verify: input["verify"]
63
+ };
64
+ };
65
+ /**
66
+ * Canonical percent string for `maxFeeRate` — `feeRateTenthsBps` hundredths of a percent
67
+ * thousandth: f=10 → "0.01%", f=1 → "0.001%", f=100 → "0.1%" (perps cap).
68
+ */
69
+ const feeRate = (tenthsBps) => {
70
+ const whole = Math.floor(tenthsBps / 1e3);
71
+ const frac = String(tenthsBps % 1e3).padStart(3, "0").replace(/0+$/, "");
72
+ return `${whole}${frac === "" ? "" : `.${frac}`}%`;
73
+ };
74
+ const errorOf = (error) => error instanceof HyperliquidError ? {
75
+ category: error.category,
76
+ message: error.message
77
+ } : {
78
+ category: "unavailable",
79
+ message: error instanceof Error ? error.message : String(error)
80
+ };
81
+ function fail(flow, category, message) {
82
+ flow.write({ error: {
83
+ category,
84
+ message
85
+ } });
86
+ throw new HyperliquidError(category, message);
87
+ }
88
+ /** Run `body`; a stale flow stops writing but a thrown error still surfaces to the caller. */
89
+ const guard = async (flow, body) => {
90
+ try {
91
+ await body();
92
+ } catch (error) {
93
+ if (!flow.stale() && flow.current().status === "enabling") flow.write({
94
+ error: errorOf(error),
95
+ requestId: void 0
96
+ });
97
+ throw error;
98
+ }
99
+ };
100
+ function createHyperliquidEnable(options) {
101
+ const { provider, userSigned } = options;
102
+ const wallet = () => sessions(options.wallet);
103
+ const sleep = async (ms) => new Promise((resolve) => {
104
+ options.setTimer(ms, resolve);
105
+ });
106
+ /** The group's kernel agents on this network, owner-verified (the registry's own read). */
107
+ const kernelAgents = async (group) => {
108
+ const listed = await wallet().list();
109
+ const owner = await provider.agents.owner(group);
110
+ return listed.filter((agent) => agent.scheme === "hyperliquid-l1-agent" && agent.scope === options.network && agent.walletId === group.walletId && agent.groupIndex === group.groupIndex && agent.owner.toLowerCase() === owner);
111
+ };
112
+ const deleteAgent = async (address) => {
113
+ try {
114
+ await wallet().delete(address);
115
+ } catch (error) {
116
+ options.logger.warn(`hyperliquid agent ${address} delete failed`, error);
117
+ }
118
+ };
119
+ /** Poll `extraAgents` until the agent address is listed or the verify window lapses. */
120
+ const waitListed = async (owner, address) => {
121
+ const deadline = options.now() + VERIFY_TIMEOUT_MS;
122
+ while (options.now() <= deadline) {
123
+ if ((await provider.account.extraAgents(owner)).some((a) => a.address.toLowerCase() === address)) return true;
124
+ if (options.now() <= deadline) await sleep(VERIFY_POLL_MS);
125
+ }
126
+ return false;
127
+ };
128
+ const waitBuilderFee = async (owner, builder, f) => {
129
+ const deadline = options.now() + VERIFY_TIMEOUT_MS;
130
+ while (options.now() <= deadline) {
131
+ if (await provider.account.maxBuilderFee(owner, builder) >= f) return true;
132
+ if (options.now() <= deadline) await sleep(VERIFY_POLL_MS);
133
+ }
134
+ return false;
135
+ };
136
+ /**
137
+ * Preconditions shared by enable and renew: clock gate, then `userRole` — only a funded master
138
+ * account ("user") may approve agents (research §Roles).
139
+ */
140
+ const preconditions = async (group, flow) => {
141
+ if (!flow.current().termsAcknowledged) fail(flow, "invalid-input", "terms not acknowledged");
142
+ if (provider.clock.skew() === void 0) await provider.markets.mids();
143
+ provider.clock.assertSkew();
144
+ const owner = await provider.agents.owner(group);
145
+ const { role } = await provider.account.role(owner);
146
+ if (role === "missing") fail(flow, "deposit-required", "deposit to Hyperliquid");
147
+ if (role !== "user") fail(flow, "invalid-input", `a ${role} account cannot approve agents`);
148
+ return owner;
149
+ };
150
+ /** Approve the agent on Hyperliquid, then verify it is listed — resumable through `verify`. */
151
+ const approveAgent = async (group, flow, owner, agent) => {
152
+ if (flow.current().step !== "verify" && flow.current().step !== "approve-builder") {
153
+ flow.write({ step: "approve-agent" });
154
+ const pending = await userSigned.approveAgent(group, {
155
+ agentAddress: agent.address,
156
+ agentName: `${options.agentName} valid_until ${agent.validUntil}`
157
+ });
158
+ flow.write({ requestId: pending.requestId });
159
+ try {
160
+ const outcome = await pending.outcome;
161
+ flow.write({ requestId: void 0 });
162
+ if (outcome.kind === "unknown") options.logger.warn("hyperliquid approveAgent outcome unknown — verifying by listing");
163
+ } catch (error) {
164
+ flow.write({ requestId: void 0 });
165
+ if (error instanceof HyperliquidError && (error.category === "approval-rejected" || error.category === "rejected")) {
166
+ await deleteAgent(agent.address);
167
+ flow.write({
168
+ status: "disabled",
169
+ agent: void 0,
170
+ step: void 0,
171
+ error: errorOf(error)
172
+ });
173
+ }
174
+ throw error;
175
+ }
176
+ }
177
+ flow.write({ step: "verify" });
178
+ if (!await waitListed(owner, agent.address.toLowerCase())) {
179
+ flow.write({
180
+ status: "disabled",
181
+ step: void 0
182
+ });
183
+ await deleteAgent(agent.address);
184
+ fail(flow, "unavailable", "the agent never appeared on Hyperliquid");
185
+ }
186
+ };
187
+ /** The builder step: request approveBuilderFee when HL has not confirmed `f` yet. */
188
+ const approveBuilderStep = async (group, flow, owner) => {
189
+ const { builder } = options;
190
+ if (builder === void 0 || flow.current().builder === "approved") return "approved";
191
+ const fee = builder.feeRateTenthsBps;
192
+ if (await provider.account.maxBuilderFee(owner, builder.address.toLowerCase()) >= fee) return "approved";
193
+ if (flow.wasBuilderDeclined() || flow.current().builder === "declined") return "declined";
194
+ flow.write({ step: "approve-builder" });
195
+ const pending = await userSigned.approveBuilderFee(group, {
196
+ builder: builder.address,
197
+ maxFeeRate: feeRate(fee)
198
+ });
199
+ flow.write({ requestId: pending.requestId });
200
+ try {
201
+ await pending.outcome;
202
+ } catch (error) {
203
+ flow.write({ requestId: void 0 });
204
+ if (error instanceof HyperliquidError && error.category === "approval-rejected") return "declined";
205
+ throw error;
206
+ }
207
+ flow.write({ requestId: void 0 });
208
+ if (!await waitBuilderFee(owner, builder.address.toLowerCase(), fee)) fail(flow, "unavailable", "the builder fee approval never confirmed");
209
+ return "approved";
210
+ };
211
+ /**
212
+ * The enable state machine — every step writes; a failure leaves a resumable state. `input`
213
+ * supplies the kernel ceremony: the limits the approval prompt binds into the record and the
214
+ * factor that proves it. A resume past `create-agent` never reaches them again.
215
+ */
216
+ const enableFlow = async (group, flow, input) => {
217
+ const now = options.now();
218
+ if (flow.current().status !== "enabling") flow.write({
219
+ status: "enabling",
220
+ step: "create-agent",
221
+ error: void 0
222
+ });
223
+ const owner = await preconditions(group, flow);
224
+ let agents = await kernelAgents(group);
225
+ let agent = flow.current().agent === void 0 ? void 0 : agents.find((a) => a.address.toLowerCase() === flow.current().agent?.address.toLowerCase());
226
+ if (agent === void 0) {
227
+ const address = await wallet().create({
228
+ scheme: "hyperliquid-l1-agent",
229
+ owner: group,
230
+ scope: options.network,
231
+ name: options.agentName,
232
+ validUntil: now + AGENT_VALID_MS,
233
+ limits: input.limits,
234
+ verify: input.verify
235
+ });
236
+ agents = await kernelAgents(group);
237
+ agent = agents.find((a) => a.address.toLowerCase() === address.toLowerCase());
238
+ }
239
+ if (agent === void 0) return fail(flow, "unavailable", "the kernel created no agent");
240
+ flow.write({ agent: {
241
+ address: agent.address,
242
+ name: agent.name,
243
+ validUntil: agent.validUntil,
244
+ network: agent.scope
245
+ } });
246
+ await approveAgent(group, flow, owner, agent);
247
+ const builderState = await approveBuilderStep(group, flow, owner);
248
+ await provider.agents.refresh();
249
+ provider.agents.markEnabled(agent.address);
250
+ flow.write({
251
+ status: "enabled",
252
+ step: void 0,
253
+ requestId: void 0,
254
+ builder: builderState,
255
+ renewalDue: agent.validUntil - options.now() < RENEWAL_WINDOW_MS,
256
+ error: void 0
257
+ });
258
+ };
259
+ return {
260
+ provider: {
261
+ error: (category, message) => new HyperliquidError(category, message),
262
+ groups: async () => {
263
+ const listed = await wallet().list();
264
+ const seen = /* @__PURE__ */ new Map();
265
+ for (const agent of listed) if (agent.scheme === "hyperliquid-l1-agent" && agent.scope === options.network) seen.set(`${agent.walletId}/${agent.groupIndex}`, {
266
+ walletId: agent.walletId,
267
+ groupIndex: agent.groupIndex
268
+ });
269
+ return [...seen.values()];
270
+ },
271
+ enable: async (group, raw, input) => {
272
+ const parsed = requireEnableInput(input);
273
+ const flow = await options.hints.track(group, raw);
274
+ await guard(flow, async () => {
275
+ await enableFlow(group, flow, parsed);
276
+ });
277
+ },
278
+ renew: async (group, raw, input) => {
279
+ const parsed = requireEnableInput(input);
280
+ const flow = await options.hints.track(group, raw);
281
+ const before = await kernelAgents(group);
282
+ try {
283
+ flow.write({
284
+ status: "enabling",
285
+ step: "create-agent",
286
+ agent: void 0,
287
+ error: void 0
288
+ });
289
+ await enableFlow(group, flow, parsed);
290
+ for (const old of before) if (old.address.toLowerCase() !== flow.current().agent?.address.toLowerCase()) await deleteAgent(old.address);
291
+ } catch (error) {
292
+ const old = (await kernelAgents(group)).find((a) => a.address.toLowerCase() !== flow.current().agent?.address.toLowerCase() && a.validUntil > options.now());
293
+ flow.write(old === void 0 ? {
294
+ status: "needs-reauthorization",
295
+ step: void 0,
296
+ requestId: void 0,
297
+ error: errorOf(error)
298
+ } : {
299
+ status: "enabled",
300
+ agent: {
301
+ address: old.address,
302
+ name: old.name,
303
+ validUntil: old.validUntil,
304
+ network: old.scope
305
+ },
306
+ step: void 0,
307
+ requestId: void 0,
308
+ renewalDue: old.validUntil - options.now() < RENEWAL_WINDOW_MS,
309
+ error: errorOf(error)
310
+ });
311
+ throw error;
312
+ }
313
+ },
314
+ disable: async (group, { revoke, verify }, raw) => {
315
+ const flow = await options.hints.track(group, raw);
316
+ await guard(flow, async () => {
317
+ await provider.agents.refresh();
318
+ const agents = await kernelAgents(group);
319
+ for (const agent of agents) await deleteAgent(agent.address);
320
+ flow.write({
321
+ status: "disabled",
322
+ agent: void 0,
323
+ builder: void 0,
324
+ error: void 0
325
+ });
326
+ if (revoke) {
327
+ flow.write({ step: "revoke" });
328
+ if (!isVerifyFactor(verify)) fail(flow, "invalid-input", "needs a verify factor");
329
+ let throwaway;
330
+ try {
331
+ const address = await wallet().create({
332
+ scheme: "hyperliquid-l1-agent",
333
+ owner: group,
334
+ scope: options.network,
335
+ name: options.agentName,
336
+ validUntil: options.now() + REVOKE_VALID_MS,
337
+ limits: REVOKE_LIMITS,
338
+ verify
339
+ });
340
+ throwaway = address;
341
+ const record = (await kernelAgents(group)).find((a) => a.address.toLowerCase() === address.toLowerCase());
342
+ if (record === void 0) throw new HyperliquidError("unavailable", "the kernel created no agent");
343
+ const pending = await userSigned.approveAgent(group, {
344
+ agentAddress: address,
345
+ agentName: `${options.agentName} valid_until ${record.validUntil}`
346
+ });
347
+ flow.write({ requestId: pending.requestId });
348
+ await pending.outcome;
349
+ flow.write({
350
+ requestId: void 0,
351
+ step: void 0
352
+ });
353
+ } catch (error) {
354
+ flow.write({
355
+ step: "revoke",
356
+ requestId: void 0,
357
+ error: errorOf(error)
358
+ });
359
+ throw error;
360
+ } finally {
361
+ if (throwaway !== void 0) await deleteAgent(throwaway);
362
+ }
363
+ }
364
+ });
365
+ },
366
+ cancel: async (group, raw) => {
367
+ const state = raw.current();
368
+ if (state.status !== "enabling") throw new HyperliquidError("invalid-input", "no enablement flow is running");
369
+ if (state.agent !== void 0 && provider.agents.enabled(state.agent.address)) throw new HyperliquidError("invalid-input", "the recorded agent is already enabled");
370
+ if (state.requestId !== void 0) options.requests.reject(state.requestId);
371
+ const flow = await options.hints.track(group, raw);
372
+ const agents = await kernelAgents(group);
373
+ for (const agent of agents) if (agent.address.toLowerCase() === state.agent?.address.toLowerCase() && !provider.agents.enabled(agent.address)) await deleteAgent(agent.address);
374
+ const [restored] = agents.filter((a) => a.address.toLowerCase() !== state.agent?.address.toLowerCase() && a.validUntil > options.now()).sort((a, b) => b.validUntil - a.validUntil);
375
+ if (restored === void 0) flow.write({
376
+ status: "disabled",
377
+ step: void 0,
378
+ requestId: void 0,
379
+ agent: void 0,
380
+ error: void 0
381
+ });
382
+ else {
383
+ provider.agents.markEnabled(restored.address);
384
+ flow.write({
385
+ status: "enabled",
386
+ agent: {
387
+ address: restored.address,
388
+ name: restored.name,
389
+ validUntil: restored.validUntil,
390
+ network: restored.scope
391
+ },
392
+ step: void 0,
393
+ requestId: void 0,
394
+ renewalDue: restored.validUntil - options.now() < RENEWAL_WINDOW_MS,
395
+ error: void 0
396
+ });
397
+ }
398
+ },
399
+ reconcile: async (group, raw) => {
400
+ const flow = await options.hints.track(group, raw);
401
+ const now = options.now();
402
+ const owner = await provider.agents.owner(group);
403
+ const agents = await kernelAgents(group);
404
+ const listed = await provider.account.extraAgents(owner);
405
+ const onHl = new Set(listed.map((a) => a.address.toLowerCase()));
406
+ const [newest] = agents.filter((a) => a.validUntil > now).sort((a, b) => b.validUntil - a.validUntil);
407
+ if (newest === void 0) {
408
+ for (const agent of agents) await deleteAgent(agent.address);
409
+ flow.write({
410
+ status: flow.wasEnabledAgent() === void 0 ? "disabled" : "needs-reauthorization",
411
+ agent: void 0,
412
+ builder: void 0
413
+ });
414
+ return;
415
+ }
416
+ if (!onHl.has(newest.address.toLowerCase())) {
417
+ if (now - newest.createdAt < ORPHAN_AGE_MS) flow.write({
418
+ status: "enabling",
419
+ step: "approve-agent",
420
+ agent: {
421
+ address: newest.address,
422
+ name: newest.name,
423
+ validUntil: newest.validUntil,
424
+ network: newest.scope
425
+ }
426
+ });
427
+ else {
428
+ await deleteAgent(newest.address);
429
+ flow.write({
430
+ status: flow.wasEnabledAgent() === void 0 ? "disabled" : "needs-reauthorization",
431
+ agent: void 0,
432
+ builder: void 0
433
+ });
434
+ }
435
+ return;
436
+ }
437
+ for (const agent of agents) if (agent.address.toLowerCase() !== newest.address.toLowerCase()) await deleteAgent(agent.address);
438
+ if (provider.agents.rejected(newest.address)) {
439
+ flow.write({
440
+ status: "needs-reauthorization",
441
+ step: void 0,
442
+ requestId: void 0
443
+ });
444
+ return;
445
+ }
446
+ const { builder } = options;
447
+ const builderConfirmed = builder !== void 0 && await provider.account.maxBuilderFee(owner, builder.address.toLowerCase()) >= builder.feeRateTenthsBps;
448
+ if (builder !== void 0 && !builderConfirmed) {
449
+ if (flow.wasBuilderDeclined()) {
450
+ await provider.agents.refresh();
451
+ provider.agents.markEnabled(newest.address);
452
+ flow.write({
453
+ status: "enabled",
454
+ step: void 0,
455
+ agent: {
456
+ address: newest.address,
457
+ name: newest.name,
458
+ validUntil: newest.validUntil,
459
+ network: newest.scope
460
+ },
461
+ builder: "declined",
462
+ renewalDue: newest.validUntil - now < RENEWAL_WINDOW_MS,
463
+ error: void 0
464
+ });
465
+ return;
466
+ }
467
+ flow.write({
468
+ status: "enabling",
469
+ step: "approve-builder",
470
+ agent: {
471
+ address: newest.address,
472
+ name: newest.name,
473
+ validUntil: newest.validUntil,
474
+ network: newest.scope
475
+ }
476
+ });
477
+ return;
478
+ }
479
+ await provider.agents.refresh();
480
+ provider.agents.markEnabled(newest.address);
481
+ flow.write({
482
+ status: "enabled",
483
+ step: void 0,
484
+ agent: {
485
+ address: newest.address,
486
+ name: newest.name,
487
+ validUntil: newest.validUntil,
488
+ network: newest.scope
489
+ },
490
+ ...builder === void 0 || builderConfirmed ? { builder: "approved" } : {},
491
+ renewalDue: newest.validUntil - now < RENEWAL_WINDOW_MS,
492
+ error: void 0
493
+ });
494
+ },
495
+ authorities: async (group) => {
496
+ const { builder } = options;
497
+ if (builder === void 0) return [];
498
+ const owner = await provider.agents.owner(group);
499
+ const approved = await provider.account.maxBuilderFee(owner, builder.address.toLowerCase());
500
+ if (approved <= 0) return [];
501
+ return [{
502
+ kind: "builder-fee",
503
+ network: options.network,
504
+ account: owner,
505
+ holder: builder.address,
506
+ limit: approved.toString(),
507
+ revoke: "none"
508
+ }];
509
+ }
510
+ },
511
+ approveBuilder: async (group, raw) => {
512
+ const flow = await options.hints.track(group, raw);
513
+ if (flow.current().status !== "enabled") throw new HyperliquidError("invalid-input", "the group is not enabled");
514
+ const { builder } = options;
515
+ if (builder === void 0) throw new HyperliquidError("invalid-input", "no builder is configured");
516
+ const fee = builder.feeRateTenthsBps;
517
+ const owner = await provider.agents.owner(group);
518
+ if (await provider.account.maxBuilderFee(owner, builder.address.toLowerCase()) >= fee) {
519
+ flow.write({ builder: "approved" });
520
+ return;
521
+ }
522
+ const pending = await userSigned.approveBuilderFee(group, {
523
+ builder: builder.address,
524
+ maxFeeRate: feeRate(fee)
525
+ });
526
+ flow.write({ requestId: pending.requestId });
527
+ try {
528
+ await pending.outcome;
529
+ } catch (error) {
530
+ flow.write({ requestId: void 0 });
531
+ if (error instanceof HyperliquidError && error.category === "approval-rejected") {
532
+ flow.write({ builder: "declined" });
533
+ return;
534
+ }
535
+ throw error;
536
+ }
537
+ flow.write({ requestId: void 0 });
538
+ if (!await waitBuilderFee(owner, builder.address.toLowerCase(), fee)) fail(flow, "unavailable", "the builder fee approval never confirmed");
539
+ flow.write({ builder: "approved" });
540
+ }
541
+ };
542
+ }
543
+ // src/apps/hyperliquid/account.ts
544
+ /** Every account read addresses the master account — agents query it lowercased. */
545
+ const master = (user) => `0x${user.toLowerCase().replace(/^0x/, "")}`;
546
+ function createHyperliquidAccount(config) {
547
+ return {
548
+ state: async (params) => clearinghouseState(config, {
549
+ ...params,
550
+ user: master(params.user)
551
+ }),
552
+ spot: async (params) => spotClearinghouseState(config, {
553
+ ...params,
554
+ user: master(params.user)
555
+ }),
556
+ openOrders: async (params) => frontendOpenOrders(config, {
557
+ ...params,
558
+ user: master(params.user)
559
+ }),
560
+ fills: async (params) => userFills(config, {
561
+ ...params,
562
+ user: master(params.user)
563
+ }),
564
+ funding: async (params) => userFunding(config, {
565
+ ...params,
566
+ user: master(params.user)
567
+ }),
568
+ portfolio: async (user) => portfolio(config, { user: master(user) }),
569
+ rateLimit: async (user) => userRateLimit(config, { user: master(user) }),
570
+ fees: async (user) => userFees(config, { user: master(user) }),
571
+ orderStatus: async (params) => orderStatus(config, {
572
+ ...params,
573
+ user: master(params.user)
574
+ }),
575
+ extraAgents: async (user) => extraAgents(config, { user: master(user) }),
576
+ maxBuilderFee: async (user, builder) => maxBuilderFee(config, {
577
+ user: master(user),
578
+ builder: master(builder)
579
+ }),
580
+ role: async (user) => userRole(config, { user: master(user) })
581
+ };
582
+ }
583
+ // src/apps/hyperliquid/numbers.ts
584
+ const DECIMAL = /^[0-9]+(?:\.[0-9]+)?$/;
585
+ const MAX_SIG_FIGS = 4;
586
+ const pow10 = (exponent) => 10n ** BigInt(exponent);
587
+ const parsePositive = (text, field) => {
588
+ if (!DECIMAL.test(text)) throw new HyperliquidError("invalid-input", `${field} is not a decimal: ${text}`);
589
+ const value = parseDecimal(text);
590
+ if (value.units <= 0n) throw new HyperliquidError("invalid-input", `${field} must be positive: ${text}`);
591
+ return value;
592
+ };
593
+ const isInteger = (value) => value.scale <= 0 || value.units % pow10(value.scale) === 0n;
594
+ /** `formatDecimal` needs a non-negative scale — fold a negative one into the units. */
595
+ const canonical = (value) => value.scale < 0 ? {
596
+ units: value.units * pow10(-value.scale),
597
+ scale: 0
598
+ } : value;
599
+ const format = (value) => formatDecimal(canonical(value));
600
+ /** The exponent of the value's most significant decimal digit. */
601
+ const leadingPosition = (value) => String(value.units).length - value.scale - 1;
602
+ const lessThan = (a, b) => {
603
+ const shift = Math.min(a.scale, b.scale, 0);
604
+ return a.units * pow10(b.scale - shift) < b.units * pow10(a.scale - shift);
605
+ };
606
+ /** Round to `scale` fractional decimals — a negative `scale` rounds to powers of ten. */
607
+ const roundToScale = (value, scale, direction) => {
608
+ const drop = value.scale - scale;
609
+ if (drop <= 0) return value;
610
+ const quantum = pow10(drop);
611
+ return {
612
+ units: direction === "down" ? value.units / quantum : (value.units + quantum - 1n) / quantum,
613
+ scale
614
+ };
615
+ };
616
+ const maxDecimals = (market, szDecimals) => Math.max((market === "perp" ? 6 : 8) - szDecimals, 0);
617
+ const checkSzDecimals = (szDecimals) => {
618
+ if (!Number.isInteger(szDecimals) || szDecimals < 0) throw new HyperliquidError("invalid-input", `szDecimals ${szDecimals} is not an integer ≥ 0`);
619
+ };
620
+ /**
621
+ * "down" mirrors the SDK's `formatPrice` — decimal places first, then significant figures — so
622
+ * property tests can use it as the oracle. "up" returns the smallest valid price ≥ the input: the
623
+ * minimum of the 5-significant-figure ceiling and the always-valid integer ceiling.
624
+ */
625
+ const round = (value, szDecimals, market, direction) => {
626
+ const limit = maxDecimals(market, szDecimals);
627
+ if (direction === "down") {
628
+ const decimals = roundToScale(value, limit, "down");
629
+ if (decimals.units === 0n) throw new HyperliquidError("invalid-input", "price rounds to 0");
630
+ if (isInteger(decimals)) return decimals;
631
+ return roundToScale(decimals, MAX_SIG_FIGS - leadingPosition(decimals), "down");
632
+ }
633
+ const integer = roundToScale(value, 0, "up");
634
+ const grid = Math.min(MAX_SIG_FIGS - leadingPosition(value), limit);
635
+ const significant = roundToScale(value, grid, "up");
636
+ return lessThan(integer, significant) ? integer : significant;
637
+ };
638
+ /** `price` rounded to the tick rules for `market` in `direction`; 0 is an error. */
639
+ const roundPrice = (price, szDecimals, market, direction) => {
640
+ checkSzDecimals(szDecimals);
641
+ return format(round(parsePositive(price, "price"), szDecimals, market, direction));
642
+ };
643
+ /** `size` rounded down to `szDecimals` decimals — the lot size; 0 is an error. */
644
+ const roundSize = (size, szDecimals) => {
645
+ checkSzDecimals(szDecimals);
646
+ const value = parsePositive(size, "size");
647
+ const result = roundToScale(value, szDecimals, "down");
648
+ if (result.units === 0n) throw new HyperliquidError("invalid-input", "size rounds to 0");
649
+ return format(result);
650
+ };
651
+ /** A limit price never worse than the user's: buys round down, sells round up. */
652
+ const limitPrice = (price, side, szDecimals, market) => roundPrice(price, szDecimals, market, side === "buy" ? "down" : "up");
653
+ /**
654
+ * The slippage-bounded price for a marketable (IOC) order: `reference` moved `slippageBps` basis
655
+ * points against the order — buy: ×(1 + bps/10⁴), sell: ×(1 − bps/10⁴) — then rounded the way
656
+ * {@link limitPrice} rounds. `slippageBps` is an integer: 1..10000 for a buy, 1..9999 for a sell (0
657
+ * or 100% is no market order).
658
+ */
659
+ const slippagePrice = (reference, side, slippageBps, szDecimals, market) => {
660
+ checkSzDecimals(szDecimals);
661
+ const bound = side === "buy" ? 1e4 : 9999;
662
+ if (!Number.isInteger(slippageBps) || slippageBps < 1 || slippageBps > bound) throw new HyperliquidError("invalid-input", `slippageBps ${slippageBps} out of range for a ${side}`);
663
+ const value = parsePositive(reference, "reference");
664
+ const factor = BigInt(side === "buy" ? 1e4 + slippageBps : 1e4 - slippageBps);
665
+ const scaled = {
666
+ units: value.units * factor,
667
+ scale: value.scale + 4
668
+ };
669
+ return format(round(scaled, szDecimals, market, side === "buy" ? "down" : "up"));
670
+ };
671
+ /** `price` × `size` exactly, as a canonical decimal string. */
672
+ const notional = (price, size) => {
673
+ const px = parsePositive(price, "price");
674
+ const sz = parsePositive(size, "size");
675
+ return format({
676
+ units: px.units * sz.units,
677
+ scale: px.scale + sz.scale
678
+ });
679
+ };
680
+ /** Hyperliquid's minimum order value: notional ≥ 10 quote units (USDC perps, quote token spot). */
681
+ const meetsMinimum = (price, size) => {
682
+ const px = parsePositive(price, "price");
683
+ const sz = parsePositive(size, "size");
684
+ return px.units * sz.units >= pow10(px.scale + sz.scale + 1);
685
+ };
686
+ // src/apps/hyperliquid/actions.ts
687
+ /** Kernel caps action arrays at 64 entries (packages/wallet/src/protocol/apps.ts `arr(.., 64)`). */
688
+ const BATCH_CAP = 64;
689
+ const deepFreeze = (value) => {
690
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
691
+ for (const item of Object.values(value)) deepFreeze(item);
692
+ Object.freeze(value);
693
+ }
694
+ return value;
695
+ };
696
+ const cloidOf$1 = (random) => `0x${Array.from(random(16), (b) => b.toString(16).padStart(2, "0")).join("")}`;
697
+ const isCloid = (value) => /^0x[0-9a-f]{32}$/.test(value);
698
+ const flip = (side) => side === "buy" ? "sell" : "buy";
699
+ /** One wire order: the key order is the kernel schema's (`a,b,p,s,r,t,c`) — hashing order. */
700
+ const wireOrder = (order) => ({
701
+ a: order.asset,
702
+ b: order.side === "buy",
703
+ p: order.price,
704
+ s: order.size,
705
+ r: order.reduceOnly,
706
+ t: order.type,
707
+ ...order.cloid === void 0 ? {} : { c: order.cloid }
708
+ });
709
+ /** Orders below the venue's minimum notional are rejected outright — check before signing. */
710
+ const checkMinimum = (p, s) => {
711
+ if (!meetsMinimum(p, s)) throw new HyperliquidError("invalid-input", "order value is below the 10-quote minimum");
712
+ };
713
+ /** The wire `t`/`p` for a trigger spec — shared by standalone triggers and TP/SL children. */
714
+ const triggerOrder = (spec, side, asset) => {
715
+ const triggerPx = limitPrice(spec.triggerPx, side, asset.szDecimals, asset.market);
716
+ const isMarket = spec.market !== false;
717
+ let p;
718
+ if (spec.price !== void 0) p = limitPrice(spec.price, side, asset.szDecimals, asset.market);
719
+ else if (isMarket) {
720
+ if (spec.slippageBps === void 0) throw new HyperliquidError("invalid-input", "a market trigger needs slippageBps or an explicit price");
721
+ p = slippagePrice(triggerPx, side, spec.slippageBps, asset.szDecimals, asset.market);
722
+ } else throw new HyperliquidError("invalid-input", "a limit trigger needs an explicit price");
723
+ return {
724
+ p,
725
+ t: { trigger: {
726
+ isMarket,
727
+ triggerPx,
728
+ tpsl: spec.tpsl
729
+ } }
730
+ };
731
+ };
732
+ function createHyperliquidActions(options) {
733
+ let meta;
734
+ let spotMeta;
735
+ const refreshMeta = async () => {
736
+ const [perp, spot] = await Promise.all([options.markets.perps(), options.markets.spot()]);
737
+ [meta] = perp;
738
+ [spotMeta] = spot;
739
+ };
740
+ const lookup = (coin) => {
741
+ const perpIndex = meta?.universe.findIndex((entry) => entry.name === coin) ?? -1;
742
+ const perp = perpIndex < 0 ? void 0 : meta?.universe[perpIndex];
743
+ if (perp !== void 0) return {
744
+ asset: perpIndex,
745
+ szDecimals: perp.szDecimals,
746
+ market: "perp",
747
+ maxLeverage: perp.maxLeverage
748
+ };
749
+ const pair = spotMeta?.universe.find((entry) => entry.name === coin);
750
+ const base = pair === void 0 ? void 0 : spotMeta?.tokens[pair.tokens[0] ?? -1];
751
+ if (pair !== void 0 && base !== void 0) return {
752
+ asset: 1e4 + pair.index,
753
+ szDecimals: base.szDecimals,
754
+ market: "spot"
755
+ };
756
+ };
757
+ const resolve = async (coin) => {
758
+ if (coin.includes(":") || coin.startsWith("#")) throw new HyperliquidError("invalid-input", `${coin} is not a main-DEX market`);
759
+ if (meta === void 0 || spotMeta === void 0) await refreshMeta();
760
+ let found = lookup(coin);
761
+ if (found === void 0) {
762
+ await refreshMeta();
763
+ found = lookup(coin);
764
+ }
765
+ if (found === void 0) throw new HyperliquidError("invalid-input", `unknown market ${coin}`);
766
+ return found;
767
+ };
768
+ const mid = async (coin) => {
769
+ const price = (await options.markets.mids())[coin];
770
+ if (price === void 0) throw new HyperliquidError("unavailable", `no mid price for ${coin}`);
771
+ return price;
772
+ };
773
+ /** The wire `t`/`p` for an order kind — market orders price off a fresh mid. */
774
+ const orderType = async (coin, kind, side, asset) => {
775
+ if (kind.kind === "trigger") return triggerOrder(kind, side, asset);
776
+ if (kind.kind === "market") return {
777
+ p: slippagePrice(await mid(coin), side, kind.slippageBps, asset.szDecimals, asset.market),
778
+ t: { limit: { tif: "Ioc" } }
779
+ };
780
+ return {
781
+ p: limitPrice(kind.price, side, asset.szDecimals, asset.market),
782
+ t: { limit: { tif: kind.tif ?? "Gtc" } }
783
+ };
784
+ };
785
+ const buildOrder = async (params, tpsl, spec, child) => {
786
+ const asset = await resolve(params.coin);
787
+ const side = child?.side ?? params.side;
788
+ const size = roundSize(child?.size ?? params.size, asset.szDecimals);
789
+ const { p, t } = spec !== void 0 && tpsl !== void 0 ? triggerOrder({
790
+ ...spec,
791
+ tpsl
792
+ }, side, asset) : await orderType(params.coin, params.order, side, asset);
793
+ checkMinimum(p, size);
794
+ return {
795
+ order: wireOrder({
796
+ asset: asset.asset,
797
+ side,
798
+ price: p,
799
+ size,
800
+ reduceOnly: child !== void 0 || params.reduceOnly === true,
801
+ type: t,
802
+ cloid: cloidOf$1(options.random)
803
+ }),
804
+ price: p
805
+ };
806
+ };
807
+ /** Like {@link buildOrder} for modify/batchModify: the same wire order, no fresh cloid. */
808
+ const buildModifiedOrder = async (params) => {
809
+ const asset = await resolve(params.coin);
810
+ const size = roundSize(params.size, asset.szDecimals);
811
+ const { p, t } = await orderType(params.coin, params.order, params.side, asset);
812
+ checkMinimum(p, size);
813
+ return wireOrder({
814
+ asset: asset.asset,
815
+ side: params.side,
816
+ price: p,
817
+ size,
818
+ reduceOnly: params.reduceOnly === true,
819
+ type: t
820
+ });
821
+ };
822
+ return {
823
+ resolve,
824
+ place: async (params) => {
825
+ const attached = params.takeProfit !== void 0 || params.stopLoss !== void 0;
826
+ if (params.positionTpsl === true && params.order.kind !== "trigger") throw new HyperliquidError("invalid-input", "positionTpsl orders must be trigger orders");
827
+ if (attached && (params.order.kind === "trigger" || params.positionTpsl === true)) throw new HyperliquidError("invalid-input", "only an entry order takes attached TP/SL children");
828
+ const entry = await buildOrder(params);
829
+ const orders = [entry.order];
830
+ if (params.takeProfit !== void 0) {
831
+ const tp = await buildOrder(params, "tp", params.takeProfit, {
832
+ side: flip(params.side),
833
+ size: entry.order.s
834
+ });
835
+ orders.push(tp.order);
836
+ }
837
+ if (params.stopLoss !== void 0) {
838
+ const sl = await buildOrder(params, "sl", params.stopLoss, {
839
+ side: flip(params.side),
840
+ size: entry.order.s
841
+ });
842
+ orders.push(sl.order);
843
+ }
844
+ const grouping = attached ? "normalTpsl" : params.positionTpsl === true ? "positionTpsl" : "na";
845
+ return {
846
+ action: deepFreeze({
847
+ type: "order",
848
+ orders,
849
+ grouping
850
+ }),
851
+ price: entry.price
852
+ };
853
+ },
854
+ modify: async (params) => deepFreeze({
855
+ type: "modify",
856
+ oid: params.oid,
857
+ order: await buildModifiedOrder(params)
858
+ }),
859
+ batchModify: async (modifies) => {
860
+ const entries = [];
861
+ for (const item of modifies) entries.push({
862
+ oid: item.oid,
863
+ order: await buildModifiedOrder(item)
864
+ });
865
+ return deepFreeze({
866
+ type: "batchModify",
867
+ modifies: entries
868
+ });
869
+ },
870
+ cancel: async (cancels) => {
871
+ const entries = [];
872
+ for (const item of cancels) {
873
+ const asset = await resolve(item.coin);
874
+ entries.push({
875
+ a: asset.asset,
876
+ o: item.oid
877
+ });
878
+ }
879
+ return deepFreeze({
880
+ type: "cancel",
881
+ cancels: entries
882
+ });
883
+ },
884
+ cancelByCloid: async (cancels) => {
885
+ const entries = [];
886
+ for (const item of cancels) {
887
+ if (!isCloid(item.cloid)) throw new HyperliquidError("invalid-input", "not a cloid");
888
+ const asset = await resolve(item.coin);
889
+ entries.push({
890
+ asset: asset.asset,
891
+ cloid: item.cloid
892
+ });
893
+ }
894
+ return deepFreeze({
895
+ type: "cancelByCloid",
896
+ cancels: entries
897
+ });
898
+ },
899
+ cancelBatches: (entries) => {
900
+ const batches = [];
901
+ for (let i = 0; i < entries.length; i += BATCH_CAP) batches.push(deepFreeze({
902
+ type: "cancel",
903
+ cancels: entries.slice(i, i + BATCH_CAP)
904
+ }));
905
+ return batches;
906
+ },
907
+ twapCancel: async (params) => {
908
+ const asset = await resolve(params.coin);
909
+ return deepFreeze({
910
+ type: "twapCancel",
911
+ a: asset.asset,
912
+ t: params.twapId
913
+ });
914
+ },
915
+ setLeverage: async (params) => {
916
+ const asset = await resolve(params.coin);
917
+ if (asset.market !== "perp" || asset.maxLeverage === void 0) throw new HyperliquidError("invalid-input", `${params.coin} has no leverage`);
918
+ if (!Number.isInteger(params.leverage) || params.leverage < 1 || params.leverage > asset.maxLeverage) throw new HyperliquidError("invalid-input", `leverage must be an integer in 1..${asset.maxLeverage}`);
919
+ return deepFreeze({
920
+ type: "updateLeverage",
921
+ asset: asset.asset,
922
+ isCross: params.marginMode === "cross",
923
+ leverage: params.leverage
924
+ });
925
+ },
926
+ adjustMargin: async (params) => {
927
+ const asset = await resolve(params.coin);
928
+ if (asset.market !== "perp") throw new HyperliquidError("invalid-input", "isolated margin applies to perps");
929
+ const amount = parseDecimal(params.amount);
930
+ if (amount.scale > 6) throw new HyperliquidError("invalid-input", "margin adjustments allow 6 decimals");
931
+ const ntli = Number(amount.units * 10n ** BigInt(6 - amount.scale));
932
+ if (!Number.isSafeInteger(ntli) || ntli === 0) throw new HyperliquidError("invalid-input", "not a valid margin adjustment");
933
+ return deepFreeze({
934
+ type: "updateIsolatedMargin",
935
+ asset: asset.asset,
936
+ isBuy: true,
937
+ ntli
938
+ });
939
+ }
940
+ };
941
+ }
942
+ // src/apps/hyperliquid/agents.ts
943
+ const keyOf = (group) => `${group.walletId}:${group.groupIndex}`;
944
+ function createHyperliquidAgentRegistry(options) {
945
+ /** Group key → the lowercase evm.bip44 address, derived once per group. */
946
+ const owners = /* @__PURE__ */ new Map();
947
+ /** Kernel-listed, scheme- and network-matched, owner-verified agents. */
948
+ let verified = [];
949
+ const enabled = /* @__PURE__ */ new Set();
950
+ const rejected = /* @__PURE__ */ new Set();
951
+ const ownerOf = async (group) => {
952
+ const key = keyOf(group);
953
+ let owner = owners.get(key);
954
+ if (owner === void 0) {
955
+ owner = (await options.evmAddress(group)).toLowerCase();
956
+ owners.set(key, owner);
957
+ }
958
+ return owner;
959
+ };
960
+ return {
961
+ owner: ownerOf,
962
+ refresh: async () => {
963
+ const listed = await options.agents.list();
964
+ const next = [];
965
+ for (const agent of listed) {
966
+ if (agent.scheme !== "hyperliquid-l1-agent" || agent.scope !== options.network) continue;
967
+ const owner = await ownerOf(agent);
968
+ if (agent.owner.toLowerCase() !== owner) {
969
+ options.logger.warn(`hyperliquid agent ${agent.address} skipped: owner ${agent.owner} is not the group account`);
970
+ continue;
971
+ }
972
+ next.push(agent);
973
+ }
974
+ verified = next;
975
+ },
976
+ markEnabled: (address) => {
977
+ enabled.add(address.toLowerCase());
978
+ },
979
+ markRejected: (address) => {
980
+ rejected.add(address.toLowerCase());
981
+ },
982
+ rejected: (address) => rejected.has(address.toLowerCase()),
983
+ enabled: (address) => enabled.has(address.toLowerCase()),
984
+ reset: () => {
985
+ owners.clear();
986
+ verified = [];
987
+ enabled.clear();
988
+ rejected.clear();
989
+ },
990
+ require: (group) => {
991
+ const own = verified.filter((agent) => agent.walletId === group.walletId && agent.groupIndex === group.groupIndex);
992
+ if (own.length === 0) throw new HyperliquidError("not-enabled", "the account has no Hyperliquid agent");
993
+ const marked = own.filter((agent) => enabled.has(agent.address.toLowerCase()));
994
+ const usable = marked.filter((agent) => !rejected.has(agent.address.toLowerCase()) && agent.validUntil > options.now());
995
+ let agent;
996
+ for (const candidate of usable) if (agent === void 0 || candidate.validUntil > agent.validUntil) agent = candidate;
997
+ if (agent === void 0) throw new HyperliquidError(marked.length > 0 ? "reauthorization-required" : "not-enabled", marked.length > 0 ? "the enabled Hyperliquid agent expired or was rejected" : "the account has no enabled Hyperliquid agent");
998
+ return {
999
+ address: agent.address,
1000
+ owner: agent.owner.toLowerCase(),
1001
+ validUntil: agent.validUntil
1002
+ };
1003
+ }
1004
+ };
1005
+ }
1006
+ // src/apps/hyperliquid/clock.ts
1007
+ /** |skew| beyond this refuses to sign: the 15 s expiresAfter window needs ≥ 10 s of slack. */
1008
+ const MAX_SKEW_MS = 5e3;
1009
+ function createHyperliquidClock(now) {
1010
+ let estimate;
1011
+ const lastNonce = /* @__PURE__ */ new Map();
1012
+ return {
1013
+ record: (serverMs, requestStart, responseEnd) => {
1014
+ estimate = serverMs + 500 - (requestStart + responseEnd) / 2;
1015
+ },
1016
+ skew: () => estimate,
1017
+ assertSkew: () => {
1018
+ if (estimate !== void 0 && Math.abs(estimate) > 5e3) throw new HyperliquidError("clock-skew", `device clock off by ${estimate} ms`);
1019
+ },
1020
+ nextNonce: (signer) => {
1021
+ const next = Math.max(now(), (lastNonce.get(signer) ?? 0) + 1);
1022
+ lastNonce.set(signer, next);
1023
+ return next;
1024
+ }
1025
+ };
1026
+ }
1027
+ // src/apps/hyperliquid/exchange.ts
1028
+ /** The official app's action horizon: 15 s (research §Endpoints). */
1029
+ const EXPIRES_AFTER_MS = 15e3;
1030
+ /** Poll cadence for cloid reconciliation — orderStatus is weight 2, the deadline is seconds away. */
1031
+ const RECONCILE_POLL_MS = 1e3;
1032
+ /**
1033
+ * Late reconciliation cadence for `unknown` cloids — orderStatus is weight 2, so a 10 s cadence
1034
+ * over {@link MAX_UNRESOLVED} entries stays far under the 1200 weight/min limit.
1035
+ */
1036
+ const RECONCILE_LATE_POLL_MS = 1e4;
1037
+ /**
1038
+ * Endpoint catch-up budget: past ten minutes a pending cloid is dropped from the set silently — its
1039
+ * outcome stays `unknown`, it is simply no longer re-asked.
1040
+ */
1041
+ const RECONCILE_LATE_WINDOW_MS = 6e5;
1042
+ /** Outstanding cloids cannot grow without bound — past the cap the oldest entry is evicted. */
1043
+ const MAX_UNRESOLVED = 64;
1044
+ /** After `expiresAfter` plus the skew bound the action can no longer commit; +2 s of slack. */
1045
+ const reconcileDeadline = (expiresAfter) => expiresAfter + MAX_SKEW_MS + 2e3;
1046
+ const isRecord$1 = (value) => typeof value === "object" && value !== null;
1047
+ const stringOf = (value) => typeof value === "string" ? value : void 0;
1048
+ const numberOf = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1049
+ /** Order statuses the docs list as `*Rejected` — mapped to reasons by name. */
1050
+ const statusReason = (status) => {
1051
+ if (status.includes("OpenInterest")) return "open-interest-cap";
1052
+ switch (status) {
1053
+ case "tickRejected": return "tick";
1054
+ case "minTradeNtlRejected": return "min-notional";
1055
+ case "perpMarginRejected": return "margin";
1056
+ case "reduceOnlyRejected": return "reduce-only";
1057
+ case "badAloPxRejected": return "post-only-would-match";
1058
+ case "iocCancelRejected": return "ioc-no-match";
1059
+ case "badTriggerPxRejected": return "bad-trigger";
1060
+ case "marketOrderNoLiquidityRejected": return "no-liquidity";
1061
+ case "insufficientSpotBalanceRejected": return "insufficient-spot-balance";
1062
+ case "oracleRejected": return "oracle";
1063
+ case "perpMaxPositionRejected": return "max-position";
1064
+ default: return "other";
1065
+ }
1066
+ };
1067
+ /** The same classes for the `error` strings in order-statuses (docs error-responses table). */
1068
+ const messageReason = (message) => {
1069
+ if (message.includes("divisible by tick size")) return "tick";
1070
+ if (message.includes("minimum value")) return "min-notional";
1071
+ if (message.includes("Insufficient margin")) return "margin";
1072
+ if (message.includes("Reduce only order")) return "reduce-only";
1073
+ if (message.includes("Post only order")) return "post-only-would-match";
1074
+ if (message.includes("could not immediately match")) return "ioc-no-match";
1075
+ if (message.includes("Invalid TP/SL price")) return "bad-trigger";
1076
+ if (message.includes("No liquidity available for market order")) return "no-liquidity";
1077
+ if (message.includes("open interest")) return "open-interest-cap";
1078
+ if (message.includes("insufficient spot balance")) return "insufficient-spot-balance";
1079
+ if (message.includes("too far from oracle")) return "oracle";
1080
+ if (message.includes("margin tier limit")) return "max-position";
1081
+ return "other";
1082
+ };
1083
+ /** `status: "err"` strings that mean the agent is unusable — never retried with another key. */
1084
+ const AGENT_REJECTION = /User or API Wallet 0x[0-9a-fA-F]+ does not exist|Must deposit before performing actions/;
1085
+ const cloidOf = (entry) => stringOf(entry["cloid"]);
1086
+ const pendingKey = (master, cloid) => `${master}|${cloid}`.toLowerCase();
1087
+ /**
1088
+ * An answered order status — strict on the documented shapes: anything else means the response was
1089
+ * misread, and a misread "rejected" is how duplicate orders happen. `undefined` → reconcile.
1090
+ */
1091
+ const orderStatusOutcome = (entry, cloid) => {
1092
+ if (entry === "waitingForFill" || entry === "waitingForTrigger") return {
1093
+ kind: "resting",
1094
+ cloid
1095
+ };
1096
+ if (isRecord$1(entry) && isRecord$1(entry["resting"])) {
1097
+ const oid = numberOf(entry["resting"]["oid"]);
1098
+ return oid === void 0 ? void 0 : {
1099
+ kind: "resting",
1100
+ oid,
1101
+ cloid: cloidOf(entry["resting"]) ?? cloid
1102
+ };
1103
+ }
1104
+ if (isRecord$1(entry) && isRecord$1(entry["filled"])) {
1105
+ const totalSz = stringOf(entry["filled"]["totalSz"]);
1106
+ const avgPx = stringOf(entry["filled"]["avgPx"]);
1107
+ return totalSz === void 0 || avgPx === void 0 ? void 0 : {
1108
+ kind: "filled",
1109
+ oid: numberOf(entry["filled"]["oid"]),
1110
+ cloid: cloidOf(entry["filled"]) ?? cloid,
1111
+ totalSz,
1112
+ avgPx
1113
+ };
1114
+ }
1115
+ const message = isRecord$1(entry) ? stringOf(entry["error"]) : void 0;
1116
+ return message === void 0 ? void 0 : {
1117
+ kind: "rejected",
1118
+ cloid,
1119
+ reason: messageReason(message),
1120
+ message
1121
+ };
1122
+ };
1123
+ const cancelStatusOutcome = (entry) => {
1124
+ if (entry === "success") return { kind: "cancelled" };
1125
+ const message = isRecord$1(entry) ? stringOf(entry["error"]) : void 0;
1126
+ return message === void 0 ? { kind: "unknown" } : {
1127
+ kind: "rejected",
1128
+ message
1129
+ };
1130
+ };
1131
+ /**
1132
+ * The docs warn that a pre-validation failure returns ONE error for the whole batch; a single
1133
+ * `{error}` status among n orders applies to every entry (error-responses doc).
1134
+ */
1135
+ const broadcast = (statuses, count) => {
1136
+ const [only] = statuses;
1137
+ if (statuses.length === 1 && count > 1 && isRecord$1(only) && typeof only["error"] === "string") return Array.from({ length: count }, () => only);
1138
+ return statuses;
1139
+ };
1140
+ const statusesOf = (body) => {
1141
+ if (!isRecord$1(body) || body["status"] !== "ok" || !isRecord$1(body["response"])) return;
1142
+ const { data } = body["response"];
1143
+ if (!isRecord$1(data) || !Array.isArray(data["statuses"])) return;
1144
+ return data["statuses"];
1145
+ };
1146
+ /** `origSz − sz` exactly — the filled part of an order, canonical, or undefined when unreadable. */
1147
+ const filledSize = (order) => {
1148
+ const orig = stringOf(order["origSz"]);
1149
+ const open = stringOf(order["sz"]);
1150
+ if (orig === void 0 || open === void 0) return;
1151
+ const a = parseDecimal(orig);
1152
+ const b = parseDecimal(open);
1153
+ const scale = Math.max(a.scale, b.scale);
1154
+ const diff = a.units * 10n ** BigInt(scale - a.scale) - b.units * 10n ** BigInt(scale - b.scale);
1155
+ return formatDecimal({
1156
+ units: diff < 0n ? 0n : diff,
1157
+ scale
1158
+ });
1159
+ };
1160
+ const positive = (size) => size !== void 0 && parseDecimal(size).units > 0n;
1161
+ /**
1162
+ * `orderStatus` → the outcome for one cloid, or `undefined` to keep polling (unknownOid and
1163
+ * malformed answers both keep polling — a misread is never a verdict).
1164
+ */
1165
+ const statusOutcome = (result, cloid) => {
1166
+ if (!isRecord$1(result) || result["status"] !== "order" || !isRecord$1(result["order"])) return;
1167
+ const detail = result["order"];
1168
+ const order = isRecord$1(detail["order"]) ? detail["order"] : {};
1169
+ const status = stringOf(detail["status"]) ?? "";
1170
+ const oid = numberOf(order["oid"]);
1171
+ const filled = filledSize(order);
1172
+ if (status === "open" || status === "triggered") return positive(filled) ? {
1173
+ kind: "resting",
1174
+ oid,
1175
+ cloid,
1176
+ filledSz: filled
1177
+ } : {
1178
+ kind: "resting",
1179
+ oid,
1180
+ cloid
1181
+ };
1182
+ if (status === "filled") return {
1183
+ kind: "filled",
1184
+ oid,
1185
+ cloid,
1186
+ totalSz: filled ?? stringOf(order["origSz"]) ?? "0"
1187
+ };
1188
+ if (status === "") return;
1189
+ return positive(filled) ? {
1190
+ kind: "filled",
1191
+ oid,
1192
+ cloid,
1193
+ totalSz: filled
1194
+ } : {
1195
+ kind: "rejected",
1196
+ cloid,
1197
+ reason: statusReason(status),
1198
+ message: status
1199
+ };
1200
+ };
1201
+ const cloids = (action) => action.type === "order" || action.type === "batchModify" ? action.type === "order" ? action.orders.map((order) => order.c) : action.modifies.map((item) => item.order.c) : [];
1202
+ /** `data.status` of single-status responses like twapOrder: `{running:{twapId}} | {error}`. */
1203
+ const singleStatus = (body) => {
1204
+ const data = isRecord$1(body) && isRecord$1(body["response"]) && isRecord$1(body["response"]["data"]) ? body["response"]["data"] : void 0;
1205
+ const status = isRecord$1(data?.["status"]) ? data?.["status"] : void 0;
1206
+ if (status === void 0) return;
1207
+ const message = stringOf(status["error"]);
1208
+ if (message !== void 0) throw new HyperliquidError("rejected", message);
1209
+ if (isRecord$1(status["running"])) {
1210
+ const twapId = numberOf(status["running"]["twapId"]);
1211
+ return twapId === void 0 ? { kind: "ok" } : {
1212
+ kind: "ok",
1213
+ twapId
1214
+ };
1215
+ }
1216
+ };
1217
+ function createHyperliquidExchange(options) {
1218
+ const sleep = async (ms) => new Promise((resolve) => {
1219
+ options.setTimer(ms, resolve);
1220
+ });
1221
+ /** One cheap info call when no skew estimate exists yet — any Date-bearing response works. */
1222
+ const assertClock = async () => {
1223
+ if (options.clock.skew() === void 0) await options.markets.mids();
1224
+ options.clock.assertSkew();
1225
+ };
1226
+ const listeners = /* @__PURE__ */ new Set();
1227
+ const emit = (correction) => {
1228
+ for (const listener of listeners) listener(correction);
1229
+ };
1230
+ const pending = /* @__PURE__ */ new Map();
1231
+ let pollCancel;
1232
+ let lockWatch;
1233
+ let session = 0;
1234
+ const watchLock = () => {
1235
+ lockWatch ??= options.wallet.subscribe(() => {
1236
+ if (options.wallet.getSnapshot().vault !== "unlocked") {
1237
+ session += 1;
1238
+ pending.clear();
1239
+ pollCancel?.();
1240
+ pollCancel = void 0;
1241
+ }
1242
+ });
1243
+ };
1244
+ /** One orderStatus read for a pending cloid — a definite answer corrects and drops it. */
1245
+ const probe = async (entry) => {
1246
+ let outcome;
1247
+ try {
1248
+ outcome = statusOutcome(await options.account.orderStatus({
1249
+ user: entry.master,
1250
+ oid: entry.cloid
1251
+ }), entry.cloid);
1252
+ } catch {
1253
+ return;
1254
+ }
1255
+ if (outcome !== void 0 && pending.get(pendingKey(entry.master, entry.cloid)) === entry) {
1256
+ pending.delete(pendingKey(entry.master, entry.cloid));
1257
+ emit({
1258
+ group: entry.group,
1259
+ cloid: entry.cloid,
1260
+ outcome
1261
+ });
1262
+ }
1263
+ };
1264
+ const schedulePoll = () => {
1265
+ if (pollCancel === void 0 && pending.size > 0) pollCancel = options.setTimer(RECONCILE_LATE_POLL_MS, () => {
1266
+ pollCancel = void 0;
1267
+ (async () => {
1268
+ for (const entry of pending.values()) if (options.now() - entry.since >= RECONCILE_LATE_WINDOW_MS) pending.delete(pendingKey(entry.master, entry.cloid));
1269
+ else await probe(entry);
1270
+ schedulePoll();
1271
+ })();
1272
+ });
1273
+ };
1274
+ const registerPending = (group, master, cloid, signedIn) => {
1275
+ if (signedIn !== session || options.wallet.getSnapshot().vault !== "unlocked") return;
1276
+ const key = pendingKey(master, cloid);
1277
+ if (!pending.has(key) && pending.size >= MAX_UNRESOLVED) {
1278
+ const [oldest] = pending.keys();
1279
+ if (oldest !== void 0) pending.delete(oldest);
1280
+ }
1281
+ pending.set(key, {
1282
+ group,
1283
+ master,
1284
+ cloid,
1285
+ since: options.now()
1286
+ });
1287
+ schedulePoll();
1288
+ };
1289
+ const sighted = (user, entry) => {
1290
+ if (!isRecord$1(entry) || pending.size === 0) return;
1291
+ const { orders } = entry;
1292
+ if (Array.isArray(orders)) for (const order of orders) {
1293
+ const cloid = isRecord$1(order) ? stringOf(order["cloid"]) : void 0;
1294
+ const oid = isRecord$1(order) ? numberOf(order["oid"]) : void 0;
1295
+ if (cloid === void 0 || oid === void 0) continue;
1296
+ const hit = pending.get(pendingKey(user, cloid));
1297
+ if (hit !== void 0) {
1298
+ pending.delete(pendingKey(user, cloid));
1299
+ emit({
1300
+ group: hit.group,
1301
+ cloid,
1302
+ outcome: {
1303
+ kind: "resting",
1304
+ oid,
1305
+ cloid
1306
+ }
1307
+ });
1308
+ }
1309
+ }
1310
+ const { fills } = entry;
1311
+ if (Array.isArray(fills)) for (const fill of fills) {
1312
+ const cloid = isRecord$1(fill) ? stringOf(fill["cloid"]) : void 0;
1313
+ const hit = cloid === void 0 ? void 0 : pending.get(pendingKey(user, cloid));
1314
+ if (hit !== void 0) probe(hit);
1315
+ }
1316
+ };
1317
+ /**
1318
+ * The POST's outcome is unknown — the action may have committed. Poll orderStatus by cloid every
1319
+ * second; never re-POST. Deadline: `expiresAfter + MAX_SKEW + 2 s` — past it the action cannot be
1320
+ * accepted anymore.
1321
+ */
1322
+ const reconcile = async (group, master, cloid, expiresAfter, signedIn) => {
1323
+ if (cloid === void 0) return { kind: "unknown" };
1324
+ const deadline = reconcileDeadline(expiresAfter);
1325
+ while (options.now() <= deadline) {
1326
+ try {
1327
+ const result = await options.account.orderStatus({
1328
+ user: master,
1329
+ oid: cloid
1330
+ });
1331
+ const outcome = statusOutcome(result, cloid);
1332
+ if (outcome !== void 0) return outcome;
1333
+ } catch {}
1334
+ if (options.now() <= deadline) await sleep(RECONCILE_POLL_MS);
1335
+ }
1336
+ registerPending(group, master, cloid, signedIn);
1337
+ return {
1338
+ kind: "unknown",
1339
+ cloid
1340
+ };
1341
+ };
1342
+ const sign = async (agent, action, nonce, expiresAfter) => {
1343
+ let signature;
1344
+ try {
1345
+ signature = await sessions(options.wallet).sign({
1346
+ scheme: "hyperliquid-l1-agent",
1347
+ address: agent.address,
1348
+ params: {
1349
+ action,
1350
+ nonce,
1351
+ expiresAfter
1352
+ }
1353
+ });
1354
+ } catch (error) {
1355
+ if (error instanceof WalletError) {
1356
+ if (error.code === "not-found" || error.code === "invalid-input" && options.now() >= agent.validUntil) {
1357
+ options.registry.markRejected(agent.address);
1358
+ throw new HyperliquidError("reauthorization-required", "the agent is gone", error);
1359
+ }
1360
+ if (error.code === "invalid-input") throw new HyperliquidError("invalid-input", "kernel rejected", error);
1361
+ const mapped = SESSION_ERRORS[error.code];
1362
+ if (mapped) throw new HyperliquidError(mapped[0], mapped[1], error);
1363
+ }
1364
+ throw new HyperliquidError("unavailable", "the wallet failed to sign", error);
1365
+ }
1366
+ if (signature.length !== 65) throw new HyperliquidError("unavailable", "the kernel returned a malformed signature");
1367
+ const hex = Array.from(signature, (b) => b.toString(16).padStart(2, "0")).join("");
1368
+ return {
1369
+ r: `0x${hex.slice(0, 64)}`,
1370
+ s: `0x${hex.slice(64, 128)}`,
1371
+ v: signature[64] ?? 27
1372
+ };
1373
+ };
1374
+ /**
1375
+ * Gate → require → nonce → sign → POST the exact frozen action. A transport failure after signing
1376
+ * means the action may have committed: the caller maps that to a reconciliation, never a retry.
1377
+ */
1378
+ const execute = async (group, action, onOk, onLost) => {
1379
+ const agent = options.registry.require(group);
1380
+ await assertClock();
1381
+ const nonce = options.clock.nextNonce(agent.address);
1382
+ const expiresAfter = options.now() + EXPIRES_AFTER_MS;
1383
+ watchLock();
1384
+ const signedIn = session;
1385
+ const body = {
1386
+ action,
1387
+ nonce,
1388
+ signature: await sign(agent, action, nonce, expiresAfter),
1389
+ expiresAfter
1390
+ };
1391
+ let response;
1392
+ try {
1393
+ response = await options.transport.request("exchange", body);
1394
+ } catch (error) {
1395
+ if (error instanceof HyperliquidError) return onLost(agent.owner, expiresAfter, signedIn);
1396
+ throw error;
1397
+ }
1398
+ if (isRecord$1(response) && response["status"] === "err") {
1399
+ const message = stringOf(response["response"]) ?? "rejected";
1400
+ if (AGENT_REJECTION.test(message)) {
1401
+ options.registry.markRejected(agent.address);
1402
+ throw new HyperliquidError("reauthorization-required", message);
1403
+ }
1404
+ throw new HyperliquidError("rejected", message);
1405
+ }
1406
+ return onOk(response, agent.owner, expiresAfter, signedIn);
1407
+ };
1408
+ return {
1409
+ order: async (group, action) => execute(group, action, async (body, master, expiresAfter, signedIn) => {
1410
+ const count = action.type === "order" ? action.orders.length : action.type === "batchModify" ? action.modifies.length : 1;
1411
+ const known = cloids(action);
1412
+ const raw = statusesOf(body);
1413
+ const entries = raw === void 0 ? void 0 : broadcast(raw, count);
1414
+ if (entries === void 0 || entries.length !== count) return Promise.all(known.map(async (cloid) => reconcile(group, master, cloid, expiresAfter, signedIn)));
1415
+ return Promise.all(entries.map(async (entry, index) => {
1416
+ return orderStatusOutcome(entry, known[index]) ?? reconcile(group, master, known[index], expiresAfter, signedIn);
1417
+ }));
1418
+ }, async (master, expiresAfter, signedIn) => {
1419
+ const known = cloids(action);
1420
+ if (known.length === 0) return [{ kind: "unknown" }];
1421
+ return Promise.all(known.map(async (cloid) => reconcile(group, master, cloid, expiresAfter, signedIn)));
1422
+ }),
1423
+ cancel: async (group, action) => {
1424
+ const count = action.type === "cancel" || action.type === "cancelByCloid" ? action.cancels.length : 1;
1425
+ return execute(group, action, (body) => {
1426
+ const raw = statusesOf(body);
1427
+ const entries = raw === void 0 ? void 0 : broadcast(raw, count);
1428
+ return entries === void 0 || entries.length !== count ? Array.from({ length: count }, () => ({ kind: "unknown" })) : entries.map(cancelStatusOutcome);
1429
+ }, () => Array.from({ length: count }, () => ({ kind: "unknown" })));
1430
+ },
1431
+ action: async (group, action) => execute(group, action, (body) => singleStatus(body) ?? { kind: "ok" }, () => ({ kind: "unknown" })),
1432
+ corrections: { subscribe: (listener) => {
1433
+ listeners.add(listener);
1434
+ return () => {
1435
+ listeners.delete(listener);
1436
+ };
1437
+ } },
1438
+ sighted
1439
+ };
1440
+ }
1441
+ // src/apps/hyperliquid/socket.ts
1442
+ /**
1443
+ * An `ISubscriptionTransport` over the shared apps socket core (`../socket.ts`): subscribe/
1444
+ * unsubscribe frames, confirmation matching by "payload ⊆ echo" (most specific pending wins),
1445
+ * `{"method":"ping"}` heartbeats answered by `{channel:"pong"}`, and the server-side limits
1446
+ * enforced client-side. Matching mirrors `@nktkas/hyperliquid` `transport/websocket/_id.js`
1447
+ * (`isSubset`/`specificity`/`requestToId`) and `transport/websocket/_dispatcher.js` (queue +
1448
+ * response handling); the SDK's subscription functions consume `{ detail }` events only
1449
+ * (`api/subscription/_methods/l2Book.js` etc.).
1450
+ */
1451
+ const HYPERLIQUID_WS = {
1452
+ Mainnet: "wss://api.hyperliquid.xyz/ws",
1453
+ Testnet: "wss://api.hyperliquid-testnet.xyz/ws"
1454
+ };
1455
+ const OPEN = 1;
1456
+ const PING_MS = 3e4;
1457
+ const PONG_MS = 1e4;
1458
+ const CONFIRM_MS = 1e4;
1459
+ const MAX_SUBSCRIPTIONS = 1e3;
1460
+ const MAX_USERS = 10;
1461
+ const HEX = /^0x[0-9a-f]+$/i;
1462
+ const normalize = (value) => {
1463
+ if (typeof value === "string" && HEX.test(value)) return value.toLowerCase();
1464
+ if (Array.isArray(value)) return value.map(normalize);
1465
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1).map(([key, item]) => [key, normalize(item)]));
1466
+ return value;
1467
+ };
1468
+ const idOf = (value) => JSON.stringify(normalize(value));
1469
+ const specificity = (value) => typeof value === "object" && value !== null ? Object.values(value).reduce((sum, item) => sum + specificity(item), 0) : 1;
1470
+ const isSubset = (subset, superset) => {
1471
+ if (typeof subset === "string" && typeof superset === "string") return HEX.test(subset) && HEX.test(superset) ? subset.toLowerCase() === superset.toLowerCase() : subset === superset;
1472
+ if (typeof subset !== "object" || typeof superset !== "object" || subset === null || superset === null) return subset === superset;
1473
+ if (Array.isArray(subset)) return Array.isArray(superset) && subset.length === superset.length && subset.every((item, i) => isSubset(item, superset[i]));
1474
+ const sup = new Map(Object.entries(superset));
1475
+ return Object.entries(subset).every(([key, item]) => isSubset(item, sup.get(key)));
1476
+ };
1477
+ /**
1478
+ * `subset ⊆ superset` with hex strings compared case-insensitively — the same rule the confirmation
1479
+ * matching uses; the live layer matches `onConfirmed` payloads with it.
1480
+ */
1481
+ const payloadContains = isSubset;
1482
+ const isRecord = (value) => typeof value === "object" && value !== null;
1483
+ const userOf = (payload) => {
1484
+ const user = isRecord(payload) ? payload["user"] : void 0;
1485
+ return typeof user === "string" ? user.toLowerCase() : void 0;
1486
+ };
1487
+ /** `{channel:"pong"}` answers `{"method":"ping"}` — checked before the dispatcher sees the frame. */
1488
+ const isPong = (raw) => {
1489
+ try {
1490
+ const frame = JSON.parse(raw);
1491
+ return isRecord(frame) && frame["channel"] === "pong";
1492
+ } catch {
1493
+ return false;
1494
+ }
1495
+ };
1496
+ function createHyperliquidSocket(options) {
1497
+ const entries = /* @__PURE__ */ new Map();
1498
+ const confirmedListeners = /* @__PURE__ */ new Set();
1499
+ const send = (method, payload) => {
1500
+ core.send(JSON.stringify({
1501
+ method,
1502
+ subscription: payload
1503
+ }));
1504
+ };
1505
+ /** Each caller's unsubscribe drops its own listener; the wire frame goes when the last leaves. */
1506
+ const unsubscribe = (id, listener) => ({ unsubscribe: async () => {
1507
+ const entry = entries.get(id);
1508
+ entry?.listeners.delete(listener);
1509
+ if (entry !== void 0 && entry.listeners.size === 0 && entries.delete(id) && core.readyState() === OPEN) send("unsubscribe", entry.payload);
1510
+ await Promise.resolve();
1511
+ } });
1512
+ const fail = (id, error) => {
1513
+ const entry = entries.get(id);
1514
+ if (entry === void 0) return;
1515
+ entry.timer?.();
1516
+ entries.delete(id);
1517
+ if (entry.resolved) entry.onError?.(error);
1518
+ else entry.reject(error);
1519
+ };
1520
+ const resubscribe = () => {
1521
+ for (const entry of entries.values()) {
1522
+ entry.confirmed = false;
1523
+ send("subscribe", entry.payload);
1524
+ }
1525
+ };
1526
+ const onMessage = (raw) => {
1527
+ let frame;
1528
+ try {
1529
+ frame = JSON.parse(raw);
1530
+ } catch {
1531
+ return;
1532
+ }
1533
+ if (!isRecord(frame)) return;
1534
+ const { channel } = frame;
1535
+ const { data } = frame;
1536
+ if (channel === "subscriptionResponse") {
1537
+ const echo = isRecord(data) ? data["subscription"] : void 0;
1538
+ const [winner] = [...entries.entries()].filter(([, entry]) => !entry.confirmed && isSubset(entry.payload, echo)).sort(([, a], [, b]) => specificity(b.payload) - specificity(a.payload));
1539
+ if (winner !== void 0) {
1540
+ const [id, entry] = winner;
1541
+ entry.timer?.();
1542
+ entry.timer = void 0;
1543
+ entry.confirmed = true;
1544
+ entry.resolved = true;
1545
+ const [first] = entry.listeners;
1546
+ entry.resolve(unsubscribe(id, first ?? (() => void 0)));
1547
+ for (const listener of confirmedListeners) listener(entry.channel, entry.payload);
1548
+ }
1549
+ return;
1550
+ }
1551
+ if (channel === "error") {
1552
+ const text = typeof data === "string" ? data : JSON.stringify(data);
1553
+ const [target] = [...entries.entries()].find(([id, entry]) => !entry.confirmed && (text.includes("Already subscribed") || text.includes("Invalid subscription") || text.includes(idOf(entry.payload)) || text.includes(id))) ?? [];
1554
+ if (target !== void 0) fail(target, new TransportError(text));
1555
+ return;
1556
+ }
1557
+ for (const entry of entries.values()) if (entry.channel === channel && entry.confirmed) {
1558
+ const event = { detail: data };
1559
+ for (const listener of entry.listeners) listener(event);
1560
+ }
1561
+ };
1562
+ const core = createAppSocketCore({
1563
+ url: HYPERLIQUID_WS[options.network],
1564
+ socket: options.socket,
1565
+ setTimer: options.setTimer,
1566
+ random: options.random,
1567
+ heartbeat: {
1568
+ intervalMs: PING_MS,
1569
+ pongTimeoutMs: PONG_MS,
1570
+ ping: JSON.stringify({ method: "ping" }),
1571
+ isPong
1572
+ },
1573
+ onOpen: resubscribe,
1574
+ onMessage,
1575
+ onUserClose: () => {
1576
+ for (const id of entries.keys()) fail(id, new TransportError("the socket was closed"));
1577
+ }
1578
+ });
1579
+ return {
1580
+ isTestnet: options.network === "Testnet",
1581
+ status: core.status,
1582
+ onStatus: core.onStatus,
1583
+ onConfirmed: (listener) => {
1584
+ confirmedListeners.add(listener);
1585
+ return () => {
1586
+ confirmedListeners.delete(listener);
1587
+ };
1588
+ },
1589
+ subscribe: async (channel, payload, listener, callOptions) => {
1590
+ if (core.closedByUser()) throw new TransportError("the socket is closed");
1591
+ const id = `${channel}:${idOf(payload)}`;
1592
+ const existing = entries.get(id);
1593
+ if (existing !== void 0) {
1594
+ const own = listener;
1595
+ existing.listeners.add(own);
1596
+ if (existing.confirmed) return unsubscribe(id, own);
1597
+ return new Promise((resolve, reject) => {
1598
+ const { resolve: outerResolve, reject: outerReject } = existing;
1599
+ existing.resolve = (sub) => {
1600
+ outerResolve(sub);
1601
+ resolve(unsubscribe(id, own));
1602
+ };
1603
+ existing.reject = (error) => {
1604
+ outerReject(error);
1605
+ reject(error);
1606
+ };
1607
+ });
1608
+ }
1609
+ const users = new Set([...entries.values()].map((entry) => userOf(entry.payload)).filter((user) => user !== void 0));
1610
+ const user = userOf(payload);
1611
+ if (user !== void 0) users.add(user);
1612
+ if (entries.size >= MAX_SUBSCRIPTIONS) throw new TransportError("the 1000-subscription limit is reached");
1613
+ if (users.size > MAX_USERS) throw new TransportError("the 10-user subscription limit is reached");
1614
+ const entry = {
1615
+ channel,
1616
+ payload,
1617
+ listeners: /* @__PURE__ */ new Set([listener]),
1618
+ resolve: () => void 0,
1619
+ reject: () => void 0,
1620
+ ...callOptions?.onError === void 0 ? {} : { onError: callOptions.onError },
1621
+ confirmed: false,
1622
+ resolved: false
1623
+ };
1624
+ const promise = new Promise((resolve, reject) => {
1625
+ entry.resolve = resolve;
1626
+ entry.reject = reject;
1627
+ });
1628
+ entry.timer = options.setTimer(CONFIRM_MS, () => {
1629
+ fail(id, new TransportError("the subscription was not confirmed within 10 s"));
1630
+ });
1631
+ callOptions?.signal?.addEventListener("abort", () => {
1632
+ fail(id, new TransportError("the subscription was aborted"));
1633
+ });
1634
+ entries.set(id, entry);
1635
+ core.connect();
1636
+ if (core.readyState() === OPEN) send("subscribe", payload);
1637
+ return promise;
1638
+ },
1639
+ close: core.close
1640
+ };
1641
+ }
1642
+ // src/apps/hyperliquid/live.ts
1643
+ /**
1644
+ * Live Hyperliquid views over the reconnecting `HyperliquidSocket` — market reads need no unlocked
1645
+ * wallet; user views resolve the group to its owner and follow the wallet lock (a lock closes
1646
+ * them). Every view reports `LiveState`: `connecting` until the subscription confirms AND the first
1647
+ * post-confirmation snapshot is applied, `live` while streaming, `stale` on any disconnect — data
1648
+ * is kept, never presented as live. A reconnect re-confirms the subscription (the socket
1649
+ * resubscribes and fires `onConfirmed`) and the view only goes `live` again on a fresh snapshot —
1650
+ * delta channels re-fetch over HTTP, snapshot channels wait for the server's first frame.
1651
+ *
1652
+ * Message shapes follow the SDK's subscription functions (`@nktkas/hyperliquid/api/subscription`,
1653
+ * docs for-developers/api/websocket/subscriptions): `l2Book` frames are full books (`{coin, time,
1654
+ * levels:[bids,asks]}`), `trades` frames are delta arrays, `candle` frames are single candles
1655
+ * upserted by open time `t`, `clearinghouseState`/`openOrders` frames are full state, `userFills`
1656
+ * frames are `{user, fills, isSnapshot?}` — `isSnapshot` replaces, deltas append deduplicated by
1657
+ * `tid`.
1658
+ */
1659
+ const TRADES_CAP = 100;
1660
+ const CANDLES_WINDOW = 200;
1661
+ const SNAPSHOT_BACKOFF_MIN_MS = 500;
1662
+ const SNAPSHOT_BACKOFF_MAX_MS = 3e4;
1663
+ /** Milliseconds per candle interval — the snapshot window is CANDLES_WINDOW intervals deep. */
1664
+ const INTERVAL_MS = {
1665
+ "1m": 6e4,
1666
+ "3m": 18e4,
1667
+ "5m": 3e5,
1668
+ "15m": 9e5,
1669
+ "30m": 18e5,
1670
+ "1h": 36e5,
1671
+ "2h": 72e5,
1672
+ "4h": 144e5,
1673
+ "8h": 288e5,
1674
+ "12h": 432e5,
1675
+ "1d": 864e5,
1676
+ "3d": 2592e5,
1677
+ "1w": 6048e5,
1678
+ "1M": 2592e6
1679
+ };
1680
+ const dedupeByTid = (list) => {
1681
+ const seen = /* @__PURE__ */ new Set();
1682
+ const out = [];
1683
+ for (const item of list) if (!seen.has(item.tid)) {
1684
+ seen.add(item.tid);
1685
+ out.push(item);
1686
+ }
1687
+ return out;
1688
+ };
1689
+ /** `channel` and the subscribed-payload subset a view waits to see re-confirmed. */
1690
+ const match = (channel, expected) => (ch, payload) => ch === channel && payloadContains(expected, payload);
1691
+ const liveFromPromise = (build) => {
1692
+ const listeners = /* @__PURE__ */ new Set();
1693
+ let inner;
1694
+ let innerOff;
1695
+ let current = {
1696
+ status: "connecting",
1697
+ data: void 0,
1698
+ updatedAt: void 0
1699
+ };
1700
+ let closed = false;
1701
+ const emit = (next) => {
1702
+ current = next;
1703
+ for (const listener of listeners) listener(next);
1704
+ };
1705
+ const ready = (async () => {
1706
+ try {
1707
+ const built = await build();
1708
+ inner = built;
1709
+ if (closed) {
1710
+ built.close();
1711
+ return;
1712
+ }
1713
+ innerOff = built.subscribe(emit);
1714
+ emit(built.getState());
1715
+ } catch {
1716
+ emit({
1717
+ status: "stale",
1718
+ data: void 0,
1719
+ updatedAt: void 0
1720
+ });
1721
+ }
1722
+ })();
1723
+ return {
1724
+ getState: () => inner?.getState() ?? current,
1725
+ subscribe: (listener) => {
1726
+ listeners.add(listener);
1727
+ return () => {
1728
+ listeners.delete(listener);
1729
+ };
1730
+ },
1731
+ close: async () => {
1732
+ if (closed) return;
1733
+ closed = true;
1734
+ await ready;
1735
+ innerOff?.();
1736
+ await inner?.close();
1737
+ emit({
1738
+ status: "stale",
1739
+ data: void 0,
1740
+ updatedAt: void 0
1741
+ });
1742
+ }
1743
+ };
1744
+ };
1745
+ function createHyperliquidLive(options) {
1746
+ const { socket, transport, ownerOf, now, setTimer, random, wallet } = options;
1747
+ const jittered = (ms) => ms + Math.floor((random(1)[0] ?? 0) / 256 * ms);
1748
+ const config = { transport: socket };
1749
+ const http = { transport };
1750
+ const userViews = /* @__PURE__ */ new Set();
1751
+ let walletUnsubscribe;
1752
+ const watchLock = (view) => {
1753
+ userViews.add(view);
1754
+ if (wallet.getSnapshot().vault !== "unlocked") view.close();
1755
+ walletUnsubscribe ??= wallet.subscribe(() => {
1756
+ if (wallet.getSnapshot().vault !== "unlocked") for (const v of [...userViews]) v.close();
1757
+ });
1758
+ };
1759
+ /**
1760
+ * The shared skeleton: status bookkeeping, confirmed/status wiring, delta buffering while a
1761
+ * snapshot is in flight, and `close` teardown. `subscribeSocket` is the SDK call (its validation +
1762
+ * event filtering stay active); `matches` names the payload this view waits to see confirmed;
1763
+ * `snapshot` (delta channels only) fetches the window each confirmation opens.
1764
+ */
1765
+ const view = (args) => {
1766
+ const listeners = /* @__PURE__ */ new Set();
1767
+ let data;
1768
+ let updatedAt;
1769
+ let status = "connecting";
1770
+ let closed = false;
1771
+ let ready = false;
1772
+ let generation = 0;
1773
+ let subscription;
1774
+ const buffered = [];
1775
+ const state = () => ({
1776
+ status,
1777
+ data,
1778
+ updatedAt
1779
+ });
1780
+ const emit = () => {
1781
+ const current = state();
1782
+ for (const listener of listeners) listener(current);
1783
+ };
1784
+ const set = (patch) => {
1785
+ status = patch.status ?? status;
1786
+ if ("data" in patch) ({data} = patch);
1787
+ if ("updatedAt" in patch) ({updatedAt} = patch);
1788
+ emit();
1789
+ };
1790
+ const onConfirmed = async () => {
1791
+ const gen = ++generation;
1792
+ ready = false;
1793
+ buffered.length = 0;
1794
+ set({ status: "connecting" });
1795
+ if (args.snapshot === void 0) return;
1796
+ let snap;
1797
+ for (let attempt = 0; snap === void 0; attempt += 1) {
1798
+ try {
1799
+ snap = await args.snapshot();
1800
+ } catch {
1801
+ if (closed || gen !== generation) return;
1802
+ const backoff = Math.min(SNAPSHOT_BACKOFF_MAX_MS, SNAPSHOT_BACKOFF_MIN_MS * 2 ** attempt);
1803
+ await new Promise((resolve) => {
1804
+ setTimer(jittered(backoff), resolve);
1805
+ });
1806
+ }
1807
+ if (closed || gen !== generation) return;
1808
+ }
1809
+ if (closed || gen !== generation) return;
1810
+ let acc = snap;
1811
+ for (const message of buffered.splice(0)) if (args.delta !== void 0) acc = args.delta(acc, message);
1812
+ ready = true;
1813
+ set({
1814
+ status: "live",
1815
+ data: acc,
1816
+ updatedAt: now()
1817
+ });
1818
+ };
1819
+ const onMessage = (message) => {
1820
+ if (closed) return;
1821
+ if (args.snapshot !== void 0) {
1822
+ if (!ready) {
1823
+ buffered.push(message);
1824
+ return;
1825
+ }
1826
+ if (args.delta !== void 0) set({
1827
+ data: args.delta(data, message),
1828
+ updatedAt: now()
1829
+ });
1830
+ return;
1831
+ }
1832
+ if (args.frame === void 0) return;
1833
+ const next = args.frame(data, message);
1834
+ if (next !== void 0) {
1835
+ ready = true;
1836
+ set({
1837
+ status: "live",
1838
+ data: next,
1839
+ updatedAt: now()
1840
+ });
1841
+ }
1842
+ };
1843
+ const offConfirmed = socket.onConfirmed((channel, payload) => {
1844
+ if (!closed && args.matches(channel, payload)) onConfirmed();
1845
+ });
1846
+ const offStatus = socket.onStatus((next) => {
1847
+ if (closed) return;
1848
+ if (next === "closed") {
1849
+ ready = false;
1850
+ set({ status: "stale" });
1851
+ }
1852
+ });
1853
+ const onError = () => {
1854
+ ready = false;
1855
+ set({ status: "stale" });
1856
+ };
1857
+ const started = (async () => {
1858
+ try {
1859
+ subscription = await args.start(onMessage, onError);
1860
+ } catch {
1861
+ ready = false;
1862
+ set({ status: "stale" });
1863
+ }
1864
+ })();
1865
+ return {
1866
+ getState: state,
1867
+ subscribe: (listener) => {
1868
+ listeners.add(listener);
1869
+ return () => {
1870
+ listeners.delete(listener);
1871
+ };
1872
+ },
1873
+ close: async () => {
1874
+ if (closed) return;
1875
+ closed = true;
1876
+ offConfirmed();
1877
+ offStatus();
1878
+ await started;
1879
+ await subscription?.unsubscribe();
1880
+ if (args.accountData === true) set({
1881
+ status: "stale",
1882
+ data: void 0,
1883
+ updatedAt: void 0
1884
+ });
1885
+ else if (status !== "stale") set({ status: "stale" });
1886
+ }
1887
+ };
1888
+ };
1889
+ const userView = (build, group) => {
1890
+ const inner = liveFromPromise(async () => build(await ownerOf(group)));
1891
+ const view = {
1892
+ getState: () => inner.getState(),
1893
+ subscribe: (listener) => inner.subscribe(listener),
1894
+ close: async () => {
1895
+ userViews.delete(view);
1896
+ await inner.close();
1897
+ }
1898
+ };
1899
+ watchLock(view);
1900
+ return view;
1901
+ };
1902
+ return {
1903
+ book: (coin, params) => view({
1904
+ matches: match("l2Book", {
1905
+ type: "l2Book",
1906
+ coin,
1907
+ ...params?.nSigFigs === void 0 ? {} : { nSigFigs: params.nSigFigs }
1908
+ }),
1909
+ start: async (listener, onError) => l2Book$1(config, {
1910
+ coin,
1911
+ ...params?.nSigFigs === void 0 ? {} : { nSigFigs: params.nSigFigs }
1912
+ }, listener, { onError }),
1913
+ frame: (_current, message) => message
1914
+ }),
1915
+ trades: (coin) => view({
1916
+ matches: match("trades", {
1917
+ type: "trades",
1918
+ coin
1919
+ }),
1920
+ start: async (listener, onError) => trades(config, { coin }, (tradesEvent) => {
1921
+ for (const trade of tradesEvent) listener(trade);
1922
+ }, { onError }),
1923
+ snapshot: async () => dedupeByTid(await recentTrades(http, { coin })).slice(0, TRADES_CAP),
1924
+ delta: (current, message) => dedupeByTid([message, ...current ?? []]).slice(0, TRADES_CAP)
1925
+ }),
1926
+ candles: (coin, interval) => view({
1927
+ matches: match("candle", {
1928
+ type: "candle",
1929
+ coin,
1930
+ interval
1931
+ }),
1932
+ start: async (listener, onError) => candle(config, {
1933
+ coin,
1934
+ interval
1935
+ }, listener, { onError }),
1936
+ snapshot: async () => {
1937
+ const endTime = now();
1938
+ return candleSnapshot(http, {
1939
+ coin,
1940
+ interval,
1941
+ startTime: Math.max(0, endTime - INTERVAL_MS[interval] * CANDLES_WINDOW),
1942
+ endTime
1943
+ });
1944
+ },
1945
+ delta: (current, message) => {
1946
+ return [...(current ?? []).filter((c) => c.t !== message.t), message].sort((a, b) => a.t - b.t);
1947
+ }
1948
+ }),
1949
+ account: (group) => userView((user) => view({
1950
+ matches: match("clearinghouseState", {
1951
+ type: "clearinghouseState",
1952
+ user
1953
+ }),
1954
+ start: async (listener, onError) => clearinghouseState$1(config, { user }, listener, { onError }),
1955
+ frame: (_current, message) => message,
1956
+ accountData: true
1957
+ }), group),
1958
+ spotState: (group) => userView((user) => view({
1959
+ matches: match("spotState", {
1960
+ type: "spotState",
1961
+ user
1962
+ }),
1963
+ start: async (listener, onError) => spotState(config, { user }, listener, { onError }),
1964
+ frame: (_current, message) => message,
1965
+ accountData: true
1966
+ }), group),
1967
+ openOrders: (group) => userView((user) => view({
1968
+ matches: match("openOrders", {
1969
+ type: "openOrders",
1970
+ user
1971
+ }),
1972
+ start: async (listener, onError) => openOrders(config, { user }, listener, { onError }),
1973
+ frame: (_current, message) => {
1974
+ options.sighted?.(user, message);
1975
+ return message;
1976
+ },
1977
+ accountData: true
1978
+ }), group),
1979
+ fills: (group) => userView((user) => view({
1980
+ matches: match("userFills", {
1981
+ type: "userFills",
1982
+ user
1983
+ }),
1984
+ start: async (listener, onError) => userFills$1(config, { user }, listener, { onError }),
1985
+ frame: (current, message) => {
1986
+ options.sighted?.(user, message);
1987
+ if (message.isSnapshot === true) return dedupeByTid(message.fills);
1988
+ if (current === void 0) return;
1989
+ return dedupeByTid([...message.fills, ...current]);
1990
+ },
1991
+ accountData: true
1992
+ }), group)
1993
+ };
1994
+ }
1995
+ // src/apps/hyperliquid/markets.ts
1996
+ function createHyperliquidMarkets(config) {
1997
+ return {
1998
+ perps: async (params) => metaAndAssetCtxs(config, params ?? {}),
1999
+ spot: async () => spotMetaAndAssetCtxs(config),
2000
+ book: async (params) => l2Book(config, params),
2001
+ candles: async (params) => candleSnapshot(config, params),
2002
+ trades: async (params) => recentTrades(config, params),
2003
+ fundingHistory: async (params) => fundingHistory(config, params),
2004
+ predictedFundings: async () => predictedFundings(config),
2005
+ mids: async (params) => allMids(config, params ?? {})
2006
+ };
2007
+ }
2008
+ // src/apps/hyperliquid/trade.ts
2009
+ function createHyperliquidTrade(options) {
2010
+ const place = async (group, params) => {
2011
+ const built = await options.actions.place(params);
2012
+ const builder = options.builderFor?.(group);
2013
+ const action = builder === void 0 ? built.action : deepFreeze({
2014
+ ...built.action,
2015
+ builder: {
2016
+ b: builder.address.toLowerCase(),
2017
+ f: builder.feeRateTenthsBps
2018
+ }
2019
+ });
2020
+ return {
2021
+ outcomes: await options.exchange.order(group, action),
2022
+ price: built.price
2023
+ };
2024
+ };
2025
+ return {
2026
+ place,
2027
+ modify: async (group, params) => options.exchange.action(group, await options.actions.modify(params)),
2028
+ batchModify: async (group, modifies) => options.exchange.order(group, await options.actions.batchModify(modifies)),
2029
+ cancel: async (group, cancels) => options.exchange.cancel(group, await options.actions.cancel(cancels)),
2030
+ cancelByCloid: async (group, cancels) => options.exchange.cancel(group, await options.actions.cancelByCloid(cancels)),
2031
+ cancelAll: async (group) => {
2032
+ const { owner } = options.registry.require(group);
2033
+ const open = await options.account.openOrders({ user: owner });
2034
+ const entries = [];
2035
+ for (const order of open) {
2036
+ const asset = await options.actions.resolve(order.coin);
2037
+ entries.push({
2038
+ a: asset.asset,
2039
+ o: order.oid
2040
+ });
2041
+ }
2042
+ const outcomes = [];
2043
+ for (const batch of options.actions.cancelBatches(entries)) outcomes.push(...await options.exchange.cancel(group, batch));
2044
+ return outcomes;
2045
+ },
2046
+ twapCancel: async (group, params) => options.exchange.action(group, await options.actions.twapCancel(params)),
2047
+ setLeverage: async (group, params) => options.exchange.action(group, await options.actions.setLeverage(params)),
2048
+ adjustMargin: async (group, params) => options.exchange.action(group, await options.actions.adjustMargin(params)),
2049
+ close: async (group, params) => {
2050
+ const { owner } = options.registry.require(group);
2051
+ const position = (await options.account.state({ user: owner })).assetPositions.find((entry) => entry.position.coin === params.coin);
2052
+ const szi = position === void 0 ? void 0 : position.position.szi;
2053
+ if (szi === void 0 || parseDecimal(szi).units === 0n) throw new HyperliquidError("invalid-input", `no open position in ${params.coin}`);
2054
+ return place(group, {
2055
+ coin: params.coin,
2056
+ side: szi.startsWith("-") ? "buy" : "sell",
2057
+ size: szi.replace(/^-/, ""),
2058
+ reduceOnly: true,
2059
+ order: {
2060
+ kind: "market",
2061
+ slippageBps: params.slippageBps
2062
+ }
2063
+ });
2064
+ },
2065
+ corrections: options.exchange.corrections
2066
+ };
2067
+ }
2068
+ const BASE_URL = {
2069
+ Mainnet: "https://api.hyperliquid.xyz",
2070
+ Testnet: "https://api.hyperliquid-testnet.xyz"
2071
+ };
2072
+ /**
2073
+ * The SDK `IRequestTransport` over the injected `fetch` — never the global one — with a timeout on
2074
+ * the injected timer. Every response's `Date` header feeds the clock. A deadline miss surfaces as
2075
+ * `HyperliquidError("timeout")`, never a generic network error: an /exchange post that timed out
2076
+ * may still have committed.
2077
+ */
2078
+ function createHyperliquidTransport(options) {
2079
+ const timeoutMs = options.timeoutMs ?? 1e4;
2080
+ const base = BASE_URL[options.network];
2081
+ return {
2082
+ isTestnet: options.network === "Testnet",
2083
+ request: async (endpoint, payload, signal) => {
2084
+ const requestStart = options.now();
2085
+ const bound = timeoutSignal(timeoutMs, options.setTimer);
2086
+ let callerAborted = false;
2087
+ const onAbort = () => {
2088
+ callerAborted = true;
2089
+ bound.abort();
2090
+ };
2091
+ signal?.addEventListener("abort", onAbort, { once: true });
2092
+ try {
2093
+ const response = await options.fetch(`${base}/${endpoint}`, {
2094
+ method: "POST",
2095
+ headers: { "content-type": "application/json" },
2096
+ body: JSON.stringify(payload),
2097
+ signal: bound.signal
2098
+ });
2099
+ const date = response.headers.get("date");
2100
+ if (date !== null) {
2101
+ const serverMs = Date.parse(date);
2102
+ if (!Number.isNaN(serverMs)) options.clock.record(serverMs, requestStart, options.now());
2103
+ }
2104
+ if (!response.ok) throw new HyperliquidError("unavailable", `POST /${endpoint} answered ${response.status}`);
2105
+ try {
2106
+ return await response.json();
2107
+ } catch (error) {
2108
+ throw new HyperliquidError("network", `POST /${endpoint} answered non-JSON`, error);
2109
+ }
2110
+ } catch (error) {
2111
+ if (error instanceof HyperliquidError) throw error;
2112
+ if (bound.signal.aborted && !callerAborted) throw new HyperliquidError("timeout", `POST /${endpoint} timed out`, error);
2113
+ throw new HyperliquidError("network", `POST /${endpoint} failed`, error);
2114
+ } finally {
2115
+ bound.cancel();
2116
+ signal?.removeEventListener("abort", onAbort);
2117
+ }
2118
+ }
2119
+ };
2120
+ }
2121
+ // src/apps/hyperliquid/user-signed.ts
2122
+ /**
2123
+ * Hyperliquid user-signed actions: EIP-712 documents the account owner signs itself (no agent key)
2124
+ * under the `HyperliquidSignTransaction` domain. The typed-data shape is exact — the kernel's
2125
+ * recognizer (`wallet-chains/evm/hyperliquid.ts`) describes each document only when the type field
2126
+ * list is verbatim, so the approval UI shows the real action instead of a blind payload.
2127
+ *
2128
+ * The EIP-712 field lists come from the SDK's own `…Types` constants — if the SDK's list changes,
2129
+ * the import resolves but the recognizer's `sameFields` check fails, surfacing as a blind payload
2130
+ * instead of a wrong signature.
2131
+ */
2132
+ /** The chain ids the user-signed domain commits to (design §2 — the signature chain). */
2133
+ const CHAIN = {
2134
+ Mainnet: {
2135
+ id: 42161,
2136
+ caip: "eip155:42161",
2137
+ signatureChainId: "0xa4b1"
2138
+ },
2139
+ Testnet: {
2140
+ id: 421614,
2141
+ caip: "eip155:421614",
2142
+ signatureChainId: "0x66eee"
2143
+ }
2144
+ };
2145
+ const EIP712_DOMAIN = [
2146
+ {
2147
+ name: "name",
2148
+ type: "string"
2149
+ },
2150
+ {
2151
+ name: "version",
2152
+ type: "string"
2153
+ },
2154
+ {
2155
+ name: "chainId",
2156
+ type: "uint256"
2157
+ },
2158
+ {
2159
+ name: "verifyingContract",
2160
+ type: "address"
2161
+ }
2162
+ ];
2163
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
2164
+ const accountRef = (group) => ({
2165
+ kind: "hd",
2166
+ walletId: group.walletId,
2167
+ groupIndex: group.groupIndex,
2168
+ template: "evm.bip44"
2169
+ });
2170
+ /** The kernel's 65-byte r‖s‖v → Hyperliquid's `{r, s, v}` (v already 27/28). */
2171
+ const signatureOf = (result) => {
2172
+ const bytes = result.signature;
2173
+ if (bytes.length !== 65) throw new HyperliquidError("unavailable", "the kernel returned a malformed signature");
2174
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2175
+ return {
2176
+ r: `0x${hex.slice(0, 64)}`,
2177
+ s: `0x${hex.slice(64, 128)}`,
2178
+ v: bytes[64] ?? 27
2179
+ };
2180
+ };
2181
+ /** The `/exchange` envelope's `status`/`response` fields without asserting the body. */
2182
+ const fieldOf = (body, field) => {
2183
+ if (typeof body !== "object" || body === null) return;
2184
+ return field === "status" ? "status" in body ? body.status : void 0 : "response" in body ? body.response : void 0;
2185
+ };
2186
+ function createHyperliquidUserSigned(options) {
2187
+ const chain = CHAIN[options.network];
2188
+ const assertClock = async () => {
2189
+ if (options.clock.skew() === void 0) await options.markets.mids();
2190
+ options.clock.assertSkew();
2191
+ };
2192
+ /**
2193
+ * Build the document, open the request, and return `{requestId, outcome}` — the outcome waits for
2194
+ * the approval, posts the action, and maps the answer. A lost POST is `unknown`: user-signed
2195
+ * actions have no cloid to reconcile by and are never re-posted.
2196
+ */
2197
+ const send = async (group, doc) => {
2198
+ await assertClock();
2199
+ const owner = await options.ownerOf(group);
2200
+ const nonce = options.clock.nextNonce(owner);
2201
+ const message = {
2202
+ hyperliquidChain: options.network,
2203
+ ...doc.fields,
2204
+ [doc.nonceField]: nonce
2205
+ };
2206
+ const typedData = JSON.stringify({
2207
+ types: {
2208
+ EIP712Domain: EIP712_DOMAIN,
2209
+ [doc.primaryType]: doc.types
2210
+ },
2211
+ primaryType: doc.primaryType,
2212
+ domain: {
2213
+ name: "HyperliquidSignTransaction",
2214
+ version: "1",
2215
+ chainId: chain.id,
2216
+ verifyingContract: ZERO_ADDRESS
2217
+ },
2218
+ message
2219
+ });
2220
+ const pending = await options.requests.prepare({
2221
+ method: "evm-sign",
2222
+ account: accountRef(group),
2223
+ network: chain.caip,
2224
+ request: {
2225
+ kind: "evm.typed-data",
2226
+ network: chain.caip,
2227
+ account: accountRef(group),
2228
+ typedData
2229
+ }
2230
+ });
2231
+ const action = {
2232
+ type: doc.type,
2233
+ signatureChainId: chain.signatureChainId,
2234
+ hyperliquidChain: options.network,
2235
+ ...doc.fields,
2236
+ [doc.nonceField]: nonce
2237
+ };
2238
+ const outcome = (async () => {
2239
+ let signature;
2240
+ try {
2241
+ const result = await options.requests.outcome(pending.id);
2242
+ if (!("kind" in result) || result.kind !== "evm.typed-data" && result.kind !== "evm.personal-message") throw new HyperliquidError("unavailable", "the request resolved without a signature");
2243
+ signature = signatureOf(result);
2244
+ } catch (error) {
2245
+ if (error instanceof RequestEndedError) throw new HyperliquidError("approval-rejected", `the request was ${error.stage}`, error);
2246
+ throw error;
2247
+ }
2248
+ try {
2249
+ const body = await options.transport.request("exchange", {
2250
+ action,
2251
+ nonce,
2252
+ signature
2253
+ });
2254
+ const status = fieldOf(body, "status");
2255
+ if (status === "ok") return { kind: "ok" };
2256
+ if (status === "err") {
2257
+ const response = fieldOf(body, "response");
2258
+ throw new HyperliquidError("rejected", typeof response === "string" ? response : "Hyperliquid rejected the action");
2259
+ }
2260
+ return { kind: "unknown" };
2261
+ } catch (error) {
2262
+ if (error instanceof HyperliquidError && error.category === "rejected") throw error;
2263
+ return { kind: "unknown" };
2264
+ }
2265
+ })();
2266
+ (async () => {
2267
+ try {
2268
+ await outcome;
2269
+ } catch {}
2270
+ })();
2271
+ return {
2272
+ requestId: pending.id,
2273
+ outcome
2274
+ };
2275
+ };
2276
+ return {
2277
+ approveAgent: async (group, { agentAddress, agentName }) => send(group, {
2278
+ type: "approveAgent",
2279
+ types: ApproveAgentTypes["HyperliquidTransaction:ApproveAgent"],
2280
+ primaryType: "HyperliquidTransaction:ApproveAgent",
2281
+ fields: {
2282
+ agentAddress: agentAddress.toLowerCase(),
2283
+ agentName
2284
+ },
2285
+ nonceField: "nonce"
2286
+ }),
2287
+ approveBuilderFee: async (group, { builder, maxFeeRate }) => send(group, {
2288
+ type: "approveBuilderFee",
2289
+ types: ApproveBuilderFeeTypes["HyperliquidTransaction:ApproveBuilderFee"],
2290
+ primaryType: "HyperliquidTransaction:ApproveBuilderFee",
2291
+ fields: {
2292
+ maxFeeRate,
2293
+ builder: builder.toLowerCase()
2294
+ },
2295
+ nonceField: "nonce"
2296
+ }),
2297
+ usdClassTransfer: async (group, { amount, toPerp }) => send(group, {
2298
+ type: "usdClassTransfer",
2299
+ types: UsdClassTransferTypes["HyperliquidTransaction:UsdClassTransfer"],
2300
+ primaryType: "HyperliquidTransaction:UsdClassTransfer",
2301
+ fields: {
2302
+ amount,
2303
+ toPerp
2304
+ },
2305
+ nonceField: "nonce"
2306
+ }),
2307
+ usdSend: async (group, { destination, amount }) => send(group, {
2308
+ type: "usdSend",
2309
+ types: UsdSendTypes["HyperliquidTransaction:UsdSend"],
2310
+ primaryType: "HyperliquidTransaction:UsdSend",
2311
+ fields: {
2312
+ destination: destination.toLowerCase(),
2313
+ amount
2314
+ },
2315
+ nonceField: "time"
2316
+ }),
2317
+ spotSend: async (group, { destination, token, amount }) => send(group, {
2318
+ type: "spotSend",
2319
+ types: SpotSendTypes["HyperliquidTransaction:SpotSend"],
2320
+ primaryType: "HyperliquidTransaction:SpotSend",
2321
+ fields: {
2322
+ destination: destination.toLowerCase(),
2323
+ token,
2324
+ amount
2325
+ },
2326
+ nonceField: "time"
2327
+ }),
2328
+ withdraw: async (group, { destination, amount }) => send(group, {
2329
+ type: "withdraw3",
2330
+ types: Withdraw3Types["HyperliquidTransaction:Withdraw"],
2331
+ primaryType: "HyperliquidTransaction:Withdraw",
2332
+ fields: {
2333
+ destination: destination.toLowerCase(),
2334
+ amount
2335
+ },
2336
+ nonceField: "time"
2337
+ })
2338
+ };
2339
+ }
2340
+ // src/apps/hyperliquid/provider.ts
2341
+ const HYPERLIQUID_DEPOSIT = {
2342
+ Mainnet: {
2343
+ tokenMessenger: "0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",
2344
+ usdc: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
2345
+ forwarder: "0xb21D281DEdb17AE5B501F6AA8256fe38C4e45757",
2346
+ network: "eip155:42161",
2347
+ destinationDomain: 19,
2348
+ minFinalityThreshold: 1e3,
2349
+ dex: "perps"
2350
+ },
2351
+ Testnet: {
2352
+ tokenMessenger: "0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA",
2353
+ usdc: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
2354
+ forwarder: "0x02e39ECb8368b41bF68FF99ff351aC9864e5E2a2",
2355
+ network: "eip155:421614",
2356
+ destinationDomain: 19,
2357
+ minFinalityThreshold: 1e3,
2358
+ dex: "perps"
2359
+ }
2360
+ };
2361
+ /** The Iris fee API host per network — the finality-1000 forward fee row feeds `maxFee`. */
2362
+ const IRIS_FEES_URL = {
2363
+ Mainnet: "https://iris-api.circle.com/v2/burn/USDC/fees/3/19?forward=true&hyperCoreDeposit=true",
2364
+ Testnet: "https://iris-api-sandbox.circle.com/v2/burn/USDC/fees/3/19?forward=true&hyperCoreDeposit=true"
2365
+ };
2366
+ /** The eth_call selectors the deposit reads: localMinter(), burnLimitsPerMessage, allowance. */
2367
+ const SEL_LOCAL_MINTER = "0xcb75c11c";
2368
+ const SEL_BURN_LIMIT = "0xa56ec632";
2369
+ const SEL_ALLOWANCE = "0xdd62ed3e";
2370
+ const ethCallWord = async (client, to, data) => {
2371
+ const result = await client.transport.request({
2372
+ method: "eth_call",
2373
+ params: [{
2374
+ to,
2375
+ data
2376
+ }, "latest"]
2377
+ });
2378
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(result)) throw new HyperliquidError("unavailable", "the CCTP chain read answered malformed");
2379
+ return result;
2380
+ };
2381
+ const isObject = (v) => typeof v === "object" && v !== null;
2382
+ const word = (v) => v.slice(2).toLowerCase().padStart(64, "0");
2383
+ /** What the Iris forward-fee endpoint contributes: flat fee + the burn's bps minimum. */
2384
+ const fetchMaxFee = async (fetcher, url, amount) => {
2385
+ let body;
2386
+ try {
2387
+ const res = await fetcher(url);
2388
+ body = res.ok ? await res.json() : void 0;
2389
+ } catch {
2390
+ body = void 0;
2391
+ }
2392
+ const row = (Array.isArray(body) ? body.filter(isObject) : []).find((r) => r["finalityThreshold"] === 1e3 && typeof r["minimumFee"] === "number" && isObject(r["forwardFee"]) && typeof r["forwardFee"]["high"] === "number");
2393
+ if (row === void 0 || !Number.isInteger(row.minimumFee) || row.minimumFee < 0 || !Number.isInteger(row.forwardFee.high) || row.forwardFee.high < 0) throw new HyperliquidError("unavailable", "the Circle fee endpoint answered malformed");
2394
+ return BigInt(row.forwardFee.high) + (amount * BigInt(row.minimumFee) + 9999n) / 10000n;
2395
+ };
2396
+ /** The per-message burn limit for this route's USDC — `localMinter` → `burnLimitsPerMessage`. */
2397
+ const readBurnLimit = async (client, messenger, usdc) => {
2398
+ const minter = (await ethCallWord(client, messenger, SEL_LOCAL_MINTER)).slice(26);
2399
+ if (!/^[0-9a-fA-F]{40}$/.test(minter)) throw new HyperliquidError("unavailable", "the messenger answered no local minter");
2400
+ return BigInt(await ethCallWord(client, `0x${minter}`, `${SEL_BURN_LIMIT}${word(usdc)}`));
2401
+ };
2402
+ /** `allowance(owner, spender)` on the route's USDC. */
2403
+ const readAllowance = async (client, usdc, owner, spender) => BigInt(await ethCallWord(client, usdc, `${SEL_ALLOWANCE}${word(owner)}${word(spender)}`));
2404
+ const preview = (price, size, szDecimals) => {
2405
+ const roundedSize = roundSize(size, szDecimals);
2406
+ return {
2407
+ price,
2408
+ size: roundedSize,
2409
+ notional: notional(price, roundedSize),
2410
+ meetsMinimum: meetsMinimum(price, roundedSize)
2411
+ };
2412
+ };
2413
+ const accountOf = (options) => {
2414
+ if (options.account === void 0) throw new HyperliquidError("not-enabled", "this provider has no account api");
2415
+ return options.account;
2416
+ };
2417
+ function createHyperliquidProvider(options) {
2418
+ const clock = createHyperliquidClock(options.now);
2419
+ const transport = createHyperliquidTransport({
2420
+ ...options,
2421
+ clock
2422
+ });
2423
+ const config = { transport };
2424
+ const markets = createHyperliquidMarkets(config);
2425
+ const account = createHyperliquidAccount(config);
2426
+ const agents = createHyperliquidAgentRegistry({
2427
+ agents: { list: async () => sessions(options.wallet).list() },
2428
+ evmAddress: async (group) => {
2429
+ const account = await accountOf(options)({
2430
+ walletId: group.walletId,
2431
+ groupIndex: group.groupIndex,
2432
+ template: "evm.bip44",
2433
+ network: options.network === "Mainnet" ? "eip155:42161" : "eip155:421614"
2434
+ });
2435
+ if (!("address" in account)) throw new HyperliquidError("unavailable", "the group has no EVM address");
2436
+ return account.address;
2437
+ },
2438
+ network: options.network,
2439
+ now: options.now,
2440
+ logger: options.logger
2441
+ });
2442
+ const actions = createHyperliquidActions({
2443
+ markets,
2444
+ random: options.random,
2445
+ now: options.now
2446
+ });
2447
+ const { requests } = options;
2448
+ const userSigned = createHyperliquidUserSigned({
2449
+ requests: requests ?? {
2450
+ prepare: () => {
2451
+ throw new HyperliquidError("not-enabled", "this provider has no request pipeline");
2452
+ },
2453
+ outcome: () => {
2454
+ throw new HyperliquidError("not-enabled", "this provider has no request pipeline");
2455
+ },
2456
+ reject: () => void 0
2457
+ },
2458
+ transport,
2459
+ clock,
2460
+ markets,
2461
+ account,
2462
+ ownerOf: async (group) => agents.owner(group),
2463
+ network: options.network,
2464
+ now: options.now
2465
+ });
2466
+ const exchange = createHyperliquidExchange({
2467
+ wallet: options.wallet,
2468
+ transport,
2469
+ clock,
2470
+ markets,
2471
+ account,
2472
+ registry: agents,
2473
+ now: options.now,
2474
+ setTimer: options.setTimer
2475
+ });
2476
+ return {
2477
+ markets,
2478
+ account,
2479
+ quote: {
2480
+ limit: ({ price, size, side, szDecimals, market }) => preview(limitPrice(price, side, szDecimals, market), size, szDecimals),
2481
+ market: ({ reference, size, side, slippageBps, szDecimals, market }) => preview(slippagePrice(reference, side, slippageBps, szDecimals, market), size, szDecimals)
2482
+ },
2483
+ clock,
2484
+ trade: createHyperliquidTrade({
2485
+ actions,
2486
+ exchange,
2487
+ account,
2488
+ registry: agents,
2489
+ ...options.builderFor === void 0 ? {} : { builderFor: options.builderFor }
2490
+ }),
2491
+ agents,
2492
+ reopen: async (group, verify) => {
2493
+ const agent = agents.require(group);
2494
+ try {
2495
+ await sessions(options.wallet).open(agent.address, verify);
2496
+ } catch (error) {
2497
+ throw new HyperliquidError(...(error instanceof WalletError ? SESSION_ERRORS[error.code] : void 0) ?? ["unavailable", "open failed"], error);
2498
+ }
2499
+ },
2500
+ userSigned,
2501
+ ...options.socket === void 0 ? {} : { live: createHyperliquidLive({
2502
+ socket: options.socket,
2503
+ transport,
2504
+ ownerOf: async (group) => agents.owner(group),
2505
+ now: options.now,
2506
+ setTimer: options.setTimer,
2507
+ random: options.random,
2508
+ wallet: options.wallet,
2509
+ sighted: exchange.sighted
2510
+ }) },
2511
+ transfer: {
2512
+ toSpot: async (group, amount) => userSigned.usdClassTransfer(group, {
2513
+ amount,
2514
+ toPerp: false
2515
+ }),
2516
+ toPerp: async (group, amount) => userSigned.usdClassTransfer(group, {
2517
+ amount,
2518
+ toPerp: true
2519
+ }),
2520
+ usdSend: async (group, params) => userSigned.usdSend(group, params),
2521
+ spotSend: async (group, params) => userSigned.spotSend(group, params),
2522
+ withdraw: async (group, params) => userSigned.withdraw(group, params)
2523
+ },
2524
+ fund: {
2525
+ depositInfo: HYPERLIQUID_DEPOSIT[options.network],
2526
+ deposit: async (group, { amount, fee, dex }) => {
2527
+ const route = HYPERLIQUID_DEPOSIT[options.network];
2528
+ if (requests === void 0 || options.networks === void 0) throw new HyperliquidError("not-enabled", "this provider has no request pipeline");
2529
+ const client = options.networks.client(route.network);
2530
+ const owner = await agents.owner(group);
2531
+ const maxFee = await fetchMaxFee(options.fetch, IRIS_FEES_URL[options.network], amount);
2532
+ if (amount <= maxFee) throw new HyperliquidError("invalid-input", "the Circle fee would consume the whole deposit");
2533
+ if (amount > await readBurnLimit(client, route.tokenMessenger, route.usdc)) throw new HyperliquidError("invalid-input", "the deposit exceeds the per-message burn limit");
2534
+ const account = {
2535
+ kind: "hd",
2536
+ walletId: group.walletId,
2537
+ groupIndex: group.groupIndex,
2538
+ template: "evm.bip44"
2539
+ };
2540
+ const track = (pending) => ({
2541
+ requestId: pending.id,
2542
+ outcome: (async () => {
2543
+ try {
2544
+ if (!("family" in await requests.outcome(pending.id))) throw new HyperliquidError("unavailable", "the deposit request resolved without a transaction");
2545
+ return { kind: "ok" };
2546
+ } catch (error) {
2547
+ if (error instanceof RequestEndedError) throw new HyperliquidError("approval-rejected", `the request was ${error.stage}`, error);
2548
+ throw error;
2549
+ }
2550
+ })()
2551
+ });
2552
+ if (await readAllowance(client, route.usdc, owner, route.tokenMessenger) < amount) return {
2553
+ kind: "approval-required",
2554
+ approval: track(await requests.prepare({
2555
+ method: "evm-approve",
2556
+ account,
2557
+ network: route.network,
2558
+ token: route.usdc,
2559
+ spender: route.tokenMessenger,
2560
+ amount,
2561
+ fee
2562
+ }))
2563
+ };
2564
+ return {
2565
+ kind: "deposit",
2566
+ deposit: track(await requests.prepare({
2567
+ method: "evm-cctp",
2568
+ account,
2569
+ network: route.network,
2570
+ amount,
2571
+ dex: dex ?? route.dex,
2572
+ maxFee,
2573
+ fee
2574
+ }))
2575
+ };
2576
+ }
2577
+ }
2578
+ };
2579
+ }
2580
+ // src/apps/hyperliquid/state.ts
2581
+ /**
2582
+ * Hyperliquid's own group-state fields and the enablement hints the flows persist between sessions:
2583
+ * the last agent that reached `enabled` (reconcile's needs-reauthorization signal) and the builder
2584
+ * approval the user declined (so renew and re-enable never re-ask). Both live in one `enablement`
2585
+ * record in collection `apps.hyperliquid` under `<walletId>/<groupIndex>` — strict parse, a
2586
+ * malformed record reads as empty.
2587
+ */
2588
+ /** Exact keys only — a record with anything else reads as absent (logged by the caller). */
2589
+ const parseHints = (raw) => {
2590
+ const value = readJson(raw);
2591
+ if (typeof value !== "object" || value === null) return;
2592
+ if (Object.keys(value).some((k) => k !== "enabledAgent" && k !== "builderDeclined")) return;
2593
+ if ("enabledAgent" in value && (typeof value.enabledAgent !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value.enabledAgent))) return;
2594
+ if ("builderDeclined" in value && value.builderDeclined !== true) return;
2595
+ const hints = {};
2596
+ if ("enabledAgent" in value && typeof value.enabledAgent === "string") hints.enabledAgent = value.enabledAgent;
2597
+ if ("builderDeclined" in value && value.builderDeclined === true) hints.builderDeclined = true;
2598
+ return hints;
2599
+ };
2600
+ function createHyperliquidHints(options) {
2601
+ const name = "enablement";
2602
+ const loaded = /* @__PURE__ */ new Map();
2603
+ const loadOne = async (group) => {
2604
+ const raw = await options.storage.get(group, name);
2605
+ if (raw === void 0) return {};
2606
+ const hints = parseHints(raw);
2607
+ if (hints === void 0) {
2608
+ options.logger.warn(`hyperliquid ${name} ${group.walletId}/${group.groupIndex} skipped: malformed`);
2609
+ return {};
2610
+ }
2611
+ return hints;
2612
+ };
2613
+ const load = async (group) => {
2614
+ const key = `${group.walletId}/${group.groupIndex}`;
2615
+ let pending = loaded.get(key);
2616
+ if (pending === void 0) {
2617
+ pending = loadOne(group);
2618
+ loaded.set(key, pending);
2619
+ }
2620
+ return pending;
2621
+ };
2622
+ const persist = (group, hints) => {
2623
+ const key = `${group.walletId}/${group.groupIndex}`;
2624
+ const bytes = new TextEncoder().encode(JSON.stringify(hints));
2625
+ const put = async () => {
2626
+ try {
2627
+ await options.storage.put(group, name, bytes);
2628
+ } catch (error) {
2629
+ options.logger.warn(`hyperliquid ${name} ${key} write failed`, error);
2630
+ }
2631
+ };
2632
+ put();
2633
+ };
2634
+ return {
2635
+ track: async (group, flow) => {
2636
+ const hints = await load(group);
2637
+ return {
2638
+ current: flow.current,
2639
+ stale: flow.stale,
2640
+ wasEnabledAgent: () => hints.enabledAgent,
2641
+ wasBuilderDeclined: () => hints.builderDeclined === true,
2642
+ write: (patch) => {
2643
+ if (flow.stale()) return;
2644
+ flow.write(patch);
2645
+ const state = flow.current();
2646
+ let changed = false;
2647
+ if (state.status === "enabled" && state.agent !== void 0) {
2648
+ if (hints.enabledAgent !== state.agent.address) {
2649
+ hints.enabledAgent = state.agent.address;
2650
+ changed = true;
2651
+ }
2652
+ } else if ((state.status === "disabled" || state.status === "unavailable") && hints.enabledAgent !== void 0) {
2653
+ delete hints.enabledAgent;
2654
+ changed = true;
2655
+ }
2656
+ if (state.builder === "declined") {
2657
+ if (hints.builderDeclined !== true) {
2658
+ hints.builderDeclined = true;
2659
+ changed = true;
2660
+ }
2661
+ } else if (state.builder === "approved" && hints.builderDeclined === true) {
2662
+ delete hints.builderDeclined;
2663
+ changed = true;
2664
+ }
2665
+ if (changed) persist(group, hints);
2666
+ }
2667
+ };
2668
+ },
2669
+ reset: () => loaded.clear()
2670
+ };
2671
+ }
2672
+ // src/apps/hyperliquid/app.ts
2673
+ function hyperliquid(config) {
2674
+ const { network, agentName, builder } = config;
2675
+ if (!/^[A-Za-z0-9._-]{1,16}$/.test(agentName)) throw new Error("hyperliquid agentName must match ^[A-Za-z0-9._-]{1,16}$");
2676
+ if (builder !== void 0) {
2677
+ if (!/^0x[0-9a-fA-F]{40}$/.test(builder.address)) throw new Error("hyperliquid builder.address must be a 20-byte hex address");
2678
+ if (!Number.isInteger(builder.feeRateTenthsBps) || builder.feeRateTenthsBps < 1 || builder.feeRateTenthsBps > 100) throw new Error("hyperliquid builder.feeRateTenthsBps must be an integer in 1..100");
2679
+ }
2680
+ return {
2681
+ id: "hyperliquid",
2682
+ enableWhen: ["available"],
2683
+ create: (context) => {
2684
+ const socket = createHyperliquidSocket({
2685
+ network,
2686
+ socket: context.socket,
2687
+ setTimer: context.setTimer,
2688
+ random: context.random
2689
+ });
2690
+ const hints = createHyperliquidHints({
2691
+ storage: context.storage,
2692
+ logger: context.logger
2693
+ });
2694
+ const provider = createHyperliquidProvider({
2695
+ wallet: context.wallet,
2696
+ account: context.account,
2697
+ network,
2698
+ fetch: context.fetch,
2699
+ setTimer: context.setTimer,
2700
+ now: context.now,
2701
+ random: context.random,
2702
+ logger: context.logger,
2703
+ requests: context.requests,
2704
+ networks: context.networks,
2705
+ socket,
2706
+ builderFor: (group) => {
2707
+ if (builder === void 0) return;
2708
+ return context.groupState(group)?.builder === "approved" ? builder : void 0;
2709
+ }
2710
+ });
2711
+ const enable = createHyperliquidEnable({
2712
+ wallet: context.wallet,
2713
+ provider,
2714
+ userSigned: provider.userSigned,
2715
+ requests: context.requests,
2716
+ network,
2717
+ agentName,
2718
+ ...builder === void 0 ? {} : { builder },
2719
+ now: context.now,
2720
+ setTimer: context.setTimer,
2721
+ logger: context.logger,
2722
+ hints
2723
+ });
2724
+ return {
2725
+ api: {
2726
+ ...provider,
2727
+ approveBuilder: async (group) => context.flow(group, async (flow) => enable.approveBuilder(group, flow))
2728
+ },
2729
+ provider: enable.provider,
2730
+ unlock: provider.agents.refresh,
2731
+ lock: () => {
2732
+ provider.agents.reset();
2733
+ hints.reset();
2734
+ },
2735
+ close: () => socket.close()
2736
+ };
2737
+ }
2738
+ };
2739
+ }
2740
+ export { HYPERLIQUID_DEPOSIT, HyperliquidError, hyperliquid };
2741
+
2742
+ //# sourceMappingURL=apps-hyperliquid.mjs.map