@arca-network/sdk 1.1.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 (67) hide show
  1. package/LICENSE +91 -0
  2. package/README.md +65 -0
  3. package/dist/admin.d.ts +159 -0
  4. package/dist/admin.d.ts.map +1 -0
  5. package/dist/admin.js +399 -0
  6. package/dist/admin.js.map +1 -0
  7. package/dist/arca.d.ts +1343 -0
  8. package/dist/arca.d.ts.map +1 -0
  9. package/dist/arca.js +3454 -0
  10. package/dist/arca.js.map +1 -0
  11. package/dist/cache.d.ts +29 -0
  12. package/dist/cache.d.ts.map +1 -0
  13. package/dist/cache.js +74 -0
  14. package/dist/cache.js.map +1 -0
  15. package/dist/candle-cdn.d.ts +17 -0
  16. package/dist/candle-cdn.d.ts.map +1 -0
  17. package/dist/candle-cdn.js +138 -0
  18. package/dist/candle-cdn.js.map +1 -0
  19. package/dist/client.d.ts +98 -0
  20. package/dist/client.d.ts.map +1 -0
  21. package/dist/client.js +225 -0
  22. package/dist/client.js.map +1 -0
  23. package/dist/errors.d.ts +153 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +243 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/events.d.ts +2 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +6 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/index.d.ts +21 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +71 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/ladder.d.ts +40 -0
  36. package/dist/ladder.d.ts.map +1 -0
  37. package/dist/ladder.js +145 -0
  38. package/dist/ladder.js.map +1 -0
  39. package/dist/ladder.test.d.ts +2 -0
  40. package/dist/ladder.test.d.ts.map +1 -0
  41. package/dist/ladder.test.js +112 -0
  42. package/dist/ladder.test.js.map +1 -0
  43. package/dist/operation-handle.d.ts +88 -0
  44. package/dist/operation-handle.d.ts.map +1 -0
  45. package/dist/operation-handle.js +262 -0
  46. package/dist/operation-handle.js.map +1 -0
  47. package/dist/recovery.d.ts +20 -0
  48. package/dist/recovery.d.ts.map +1 -0
  49. package/dist/recovery.js +91 -0
  50. package/dist/recovery.js.map +1 -0
  51. package/dist/revalue.d.ts +22 -0
  52. package/dist/revalue.d.ts.map +1 -0
  53. package/dist/revalue.js +153 -0
  54. package/dist/revalue.js.map +1 -0
  55. package/dist/streams.d.ts +661 -0
  56. package/dist/streams.d.ts.map +1 -0
  57. package/dist/streams.js +2272 -0
  58. package/dist/streams.js.map +1 -0
  59. package/dist/types.d.ts +2814 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +118 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/websocket.d.ts +240 -0
  64. package/dist/websocket.d.ts.map +1 -0
  65. package/dist/websocket.js +1288 -0
  66. package/dist/websocket.js.map +1 -0
  67. package/package.json +48 -0
package/dist/arca.js ADDED
@@ -0,0 +1,3454 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Arca = exports.TwapWatchStream = exports.FundingWatchStream = exports.FillWatchStream = exports.ExchangeWatchStream = exports.TradeWatchStream = exports.CandleChartStream = exports.CandleWatchStream = exports.PriceWatchStream = exports.MaxOrderSizeWatchStream = exports.PnlChartStream = exports.EquityChartStream = exports.AggregationWatchStream = exports.ObjectsWatchStream = exports.ObjectWatchStream = exports.BalanceWatchStream = exports.OperationWatchStream = void 0;
4
+ exports.computeChartRange = computeChartRange;
5
+ const client_1 = require("./client");
6
+ const cache_1 = require("./cache");
7
+ const candle_cdn_1 = require("./candle-cdn");
8
+ const errors_1 = require("./errors");
9
+ const operation_handle_1 = require("./operation-handle");
10
+ const recovery_1 = require("./recovery");
11
+ const types_1 = require("./types");
12
+ const websocket_1 = require("./websocket");
13
+ const streams_1 = require("./streams");
14
+ var streams_2 = require("./streams");
15
+ Object.defineProperty(exports, "OperationWatchStream", { enumerable: true, get: function () { return streams_2.OperationWatchStream; } });
16
+ Object.defineProperty(exports, "BalanceWatchStream", { enumerable: true, get: function () { return streams_2.BalanceWatchStream; } });
17
+ Object.defineProperty(exports, "ObjectWatchStream", { enumerable: true, get: function () { return streams_2.ObjectWatchStream; } });
18
+ Object.defineProperty(exports, "ObjectsWatchStream", { enumerable: true, get: function () { return streams_2.ObjectsWatchStream; } });
19
+ Object.defineProperty(exports, "AggregationWatchStream", { enumerable: true, get: function () { return streams_2.AggregationWatchStream; } });
20
+ Object.defineProperty(exports, "EquityChartStream", { enumerable: true, get: function () { return streams_2.EquityChartStream; } });
21
+ Object.defineProperty(exports, "PnlChartStream", { enumerable: true, get: function () { return streams_2.PnlChartStream; } });
22
+ Object.defineProperty(exports, "MaxOrderSizeWatchStream", { enumerable: true, get: function () { return streams_2.MaxOrderSizeWatchStream; } });
23
+ Object.defineProperty(exports, "PriceWatchStream", { enumerable: true, get: function () { return streams_2.PriceWatchStream; } });
24
+ Object.defineProperty(exports, "CandleWatchStream", { enumerable: true, get: function () { return streams_2.CandleWatchStream; } });
25
+ Object.defineProperty(exports, "CandleChartStream", { enumerable: true, get: function () { return streams_2.CandleChartStream; } });
26
+ Object.defineProperty(exports, "TradeWatchStream", { enumerable: true, get: function () { return streams_2.TradeWatchStream; } });
27
+ Object.defineProperty(exports, "ExchangeWatchStream", { enumerable: true, get: function () { return streams_2.ExchangeWatchStream; } });
28
+ Object.defineProperty(exports, "FillWatchStream", { enumerable: true, get: function () { return streams_2.FillWatchStream; } });
29
+ Object.defineProperty(exports, "FundingWatchStream", { enumerable: true, get: function () { return streams_2.FundingWatchStream; } });
30
+ Object.defineProperty(exports, "TwapWatchStream", { enumerable: true, get: function () { return streams_2.TwapWatchStream; } });
31
+ function normalizeWatchPricesOpts(opts) {
32
+ if (typeof opts === 'string')
33
+ return { exchange: opts };
34
+ if (!opts)
35
+ return { exchange: 'sim' };
36
+ return {
37
+ exchange: opts.exchange ?? 'sim',
38
+ coins: opts.coins,
39
+ readyTimeoutMs: opts.readyTimeoutMs,
40
+ };
41
+ }
42
+ const DEFAULT_BASE_URL = 'https://api.arcaos.io';
43
+ const DEFAULT_CDN_BASE_URL = 'https://data.arcaos.io';
44
+ const REFRESH_BUFFER_MS = 30_000; // refresh 30s before expiry
45
+ // `watchEquityChart` / `watchPnlChart` treat a watch as a "live tail" when
46
+ // the requested `to` is within this distance of construction time, and slide
47
+ // the window forward on every refresh. Watches with `to` further in the past
48
+ // are treated as fixed-window watches and stay pinned to the original range.
49
+ const LIVE_TAIL_THRESHOLD_MS = 60_000;
50
+ /**
51
+ * Compute `from`/`to` ISO timestamps for a chart range preset, anchored
52
+ * to the current wall clock. Used by `watchEquityChartLive` /
53
+ * `watchPnlChartLive`. Exposed as a public helper so builders building
54
+ * custom React/Swift/Vue UIs can derive the same windows the SDK uses.
55
+ */
56
+ function computeChartRange(range) {
57
+ const nowStr = new Date().toISOString();
58
+ const d = new Date(nowStr);
59
+ switch (range) {
60
+ case '1h':
61
+ d.setHours(d.getHours() - 1);
62
+ break;
63
+ case '24h':
64
+ d.setHours(d.getHours() - 24);
65
+ break;
66
+ case '7d':
67
+ d.setDate(d.getDate() - 7);
68
+ break;
69
+ case '30d':
70
+ d.setDate(d.getDate() - 30);
71
+ break;
72
+ case '3m':
73
+ d.setMonth(d.getMonth() - 3);
74
+ break;
75
+ case '1y':
76
+ d.setFullYear(d.getFullYear() - 1);
77
+ break;
78
+ case 'ytd':
79
+ d.setMonth(0);
80
+ d.setDate(1);
81
+ d.setHours(0, 0, 0, 0);
82
+ break;
83
+ case 'all':
84
+ d.setFullYear(d.getFullYear() - 5);
85
+ break;
86
+ }
87
+ return { from: d.toISOString(), to: nowStr };
88
+ }
89
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
90
+ const TYPEID_RE = /^[a-z]{2,63}_[0-9a-hjkmnp-tv-z]{26}$/i;
91
+ /**
92
+ * Validate that a path argument starts with '/'.
93
+ * Paths without a trailing slash target a single object.
94
+ * Paths with a trailing slash aggregate all objects under that prefix.
95
+ */
96
+ function validatePath(path) {
97
+ if (!path.startsWith('/')) {
98
+ throw new Error(`Path must start with '/'. Got: "${path}". ` +
99
+ `Use a trailing slash for aggregation (e.g., '/users/alice/') ` +
100
+ `or an exact path for a single object (e.g., '/users/alice/main').`);
101
+ }
102
+ }
103
+ /**
104
+ * Resolve the history scope from caller options into the concrete
105
+ * `kind` + `objectId` sent to the server. Defaults to path scope.
106
+ * `objectId` is only honored when `kind` is `'object'`, so a stray id
107
+ * on a path request can't accidentally change the query.
108
+ */
109
+ function resolveHistoryScope(options) {
110
+ const kind = options?.kind === 'object' ? 'object' : 'path';
111
+ const objectId = kind === 'object' ? options?.objectId : undefined;
112
+ return { kind, objectId };
113
+ }
114
+ function normalizeV2EquityHistory(path, from, to, resp) {
115
+ const equityPoints = (resp.points ?? []).map((p) => ({
116
+ timestamp: p.ts,
117
+ equityUsd: p.equityUsd,
118
+ status: p.status,
119
+ cumInflowsUsd: p.cumInflowsUsd,
120
+ cumOutflowsUsd: p.cumOutflowsUsd,
121
+ lastEventOpId: p.lastEventOpId,
122
+ midSetId: p.midSetId,
123
+ }));
124
+ return {
125
+ prefix: path,
126
+ from,
127
+ to,
128
+ points: equityPoints.length,
129
+ resolution: resp.resolution,
130
+ resolutionRequested: resp.resolutionRequested,
131
+ serverNow: resp.serverNow,
132
+ equityPoints,
133
+ };
134
+ }
135
+ function normalizeV2PnlHistory(path, from, to, resp) {
136
+ const pnlPoints = (resp.points ?? []).map((p) => ({
137
+ timestamp: p.ts,
138
+ pnlUsd: p.pnlUsd,
139
+ equityUsd: p.equityUsd,
140
+ valueUsd: p.valueUsd,
141
+ status: p.status,
142
+ cumInflowsUsd: p.cumInflowsUsd,
143
+ cumOutflowsUsd: p.cumOutflowsUsd,
144
+ lastEventOpId: p.lastEventOpId,
145
+ midSetId: p.midSetId,
146
+ }));
147
+ return {
148
+ prefix: path,
149
+ from,
150
+ to,
151
+ points: pnlPoints.length,
152
+ resolution: resp.resolution,
153
+ resolutionRequested: resp.resolutionRequested,
154
+ serverNow: resp.serverNow,
155
+ startingEquityUsd: resp.startEquityUsd ?? resp.startingEquityUsd ?? '0',
156
+ effectiveFrom: resp.effectiveFrom,
157
+ pnlPoints,
158
+ externalFlows: resp.externalFlows ?? [],
159
+ midPrices: resp.midPrices ?? {},
160
+ };
161
+ }
162
+ function isIdFormat(value) {
163
+ return UUID_RE.test(value) || TYPEID_RE.test(value);
164
+ }
165
+ /**
166
+ * Pre-computed function selectors (first 4 bytes of keccak256 of the signature)
167
+ * for the ArcaCustodyPool contract. These are fixed since the contract ABI is known.
168
+ *
169
+ * Verified against: `cast sig "lockBoundary(bytes32)"` etc. from Foundry.
170
+ */
171
+ const CUSTODY_SELECTORS = {
172
+ 'lockBoundary(bytes32)': '0x67f82a1d',
173
+ 'unlockBoundary(bytes32)': '0x83a2f7cd',
174
+ 'withdraw(bytes32)': '0x8e19899e',
175
+ 'assignRecoveryKey(bytes32,address)': '0xf5b7e3a6',
176
+ 'setTimeLock(bytes32,uint256)': '0x3e41d187',
177
+ 'cancelPendingExit(bytes32)': '0x5e50fbe8',
178
+ 'recoveryWithdrawAccount(bytes32)': '0xba7b2fbd',
179
+ };
180
+ /**
181
+ * Minimal ABI encoder for custody contract calls.
182
+ * Uses pre-computed selectors and supports bytes32, address, uint256 args.
183
+ */
184
+ function encodeCustodyCall(signature, args) {
185
+ const selector = CUSTODY_SELECTORS[signature];
186
+ if (!selector)
187
+ throw new Error(`Unknown custody function: ${signature}`);
188
+ const encoded = args.map(arg => abiEncodeParam(arg)).join('');
189
+ return selector + encoded;
190
+ }
191
+ function abiEncodeParam(value) {
192
+ if (value.startsWith('0x') && value.length === 66) {
193
+ return value.slice(2);
194
+ }
195
+ if (value.startsWith('0x') && value.length === 42) {
196
+ return value.slice(2).toLowerCase().padStart(64, '0');
197
+ }
198
+ const n = BigInt(value);
199
+ return n.toString(16).padStart(64, '0');
200
+ }
201
+ function isApiKeyConfig(config) {
202
+ return 'apiKey' in config;
203
+ }
204
+ function isTokenConfig(config) {
205
+ return 'token' in config || 'tokenProvider' in config;
206
+ }
207
+ /**
208
+ * Decode a JWT payload without verifying the signature.
209
+ * Used client-side to extract claims like realmId from scoped tokens.
210
+ */
211
+ function decodeJwtPayload(token) {
212
+ const parts = token.split('.');
213
+ if (parts.length !== 3)
214
+ throw new Error('Invalid JWT format');
215
+ const payload = parts[1];
216
+ // atob works in browser; Buffer works in Node
217
+ const json = typeof atob === 'function'
218
+ ? atob(payload.replace(/-/g, '+').replace(/_/g, '/'))
219
+ : Buffer.from(payload, 'base64url').toString('utf-8');
220
+ return JSON.parse(json);
221
+ }
222
+ /**
223
+ * The Arca SDK client.
224
+ *
225
+ * Usage with API key (backend):
226
+ * ```typescript
227
+ * const arca = new Arca({
228
+ * apiKey: 'arca_78ae7276_...',
229
+ * realm: 'development',
230
+ * });
231
+ * await arca.ready();
232
+ * ```
233
+ *
234
+ * Usage with scoped token (frontend):
235
+ * ```typescript
236
+ * const arca = Arca.fromToken(scopedJwt);
237
+ * await arca.ready();
238
+ * ```
239
+ */
240
+ /** Merge a hypothetical fill with an existing same-market position using the
241
+ * same rules as `PositionService.ApplyFill` in
242
+ * backend/services/sim-exchange-go/internal/service/position.go. Returns the
243
+ * resulting (size, entryPrice, side) triple, or `null` when the fill would
244
+ * fully close the existing position. */
245
+ function mergeOrderWithPosition(newSide, newSize, fillPrice, existing) {
246
+ if (!Number.isFinite(newSize) || newSize <= 0 || !Number.isFinite(fillPrice) || fillPrice <= 0) {
247
+ return null;
248
+ }
249
+ if (!existing) {
250
+ return { size: newSize, entry: fillPrice, side: newSide };
251
+ }
252
+ const exSize = Number.parseFloat(existing.size);
253
+ const exEntry = Number.parseFloat(existing.entryPrice);
254
+ if (!Number.isFinite(exSize) || exSize <= 0 || !Number.isFinite(exEntry) || exEntry <= 0) {
255
+ return { size: newSize, entry: fillPrice, side: newSide };
256
+ }
257
+ if (existing.side === newSide) {
258
+ const mergedSize = exSize + newSize;
259
+ const mergedEntry = (exSize * exEntry + newSize * fillPrice) / mergedSize;
260
+ return { size: mergedSize, entry: mergedEntry, side: newSide };
261
+ }
262
+ if (newSize < exSize) {
263
+ return { size: exSize - newSize, entry: exEntry, side: existing.side };
264
+ }
265
+ if (newSize === exSize) {
266
+ return null;
267
+ }
268
+ return { size: newSize - exSize, entry: fillPrice, side: newSide };
269
+ }
270
+ class Arca {
271
+ static fees = {
272
+ exchangeTransfer: '0.05',
273
+ };
274
+ /**
275
+ * Pure calculator that converts between spend (gross), notional (net), and
276
+ * token representations of an order. All inputs come from `ActiveAssetData`
277
+ * or `watchMaxOrderSize`. No network call.
278
+ *
279
+ * `tokens` in the result is the committed quantity submitted to the exchange.
280
+ * Dollar values are estimates at the provided `price`. For limit orders
281
+ * (where `price` is the limit), the breakdown is exact contingent on fill.
282
+ * For market orders (where `price` is mark), actual fill price may differ.
283
+ */
284
+ static orderBreakdown(opts) {
285
+ const price = Number.parseFloat(opts.price);
286
+ const feeRate = Number.parseFloat(opts.feeRate);
287
+ const leverage = opts.leverage;
288
+ const szDecimals = opts.szDecimals ?? 5;
289
+ const amount = Number.parseFloat(opts.amount);
290
+ if (!Number.isFinite(price) || price <= 0 || !Number.isFinite(leverage) || leverage <= 0 ||
291
+ !Number.isFinite(feeRate) || feeRate < 0 || !Number.isFinite(amount) || amount <= 0) {
292
+ return { tokens: '0', notionalUsd: '0', marginRequired: '0', estimatedFee: '0', totalSpend: '0', price: opts.price, feeRate: opts.feeRate };
293
+ }
294
+ let notional;
295
+ switch (opts.amountType) {
296
+ case 'spend':
297
+ if (opts.marginTiers && opts.marginTiers.length > 0) {
298
+ const targetSpend = amount;
299
+ let deduction = 0;
300
+ const tierMaxLev = opts.marginTiers[0].maxLeverage;
301
+ let effLev = leverage;
302
+ if (tierMaxLev < effLev)
303
+ effLev = tierMaxLev;
304
+ let activeRate = 1 / effLev;
305
+ let prevRate = activeRate;
306
+ let prevDeduction = 0;
307
+ for (let i = 0; i < opts.marginTiers.length; i++) {
308
+ const tier = opts.marginTiers[i];
309
+ const lowerBound = Number.parseFloat(tier.lowerBound);
310
+ let tierLev = tier.maxLeverage;
311
+ let lev = leverage;
312
+ if (tierLev < lev)
313
+ lev = tierLev;
314
+ const rate = 1 / lev;
315
+ const nextDeduction = prevDeduction + lowerBound * (rate - prevRate);
316
+ const spendAtBound = lowerBound * rate - nextDeduction + lowerBound * feeRate;
317
+ if (targetSpend < spendAtBound) {
318
+ break;
319
+ }
320
+ activeRate = rate;
321
+ prevRate = rate;
322
+ prevDeduction = nextDeduction;
323
+ deduction = nextDeduction;
324
+ }
325
+ notional = (targetSpend + deduction) / (activeRate + feeRate);
326
+ }
327
+ else {
328
+ notional = amount / (1 / leverage + feeRate);
329
+ }
330
+ break;
331
+ case 'notional':
332
+ notional = amount;
333
+ break;
334
+ case 'tokens':
335
+ notional = amount * price;
336
+ break;
337
+ default:
338
+ return { tokens: '0', notionalUsd: '0', marginRequired: '0', estimatedFee: '0', totalSpend: '0', price: opts.price, feeRate: opts.feeRate };
339
+ }
340
+ let tokens = Math.floor(notional / price * (10 ** szDecimals)) / (10 ** szDecimals);
341
+ let actualNotional = tokens * price;
342
+ let marginRequiredNum = 0;
343
+ let nextTierThresholdNum;
344
+ let mmRequiredNum;
345
+ if (opts.marginTiers && opts.marginTiers.length > 0) {
346
+ let deduction = 0;
347
+ const tierMaxLev = opts.marginTiers[0].maxLeverage;
348
+ let effLev = leverage;
349
+ if (tierMaxLev < effLev)
350
+ effLev = tierMaxLev;
351
+ let activeRate = 1 / effLev;
352
+ let prevRate = activeRate;
353
+ let prevDeduction = 0;
354
+ for (let i = 0; i < opts.marginTiers.length; i++) {
355
+ const tier = opts.marginTiers[i];
356
+ const lowerBound = Number.parseFloat(tier.lowerBound);
357
+ let tierLev = tier.maxLeverage;
358
+ let lev = leverage;
359
+ if (tierLev < lev)
360
+ lev = tierLev;
361
+ const rate = 1 / lev;
362
+ if (actualNotional < lowerBound) {
363
+ nextTierThresholdNum = lowerBound;
364
+ break;
365
+ }
366
+ deduction = prevDeduction + lowerBound * (rate - prevRate);
367
+ activeRate = rate;
368
+ prevRate = rate;
369
+ prevDeduction = deduction;
370
+ }
371
+ marginRequiredNum = actualNotional * activeRate - deduction;
372
+ let mmDeduction = 0;
373
+ let mmActiveRate = 0.5 / opts.marginTiers[0].maxLeverage;
374
+ let mmPrevRate = mmActiveRate;
375
+ let mmPrevDeduction = 0;
376
+ for (let i = 0; i < opts.marginTiers.length; i++) {
377
+ const tier = opts.marginTiers[i];
378
+ const lowerBound = Number.parseFloat(tier.lowerBound);
379
+ const rate = 0.5 / tier.maxLeverage;
380
+ if (actualNotional < lowerBound) {
381
+ break;
382
+ }
383
+ mmDeduction = mmPrevDeduction + lowerBound * (rate - mmPrevRate);
384
+ mmActiveRate = rate;
385
+ mmPrevRate = rate;
386
+ mmPrevDeduction = mmDeduction;
387
+ }
388
+ mmRequiredNum = actualNotional * mmActiveRate - mmDeduction;
389
+ }
390
+ else {
391
+ marginRequiredNum = actualNotional / leverage;
392
+ }
393
+ const estimatedFee = actualNotional * feeRate;
394
+ const totalSpend = marginRequiredNum + estimatedFee;
395
+ const fmt = (v, d = 8) => {
396
+ if (!Number.isFinite(v))
397
+ return '0';
398
+ return v.toFixed(d).replace(/\.?0+$/, '');
399
+ };
400
+ let estimatedLiquidationPrice;
401
+ if ((opts.maintenanceMarginRate !== undefined || opts.marginTiers !== undefined) && opts.accountContext !== undefined) {
402
+ const ctx = opts.accountContext;
403
+ const equity = Number.parseFloat(ctx.equity);
404
+ const otherMM = Number.parseFloat(ctx.otherMaintenanceMargin);
405
+ if (Number.isFinite(equity) && Number.isFinite(otherMM)) {
406
+ // Apply the same merge semantics as backend `PositionService.ApplyFill`
407
+ // so the preview matches the position the user will actually have.
408
+ const newSide = opts.side === 'buy' ? 'long' : 'short';
409
+ const merged = mergeOrderWithPosition(newSide, tokens, price, ctx.existingPosition);
410
+ if (merged !== null && merged.size > 0) {
411
+ const mergedNotional = merged.size * merged.entry;
412
+ let mmMerged = 0;
413
+ if (opts.marginTiers && opts.marginTiers.length > 0) {
414
+ let mmDeduction = 0;
415
+ let mmActiveRate = 0.5 / opts.marginTiers[0].maxLeverage;
416
+ let mmPrevRate = mmActiveRate;
417
+ let mmPrevDeduction = 0;
418
+ for (let i = 0; i < opts.marginTiers.length; i++) {
419
+ const tier = opts.marginTiers[i];
420
+ const lowerBound = Number.parseFloat(tier.lowerBound);
421
+ const rate = 0.5 / tier.maxLeverage;
422
+ if (mergedNotional < lowerBound) {
423
+ break;
424
+ }
425
+ mmDeduction = mmPrevDeduction + lowerBound * (rate - mmPrevRate);
426
+ mmActiveRate = rate;
427
+ mmPrevRate = rate;
428
+ mmPrevDeduction = mmDeduction;
429
+ }
430
+ mmMerged = mergedNotional * mmActiveRate - mmDeduction;
431
+ }
432
+ else if (opts.maintenanceMarginRate !== undefined) {
433
+ const mmr = Number.parseFloat(opts.maintenanceMarginRate);
434
+ mmMerged = mmr * mergedNotional;
435
+ }
436
+ const equityPost = equity - estimatedFee;
437
+ const marginAvail = equityPost - (otherMM + mmMerged);
438
+ if (marginAvail > 0) {
439
+ // At the fill instant, mid == price (we're projecting the moment
440
+ // the order fills). The merged position's uPnL contribution is
441
+ // invariant to the new fill, so equityPost only changes by the fee.
442
+ const perUnit = marginAvail / merged.size;
443
+ const liq = merged.side === 'long' ? price - perUnit : price + perUnit;
444
+ if (liq > 0) {
445
+ estimatedLiquidationPrice = fmt(liq);
446
+ }
447
+ }
448
+ }
449
+ }
450
+ }
451
+ return {
452
+ tokens: fmt(tokens, szDecimals),
453
+ notionalUsd: fmt(actualNotional),
454
+ marginRequired: fmt(marginRequiredNum),
455
+ estimatedFee: fmt(estimatedFee),
456
+ totalSpend: fmt(totalSpend),
457
+ price: opts.price,
458
+ feeRate: opts.feeRate,
459
+ ...(estimatedLiquidationPrice !== undefined ? { estimatedLiquidationPrice } : {}),
460
+ ...(opts.marginTiers ? { effectiveLeverage: actualNotional > 0 ? fmt(actualNotional / marginRequiredNum) : fmt(leverage) } : {}),
461
+ ...(opts.marginTiers && mmRequiredNum !== undefined && actualNotional > 0 ? { effectiveMaintenanceMarginRate: fmt(mmRequiredNum / actualNotional) } : {}),
462
+ ...(nextTierThresholdNum !== undefined ? { nextTierThreshold: fmt(nextTierThresholdNum) } : {}),
463
+ };
464
+ }
465
+ client;
466
+ realmInput;
467
+ resolvedRealmId = null;
468
+ initPromise = null;
469
+ candleCdnBaseUrl = null;
470
+ // Token lifecycle management
471
+ tokenProvider = null;
472
+ pendingRefresh = null;
473
+ refreshTimer = null;
474
+ tokenFetchPromise = null;
475
+ authErrorListeners = new Set();
476
+ // Market metadata cache
477
+ metaCache = null;
478
+ metaPromise = null;
479
+ // TWAP limits cache. Static for the process lifetime so a single GET
480
+ // covers every subsequent call to getTwapLimits()/recommendedIntervalSeconds().
481
+ twapLimitsCache = null;
482
+ /** WebSocket manager for real-time events. */
483
+ ws;
484
+ historyCache;
485
+ constructor(config) {
486
+ const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
487
+ if (isApiKeyConfig(config)) {
488
+ this.client = new client_1.ArcaClient({
489
+ credential: config.apiKey,
490
+ credentialType: 'apiKey',
491
+ baseUrl: `${baseUrl}/api/v1`,
492
+ onStepUpRequired: config.onStepUpRequired,
493
+ });
494
+ this.realmInput = config.realm;
495
+ }
496
+ else if (isTokenConfig(config)) {
497
+ const initialToken = config.token ?? '';
498
+ this.tokenProvider = config.tokenProvider ?? null;
499
+ this.client = new client_1.ArcaClient({
500
+ credential: initialToken,
501
+ credentialType: 'token',
502
+ baseUrl: `${baseUrl}/api/v1`,
503
+ onUnauthorized: this.tokenProvider
504
+ ? () => this.refreshTokenFromProvider()
505
+ : undefined,
506
+ onAuthError: (err) => this.emitAuthError(err),
507
+ onStepUpRequired: config.onStepUpRequired,
508
+ });
509
+ this.realmInput = config.realm ?? null;
510
+ if (initialToken) {
511
+ this.extractRealmAndScheduleRefresh(initialToken);
512
+ }
513
+ else if (this.tokenProvider) {
514
+ this.tokenFetchPromise = this.refreshTokenFromProvider();
515
+ }
516
+ }
517
+ else {
518
+ throw new Error('ArcaConfig must include either apiKey, token, or tokenProvider');
519
+ }
520
+ const wsGetToken = this.tokenProvider
521
+ ? () => this.refreshTokenFromProvider()
522
+ : undefined;
523
+ this.ws = new websocket_1.WebSocketManager({
524
+ baseUrl: `${baseUrl}/api/v1`,
525
+ credential: isApiKeyConfig(config) ? config.apiKey : config.token ?? '',
526
+ credentialType: isApiKeyConfig(config) ? 'apiKey' : 'token',
527
+ getRealmId: () => this.realmId(),
528
+ getToken: wsGetToken,
529
+ });
530
+ this.historyCache = new cache_1.HistoryCache(config.cache);
531
+ const cdnUrl = config.candleCdnBaseUrl === undefined
532
+ ? DEFAULT_CDN_BASE_URL
533
+ : config.candleCdnBaseUrl;
534
+ if (cdnUrl) {
535
+ this.candleCdnBaseUrl = cdnUrl.replace(/\/+$/, '');
536
+ }
537
+ }
538
+ /**
539
+ * Create an Arca instance from a scoped JWT token.
540
+ * The realm is extracted from the token claims automatically.
541
+ *
542
+ * @param token - Scoped JWT issued by POST /auth/token
543
+ * @param opts - Optional overrides (baseUrl, realm)
544
+ */
545
+ static fromToken(token, opts) {
546
+ return new Arca({
547
+ token,
548
+ tokenProvider: opts?.tokenProvider,
549
+ realm: opts?.realm,
550
+ baseUrl: opts?.baseUrl,
551
+ });
552
+ }
553
+ /**
554
+ * Create an Arca instance with automatic token management.
555
+ * The provider is called immediately to get the first token and
556
+ * then automatically before each expiry.
557
+ *
558
+ * @param tokenProvider - Async function returning a fresh scoped JWT
559
+ * @param opts - Optional overrides (baseUrl, realm, initial token)
560
+ */
561
+ static fromTokenProvider(tokenProvider, opts) {
562
+ return new Arca({
563
+ token: opts?.token,
564
+ tokenProvider,
565
+ realm: opts?.realm,
566
+ baseUrl: opts?.baseUrl,
567
+ });
568
+ }
569
+ /**
570
+ * Replace the scoped JWT token used for HTTP requests and WebSocket
571
+ * authentication. The new token takes effect immediately for HTTP;
572
+ * the WebSocket reconnects immediately if it's currently disconnected.
573
+ *
574
+ * @param token - A fresh scoped JWT issued by POST /auth/token
575
+ */
576
+ updateToken(token) {
577
+ this.client.updateCredential(token);
578
+ this.ws.updateToken(token);
579
+ this.scheduleProactiveRefresh(token);
580
+ }
581
+ /**
582
+ * Register or clear the handler invoked when a request fails with
583
+ * HTTP 412 `STEP_UP_REQUIRED`. The handler is responsible for
584
+ * interactively obtaining a single-use step-up JWT (typically by
585
+ * showing an in-app confirmation modal that creates and approves a
586
+ * step-up request); the SDK retries the original request once with
587
+ * that token and restores the original credential afterward.
588
+ *
589
+ * Pass `undefined` to clear a previously-registered handler.
590
+ *
591
+ * See `.cursor/rules/step-up-auth.mdc` for the full step-up contract.
592
+ */
593
+ setStepUpHandler(handler) {
594
+ this.client.setStepUpHandler(handler);
595
+ }
596
+ /**
597
+ * Register a listener for unrecoverable authentication errors.
598
+ * Fires when:
599
+ * - HTTP 401 is received and no tokenProvider is configured
600
+ * - The tokenProvider itself throws (refresh failed)
601
+ *
602
+ * Use this to show a "session expired" UI or prompt re-authentication.
603
+ * Returns an unsubscribe function.
604
+ */
605
+ onAuthError(listener) {
606
+ this.authErrorListeners.add(listener);
607
+ return () => { this.authErrorListeners.delete(listener); };
608
+ }
609
+ /**
610
+ * Clear the in-memory cache of historical data responses
611
+ * (equity history, PnL history, candles).
612
+ */
613
+ clearHistoryCache() {
614
+ this.historyCache.clear();
615
+ }
616
+ /**
617
+ * Initialize the SDK by resolving the realm slug to an ID.
618
+ * This is called automatically on the first API call, but can be
619
+ * called explicitly for eager initialization.
620
+ */
621
+ async ready() {
622
+ if (this.tokenFetchPromise) {
623
+ const token = await this.tokenFetchPromise;
624
+ this.tokenFetchPromise = null;
625
+ this.extractRealmAndScheduleRefresh(token);
626
+ }
627
+ if (this.resolvedRealmId)
628
+ return;
629
+ if (!this.initPromise) {
630
+ this.initPromise = this.resolveRealm();
631
+ }
632
+ await this.initPromise;
633
+ }
634
+ // ---- Arca Objects ----
635
+ /**
636
+ * Create a user account (denominated Arca object) at the given path.
637
+ *
638
+ * Idempotent: creates the account if it doesn't exist, returns the
639
+ * existing one if it does. Safe to call on every request.
640
+ *
641
+ * @example
642
+ * // Create a user wallet
643
+ * const wallet = await arca.ensureDenominatedArca({
644
+ * ref: '/users/alice/wallet',
645
+ * });
646
+ *
647
+ * `await` resolves when the object is active (immediate for existing
648
+ * objects, waits for creation workflow otherwise).
649
+ * Use `.submitted` to access the HTTP response before the operation settles.
650
+ */
651
+ ensureDenominatedArca(opts) {
652
+ return this.op(() => this.client.post('/objects', {
653
+ realmId: this.realmId(),
654
+ path: opts.ref,
655
+ type: 'denominated',
656
+ metadata: opts.metadata ?? null,
657
+ labels: opts.labels ?? null,
658
+ operationPath: opts.operationPath ?? null,
659
+ }));
660
+ }
661
+ /**
662
+ * Ensure an Arca object of any type exists at the given path.
663
+ * Creates it if it doesn't exist; returns the existing one if it does
664
+ * (matching type). Safe to call on every request.
665
+ *
666
+ * `await` resolves when the object is active (immediate for existing
667
+ * objects, waits for creation workflow otherwise).
668
+ * Use `.submitted` to access the HTTP response before the operation settles.
669
+ */
670
+ ensureArca(opts) {
671
+ return this.op(() => this.client.post('/objects', {
672
+ realmId: this.realmId(),
673
+ path: opts.ref,
674
+ type: opts.type,
675
+ metadata: opts.metadata ?? null,
676
+ labels: opts.labels ?? null,
677
+ operationPath: opts.operationPath ?? null,
678
+ }));
679
+ }
680
+ /**
681
+ * Ensure an info object exists at the given directory path.
682
+ * Info objects store labels (key-value metadata) but cannot hold balances.
683
+ * Appends `/.info` to the path if not already present.
684
+ *
685
+ * `await` resolves when the object is active.
686
+ * Use `.submitted` to access the HTTP response before the operation settles.
687
+ */
688
+ ensureInfo(opts) {
689
+ const ref = opts.ref.endsWith('/.info') ? opts.ref : `${opts.ref}/.info`;
690
+ return this.op(() => this.client.post('/objects', {
691
+ realmId: this.realmId(),
692
+ path: ref,
693
+ type: 'info',
694
+ metadata: null,
695
+ labels: opts.labels ?? null,
696
+ operationPath: opts.operationPath ?? null,
697
+ }));
698
+ }
699
+ /**
700
+ * Delete an Arca object by path. If sweepTo is provided, remaining funds
701
+ * are transferred to that Arca before deletion.
702
+ *
703
+ * If the object is already deleted, returns the existing state.
704
+ */
705
+ ensureDeleted(opts) {
706
+ return this.op(() => this.client.post('/objects/delete', {
707
+ realmId: this.realmId(),
708
+ path: opts.ref,
709
+ sweepToPath: opts.sweepTo ?? null,
710
+ liquidatePositions: opts.liquidatePositions ?? false,
711
+ operationPath: opts.operationPath ?? null,
712
+ }));
713
+ }
714
+ /**
715
+ * Get an Arca object by path.
716
+ */
717
+ async getObject(path) {
718
+ await this.ready();
719
+ return this.client.get('/objects/by-path', {
720
+ realmId: this.realmId(),
721
+ path,
722
+ });
723
+ }
724
+ /**
725
+ * Get an Arca object's full detail (operations, events, deltas, balances) by ID.
726
+ */
727
+ async getObjectDetail(objectId) {
728
+ await this.ready();
729
+ return this.client.get(`/objects/${objectId}`);
730
+ }
731
+ /**
732
+ * List Arca objects, optionally filtered by path.
733
+ *
734
+ * @param opts.path - Object path or path prefix to filter by.
735
+ * Exact path (no trailing slash): returns the single matching object.
736
+ * Path prefix (trailing slash): returns all objects under that prefix.
737
+ * Examples: '/users/alice/main' (single), '/users/alice/' (subtree)
738
+ */
739
+ async listObjects(opts) {
740
+ await this.ready();
741
+ const params = { realmId: this.realmId() };
742
+ const p = opts?.path ?? opts?.prefix;
743
+ if (p) {
744
+ validatePath(p);
745
+ params.prefix = p;
746
+ }
747
+ if (opts?.includeDeleted)
748
+ params.includeDeleted = 'true';
749
+ if (opts?.limit != null)
750
+ params.limit = String(opts.limit);
751
+ if (opts?.cursor)
752
+ params.cursor = opts.cursor;
753
+ return this.client.get('/objects', params);
754
+ }
755
+ /**
756
+ * Get balances for an Arca object by ID.
757
+ */
758
+ async getBalances(objectId) {
759
+ await this.ready();
760
+ const res = await this.client.get(`/objects/${objectId}/balances`);
761
+ return res.balances;
762
+ }
763
+ /**
764
+ * Get balances for an Arca object by path.
765
+ * Resolves the path to an object ID, then fetches balances.
766
+ */
767
+ async getBalancesByPath(path) {
768
+ const obj = await this.getObject(path);
769
+ return this.getBalances(obj.id);
770
+ }
771
+ /**
772
+ * Browse Arca objects in a folder-like structure.
773
+ * Returns folders (path segments) and objects at the given path.
774
+ *
775
+ * @param opts.path - Path prefix to browse (default: '/'). Must end with '/'.
776
+ */
777
+ async browseObjects(opts) {
778
+ await this.ready();
779
+ const p = opts?.path ?? opts?.prefix ?? '/';
780
+ validatePath(p);
781
+ const params = {
782
+ realmId: this.realmId(),
783
+ prefix: p,
784
+ };
785
+ if (opts?.includeDeleted)
786
+ params.includeDeleted = 'true';
787
+ return this.client.get('/objects/browse', params);
788
+ }
789
+ /**
790
+ * Declare a path as an isolation zone before adding objects beneath it.
791
+ * Returns the existing declaration when the same path was already created.
792
+ */
793
+ async createIsolationZone(opts) {
794
+ await this.ready();
795
+ validatePath(opts.path);
796
+ const path = opts.path !== '/' ? opts.path.replace(/\/+$/, '') : opts.path;
797
+ if (path === '/') {
798
+ throw new Error('Isolation zones must be created at a non-root path.');
799
+ }
800
+ return this.client.post('/isolation-zones', {
801
+ realmId: this.realmId(),
802
+ path,
803
+ });
804
+ }
805
+ /**
806
+ * Update labels on an Arca object.
807
+ * Pass null as a label value to remove that key.
808
+ */
809
+ async updateLabels(opts) {
810
+ await this.ready();
811
+ return this.client.patch(`/objects/${opts.objectId}/labels`, { realmId: this.realmId() }, { labels: opts.labels });
812
+ }
813
+ /**
814
+ * Read folder-level labels for a path. Folders are virtual
815
+ * aggregations of arca paths; labels live in their own table and
816
+ * are surfaced inline on `browseObjects()` rows so the portal can
817
+ * disambiguate visually-identical folders.
818
+ *
819
+ * Returns `{ labels: {} }` when no labels are set on the folder.
820
+ */
821
+ async getFolderLabels(path) {
822
+ await this.ready();
823
+ validatePath(path);
824
+ return this.client.get('/folders/labels', {
825
+ realmId: this.realmId(),
826
+ path,
827
+ });
828
+ }
829
+ /**
830
+ * Replace the label set on a folder path. The `labels` field is a
831
+ * full overwrite — pass the desired final state, not a delta. Pass
832
+ * `{}` to remove all labels on the folder.
833
+ *
834
+ * Validation matches leaf-arca labels: 32 keys max, key pattern
835
+ * `^[a-zA-Z][a-zA-Z0-9._-]*$`, `arca.` and `_` reserved prefixes,
836
+ * value ≤ 256 chars.
837
+ */
838
+ async updateFolderLabels(opts) {
839
+ await this.ready();
840
+ validatePath(opts.path);
841
+ return this.client.put('/folders/labels', {
842
+ realmId: this.realmId(),
843
+ path: opts.path,
844
+ labels: opts.labels,
845
+ });
846
+ }
847
+ /**
848
+ * Get version history for an Arca object.
849
+ */
850
+ async getObjectVersions(objectId) {
851
+ await this.ready();
852
+ return this.client.get(`/objects/${objectId}/versions`);
853
+ }
854
+ /**
855
+ * Get snapshot balances for an Arca object at a specific point in time.
856
+ */
857
+ async getSnapshotBalances(objectId, asOf) {
858
+ await this.ready();
859
+ return this.client.get(`/objects/${objectId}/snapshot`, {
860
+ realmId: this.realmId(),
861
+ asOf,
862
+ });
863
+ }
864
+ // ---- Transfers ----
865
+ /**
866
+ * Execute a transfer between two Arca objects.
867
+ * Settlement is immediate for denominated targets (await resolves instantly),
868
+ * or async for exchange targets (await waits for settlement).
869
+ * The operation path serves as the idempotency key.
870
+ */
871
+ transfer(opts) {
872
+ const body = {
873
+ realmId: this.realmId(),
874
+ path: opts.path,
875
+ sourceArcaPath: opts.from,
876
+ targetArcaPath: opts.to,
877
+ amount: opts.amount,
878
+ };
879
+ if (opts.feeOverride !== undefined) {
880
+ body.feeOverride = opts.feeOverride;
881
+ }
882
+ return this.op(() => this.client.post('/transfer', body), {
883
+ type: 'transfer',
884
+ balanceChanges: {
885
+ [opts.from]: { departing: opts.amount },
886
+ [opts.to]: { arriving: opts.amount },
887
+ },
888
+ });
889
+ }
890
+ // ---- Fees ----
891
+ /**
892
+ * Estimate the fee for a transfer or order operation.
893
+ */
894
+ async estimateFee(params) {
895
+ await this.ready();
896
+ const query = {
897
+ realmId: this.realmId(),
898
+ action: params.action,
899
+ amount: params.amount,
900
+ };
901
+ if (params.sourcePath)
902
+ query.sourcePath = params.sourcePath;
903
+ if (params.targetPath)
904
+ query.targetPath = params.targetPath;
905
+ if (params.feeOverride !== undefined)
906
+ query.feeOverride = params.feeOverride;
907
+ return this.client.get('/fees/estimate', query);
908
+ }
909
+ // ---- Fund / Defund Account ----
910
+ /**
911
+ * Programmatically fund an Arca object. This is a developer tool for
912
+ * development realm use (competitions, programmatic account seeding).
913
+ * For production deposit flows, use `createPaymentLink({ type: 'deposit' })`.
914
+ *
915
+ * `await` waits for settlement. Use `.submitted` to access
916
+ * the poolAddress and other response data before settlement.
917
+ */
918
+ fundAccount(opts) {
919
+ return this.op(() => this.client.post('/fund-account', {
920
+ realmId: this.realmId(),
921
+ arcaPath: opts.arcaRef,
922
+ amount: opts.amount,
923
+ path: opts.path ?? null,
924
+ senderAddress: opts.senderAddress ?? null,
925
+ durationSeconds: opts.durationSeconds ?? null,
926
+ willSucceed: opts.willSucceed ?? null,
927
+ }));
928
+ }
929
+ /**
930
+ * Programmatically withdraw from an Arca object. This is a developer/test tool
931
+ * for non-production use. For production withdrawal flows, use
932
+ * `createPaymentLink({ type: 'withdrawal' })`.
933
+ */
934
+ defundAccount(opts) {
935
+ return this.op(() => this.client.post('/defund-account', {
936
+ realmId: this.realmId(),
937
+ arcaPath: opts.arcaPath,
938
+ amount: opts.amount,
939
+ destinationAddress: opts.destinationAddress ?? '',
940
+ path: opts.path ?? null,
941
+ }));
942
+ }
943
+ // ---- Payment Links ----
944
+ /**
945
+ * Create a hosted deposit or withdrawal page for an end user.
946
+ *
947
+ * Returns a URL that the user can visit to deposit into (or withdraw from)
948
+ * the specified Arca object. Use this instead of `fundAccount()`/`defundAccount()`
949
+ * in production.
950
+ *
951
+ * @example
952
+ * const link = await arca.createPaymentLink({
953
+ * objectId: walletId,
954
+ * direction: 'deposit',
955
+ * amount: '100',
956
+ * returnUrl: 'https://myapp.com/dashboard',
957
+ * });
958
+ * // Redirect user to link.url
959
+ */
960
+ createPaymentLink(opts) {
961
+ return this.op(() => this.client.post('/payment-links', {
962
+ realmId: this.realmId(),
963
+ type: opts.type,
964
+ arcaPath: opts.arcaRef,
965
+ amount: opts.amount,
966
+ returnUrl: opts.returnUrl ?? null,
967
+ returnStrategy: opts.returnStrategy ?? null,
968
+ expiresInMinutes: opts.expiresInMinutes ?? null,
969
+ metadata: opts.metadata ? JSON.stringify(opts.metadata) : null,
970
+ destinationAddress: opts.destinationAddress ?? null,
971
+ }));
972
+ }
973
+ /**
974
+ * List payment links for this realm, optionally filtered by type or status.
975
+ */
976
+ async listPaymentLinks(opts) {
977
+ await this.ready();
978
+ const params = new URLSearchParams({ realmId: this.realmId() });
979
+ if (opts?.type)
980
+ params.set('type', opts.type);
981
+ if (opts?.status)
982
+ params.set('status', opts.status);
983
+ return this.client.get(`/payment-links?${params}`);
984
+ }
985
+ // ---- Operations ----
986
+ /**
987
+ * Get operation detail by ID (includes correlated events and deltas).
988
+ */
989
+ async getOperation(operationId, options) {
990
+ await this.ready();
991
+ const params = {};
992
+ if (options?.includeEvidence)
993
+ params.includeEvidence = 'true';
994
+ return this.client.get(`/operations/${operationId}`, params);
995
+ }
996
+ /**
997
+ * List operations in the realm.
998
+ */
999
+ async listOperations(opts) {
1000
+ await this.ready();
1001
+ const params = { realmId: this.realmId() };
1002
+ if (opts?.types?.length) {
1003
+ params.types = opts.types.join(',');
1004
+ }
1005
+ else if (opts?.type) {
1006
+ params.type = opts.type;
1007
+ }
1008
+ if (opts?.arcaPath)
1009
+ params.arcaPath = opts.arcaPath;
1010
+ if (opts?.arcaId)
1011
+ params.arcaId = opts.arcaId;
1012
+ if (opts?.path)
1013
+ params.path = opts.path;
1014
+ if (opts?.includeContext)
1015
+ params.includeContext = 'true';
1016
+ if (opts?.limit)
1017
+ params.limit = String(opts.limit);
1018
+ if (opts?.cursor)
1019
+ params.cursor = opts.cursor;
1020
+ return this.client.get('/operations', params);
1021
+ }
1022
+ /**
1023
+ * Export realm-scoped operation audit evidence over a time range.
1024
+ */
1025
+ async exportOperationEvidence(opts) {
1026
+ await this.ready();
1027
+ const params = {
1028
+ realmId: this.realmId(),
1029
+ from: opts.from,
1030
+ to: opts.to,
1031
+ };
1032
+ if (opts.types?.length) {
1033
+ params.types = opts.types.join(',');
1034
+ }
1035
+ else if (opts.type) {
1036
+ params.type = opts.type;
1037
+ }
1038
+ if (opts.arcaPath)
1039
+ params.arcaPath = opts.arcaPath;
1040
+ if (opts.arcaId)
1041
+ params.arcaId = opts.arcaId;
1042
+ if (opts.path)
1043
+ params.path = opts.path;
1044
+ if (opts.limit)
1045
+ params.limit = String(opts.limit);
1046
+ if (opts.cursor)
1047
+ params.cursor = opts.cursor;
1048
+ return this.client.get('/operations/export', params);
1049
+ }
1050
+ /**
1051
+ * List events in the realm.
1052
+ */
1053
+ async listEvents(opts) {
1054
+ await this.ready();
1055
+ const params = { realmId: this.realmId() };
1056
+ if (opts?.arcaPath)
1057
+ params.arcaPath = opts.arcaPath;
1058
+ if (opts?.path)
1059
+ params.path = opts.path;
1060
+ if (opts?.limit)
1061
+ params.limit = String(opts.limit);
1062
+ if (opts?.cursor)
1063
+ params.cursor = opts.cursor;
1064
+ return this.client.get('/events', params);
1065
+ }
1066
+ /**
1067
+ * Get event detail by ID (includes the parent operation and correlated deltas).
1068
+ */
1069
+ async getEventDetail(eventId) {
1070
+ await this.ready();
1071
+ return this.client.get(`/events/${eventId}`);
1072
+ }
1073
+ // ---- State Deltas ----
1074
+ /**
1075
+ * List balance change records (state deltas) for a given path.
1076
+ *
1077
+ * Each delta is an immutable record of a balance change — who changed,
1078
+ * how much, and which operation caused it. Useful for building
1079
+ * transaction history views.
1080
+ */
1081
+ async listDeltas(arcaPath) {
1082
+ await this.ready();
1083
+ return this.client.get('/deltas', {
1084
+ realmId: this.realmId(),
1085
+ arcaPath,
1086
+ });
1087
+ }
1088
+ // ---- Nonces ----
1089
+ /**
1090
+ * Get the next unique nonce for a path prefix.
1091
+ * Useful for constructing unique idempotent operation paths.
1092
+ *
1093
+ * **Important:** Reserve the nonce *before* the operation and store the
1094
+ * resulting path. Reuse the stored path on retry — never call `nonce()`
1095
+ * inline inside an operation call, as each invocation produces a new
1096
+ * unique path and defeats idempotency.
1097
+ *
1098
+ * @param path - Path prefix for nonce generation (e.g. '/op/transfer/fund').
1099
+ * Always used as a prefix — the nonce number is appended.
1100
+ * @param separator - Override separator between path and nonce number.
1101
+ * Default: '/' if path ends with '/', otherwise '-'.
1102
+ * Use ':' for operation nonces (e.g. '/op/create/wallets/main:1').
1103
+ */
1104
+ async nonce(path, separator) {
1105
+ validatePath(path);
1106
+ await this.ready();
1107
+ const body = {
1108
+ realmId: this.realmId(),
1109
+ prefix: path,
1110
+ };
1111
+ if (separator !== undefined) {
1112
+ body.separator = separator;
1113
+ }
1114
+ return this.client.post('/nonce', body);
1115
+ }
1116
+ // ---- Summary ----
1117
+ /**
1118
+ * Get aggregate counts and statistics for the realm: total objects,
1119
+ * operations, events, and active watches.
1120
+ */
1121
+ async summary() {
1122
+ await this.ready();
1123
+ return this.client.get('/summary', {
1124
+ realmId: this.realmId(),
1125
+ });
1126
+ }
1127
+ // ---- Aggregation & P&L ----
1128
+ /**
1129
+ * Get aggregated valuation for objects at a path.
1130
+ *
1131
+ * @param path - Object path or path prefix.
1132
+ * Exact path (no trailing slash): returns valuation for a single object.
1133
+ * Path prefix (trailing slash): returns aggregated valuation for all objects under that prefix.
1134
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1135
+ * @param options.asOf - ISO timestamp for historical aggregation.
1136
+ */
1137
+ async getPathAggregation(path, options) {
1138
+ validatePath(path);
1139
+ await this.ready();
1140
+ const params = {
1141
+ realmId: this.realmId(),
1142
+ prefix: path,
1143
+ };
1144
+ if (options?.asOf)
1145
+ params.asOf = options.asOf;
1146
+ return this.client.get('/objects/aggregate', params);
1147
+ }
1148
+ /**
1149
+ * Get P&L (profit and loss) for objects at a path over a time range.
1150
+ *
1151
+ * @param path - Object path or path prefix.
1152
+ * Exact path (no trailing slash): returns P&L for a single object.
1153
+ * Path prefix (trailing slash): returns aggregated P&L for all objects under that prefix.
1154
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1155
+ * @param from - ISO timestamp for the start of the range.
1156
+ * @param to - ISO timestamp for the end of the range.
1157
+ */
1158
+ async getPnl(path, from, to) {
1159
+ validatePath(path);
1160
+ await this.ready();
1161
+ return this.client.get('/objects/pnl', {
1162
+ realmId: this.realmId(),
1163
+ prefix: path,
1164
+ from,
1165
+ to,
1166
+ });
1167
+ }
1168
+ /**
1169
+ * Get P&L history (time-series) for objects at a path.
1170
+ *
1171
+ * @param path - Object path or path prefix.
1172
+ * Exact path (no trailing slash): returns P&L history for a single object.
1173
+ * Path prefix (trailing slash): returns aggregated P&L history for all objects under that prefix.
1174
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1175
+ * @param from - ISO timestamp for the start of the range.
1176
+ * @param to - ISO timestamp for the end of the range.
1177
+ * @param points - Number of samples (default 1000, max 1000). The backend
1178
+ * ladder picks the finest resolution whose bucket count fits within
1179
+ * `points`, so the default targets `5m` for 24h, `1h` for 1M, and `4h`
1180
+ * for 3M ranges.
1181
+ */
1182
+ async getPnlHistory(path, from, to, points = 1000, options) {
1183
+ validatePath(path);
1184
+ const anchor = options?.anchor ?? 'zero';
1185
+ const { kind, objectId } = resolveHistoryScope(options);
1186
+ const key = (0, cache_1.buildCacheKey)('pnlHistory', { target: path, kind, objectId, from, to, points: String(points), anchor });
1187
+ const cached = this.historyCache.get(key);
1188
+ if (cached)
1189
+ return cached;
1190
+ await this.ready();
1191
+ const result = await this.client.get('/objects/pnl/history', {
1192
+ realmId: this.realmId(),
1193
+ target: path,
1194
+ kind,
1195
+ ...(objectId ? { objectId } : {}),
1196
+ from,
1197
+ to,
1198
+ points: String(points),
1199
+ anchor,
1200
+ });
1201
+ const normalized = normalizeV2PnlHistory(path, from, to, result);
1202
+ this.historyCache.set(key, normalized);
1203
+ return normalized;
1204
+ }
1205
+ /**
1206
+ * Get equity history (time-series) for objects at a path.
1207
+ *
1208
+ * @param path - Object path or path prefix.
1209
+ * Exact path (no trailing slash): returns equity history for a single object.
1210
+ * Path prefix (trailing slash): returns aggregated equity history for all objects under that prefix.
1211
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1212
+ * @param from - ISO timestamp for the start of the range.
1213
+ * @param to - ISO timestamp for the end of the range.
1214
+ * @param points - Number of samples (default 1000, max 1000). The backend
1215
+ * ladder picks the finest resolution whose bucket count fits within
1216
+ * `points`, so the default targets `5m` for 24h, `1h` for 1M, and `4h`
1217
+ * for 3M ranges.
1218
+ */
1219
+ async getEquityHistory(path, from, to, points = 1000, options) {
1220
+ validatePath(path);
1221
+ const { kind, objectId } = resolveHistoryScope(options);
1222
+ const key = (0, cache_1.buildCacheKey)('equityHistory', { target: path, kind, objectId, from, to, points: String(points) });
1223
+ const cached = this.historyCache.get(key);
1224
+ if (cached)
1225
+ return cached;
1226
+ await this.ready();
1227
+ const result = await this.client.get('/objects/aggregate/history', {
1228
+ realmId: this.realmId(),
1229
+ target: path,
1230
+ kind,
1231
+ ...(objectId ? { objectId } : {}),
1232
+ from,
1233
+ to,
1234
+ points: String(points),
1235
+ });
1236
+ const normalized = normalizeV2EquityHistory(path, from, to, result);
1237
+ this.historyCache.set(key, normalized);
1238
+ return normalized;
1239
+ }
1240
+ /**
1241
+ * Create a live equity chart that merges historical data with real-time
1242
+ * aggregation updates. The last point reflects the current live equity;
1243
+ * when the interval boundary crosses, the live point is promoted to
1244
+ * historical and a new live point starts.
1245
+ *
1246
+ * @param path - Object path or path prefix.
1247
+ * Exact path (no trailing slash): chart for a single object.
1248
+ * Path prefix (trailing slash): chart aggregated across all objects under that prefix.
1249
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1250
+ */
1251
+ async watchEquityChart(path, from, to, points = 1000, options) {
1252
+ validatePath(path);
1253
+ await this.ready();
1254
+ // Start the WebSocket connect + auth handshake now so it overlaps the
1255
+ // history REST below instead of stacking after it. ensureConnected is
1256
+ // idempotent and synchronous; watchAggregation calls it again as a no-op.
1257
+ this.ws.ensureConnected();
1258
+ const exchange = options?.exchange ?? 'sim';
1259
+ const { kind, objectId } = resolveHistoryScope(options);
1260
+ const scopeOpts = { kind, objectId };
1261
+ // Live-tail heuristic: if `to` was within ~60s of construction time, the
1262
+ // caller is asking for "last N hours up to now" (a sliding window). On
1263
+ // every refresh, recompute `from`/`to` so the window stays current.
1264
+ // Otherwise the watch is for a fixed historical window — keep `from`/`to`
1265
+ // pinned to the originals so the chart doesn't drift.
1266
+ const fromMsOrig = Date.parse(from);
1267
+ const toMsOrig = Date.parse(to);
1268
+ const createdAtMs = Date.now();
1269
+ const isLiveTail = Number.isFinite(fromMsOrig)
1270
+ && Number.isFinite(toMsOrig)
1271
+ && Math.abs(toMsOrig - createdAtMs) <= LIVE_TAIL_THRESHOLD_MS;
1272
+ const windowMs = isLiveTail ? Math.max(0, toMsOrig - fromMsOrig) : 0;
1273
+ let currentFrom = from;
1274
+ let currentTo = to;
1275
+ let currentCacheKey = (0, cache_1.buildCacheKey)('equityHistory', { target: path, kind, objectId, from: currentFrom, to: currentTo, points: String(points) });
1276
+ const slideIfLive = () => {
1277
+ if (!isLiveTail)
1278
+ return;
1279
+ const nowMs = Date.now();
1280
+ currentFrom = new Date(nowMs - windowMs).toISOString();
1281
+ currentTo = new Date(nowMs).toISOString();
1282
+ currentCacheKey = (0, cache_1.buildCacheKey)('equityHistory', { target: path, kind, objectId, from: currentFrom, to: currentTo, points: String(points) });
1283
+ };
1284
+ // Start the history fetch, the aggregation watch, and the chart-
1285
+ // history WS watch concurrently. None depends on another's result,
1286
+ // so serializing them only added round-trips before first paint.
1287
+ const [historyResult, aggStream, chartWatch] = await Promise.all([
1288
+ this.getEquityHistory(path, currentFrom, currentTo, points, scopeOpts)
1289
+ .catch(() => ({ equityPoints: [], resolution: undefined })),
1290
+ this.watchAggregation([{ type: 'prefix', value: path }], { exchange }),
1291
+ this.ws.createChartHistoryWatch({ target: path, kind, objectId }).catch(() => null),
1292
+ ]);
1293
+ let history = historyResult;
1294
+ const stream = new streams_1.EquityChartStream(history.equityPoints, aggStream, history.resolution, () => { this.historyCache.delete(currentCacheKey); }, async () => {
1295
+ slideIfLive();
1296
+ this.historyCache.delete(currentCacheKey);
1297
+ history = await this.getEquityHistory(path, currentFrom, currentTo, points, scopeOpts);
1298
+ return history;
1299
+ }, this.ws, chartWatch?.watchId, chartWatch ? () => { this.ws.destroyChartHistoryWatch(chartWatch.watchId); } : undefined);
1300
+ // If the live aggregation shows non-zero equity but the cached history is
1301
+ // all zeros (typical for new accounts that just deposited), the cache is
1302
+ // stale. Refresh in the BACKGROUND through the stream's own refetch path
1303
+ // so first paint isn't blocked on a second history REST — the chart shows
1304
+ // the initial points immediately and corrects when the refetch lands.
1305
+ const liveEquity = aggStream.aggregation?.totalEquityUsd;
1306
+ if (liveEquity && parseFloat(liveEquity) > 0.01) {
1307
+ const allZero = history.equityPoints.length > 0 &&
1308
+ history.equityPoints.every(p => Math.abs(parseFloat(p.equityUsd)) < 0.01);
1309
+ if (allZero || history.equityPoints.length === 0) {
1310
+ stream.requestHistoryRefresh();
1311
+ }
1312
+ }
1313
+ return stream;
1314
+ }
1315
+ /**
1316
+ * Create a live P&L chart that merges historical P&L data with real-time
1317
+ * aggregation updates and operation events. The rightmost point updates on
1318
+ * each aggregation event. Operation events (deposits/transfers) update
1319
+ * cumulative flows client-side — zero additional server reads.
1320
+ *
1321
+ * @param path - Object path or path prefix.
1322
+ * Exact path (no trailing slash): P&L chart for a single object.
1323
+ * Path prefix (trailing slash): P&L chart aggregated across all objects under that prefix.
1324
+ * Examples: '/users/alice/main' (single object), '/users/alice/' (all of alice's objects)
1325
+ * @param options.anchor - `'zero'` (default): standard P&L chart starting at 0.
1326
+ * `'equity'`: each point includes `valueUsd` — the P&L shifted so the live
1327
+ * (rightmost) value equals the current account equity. The chart shape is
1328
+ * identical to the P&L chart; only the y-axis is translated.
1329
+ */
1330
+ async watchPnlChart(path, from, to, points = 1000, options) {
1331
+ validatePath(path);
1332
+ await this.ready();
1333
+ // Start the WebSocket connect + auth handshake now so it overlaps the
1334
+ // history REST below instead of stacking after it (see watchEquityChart).
1335
+ this.ws.ensureConnected();
1336
+ const exchange = options?.exchange ?? 'sim';
1337
+ const anchor = options?.anchor ?? 'zero';
1338
+ const { kind, objectId } = resolveHistoryScope(options);
1339
+ const scopeOpts = { anchor, kind, objectId };
1340
+ // See `watchEquityChart` for the live-tail / sliding-window rationale.
1341
+ const fromMsOrig = Date.parse(from);
1342
+ const toMsOrig = Date.parse(to);
1343
+ const createdAtMs = Date.now();
1344
+ const isLiveTail = Number.isFinite(fromMsOrig)
1345
+ && Number.isFinite(toMsOrig)
1346
+ && Math.abs(toMsOrig - createdAtMs) <= LIVE_TAIL_THRESHOLD_MS;
1347
+ const windowMs = isLiveTail ? Math.max(0, toMsOrig - fromMsOrig) : 0;
1348
+ let currentFrom = from;
1349
+ let currentTo = to;
1350
+ let currentCacheKey = (0, cache_1.buildCacheKey)('pnlHistory', { target: path, kind, objectId, from: currentFrom, to: currentTo, points: String(points), anchor });
1351
+ const slideIfLive = () => {
1352
+ if (!isLiveTail)
1353
+ return;
1354
+ const nowMs = Date.now();
1355
+ currentFrom = new Date(nowMs - windowMs).toISOString();
1356
+ currentTo = new Date(nowMs).toISOString();
1357
+ currentCacheKey = (0, cache_1.buildCacheKey)('pnlHistory', { target: path, kind, objectId, from: currentFrom, to: currentTo, points: String(points), anchor });
1358
+ };
1359
+ // The chart-history WS watch is independent of the history fetch, so
1360
+ // start them together. The aggregation watch needs flowsSince from
1361
+ // the history response, so it follows.
1362
+ const [history, chartWatch] = await Promise.all([
1363
+ this.getPnlHistory(path, currentFrom, currentTo, points, scopeOpts),
1364
+ this.ws.createChartHistoryWatch({ target: path, kind, objectId }).catch(() => null),
1365
+ ]);
1366
+ const flowsSince = history.effectiveFrom ?? currentFrom;
1367
+ const aggStream = await this.watchAggregation([{ type: 'prefix', value: path }], { exchange, flowsSince });
1368
+ return new streams_1.PnlChartStream(history.pnlPoints, history.externalFlows ?? [], history.startingEquityUsd, history.midPrices ?? {}, path, aggStream, this.ws, history.resolution, anchor, async () => {
1369
+ slideIfLive();
1370
+ this.historyCache.delete(currentCacheKey);
1371
+ return this.getPnlHistory(path, currentFrom, currentTo, points, scopeOpts);
1372
+ }, chartWatch?.watchId, chartWatch ? () => { this.ws.destroyChartHistoryWatch(chartWatch.watchId); } : undefined);
1373
+ }
1374
+ /**
1375
+ * Convenience: open a live equity chart for a sliding range preset
1376
+ * (`'1h'`, `'24h'`, `'7d'`, ...). Computes `from`/`to` from the current
1377
+ * wall clock and delegates to {@link watchEquityChart}, which handles
1378
+ * sliding the window forward on every refresh and self-healing across
1379
+ * tab idle. Equivalent to:
1380
+ *
1381
+ * ```ts
1382
+ * const { from, to } = computeChartRange('1h');
1383
+ * const stream = await arca.watchEquityChart(path, from, to, points);
1384
+ * ```
1385
+ */
1386
+ async watchEquityChartLive(path, options) {
1387
+ const { from, to } = computeChartRange(options.range);
1388
+ const exchangeOpts = options.exchange ? { exchange: options.exchange } : undefined;
1389
+ return this.watchEquityChart(path, from, to, options.points ?? 1000, exchangeOpts);
1390
+ }
1391
+ /**
1392
+ * Convenience: open a live P&L chart for a sliding range preset.
1393
+ * See {@link watchEquityChartLive}.
1394
+ */
1395
+ async watchPnlChartLive(path, options) {
1396
+ const { from, to } = computeChartRange(options.range);
1397
+ const passthrough = {};
1398
+ if (options.exchange !== undefined)
1399
+ passthrough.exchange = options.exchange;
1400
+ if (options.anchor !== undefined)
1401
+ passthrough.anchor = options.anchor;
1402
+ return this.watchPnlChart(path, from, to, options.points ?? 1000, passthrough);
1403
+ }
1404
+ /**
1405
+ * Create an aggregation watch that tracks a set of sources.
1406
+ * Returns the watch ID and the initial aggregation.
1407
+ * When the underlying data changes, `aggregation.updated` events are
1408
+ * pushed via WebSocket with the updated aggregation inline.
1409
+ */
1410
+ async createAggregationWatch(sources) {
1411
+ await this.ready();
1412
+ return this.client.post('/aggregations/watch', {
1413
+ realmId: this.realmId(),
1414
+ sources,
1415
+ });
1416
+ }
1417
+ /**
1418
+ * Get the current aggregation for an existing watch.
1419
+ */
1420
+ async getWatchAggregation(watchId) {
1421
+ await this.ready();
1422
+ const res = await this.client.get(`/aggregations/watch/${watchId}`);
1423
+ return res.aggregation;
1424
+ }
1425
+ /**
1426
+ * Destroy an aggregation watch. The server stops tracking and pushing updates.
1427
+ */
1428
+ async destroyAggregationWatch(watchId) {
1429
+ await this.ready();
1430
+ await this.client.delete(`/aggregations/watch/${watchId}`);
1431
+ }
1432
+ /**
1433
+ * Subscribe to real-time aggregation updates for a set of sources.
1434
+ * Automatically handles server-side watch creation, structural change events,
1435
+ * and client-side revaluation from mid prices. Call `.close()` when done.
1436
+ */
1437
+ async watchAggregation(sources, options) {
1438
+ await this.ready();
1439
+ // Begin (or reuse) the WebSocket connection before the create-watch
1440
+ // round-trip; idempotent if a caller already pre-warmed it.
1441
+ this.ws.ensureConnected();
1442
+ const exchange = options?.exchange ?? 'sim';
1443
+ const flowsSince = options?.flowsSince;
1444
+ const wsSources = sources.map(s => {
1445
+ if (s.type === 'paths')
1446
+ return { type: s.type, paths: s.paths ?? [] };
1447
+ return { type: s.type, value: s.value };
1448
+ });
1449
+ const { watchId, aggregation } = await this.ws.createAggregationWatch(wsSources, flowsSince);
1450
+ const destroyWatch = async () => { this.ws.destroyAggregationWatch(watchId); };
1451
+ const refreshWatch = async () => {
1452
+ const result = await this.ws.createAggregationWatch(wsSources, flowsSince);
1453
+ return {
1454
+ watchId: result.watchId,
1455
+ aggregation: result.aggregation,
1456
+ destroyWatch: async () => { this.ws.destroyAggregationWatch(result.watchId); },
1457
+ };
1458
+ };
1459
+ const stream = new streams_1.AggregationWatchStream(this.ws, watchId, aggregation, destroyWatch, refreshWatch, exchange);
1460
+ return stream;
1461
+ }
1462
+ // ---- Reconciliation ----
1463
+ /**
1464
+ * List reconciliation state entries for the realm.
1465
+ */
1466
+ async listReconciliationState() {
1467
+ await this.ready();
1468
+ return this.client.get('/reconciliation', {
1469
+ realmId: this.realmId(),
1470
+ });
1471
+ }
1472
+ // ---- Exchange (Perps) ----
1473
+ /**
1474
+ * Ensure a Perps Exchange Arca object exists at the given path.
1475
+ * Automatically sets type=exchange and the venue metadata.
1476
+ *
1477
+ * The `venue` decides routing: `'hl-sim'` (default) provisions a
1478
+ * simulated Hyperliquid account; `'hl'` provisions a live one.
1479
+ *
1480
+ * Note: exchange account creation involves a synchronous gRPC call from
1481
+ * the worker into sim-exchange (see `ExecuteCreateObject`), which has a
1482
+ * worse worst-case latency than transfers. The default settlement wait
1483
+ * is 60s rather than the SDK-wide 30s default. Override via
1484
+ * `await handle.wait({ timeout })` when you need a tighter bound.
1485
+ */
1486
+ ensurePerpsExchange(opts) {
1487
+ return this.op(() => this.client.post('/objects', {
1488
+ realmId: this.realmId(),
1489
+ path: opts.ref,
1490
+ type: 'exchange',
1491
+ metadata: JSON.stringify({ venue: opts.venue || 'hl-sim' }),
1492
+ operationPath: opts.operationPath,
1493
+ }), undefined, 60000);
1494
+ }
1495
+ /**
1496
+ * Get exchange account state (equity, margin, positions, orders).
1497
+ */
1498
+ async getExchangeState(objectId) {
1499
+ await this.ready();
1500
+ return this.client.get(`/objects/${objectId}/exchange/state`);
1501
+ }
1502
+ /**
1503
+ * Get active asset trading data for an exchange object: max trade sizes,
1504
+ * available margin, mark price, and fee rate. Accounts for leverage,
1505
+ * existing positions, and fees (including builder fee when provided).
1506
+ *
1507
+ * @param market - Coin in canonical format (e.g. "hl:0:BTC", "hl:1:SILVER")
1508
+ * @param applicationFeeTenthsBps - Optional application fee in tenths of a basis point
1509
+ * @param leverage - Optional leverage override. When provided, the server
1510
+ * uses this value instead of the stored leverage setting. When omitted,
1511
+ * the server reads the leverage from the account's per-market setting
1512
+ * (defaulting to 1x if none has been set via `updateLeverage`).
1513
+ */
1514
+ async getActiveAssetData(objectId, market, applicationFeeTenthsBps, leverage) {
1515
+ await this.ready();
1516
+ let url = `/objects/${objectId}/exchange/active-asset-data?market=${encodeURIComponent(market)}`;
1517
+ if (applicationFeeTenthsBps && applicationFeeTenthsBps > 0)
1518
+ url += `&applicationFeeTenthsBps=${applicationFeeTenthsBps}`;
1519
+ if (leverage && leverage > 0)
1520
+ url += `&leverage=${leverage}`;
1521
+ return this.client.get(url);
1522
+ }
1523
+ /**
1524
+ * Get the effective taker and maker fee rates for every tradeable asset on
1525
+ * an exchange account. Rates include the account's volume tier, per-asset
1526
+ * HIP-3 fee scale, platform fee, and optional builder fee.
1527
+ *
1528
+ * @param objectId - Exchange Arca object ID
1529
+ * @param applicationFeeTenthsBps - Optional application fee in tenths of a basis point
1530
+ */
1531
+ async getAssetFees(objectId, applicationFeeTenthsBps) {
1532
+ await this.ready();
1533
+ let url = `/objects/${objectId}/exchange/asset-fees`;
1534
+ if (applicationFeeTenthsBps && applicationFeeTenthsBps > 0)
1535
+ url += `?applicationFeeTenthsBps=${applicationFeeTenthsBps}`;
1536
+ return this.client.get(url);
1537
+ }
1538
+ /**
1539
+ * Update leverage for a market on an exchange Arca object.
1540
+ * Leverage is a per-market setting that applies to the entire position.
1541
+ * Re-margins any existing position at the new leverage.
1542
+ * Rejects if the account can't afford the increased margin when decreasing leverage.
1543
+ */
1544
+ async updateLeverage(opts) {
1545
+ await this.ready();
1546
+ return this.client.post(`/objects/${opts.objectId}/exchange/leverage`, {
1547
+ market: opts.market,
1548
+ leverage: opts.leverage,
1549
+ });
1550
+ }
1551
+ /**
1552
+ * Get leverage settings for a market (or all coins) on an exchange Arca object.
1553
+ */
1554
+ async getLeverage(objectId, market) {
1555
+ await this.ready();
1556
+ const params = {};
1557
+ if (market)
1558
+ params.market = market;
1559
+ return this.client.get(`/objects/${objectId}/exchange/leverage`, params);
1560
+ }
1561
+ /**
1562
+ * Get all leverage settings for an exchange Arca object.
1563
+ * Unlike getLeverage(), always returns an array.
1564
+ */
1565
+ async listLeverageSettings(objectId) {
1566
+ const result = await this.getLeverage(objectId);
1567
+ return Array.isArray(result) ? result : [result];
1568
+ }
1569
+ /**
1570
+ * Add or remove collateral from an isolated-margin position.
1571
+ *
1572
+ * Isolated positions carry their own dedicated collateral and are
1573
+ * liquidated independently of the cross pool. A positive `amount` moves USD
1574
+ * from the account's free balance into the position (lowering its
1575
+ * liquidation price); a negative `amount` removes collateral (raising it).
1576
+ * Removal is rejected if it would drop the position below its maintenance
1577
+ * margin. Only valid on isolated positions.
1578
+ */
1579
+ async updateIsolatedMargin(opts) {
1580
+ await this.ready();
1581
+ return this.client.post(`/objects/${opts.objectId}/exchange/isolated-margin`, { market: opts.market, amount: opts.amount });
1582
+ }
1583
+ /**
1584
+ * Switch an asset between cross and isolated margin for an exchange Arca
1585
+ * object. Rejected on isolated-only (HIP-3) markets and while an open
1586
+ * position exists for the asset — close the position first.
1587
+ */
1588
+ async setMarginMode(opts) {
1589
+ await this.ready();
1590
+ return this.client.post(`/objects/${opts.objectId}/exchange/margin-mode`, { market: opts.market, marginMode: opts.marginMode });
1591
+ }
1592
+ /**
1593
+ * Place an order on an exchange Arca object.
1594
+ * The operation path serves as the idempotency key.
1595
+ *
1596
+ * Returns an OrderHandle: `await` waits for placement. Use `.filled()`,
1597
+ * `.onFill()`, `.fills()` for fill lifecycle, and `.cancel()` to cancel.
1598
+ */
1599
+ placeOrder(opts) {
1600
+ const httpCall = this.ready().then(() => this.client.post(`/objects/${opts.objectId}/exchange/orders`, {
1601
+ realmId: this.realmId(),
1602
+ path: opts.path,
1603
+ market: opts.market,
1604
+ side: opts.side,
1605
+ orderType: opts.orderType,
1606
+ size: opts.size,
1607
+ price: opts.price,
1608
+ reduceOnly: opts.reduceOnly ?? false,
1609
+ timeInForce: opts.timeInForce ?? 'GTC',
1610
+ ...(opts.leverage != null && { leverage: opts.leverage }),
1611
+ ...((opts.applicationFeeTenthsBps) != null && { applicationFeeTenthsBps: opts.applicationFeeTenthsBps }),
1612
+ ...(opts.feeTargets != null && { feeTargets: opts.feeTargets }),
1613
+ ...(opts.isTrigger && { isTrigger: true }),
1614
+ ...(opts.triggerPx != null && { triggerPx: opts.triggerPx }),
1615
+ ...(opts.isMarket != null && { isMarket: opts.isMarket }),
1616
+ ...(opts.tpsl != null && { tpsl: opts.tpsl }),
1617
+ ...(opts.grouping != null && { grouping: opts.grouping }),
1618
+ ...(opts.useMax && { useMax: true }),
1619
+ ...((opts.sizeTolerance ?? opts.maxSizeTolerance) != null && { sizeTolerance: opts.sizeTolerance ?? opts.maxSizeTolerance }),
1620
+ ...(opts.isolated && { isolated: true }),
1621
+ })).then(response => {
1622
+ this.throwIfOperationFailed(response.operation);
1623
+ // Optimistically emit a fill event if the order was partially or fully filled synchronously
1624
+ if (response.operation.outcome) {
1625
+ try {
1626
+ const outcome = JSON.parse(response.operation.outcome);
1627
+ if (outcome.filledSize && parseFloat(outcome.filledSize) > 0) {
1628
+ const fillId = `fil_opt_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1629
+ const fill = {
1630
+ id: fillId,
1631
+ orderId: outcome.orderId,
1632
+ market: opts.market,
1633
+ side: opts.side,
1634
+ price: outcome.avgFillPrice || opts.price || "0",
1635
+ size: outcome.filledSize,
1636
+ fee: "0", // Unknown until canonical event
1637
+ realizedPnl: "0", // Unknown until canonical event
1638
+ isLiquidation: false,
1639
+ createdAt: new Date().toISOString(),
1640
+ isOptimistic: true,
1641
+ cloid: outcome.cloid,
1642
+ };
1643
+ this.ws.emitLocal({
1644
+ type: types_1.EventType.FillPreviewed,
1645
+ realmId: this.realmId(),
1646
+ entityPath: opts.path,
1647
+ fill: fill,
1648
+ });
1649
+ }
1650
+ }
1651
+ catch (e) {
1652
+ // Ignore parse errors
1653
+ }
1654
+ }
1655
+ return response;
1656
+ });
1657
+ const deps = {
1658
+ getOrder: (objectId, orderId) => this.getOrder(objectId, orderId),
1659
+ onFillEvent: (handler) => {
1660
+ this.ws.ensureConnected();
1661
+ this.ws.on(types_1.EventType.FillPreviewed, handler);
1662
+ return () => this.ws.off(types_1.EventType.FillPreviewed, handler);
1663
+ },
1664
+ cancelOrder: (cancelOpts) => this.cancelOrder(cancelOpts),
1665
+ listFills: (objectId) => this.listFills(objectId),
1666
+ };
1667
+ return new operation_handle_1.OrderHandle(httpCall, (id, timeout) => this.waitForOperation(id, timeout), opts.objectId, opts.path, deps);
1668
+ }
1669
+ /**
1670
+ * List orders for an exchange Arca object.
1671
+ */
1672
+ async listOrders(objectId, status) {
1673
+ await this.ready();
1674
+ const params = {};
1675
+ if (status)
1676
+ params.status = status;
1677
+ const response = await this.client.get(`/objects/${objectId}/exchange/orders`, params);
1678
+ return response.orders;
1679
+ }
1680
+ /**
1681
+ * Get a specific order with its fills.
1682
+ */
1683
+ async getOrder(objectId, orderId) {
1684
+ await this.ready();
1685
+ return this.client.get(`/objects/${objectId}/exchange/orders/${orderId}`);
1686
+ }
1687
+ /**
1688
+ * Cancel an order on an exchange Arca object.
1689
+ * The operation path serves as the idempotency key.
1690
+ */
1691
+ cancelOrder(opts) {
1692
+ return this.op(() => {
1693
+ const params = new URLSearchParams({
1694
+ realmId: this.realmId(),
1695
+ path: opts.path,
1696
+ });
1697
+ return this.client.delete(`/objects/${opts.objectId}/exchange/orders/${opts.orderId}?${params.toString()}`);
1698
+ });
1699
+ }
1700
+ // ---- Position-level TP/SL (existing positions) ----
1701
+ /**
1702
+ * Attach a stop-loss to an open position.
1703
+ *
1704
+ * Places a position-attached trigger (`grouping: 'positionTpsl'`,
1705
+ * `reduceOnly: true`) on the *closing* side inferred from the open position
1706
+ * (`long` → sell, `short` → buy). The size tracks the position automatically:
1707
+ * the venue fills it from the current position and resizes it as the
1708
+ * position changes, cancelling it when the position closes or is liquidated.
1709
+ * By default any existing stop-loss for the market is replaced (cancel + place).
1710
+ *
1711
+ * Requires an open position for `market` — throws `NotFoundError` otherwise.
1712
+ *
1713
+ * @example
1714
+ * ```ts
1715
+ * await arca.setStopLoss({
1716
+ * path: "/wallets/main/tpsl/btc-sl",
1717
+ * objectId,
1718
+ * market: "hl:0:BTC",
1719
+ * triggerPx: "58000",
1720
+ * });
1721
+ * ```
1722
+ */
1723
+ setStopLoss(opts) {
1724
+ return this.setPositionTrigger('sl', opts);
1725
+ }
1726
+ /**
1727
+ * Attach a take-profit to an open position. The position-attached
1728
+ * counterpart of {@link Arca.setStopLoss}; see it for lifecycle details.
1729
+ *
1730
+ * @example
1731
+ * ```ts
1732
+ * await arca.setTakeProfit({
1733
+ * path: "/wallets/main/tpsl/btc-tp",
1734
+ * objectId,
1735
+ * market: "hl:0:BTC",
1736
+ * triggerPx: "72000",
1737
+ * });
1738
+ * ```
1739
+ */
1740
+ setTakeProfit(opts) {
1741
+ return this.setPositionTrigger('tp', opts);
1742
+ }
1743
+ /**
1744
+ * Attach a stop-loss and/or take-profit to an open position in one call.
1745
+ * At least one of `stopLossPx` / `takeProfitPx` is required. Each leg is a
1746
+ * `positionTpsl` order keyed off a derived sub-path (`<path>/sl`, `<path>/tp`).
1747
+ * Legs are placed sequentially so a failed stop-loss surfaces before the
1748
+ * take-profit is attempted.
1749
+ *
1750
+ * @example
1751
+ * ```ts
1752
+ * const { stopLoss, takeProfit } = await arca.setPositionTpsl({
1753
+ * path: "/wallets/main/tpsl/btc",
1754
+ * objectId,
1755
+ * market: "hl:0:BTC",
1756
+ * stopLossPx: "58000",
1757
+ * takeProfitPx: "72000",
1758
+ * });
1759
+ * ```
1760
+ */
1761
+ async setPositionTpsl(opts) {
1762
+ if (opts.stopLossPx == null && opts.takeProfitPx == null) {
1763
+ throw new errors_1.ValidationError('setPositionTpsl requires at least one of stopLossPx or takeProfitPx');
1764
+ }
1765
+ const result = {};
1766
+ if (opts.stopLossPx != null) {
1767
+ const sl = this.setStopLoss({
1768
+ path: `${opts.path}/sl`,
1769
+ objectId: opts.objectId,
1770
+ market: opts.market,
1771
+ triggerPx: opts.stopLossPx,
1772
+ isMarket: opts.isMarket,
1773
+ replace: opts.replace,
1774
+ applicationFeeTenthsBps: opts.applicationFeeTenthsBps,
1775
+ feeTargets: opts.feeTargets,
1776
+ });
1777
+ await sl;
1778
+ result.stopLoss = sl;
1779
+ }
1780
+ if (opts.takeProfitPx != null) {
1781
+ const tp = this.setTakeProfit({
1782
+ path: `${opts.path}/tp`,
1783
+ objectId: opts.objectId,
1784
+ market: opts.market,
1785
+ triggerPx: opts.takeProfitPx,
1786
+ isMarket: opts.isMarket,
1787
+ replace: opts.replace,
1788
+ applicationFeeTenthsBps: opts.applicationFeeTenthsBps,
1789
+ feeTargets: opts.feeTargets,
1790
+ });
1791
+ await tp;
1792
+ result.takeProfit = tp;
1793
+ }
1794
+ return result;
1795
+ }
1796
+ /**
1797
+ * Cancel resting position-attached (`positionTpsl`) TP/SL orders for a market.
1798
+ * Pass `tpsl` to clear only the stop-loss or only the take-profit; omit it to
1799
+ * clear both. Returns the orders that were cancelled (empty if none rest).
1800
+ *
1801
+ * @example
1802
+ * ```ts
1803
+ * await arca.clearPositionTpsl({ path: "/wallets/main/tpsl/btc-clear", objectId, market: "hl:0:BTC" });
1804
+ * ```
1805
+ */
1806
+ async clearPositionTpsl(opts) {
1807
+ const existing = await this.findPositionTpslOrders(opts.objectId, opts.market, opts.tpsl);
1808
+ for (const o of existing) {
1809
+ await this.cancelOrder({
1810
+ objectId: opts.objectId,
1811
+ orderId: o.id,
1812
+ path: `${opts.path}/${o.id}`,
1813
+ });
1814
+ }
1815
+ return existing;
1816
+ }
1817
+ /** Internal: place one position-attached trigger (stop-loss or take-profit). */
1818
+ setPositionTrigger(tpsl, opts) {
1819
+ const replace = opts.replace ?? true;
1820
+ const isMarket = opts.isMarket ?? true;
1821
+ if (!isMarket && opts.limitPrice == null) {
1822
+ // Surface the trigger-limit price requirement before any network call;
1823
+ // the server enforces the same rule (exchange.ValidateTriggerFields).
1824
+ throw new errors_1.ValidationError('trigger-limit orders require a limitPrice (set isMarket: true for a market trigger)');
1825
+ }
1826
+ const httpCall = (async () => {
1827
+ const { side, leverage, isolated } = await this.inferPositionCloseParams(opts.objectId, opts.market, { leverage: opts.leverage, isolated: opts.isolated });
1828
+ // Modify = cancel-existing + place-new. Cancels use distinct sub-paths
1829
+ // so each is its own idempotent operation.
1830
+ if (replace) {
1831
+ const existing = await this.findPositionTpslOrders(opts.objectId, opts.market, tpsl);
1832
+ for (const o of existing) {
1833
+ await this.cancelOrder({ objectId: opts.objectId, orderId: o.id, path: `${opts.path}/replace-${o.id}` });
1834
+ }
1835
+ }
1836
+ await this.ready();
1837
+ const response = await this.client.post(`/objects/${opts.objectId}/exchange/orders`, {
1838
+ realmId: this.realmId(),
1839
+ path: opts.path,
1840
+ market: opts.market,
1841
+ side,
1842
+ orderType: isMarket ? 'MARKET' : 'LIMIT',
1843
+ // size 0 → the venue auto-fills from the current position and keeps the
1844
+ // trigger sized to the position as it changes (positionTpsl semantics).
1845
+ size: '0',
1846
+ ...(!isMarket && opts.limitPrice != null && { price: opts.limitPrice }),
1847
+ reduceOnly: true,
1848
+ timeInForce: opts.timeInForce ?? 'GTC',
1849
+ isTrigger: true,
1850
+ triggerPx: opts.triggerPx,
1851
+ isMarket,
1852
+ tpsl,
1853
+ grouping: 'positionTpsl',
1854
+ ...(leverage != null && { leverage }),
1855
+ ...(isolated && { isolated: true }),
1856
+ ...((opts.applicationFeeTenthsBps) != null && { applicationFeeTenthsBps: opts.applicationFeeTenthsBps }),
1857
+ ...(opts.feeTargets != null && { feeTargets: opts.feeTargets }),
1858
+ });
1859
+ this.throwIfOperationFailed(response.operation);
1860
+ return response;
1861
+ })();
1862
+ return new operation_handle_1.OrderHandle(httpCall, (id, timeout) => this.waitForOperation(id, timeout), opts.objectId, opts.path, this.orderHandleDeps());
1863
+ }
1864
+ /**
1865
+ * Internal: derive the closing side (and leverage / isolated) for a market
1866
+ * from its open position. Mirrors the inference in {@link Arca.closePosition}.
1867
+ * Throws `NotFoundError` when there is no open position.
1868
+ */
1869
+ async inferPositionCloseParams(objectId, market, overrides) {
1870
+ const positions = await this.listPositions(objectId);
1871
+ const position = positions.find(p => p.market === market);
1872
+ if (!position) {
1873
+ throw new errors_1.NotFoundError(`No open position for ${market}`);
1874
+ }
1875
+ const side = position.side === 'long' ? 'sell' : 'buy';
1876
+ const leverage = overrides?.leverage != null ? overrides.leverage : (position.leverage ?? undefined);
1877
+ let isolated;
1878
+ if (overrides?.isolated != null) {
1879
+ isolated = overrides.isolated;
1880
+ }
1881
+ else {
1882
+ const meta = await this.market(market).catch(() => undefined);
1883
+ isolated = meta?.marginModes != null
1884
+ ? (meta.marginModes.length === 1 && meta.marginModes[0] === 'isolated')
1885
+ : meta?.onlyIsolated === true;
1886
+ }
1887
+ return { side, leverage, isolated };
1888
+ }
1889
+ /**
1890
+ * Internal: list resting (WAITING_FOR_TRIGGER) `positionTpsl` orders for a
1891
+ * market, optionally filtered to one TP/SL type.
1892
+ */
1893
+ async findPositionTpslOrders(objectId, market, tpsl) {
1894
+ const orders = await this.listOrders(objectId, 'WAITING_FOR_TRIGGER');
1895
+ return orders.filter(o => o.market === market &&
1896
+ o.grouping === 'positionTpsl' &&
1897
+ (tpsl == null || o.tpsl === tpsl));
1898
+ }
1899
+ /** Internal: the OrderHandle dependency bundle shared by order-placing methods. */
1900
+ orderHandleDeps() {
1901
+ return {
1902
+ getOrder: (objectId, orderId) => this.getOrder(objectId, orderId),
1903
+ onFillEvent: (handler) => {
1904
+ this.ws.ensureConnected();
1905
+ this.ws.on(types_1.EventType.FillPreviewed, handler);
1906
+ return () => this.ws.off(types_1.EventType.FillPreviewed, handler);
1907
+ },
1908
+ cancelOrder: (cancelOpts) => this.cancelOrder(cancelOpts),
1909
+ listFills: (objectId) => this.listFills(objectId),
1910
+ };
1911
+ }
1912
+ // ---- TWAP ----
1913
+ /**
1914
+ * Start a TWAP (Time-Weighted Average Price) order that executes a total size
1915
+ * over a duration by placing market orders at regular intervals.
1916
+ *
1917
+ * @example
1918
+ * ```ts
1919
+ * const twap = await arca.placeTwap({
1920
+ * exchangeId: "/exchanges/main",
1921
+ * path: "/wallets/main/twap/btc-accumulate",
1922
+ * market: "hl:0:BTC",
1923
+ * side: "buy",
1924
+ * totalSize: "10.0",
1925
+ * durationMinutes: 120,
1926
+ * intervalSeconds: 30,
1927
+ * });
1928
+ * console.log(twap.twap.status); // "active"
1929
+ * ```
1930
+ */
1931
+ placeTwap(opts) {
1932
+ return this.op(() => this.client.post(`/objects/${opts.exchangeId}/exchange/twap`, {
1933
+ realmId: this.realmId(),
1934
+ path: opts.path,
1935
+ market: opts.market,
1936
+ side: opts.side,
1937
+ totalSize: opts.totalSize,
1938
+ durationMinutes: opts.durationMinutes,
1939
+ ...(opts.intervalSeconds != null && { intervalSeconds: opts.intervalSeconds }),
1940
+ ...(opts.randomize != null && { randomize: opts.randomize }),
1941
+ ...(opts.reduceOnly != null && { reduceOnly: opts.reduceOnly }),
1942
+ ...(opts.leverage != null && { leverage: opts.leverage }),
1943
+ ...(opts.slippageBps != null && { slippageBps: opts.slippageBps }),
1944
+ }));
1945
+ }
1946
+ /**
1947
+ * Cancel an active TWAP.
1948
+ */
1949
+ cancelTwap(exchangeId, operationId) {
1950
+ return this.op(() => this.client.delete(`/objects/${exchangeId}/exchange/twap/${operationId}?realmId=${encodeURIComponent(this.realmId())}`));
1951
+ }
1952
+ /**
1953
+ * Get TWAP status and progress by its parent operation ID.
1954
+ */
1955
+ async getTwap(exchangeId, operationId) {
1956
+ await this.ready();
1957
+ return this.client.get(`/objects/${exchangeId}/exchange/twap/${operationId}`, { realmId: this.realmId() });
1958
+ }
1959
+ /**
1960
+ * List TWAPs for an exchange object.
1961
+ * @param activeOnly - If true, only returns active TWAPs.
1962
+ */
1963
+ async listTwaps(exchangeId, activeOnly = false) {
1964
+ await this.ready();
1965
+ const params = { realmId: this.realmId() };
1966
+ if (activeOnly)
1967
+ params.active = 'true';
1968
+ return this.client.get(`/objects/${exchangeId}/exchange/twaps`, params);
1969
+ }
1970
+ /**
1971
+ * Watch a single TWAP by its parent operation ID. Returns a stream
1972
+ * that emits the latest server-side {@link Twap} on every TWAP event
1973
+ * targeting this operation (`twap.started`, `twap.progress`,
1974
+ * `twap.completed`, `twap.cancelled`, `twap.failed`).
1975
+ *
1976
+ * The first snapshot is fetched eagerly via REST so `stream.twap` is
1977
+ * populated immediately after `await stream.ready()`. Subsequent
1978
+ * updates come from the WebSocket; if the connection drops the stream
1979
+ * transitions to `reconnecting` and resumes once the socket
1980
+ * reconnects. Closing the stream releases its filter listeners but
1981
+ * does not close the underlying WebSocket.
1982
+ *
1983
+ * @example
1984
+ * ```ts
1985
+ * const stream = await arca.watchTwap(exchangeId, operationId);
1986
+ * for await (const { twap } of stream) {
1987
+ * console.log(`${twap.sliceCount}/${twap.expectedSliceCount}`,
1988
+ * 'status:', twap.status);
1989
+ * if (twap.status !== 'active') break;
1990
+ * }
1991
+ * ```
1992
+ */
1993
+ async watchTwap(exchangeId, operationId) {
1994
+ await this.ready();
1995
+ const initial = await this.getTwap(exchangeId, operationId).catch(() => null);
1996
+ return new streams_1.TwapWatchStream(this.ws, operationId, initial?.twap ?? undefined, async () => {
1997
+ const r = await this.getTwap(exchangeId, operationId).catch(() => null);
1998
+ return r?.twap ?? null;
1999
+ });
2000
+ }
2001
+ /**
2002
+ * Get TWAP limits + recommendation curve from the server. The
2003
+ * response is static for the process lifetime so the SDK caches it
2004
+ * after the first call; bumping limits is a server-side change only.
2005
+ * Use `getTwapLimits().recommendation.buckets` directly for custom
2006
+ * pickers, or call {@link recommendedIntervalSeconds} for the
2007
+ * one-shot helper that matches the iOS team's
2008
+ * "5m/15m/1h" duration tiers.
2009
+ *
2010
+ * @example
2011
+ * ```ts
2012
+ * const { limits } = await arca.getTwapLimits();
2013
+ * if (durationMinutes > limits.maxDurationMinutes) throw new Error('too long');
2014
+ * ```
2015
+ */
2016
+ async getTwapLimits() {
2017
+ if (this.twapLimitsCache)
2018
+ return this.twapLimitsCache;
2019
+ const response = await this.client.get('/twap/limits');
2020
+ this.twapLimitsCache = response;
2021
+ return response;
2022
+ }
2023
+ /**
2024
+ * Returns the recommended `intervalSeconds` for a given TWAP duration,
2025
+ * picked from the server's recommendation curve. Use this to populate
2026
+ * a default in your TWAP entry UI so retail-sized 1h TWAPs aren't
2027
+ * sliced into 120 30-second orders.
2028
+ *
2029
+ * @example
2030
+ * ```ts
2031
+ * const intervalSeconds = await arca.recommendedIntervalSeconds(60); // 300 (5m)
2032
+ * ```
2033
+ */
2034
+ async recommendedIntervalSeconds(durationMinutes) {
2035
+ const { limits, recommendation } = await this.getTwapLimits();
2036
+ for (const bucket of recommendation.buckets) {
2037
+ if (durationMinutes <= bucket.maxDurationMinutes) {
2038
+ return bucket.recommendedIntervalSeconds;
2039
+ }
2040
+ }
2041
+ return limits.defaultIntervalSeconds;
2042
+ }
2043
+ /**
2044
+ * Get venue-wide order limits. Hyperliquid enforces a $10 minimum on
2045
+ * `size * price` for every non-reduce-only order. Reduce-only orders and
2046
+ * `positionTpsl` triggers are exempt so dust positions can always be
2047
+ * closed. Use this to pre-validate {@link Arca.placeOrder} sizes.
2048
+ */
2049
+ getOrderLimits() {
2050
+ return { minOrderNotionalUsd: 10 };
2051
+ }
2052
+ /**
2053
+ * List positions for an exchange Arca object.
2054
+ */
2055
+ async listPositions(objectId) {
2056
+ await this.ready();
2057
+ const response = await this.client.get(`/objects/${objectId}/exchange/positions`);
2058
+ return response.positions;
2059
+ }
2060
+ /**
2061
+ * Close an open position (fully or partially) with `reduceOnly` enforced.
2062
+ *
2063
+ * Looks up the current position for `opts.market`, infers the closing side,
2064
+ * and places a market order sized to close the full position (or `opts.size`
2065
+ * tokens if a partial close is desired). Always sets `reduceOnly: true` so
2066
+ * the order can never accidentally open or increase a position.
2067
+ *
2068
+ * Automatically threads the position's `leverage` into the order body and
2069
+ * sets `isolated: true` for isolated-only markets — those whose
2070
+ * `marginModes` is `['isolated']` (equivalently the deprecated
2071
+ * `onlyIsolated=true`), such as `hl:1:CL`. On Hyperliquid, isolated orders
2072
+ * are bucketed by leverage — the matching engine refuses a close that
2073
+ * doesn't identify the bucket. The iOS Quick Close fix proved this; we
2074
+ * encode it once in the SDK so builders don't have to learn the rule. Pass
2075
+ * `opts.isolated` or `opts.leverage` to override the auto-fill.
2076
+ *
2077
+ * Note: the margin mode is read from the asset's `marginModes`/`onlyIsolated`
2078
+ * metadata, not from whether the market is HIP-3. HIP-3 is orthogonal — some
2079
+ * HIP-3 markets (e.g. `hl:1:TSLA`) are cross-eligible.
2080
+ *
2081
+ * Returns an OrderHandle: `await` waits for placement. Use `.filled()`,
2082
+ * `.onFill()`, `.fills()` for fill lifecycle, and `.cancel()` to cancel.
2083
+ */
2084
+ closePosition(opts) {
2085
+ // Order of network calls:
2086
+ // 1. listPositions — to find the position to close.
2087
+ // 2. asset (cached) — to derive `isolated` from the asset's
2088
+ // `marginModes` (falling back to `onlyIsolated`). Cached after
2089
+ // first call per Arca instance; cold-cache failure resolves
2090
+ // `isolated` to false, which the server will then reject for
2091
+ // isolated-only markets.
2092
+ // 3. POST order
2093
+ // Serialized via `then` rather than concurrent so HTTP call order
2094
+ // is deterministic for tests and for replay debugging.
2095
+ const httpCall = this.listPositions(opts.objectId).then(async (positions) => {
2096
+ const position = positions.find(p => p.market === opts.market);
2097
+ if (!position) {
2098
+ throw new errors_1.NotFoundError(`No open position for ${opts.market}`);
2099
+ }
2100
+ const side = position.side === 'long' ? 'sell' : 'buy';
2101
+ let size = position.size;
2102
+ if (opts.size) {
2103
+ const requested = parseFloat(opts.size);
2104
+ const available = parseFloat(position.size);
2105
+ size = requested > available ? position.size : opts.size;
2106
+ }
2107
+ const leverage = opts.leverage != null ? opts.leverage : (position.leverage ?? undefined);
2108
+ let isolated;
2109
+ if (opts.isolated != null) {
2110
+ isolated = opts.isolated;
2111
+ }
2112
+ else {
2113
+ const meta = await this.market(opts.market).catch(() => undefined);
2114
+ // Prefer the explicit margin-mode list; fall back to the deprecated
2115
+ // `onlyIsolated` boolean for older servers that don't populate it.
2116
+ // A market is isolated-only when its only supported mode is isolated.
2117
+ isolated = meta?.marginModes != null
2118
+ ? (meta.marginModes.length === 1 && meta.marginModes[0] === 'isolated')
2119
+ : meta?.onlyIsolated === true;
2120
+ }
2121
+ await this.ready();
2122
+ const response = await this.client.post(`/objects/${opts.objectId}/exchange/orders`, {
2123
+ realmId: this.realmId(),
2124
+ path: opts.path,
2125
+ market: opts.market,
2126
+ side,
2127
+ orderType: 'MARKET',
2128
+ size,
2129
+ reduceOnly: true,
2130
+ timeInForce: opts.timeInForce ?? 'IOC',
2131
+ ...(leverage != null && { leverage }),
2132
+ ...(isolated && { isolated: true }),
2133
+ ...((opts.applicationFeeTenthsBps) != null && { applicationFeeTenthsBps: opts.applicationFeeTenthsBps }),
2134
+ ...(opts.feeTargets != null && { feeTargets: opts.feeTargets }),
2135
+ });
2136
+ return { response, side };
2137
+ }).then(({ response, side }) => {
2138
+ this.throwIfOperationFailed(response.operation);
2139
+ // Optimistically emit a fill event if the order was partially or fully filled synchronously
2140
+ if (response.operation.outcome) {
2141
+ try {
2142
+ const outcome = JSON.parse(response.operation.outcome);
2143
+ if (outcome.filledSize && parseFloat(outcome.filledSize) > 0) {
2144
+ const fillId = `fil_opt_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2145
+ const fill = {
2146
+ id: fillId,
2147
+ orderId: outcome.orderId,
2148
+ market: opts.market,
2149
+ side: side,
2150
+ price: outcome.avgFillPrice || "0",
2151
+ size: outcome.filledSize,
2152
+ fee: "0",
2153
+ realizedPnl: "0",
2154
+ isLiquidation: false,
2155
+ createdAt: new Date().toISOString(),
2156
+ isOptimistic: true,
2157
+ cloid: outcome.cloid,
2158
+ };
2159
+ this.ws.emitLocal({
2160
+ type: types_1.EventType.FillPreviewed,
2161
+ realmId: this.realmId(),
2162
+ entityPath: opts.path,
2163
+ fill: fill,
2164
+ });
2165
+ }
2166
+ }
2167
+ catch (e) {
2168
+ // Ignore parse errors
2169
+ }
2170
+ }
2171
+ return response;
2172
+ });
2173
+ const deps = {
2174
+ getOrder: (objectId, orderId) => this.getOrder(objectId, orderId),
2175
+ onFillEvent: (handler) => {
2176
+ this.ws.ensureConnected();
2177
+ this.ws.on(types_1.EventType.FillPreviewed, handler);
2178
+ return () => this.ws.off(types_1.EventType.FillPreviewed, handler);
2179
+ },
2180
+ cancelOrder: (cancelOpts) => this.cancelOrder(cancelOpts),
2181
+ listFills: (objectId) => this.listFills(objectId),
2182
+ };
2183
+ return new operation_handle_1.OrderHandle(httpCall, (id, timeout) => this.waitForOperation(id, timeout), opts.objectId, opts.path, deps);
2184
+ }
2185
+ /**
2186
+ * List historical fills (trades) for an exchange Arca object.
2187
+ * Returns paginated fill data with P&L, fees, and resulting position state.
2188
+ */
2189
+ async listFills(objectId, opts) {
2190
+ await this.ready();
2191
+ const params = {};
2192
+ if (opts?.market)
2193
+ params.market = opts.market;
2194
+ if (opts?.startTime)
2195
+ params.startTime = opts.startTime;
2196
+ if (opts?.endTime)
2197
+ params.endTime = opts.endTime;
2198
+ if (opts?.limit)
2199
+ params.limit = String(opts.limit);
2200
+ if (opts?.cursor)
2201
+ params.cursor = opts.cursor;
2202
+ return this.client.get(`/objects/${objectId}/exchange/fills`, params);
2203
+ }
2204
+ /**
2205
+ * Watch fills (trade history) for an exchange Arca object.
2206
+ * Resolves the object path from `objectId`, creates a path-scoped watch,
2207
+ * then combines an initial REST snapshot with live `fill.previewed` and
2208
+ * `fill.recorded` WebSocket events. Each update contains a platform-level
2209
+ * `Fill` with P&L, fee breakdown, direction, and resulting position.
2210
+ *
2211
+ * For an activity-feed UI, read the already-merged `stream.fills` array.
2212
+ * Subscribe via `stream.onUpdate(...)` only when you need the raw
2213
+ * preview→recorded transition (e.g. an order-confirmation animation) — that
2214
+ * stream emits both phases as separate events, and deduping by `Fill.id`
2215
+ * does not work because the preview and recorded events use different ids.
2216
+ *
2217
+ * ```ts
2218
+ * const stream = await arca.watchFills('obj_...');
2219
+ * console.log(stream.fills); // merged list — one row per fill
2220
+ * stream.onUpdate(({ fill }) => console.log('preview or recorded:', fill));
2221
+ * // later: stream.close();
2222
+ * ```
2223
+ */
2224
+ async watchFills(objectId, opts) {
2225
+ await this.ready();
2226
+ const detail = await this.getObjectDetail(objectId);
2227
+ const objectPath = detail.object.path;
2228
+ const stream = new streams_1.FillWatchStream(this.ws, () => this.listFills(objectId, opts), objectId, objectPath);
2229
+ await stream.ready();
2230
+ return stream;
2231
+ }
2232
+ /**
2233
+ * Watch real-time funding payment events for an exchange Arca object.
2234
+ * Resolves the object path from `objectId`, creates a path-scoped watch,
2235
+ * then streams `exchange.funding` events. Each update includes the
2236
+ * `FundingPayment` and its `EventEnvelope` for correlation tracing.
2237
+ *
2238
+ * ```ts
2239
+ * const stream = await arca.watchFunding('obj_...');
2240
+ * stream.onUpdate(({ payment, envelope }) => {
2241
+ * console.log('funding:', payment.market, payment.payment, envelope.correlationId);
2242
+ * });
2243
+ * // later: stream.close();
2244
+ * ```
2245
+ */
2246
+ async watchFunding(objectId) {
2247
+ await this.ready();
2248
+ const detail = await this.getObjectDetail(objectId);
2249
+ const objectPath = detail.object.path;
2250
+ const stream = new streams_1.FundingWatchStream(this.ws, objectId, objectPath);
2251
+ await stream.ready();
2252
+ return stream;
2253
+ }
2254
+ /**
2255
+ * Get per-market P&L aggregation for an exchange Arca object.
2256
+ * Summarizes realized P&L, total fees, trade count, and volume by market.
2257
+ */
2258
+ async tradeSummary(objectId, opts) {
2259
+ await this.ready();
2260
+ const params = {};
2261
+ if (opts?.startTime)
2262
+ params.startTime = opts.startTime;
2263
+ if (opts?.endTime)
2264
+ params.endTime = opts.endTime;
2265
+ return this.client.get(`/objects/${objectId}/exchange/trade-summary`, params);
2266
+ }
2267
+ /**
2268
+ * Get market metadata (supported assets).
2269
+ */
2270
+ async getMarketMeta() {
2271
+ await this.ready();
2272
+ return this.client.get('/exchange/market/meta');
2273
+ }
2274
+ /**
2275
+ * Look up a single market by its **exact canonical market ID**
2276
+ * (e.g. `"hl:0:BTC"`, `"hl:1:TSLA"`).
2277
+ *
2278
+ * This is an exact-id lookup — pass the `name` field of a {@link Market},
2279
+ * not a bare symbol like `"BTC"`. To go from a human symbol to its
2280
+ * market(s), use {@link resolveMarkets} / {@link resolveMarketOrThrow}.
2281
+ *
2282
+ * Lazily fetches and caches market metadata on first call. Subsequent
2283
+ * calls return from cache without a network request.
2284
+ *
2285
+ * @example
2286
+ * ```ts
2287
+ * const btc = await arca.market("hl:0:BTC");
2288
+ * console.log(btc?.symbol); // "BTC"
2289
+ * console.log(btc?.displayName); // undefined
2290
+ * console.log(btc?.logoUrl); // "https://...-128.webp" (default 128px)
2291
+ * console.log(btc?.logoSources); // [{ url: "...", width: 256, format: "webp" }, ...]
2292
+ * ```
2293
+ *
2294
+ * @param id - Canonical market ID (the `name` field on {@link Market}).
2295
+ * @returns The matching {@link Market}, or `undefined` if not found.
2296
+ */
2297
+ async market(id) {
2298
+ const map = await this.ensureMetaLoaded();
2299
+ return map.get(id);
2300
+ }
2301
+ /**
2302
+ * Resolve a human **symbol** (e.g. `"BTC"`, `"TSLA"`) to the market(s) that
2303
+ * carry it, returning an **array** because one symbol can legitimately map
2304
+ * to many markets across exchanges and HIP-3 dexes (e.g. a native `BTC` and
2305
+ * a builder-deployed `BTC` on a different dex).
2306
+ *
2307
+ * This never fails silently: an empty array is an explicit "no market has
2308
+ * this symbol", not a guess. Match is **exact and case-sensitive** on the
2309
+ * {@link Market.symbol} field (`"kSHIB"` ≠ `"KSHIB"`). Narrow ambiguous
2310
+ * symbols with the optional `exchange` / `dex` filters.
2311
+ *
2312
+ * For the "I expect exactly one" case, use {@link resolveMarketOrThrow}.
2313
+ * If you already hold a canonical id, use {@link market} instead.
2314
+ *
2315
+ * @example
2316
+ * ```ts
2317
+ * const all = await arca.resolveMarkets("BTC"); // every BTC market
2318
+ * const hlOnly = await arca.resolveMarkets("BTC", { exchange: "hl" });
2319
+ * const tsla = await arca.resolveMarkets("TSLA", { dex: "xyz" });
2320
+ * ```
2321
+ *
2322
+ * @param symbol - Display symbol to resolve (the `symbol` field on {@link Market}).
2323
+ * @param opts - Optional `exchange` / `dex` filters.
2324
+ * @returns All matching markets; an empty array when none match.
2325
+ */
2326
+ async resolveMarkets(symbol, opts) {
2327
+ const map = await this.ensureMetaLoaded();
2328
+ const out = [];
2329
+ for (const m of map.values()) {
2330
+ if (m.symbol !== symbol)
2331
+ continue;
2332
+ if (opts?.exchange !== undefined && m.exchange !== opts.exchange)
2333
+ continue;
2334
+ if (opts?.dex !== undefined && m.dex !== opts.dex)
2335
+ continue;
2336
+ out.push(m);
2337
+ }
2338
+ return out;
2339
+ }
2340
+ /**
2341
+ * Resolve a human **symbol** to the single market that carries it, throwing
2342
+ * when the result is not exactly one.
2343
+ *
2344
+ * Use this when your code assumes a symbol is unambiguous (often after
2345
+ * narrowing with `exchange` / `dex`). Throws a {@link ValidationError} when
2346
+ * zero markets match (so a typo never silently no-ops) and when more than
2347
+ * one matches (so an ambiguous symbol never silently picks the wrong one).
2348
+ *
2349
+ * @example
2350
+ * ```ts
2351
+ * const btc = await arca.resolveMarketOrThrow("BTC", { exchange: "hl" });
2352
+ * await arca.placeOrder({ market: btc.name, ... });
2353
+ * ```
2354
+ *
2355
+ * @param symbol - Display symbol to resolve (the `symbol` field on {@link Market}).
2356
+ * @param opts - Optional `exchange` / `dex` filters.
2357
+ * @returns The single matching {@link Market}.
2358
+ * @throws {ValidationError} when zero or more than one market matches.
2359
+ */
2360
+ async resolveMarketOrThrow(symbol, opts) {
2361
+ const matches = await this.resolveMarkets(symbol, opts);
2362
+ const where = opts && (opts.exchange !== undefined || opts.dex !== undefined)
2363
+ ? ` (filters: ${JSON.stringify(opts)})`
2364
+ : '';
2365
+ if (matches.length === 0) {
2366
+ throw new errors_1.ValidationError(`No market found for symbol "${symbol}"${where}. Pass a canonical id ` +
2367
+ `to market(), or list candidates with resolveMarkets("${symbol}").`);
2368
+ }
2369
+ if (matches.length > 1) {
2370
+ const names = matches.map((m) => m.name).join(', ');
2371
+ throw new errors_1.ValidationError(`Symbol "${symbol}"${where} is ambiguous — ${matches.length} markets ` +
2372
+ `match: ${names}. Narrow with { exchange } / { dex }, or call ` +
2373
+ `market(id) with the exact canonical id.`);
2374
+ }
2375
+ return matches[0];
2376
+ }
2377
+ /**
2378
+ * Eagerly fetch and cache market metadata.
2379
+ *
2380
+ * Call at app startup to avoid latency on the first `market()` call.
2381
+ * Safe to call multiple times — skips the fetch if already cached.
2382
+ */
2383
+ async preloadMarketMeta() {
2384
+ await this.ensureMetaLoaded();
2385
+ }
2386
+ /**
2387
+ * Force re-fetch market metadata, replacing the cache.
2388
+ *
2389
+ * Use after a new asset is listed or when metadata may have changed.
2390
+ */
2391
+ async refreshMarketMeta() {
2392
+ this.metaCache = null;
2393
+ this.metaPromise = null;
2394
+ await this.ensureMetaLoaded();
2395
+ }
2396
+ async ensureMetaLoaded() {
2397
+ if (this.metaCache)
2398
+ return this.metaCache;
2399
+ if (!this.metaPromise) {
2400
+ const promise = this.getMarketMeta().then((resp) => {
2401
+ const map = new Map();
2402
+ for (const m of resp.universe) {
2403
+ map.set(m.name, m);
2404
+ }
2405
+ if (this.metaPromise === promise) {
2406
+ this.metaCache = map;
2407
+ this.metaPromise = null;
2408
+ }
2409
+ return map;
2410
+ }, (err) => {
2411
+ if (this.metaPromise === promise) {
2412
+ this.metaPromise = null;
2413
+ }
2414
+ throw err;
2415
+ });
2416
+ this.metaPromise = promise;
2417
+ }
2418
+ return this.metaPromise;
2419
+ }
2420
+ /**
2421
+ * Get current mid prices for all assets.
2422
+ */
2423
+ async getMarketMids() {
2424
+ await this.ready();
2425
+ return this.client.get('/exchange/market/mids');
2426
+ }
2427
+ /**
2428
+ * Get 24h ticker data for all assets (volume, price change, funding, delisted status).
2429
+ */
2430
+ async getMarketTickers() {
2431
+ await this.ready();
2432
+ return this.client.get('/exchange/market/tickers');
2433
+ }
2434
+ /**
2435
+ * Get L2 order book for a specific market.
2436
+ */
2437
+ async getOrderBook(market) {
2438
+ await this.ready();
2439
+ return this.client.get(`/exchange/market/book/${market}`);
2440
+ }
2441
+ /**
2442
+ * Get OHLCV candle data for a specific market.
2443
+ *
2444
+ * When `candleCdnBaseUrl` is configured, finalized historical chunks are
2445
+ * fetched directly from the CDN. The current (in-progress) period and any
2446
+ * chunks not yet published fall back to the REST API transparently.
2447
+ *
2448
+ * `market` must be a canonical market id (e.g. `"hl:0:BTC"`, `"hl:1:TSLA"`) — not
2449
+ * a bare symbol (`"TSLA"`), display name (`"Tesla"`), or Hyperliquid
2450
+ * named-deployer id (`"xyz:TSLA"`). A non-canonical id matches no market and
2451
+ * returns an empty array.
2452
+ */
2453
+ async getCandles(market, interval, options) {
2454
+ const intervalMs = {
2455
+ '15s': 15_000, '1m': 60_000, '5m': 300_000, '15m': 900_000,
2456
+ '1h': 3_600_000, '4h': 14_400_000, '1d': 86_400_000,
2457
+ };
2458
+ const now = Date.now();
2459
+ const effectiveEnd = options?.endTime ?? Math.floor(now / intervalMs[interval]) * intervalMs[interval];
2460
+ const skipBF = options?.skipBackfill === true;
2461
+ // `skipBackfill` is part of the cache key: a skipBackfill=true fetch can
2462
+ // legitimately return fewer (or zero) candles than a backfill-enabled
2463
+ // fetch for the same range, so the two must not share a cache slot.
2464
+ // Without this, an empty fast-path result would be served to a later
2465
+ // backfill-enabled retry (the watchCandleChart cold-start path).
2466
+ const key = (0, cache_1.buildCacheKey)('candles', {
2467
+ market,
2468
+ interval,
2469
+ startTime: options?.startTime !== undefined ? String(options.startTime) : undefined,
2470
+ endTime: String(effectiveEnd),
2471
+ skipBackfill: skipBF ? 'true' : undefined,
2472
+ });
2473
+ const cached = this.historyCache.get(key);
2474
+ if (cached)
2475
+ return cached;
2476
+ await this.ready();
2477
+ if (this.candleCdnBaseUrl && interval !== '15s') {
2478
+ const startMs = options?.startTime ?? (now - intervalMs[interval] * 300);
2479
+ const endMs = effectiveEnd;
2480
+ const apiFallback = async (start, end) => {
2481
+ const params = {
2482
+ interval,
2483
+ startTime: String(start),
2484
+ endTime: String(end),
2485
+ };
2486
+ if (skipBF)
2487
+ params.skipBackfill = 'true';
2488
+ const res = await this.client.get(`/exchange/market/candles/${market}`, params);
2489
+ return res.candles;
2490
+ };
2491
+ const candles = await (0, candle_cdn_1.fetchCandlesFromCDN)(this.candleCdnBaseUrl, market, interval, startMs, endMs, apiFallback);
2492
+ const result = { market, interval, candles };
2493
+ // Never cache an empty response: a transient empty (cold pod, skipped
2494
+ // backfill, not-yet-listed asset) would otherwise stick for the cache
2495
+ // TTL and starve a subsequent retry that could have populated history.
2496
+ if (candles.length > 0)
2497
+ this.historyCache.set(key, result);
2498
+ return result;
2499
+ }
2500
+ const params = { interval };
2501
+ if (options?.startTime !== undefined)
2502
+ params.startTime = String(options.startTime);
2503
+ if (options?.endTime !== undefined)
2504
+ params.endTime = String(options.endTime);
2505
+ if (skipBF)
2506
+ params.skipBackfill = 'true';
2507
+ const result = await this.client.get(`/exchange/market/candles/${market}`, params);
2508
+ if (result.candles.length > 0)
2509
+ this.historyCache.set(key, result);
2510
+ return result;
2511
+ }
2512
+ /**
2513
+ * Get sparkline close-price arrays for all tracked coins in a single request.
2514
+ * Returns a map of market name to an array of 24 hourly close prices.
2515
+ * Sparkline data is pre-computed every ~5 minutes; for real-time prices
2516
+ * use {@link watchPrices}.
2517
+ *
2518
+ * @param _interval - Ignored (sparklines always use 1h interval)
2519
+ * @param _points - Ignored (sparklines always return 24 data points)
2520
+ */
2521
+ async getSparklines(_interval, _points) {
2522
+ await this.ready();
2523
+ return this.client.get('/exchange/market/sparklines');
2524
+ }
2525
+ /**
2526
+ * Subscribe to real-time mid prices.
2527
+ *
2528
+ * The typical pattern is: call once at app startup, then read
2529
+ * `stream.get('hl:0:BTC')` (or `stream.prices['hl:0:BTC']`) any time you
2530
+ * need the current price of an asset. The server pushes a snapshot on
2531
+ * subscribe (and again after any reconnect), so `.prices` is always
2532
+ * populated by the time the returned promise resolves.
2533
+ *
2534
+ * @example
2535
+ * // Read on demand — simplest usage
2536
+ * const prices = await arca.watchPrices();
2537
+ * const btc = prices.get('hl:0:BTC'); // decimal string, or undefined
2538
+ *
2539
+ * @example
2540
+ * // Narrow to specific assets to reduce bandwidth
2541
+ * const prices = await arca.watchPrices({ coins: ['hl:0:BTC', 'hl:0:ETH'] });
2542
+ *
2543
+ * @example
2544
+ * // React to every tick
2545
+ * const prices = await arca.watchPrices();
2546
+ * prices.onUpdate((next) => render(next));
2547
+ *
2548
+ * @example
2549
+ * // Bound the initial wait so startup doesn't hang if the backend is down
2550
+ * const prices = await arca.watchPrices({ readyTimeoutMs: 5000 });
2551
+ *
2552
+ * @param opts - Either an options object, or (legacy) an exchange string.
2553
+ * - `exchange` — Exchange identifier. Default: `"sim"`.
2554
+ * - `coins` — Optional canonical market IDs to narrow the subscription
2555
+ * (e.g. `["hl:0:BTC", "hl:0:ETH"]`). Omit for all assets.
2556
+ * - `readyTimeoutMs` — Max time to wait for the initial snapshot.
2557
+ * Throws `WatchStreamReadyTimeoutError` on timeout. The stream is
2558
+ * torn down on timeout; it will not keep trying in the background.
2559
+ *
2560
+ * @returns A {@link PriceWatchStream}. Call `.close()` when done.
2561
+ */
2562
+ async watchPrices(opts) {
2563
+ const { exchange, coins, readyTimeoutMs } = normalizeWatchPricesOpts(opts);
2564
+ await this.ready();
2565
+ const stream = new streams_1.PriceWatchStream(this.ws, exchange, coins);
2566
+ try {
2567
+ await stream.ready(readyTimeoutMs);
2568
+ }
2569
+ catch (err) {
2570
+ stream.close();
2571
+ throw err;
2572
+ }
2573
+ return stream;
2574
+ }
2575
+ /**
2576
+ * Watch real-time operation events under a path prefix.
2577
+ * Creates a path-scoped watch; server sends a `watch_snapshot` with
2578
+ * recent operations, then streams `operation.created` / `operation.updated`.
2579
+ * Returns an {@link OperationWatchStream}. Call `.close()` when done.
2580
+ *
2581
+ * @param path - Arca path prefix to watch (default: "/" for all operations)
2582
+ * @param options.maxOperations - Maximum number of operations to keep in memory (default 500)
2583
+ */
2584
+ async watchOperations(path = '/', options) {
2585
+ await this.ready();
2586
+ const stream = new streams_1.OperationWatchStream(this.ws, path, async () => {
2587
+ const res = await this.listOperations(path !== '/' ? { path } : undefined);
2588
+ return res.operations;
2589
+ }, options?.maxOperations ?? 500);
2590
+ await stream.ready();
2591
+ return stream;
2592
+ }
2593
+ /**
2594
+ * Watch real-time balance updates under a path prefix.
2595
+ * Creates a path-scoped watch; server sends a `watch_snapshot` with
2596
+ * current balances (four-bucket summary), then streams `balance.updated`.
2597
+ * Call `.close()` when done.
2598
+ *
2599
+ * @param path - Arca path prefix to watch (default: "/" for all balances)
2600
+ */
2601
+ async watchBalances(path = '/') {
2602
+ await this.ready();
2603
+ const stream = new streams_1.BalanceWatchStream(this.ws, path, (entityId) => this.getBalances(entityId));
2604
+ await stream.ready();
2605
+ return stream;
2606
+ }
2607
+ /**
2608
+ * Get the valuation for a single Arca object (Axiom 10: same computation
2609
+ * path as aggregation, ensuring perfect additivity).
2610
+ */
2611
+ async getObjectValuation(path) {
2612
+ await this.ready();
2613
+ return this.client.get('/objects/valuation', {
2614
+ realmId: this.realmId(),
2615
+ path,
2616
+ });
2617
+ }
2618
+ /**
2619
+ * Watch real-time valuation updates for a single Arca object.
2620
+ * Creates a path-scoped watch with an aggregation watch for valuation;
2621
+ * server sends `watch_snapshot` with initial valuation, then streams
2622
+ * `object.valuation` events. Uses the same computation path as
2623
+ * aggregation watches (Axiom 10). Call `.close()` when done.
2624
+ *
2625
+ * @param path - Arca object path (e.g. "/users/alice/main")
2626
+ */
2627
+ async watchObject(path) {
2628
+ await this.ready();
2629
+ const stream = new streams_1.ObjectWatchStream(this.ws, path, 'sim', () => this.getObjectValuation(path));
2630
+ await stream.ready();
2631
+ return stream;
2632
+ }
2633
+ /**
2634
+ * Watch real-time valuations for multiple Arca objects simultaneously.
2635
+ * Each path gets its own ObjectWatchStream; updates from any object emit
2636
+ * a merged `Map<path, ObjectValuation>` to subscribers.
2637
+ * Call `.close()` to stop all watches.
2638
+ *
2639
+ * @param paths - Array of object paths (e.g. ["/users/alice/main", "/users/bob/main"])
2640
+ */
2641
+ async watchObjects(paths) {
2642
+ await this.ready();
2643
+ const children = await Promise.all(paths.map(p => {
2644
+ const s = new streams_1.ObjectWatchStream(this.ws, p, 'sim', () => this.getObjectValuation(p));
2645
+ return s.ready().then(() => s);
2646
+ }));
2647
+ return new streams_1.ObjectsWatchStream(children);
2648
+ }
2649
+ /**
2650
+ * Subscribe to a live, SDK-derived max order size stream for a market/side.
2651
+ * Uses `getExchangeState` + `watchPrices` and recomputes on price changes;
2652
+ * submit/retry remains backend-authoritative.
2653
+ *
2654
+ * The per-asset `maintenanceMarginRate`, `marginTiers` (the laddered
2655
+ * initial-margin schedule the server enforces at placement), and the
2656
+ * top-of-book spread (`bidRatio`/`askRatio`) are auto-fetched once via
2657
+ * `getActiveAssetData` and fed into the stream, so the previewed max accounts
2658
+ * for tiered margin on assets like BTC and for the directional execution
2659
+ * price (buys at the ask, sells at the bid). Each input is resolved
2660
+ * independently; pass all four in `opts` to skip the lookup entirely.
2661
+ * Supplying only `maintenanceMarginRate` + `marginTiers` still fetches the
2662
+ * spread rather than silently sizing at the mid.
2663
+ *
2664
+ * `maxBuyUsd`/`maxSellUsd` are a best-effort estimate (fees + tiered margin +
2665
+ * a ~10 bps buffer), not a hard guarantee — mids move between preview and
2666
+ * submission. To place exactly the max, prefer `placeOrder({ useMax: true })`
2667
+ * or a small `sizeTolerance` so the server resolves the size atomically.
2668
+ */
2669
+ async watchMaxOrderSize(opts) {
2670
+ await this.ready();
2671
+ const priceStream = await this.watchPrices();
2672
+ let exchangeState;
2673
+ let mids;
2674
+ let objectPath;
2675
+ try {
2676
+ const [exState, midsResult, detail] = await Promise.all([
2677
+ this.getExchangeState(opts.objectId),
2678
+ this.getMarketMids(),
2679
+ this.getObjectDetail(opts.objectId),
2680
+ ]);
2681
+ exchangeState = exState;
2682
+ mids = midsResult;
2683
+ objectPath = detail.object.path;
2684
+ }
2685
+ catch (err) {
2686
+ priceStream.close();
2687
+ throw err;
2688
+ }
2689
+ let resolvedFeeScale = opts.feeScale;
2690
+ if (resolvedFeeScale == null) {
2691
+ try {
2692
+ const { tickers } = await this.getMarketTickers();
2693
+ const ticker = tickers.find((t) => t.market === opts.market);
2694
+ if (ticker?.feeScale && ticker.feeScale > 0) {
2695
+ resolvedFeeScale = ticker.feeScale;
2696
+ }
2697
+ }
2698
+ catch {
2699
+ // non-critical — fall back to default scale (1)
2700
+ }
2701
+ }
2702
+ this.ws.watchPath(objectPath);
2703
+ const stream = new streams_1.MaxOrderSizeWatchStream(priceStream, { ...opts, feeScale: resolvedFeeScale }, exchangeState, mids.mids);
2704
+ // The maintenance margin rate, margin tiers, and top-of-book spread are all
2705
+ // per-asset and depend on server state the client can't derive from market
2706
+ // meta alone (the margin table and the order book aren't exposed there). A
2707
+ // single getActiveAssetData fetch resolves whichever of the three the caller
2708
+ // didn't supply, fed into the stream without blocking initial readiness.
2709
+ // - maintenanceMarginRate: without it every recompute would hardcode
2710
+ // "0.03", producing wrong liquidation estimates in
2711
+ // `Arca.orderBreakdown` for any tiered asset (e.g. BTC at 1%).
2712
+ // - marginTiers: tiered assets ladder their initial-margin rate by
2713
+ // notional. Without the server's tiers the derivation assumes a flat
2714
+ // `1/leverage` rate and over-states maxBuyUsd/maxSellUsd, so the
2715
+ // slider's upper bound is rejected at placement with
2716
+ // "insufficient balance".
2717
+ // - bid/ask spread: market buys are margin-checked at the ask and sells
2718
+ // at the bid, so the stream sizes against that directional price (a
2719
+ // spread ratio applied to the live mid) rather than the mid alone.
2720
+ // Each input is gated independently. Crucially, passing maintenanceMarginRate
2721
+ // + marginTiers does NOT suppress spread resolution — that coupling silently
2722
+ // dropped the spread correction for any caller that pre-supplied both. To
2723
+ // skip the fetch entirely, pass all four (maintenanceMarginRate, marginTiers,
2724
+ // bidRatio, askRatio).
2725
+ const needsMmr = opts.maintenanceMarginRate === undefined;
2726
+ const needsTiers = opts.marginTiers === undefined;
2727
+ const needsSpread = opts.bidRatio === undefined || opts.askRatio === undefined;
2728
+ if (needsMmr || needsTiers || needsSpread) {
2729
+ this.getActiveAssetData(opts.objectId, opts.market, opts.applicationFeeTenthsBps, opts.leverage)
2730
+ .then((data) => {
2731
+ // Only apply each fetched value where the caller didn't provide one,
2732
+ // so a pre-supplied mmr/tiers/ratio isn't clobbered by the lookup.
2733
+ if (needsMmr && data?.maintenanceMarginRate) {
2734
+ stream.updateMaintenanceMarginRate(data.maintenanceMarginRate);
2735
+ }
2736
+ if (needsTiers && data?.marginTiers && data.marginTiers.length > 0) {
2737
+ stream.updateMarginTiers(data.marginTiers);
2738
+ }
2739
+ if (needsSpread) {
2740
+ // Resolve the directional spread from the snapshot's top-of-book and
2741
+ // feed it as a ratio applied to the live mid, so the stream sizes
2742
+ // against the ask (buys) / bid (sells) the margin check uses rather
2743
+ // than the mid. Ratios stay stable as price moves; if no book was
2744
+ // available the server returns bid == ask == mark (ratio 1, no-op).
2745
+ const snapMid = data?.markPx ? Number.parseFloat(data.markPx) : NaN;
2746
+ const snapBid = data?.bidPx ? Number.parseFloat(data.bidPx) : NaN;
2747
+ const snapAsk = data?.askPx ? Number.parseFloat(data.askPx) : NaN;
2748
+ if (Number.isFinite(snapMid) && snapMid > 0) {
2749
+ const bidRatio = Number.isFinite(snapBid) && snapBid > 0 ? snapBid / snapMid : 1;
2750
+ const askRatio = Number.isFinite(snapAsk) && snapAsk > 0 ? snapAsk / snapMid : 1;
2751
+ stream.updateSpreadRatios(bidRatio, askRatio);
2752
+ }
2753
+ }
2754
+ })
2755
+ .catch(() => {
2756
+ // non-critical — stream falls back to mid-based sizing + default 0.03
2757
+ });
2758
+ }
2759
+ let exchangeRefetchInFlight = false;
2760
+ const unsub = this.ws.onExchangeNotification((event) => {
2761
+ if (event.entityId !== opts.objectId && event.entityPath !== objectPath) {
2762
+ return;
2763
+ }
2764
+ if (event.exchangeState) {
2765
+ stream.updateExchangeState(event.exchangeState);
2766
+ return;
2767
+ }
2768
+ if (exchangeRefetchInFlight) {
2769
+ return;
2770
+ }
2771
+ exchangeRefetchInFlight = true;
2772
+ this.getExchangeState(opts.objectId)
2773
+ .then((state) => {
2774
+ stream.updateExchangeState(state);
2775
+ })
2776
+ .catch(() => {
2777
+ // Retry on the next structural event or reconnect.
2778
+ })
2779
+ .finally(() => {
2780
+ exchangeRefetchInFlight = false;
2781
+ });
2782
+ });
2783
+ stream.addCleanup(unsub);
2784
+ stream.addCleanup(() => this.ws.unwatchPath(objectPath));
2785
+ await stream.ready();
2786
+ return stream;
2787
+ }
2788
+ /**
2789
+ * Subscribe to real-time candle updates.
2790
+ * Call `.close()` when done.
2791
+ *
2792
+ * @param coins - Coins in canonical format (e.g. ["hl:0:BTC", "hl:0:ETH"])
2793
+ * @param intervals - Candle intervals (e.g. ["1m", "5m"])
2794
+ */
2795
+ async watchCandles(coins, intervals) {
2796
+ await this.ready();
2797
+ this.ws.acquireCandles(coins, intervals);
2798
+ return new streams_1.CandleWatchStream(this.ws, coins, intervals);
2799
+ }
2800
+ /**
2801
+ * Subscribe to real-time market trades for the given coins.
2802
+ * Returns a {@link TradeWatchStream} that emits each trade as it happens.
2803
+ * Call `.close()` when done.
2804
+ *
2805
+ * @param coins - Coins in canonical format (e.g. `["hl:0:BTC", "hl:0:ETH"]`)
2806
+ */
2807
+ async watchTrades(coins) {
2808
+ await this.ready();
2809
+ this.ws.acquireTrades(coins);
2810
+ return new streams_1.TradeWatchStream(this.ws, coins);
2811
+ }
2812
+ /**
2813
+ * Create a live candle chart that merges historical candle data with
2814
+ * real-time WebSocket updates. The candle array stays sorted and deduped;
2815
+ * new bars appear automatically as candle events arrive.
2816
+ *
2817
+ * Use `stream.ensureRange(start, end)` when the chart viewport changes
2818
+ * (zoom, resize, scroll, jump to date) — the SDK tracks which ranges
2819
+ * have been fetched and only requests the gaps. Use `stream.loadMore()`
2820
+ * for simple backward scrolling.
2821
+ *
2822
+ * @param market - Canonical market ID (e.g. `"hl:0:BTC"`, `"hl:1:BRENTOIL"`)
2823
+ * @param interval - Candle interval (e.g. `"1m"`, `"5m"`)
2824
+ * @param options - Optional `{ count }` for initial history (default 300)
2825
+ */
2826
+ async watchCandleChart(market, interval, options) {
2827
+ await this.ready();
2828
+ this.ws.acquireCandles([market], [interval]);
2829
+ const intervalMs = {
2830
+ '15s': 15_000, '1m': 60_000, '5m': 300_000, '15m': 900_000,
2831
+ '1h': 3_600_000, '4h': 14_400_000, '1d': 86_400_000,
2832
+ };
2833
+ const count = options?.count ?? 300;
2834
+ const now = Date.now();
2835
+ const startTime = now - intervalMs[interval] * count;
2836
+ let initialCandles;
2837
+ let initialHistoryState;
2838
+ try {
2839
+ // Fast path: skip server-side HL REST backfill so the chart renders
2840
+ // immediately from hot Redis/CDN data.
2841
+ initialCandles = await this.getCandles(market, interval, {
2842
+ startTime,
2843
+ skipBackfill: true,
2844
+ });
2845
+ // When the fast path returns nothing there is nothing to render, so
2846
+ // pay for one backfill-enabled fetch before resolving. Otherwise a
2847
+ // consumer that reads `stream.candles` once (instead of subscribing to
2848
+ // updates) would see a permanently empty array — even though the
2849
+ // stream's async retryInitialLoad would have populated it moments
2850
+ // later. This is the cold-pod / not-yet-cached case the staging
2851
+ // "no candle history" reports trace back to.
2852
+ if (initialCandles.candles.length === 0) {
2853
+ try {
2854
+ const backfilled = await this.getCandles(market, interval, { startTime });
2855
+ if (backfilled.candles.length > 0) {
2856
+ initialCandles = backfilled;
2857
+ }
2858
+ }
2859
+ catch {
2860
+ // Keep the empty result; the stream's async retry keeps trying.
2861
+ }
2862
+ }
2863
+ initialHistoryState =
2864
+ initialCandles.candles.length === 0
2865
+ ? { type: 'failed', error: 'Empty history response' }
2866
+ : { type: 'loaded', count: initialCandles.candles.length };
2867
+ }
2868
+ catch (e) {
2869
+ console.error(`[Arca] initial getCandles failed; showing empty history for ${market} ${interval}:`, e);
2870
+ initialCandles = { market, interval, candles: [] };
2871
+ initialHistoryState = { type: 'failed', error: String(e) };
2872
+ }
2873
+ const fetchCandles = (c, iv, opts) => this.getCandles(c, iv, opts);
2874
+ return new streams_1.CandleChartStream(this.ws, market, interval, fetchCandles, initialCandles.candles, initialHistoryState, startTime, now, count);
2875
+ }
2876
+ /**
2877
+ * Watch the exchange state for an exchange Arca object, including positions,
2878
+ * open orders, and pending intents (order operations in flight).
2879
+ * Resolves the object path from `objectId` and creates a path-scoped watch.
2880
+ *
2881
+ * Pending intents are the exchange equivalent of transfer holds: they signal
2882
+ * that an order has been submitted but the venue hasn't confirmed it yet.
2883
+ * Use `stream.pendingIntents` to show in-progress state in the UI.
2884
+ */
2885
+ async watchExchangeState(objectId) {
2886
+ await this.ready();
2887
+ const detail = await this.getObjectDetail(objectId);
2888
+ const objectPath = detail.object.path;
2889
+ return new streams_1.ExchangeWatchStream(this.ws, objectPath, objectId, (id) => this.getExchangeState(id), 'sim');
2890
+ }
2891
+ // ---- Auto-tracking ----
2892
+ _autoTrackOps;
2893
+ _autoTrackBal;
2894
+ _autoTrackExchange;
2895
+ /**
2896
+ * Enable automatic optimistic tracking: every mutation method will
2897
+ * immediately reflect its predicted effects on the registered streams.
2898
+ *
2899
+ * - `operationStream`: gets a `trackSubmission` call for each mutation,
2900
+ * showing `submitting → pending → completed/failed`.
2901
+ * - `balanceStream`: gets an `applyPrediction` call for transfers,
2902
+ * immediately showing `departing` and `arriving` amounts.
2903
+ * - `exchangeStream` (optional): exchange intents are already backend-driven
2904
+ * and don't require client-side prediction, but registering allows future
2905
+ * client-side enrichment.
2906
+ */
2907
+ enableAutoTracking(operationStream, balanceStream, exchangeStream) {
2908
+ this._autoTrackOps = operationStream;
2909
+ this._autoTrackBal = balanceStream;
2910
+ this._autoTrackExchange = exchangeStream;
2911
+ }
2912
+ /**
2913
+ * Disable automatic tracking.
2914
+ */
2915
+ disableAutoTracking() {
2916
+ this._autoTrackOps = undefined;
2917
+ this._autoTrackBal = undefined;
2918
+ this._autoTrackExchange = undefined;
2919
+ }
2920
+ // ---- Invariants ----
2921
+ /**
2922
+ * Run all DB-only invariant checks (I1-I6) via the internal API.
2923
+ * Returns structured results per invariant with pass/fail and violations.
2924
+ *
2925
+ * Accepts either a numeric `limit` (legacy positional form) or an options
2926
+ * object. When `realmId` is provided every invariant query is scoped to
2927
+ * that realm, which is dramatically faster than the default platform-wide
2928
+ * scan as the platform grows. The 5-min platform maintenance cron uses
2929
+ * the un-scoped form; per-realm callers (e.g. the regression suite) should
2930
+ * pass `{ realmId }`.
2931
+ */
2932
+ async checkInvariants(opts) {
2933
+ await this.ready();
2934
+ let limit;
2935
+ let realmId;
2936
+ if (typeof opts === 'number') {
2937
+ limit = opts;
2938
+ }
2939
+ else if (opts) {
2940
+ limit = opts.limit;
2941
+ realmId = opts.realmId;
2942
+ }
2943
+ const params = {};
2944
+ if (limit !== undefined)
2945
+ params.limit = String(limit);
2946
+ if (realmId !== undefined && realmId !== '')
2947
+ params.realmId = realmId;
2948
+ return this.client.get('/internal/invariant-check', params);
2949
+ }
2950
+ /**
2951
+ * Wait until all operations in the realm have reached a terminal state.
2952
+ * Uses WebSocket events to react to completions instantly, with periodic
2953
+ * HTTP polls as a safety net.
2954
+ *
2955
+ * @param opts.intervalMs - Safety-net poll interval in ms (default: 5000)
2956
+ * @param opts.timeoutMs - Max wait time in ms (default: 120000)
2957
+ * @param opts.onPoll - Optional callback with the current pending count
2958
+ * @returns The number of polls performed
2959
+ */
2960
+ async waitForQuiescence(opts) {
2961
+ await this.ready();
2962
+ const interval = opts?.intervalMs ?? 5000;
2963
+ const timeout = opts?.timeoutMs ?? 120_000;
2964
+ const start = Date.now();
2965
+ let polls = 0;
2966
+ this.ws.ensureConnected();
2967
+ this.ws.watchPath('/').catch(() => { });
2968
+ const checkPending = async () => {
2969
+ const res = await this.listOperations();
2970
+ polls++;
2971
+ const pending = res.operations.filter(op => op.state === 'pending');
2972
+ opts?.onPoll?.(pending.length);
2973
+ return pending.length;
2974
+ };
2975
+ let pendingCount = await checkPending();
2976
+ if (pendingCount === 0)
2977
+ return polls;
2978
+ return new Promise((resolve, reject) => {
2979
+ let settled = false;
2980
+ const timer = setTimeout(() => {
2981
+ cleanup();
2982
+ reject(new Error(`Timed out waiting for quiescence after ${timeout}ms. ` +
2983
+ `${pendingCount} operations still pending.`));
2984
+ }, timeout);
2985
+ const safetyPoll = setInterval(async () => {
2986
+ if (settled)
2987
+ return;
2988
+ try {
2989
+ pendingCount = await checkPending();
2990
+ if (pendingCount === 0) {
2991
+ cleanup();
2992
+ resolve(polls);
2993
+ }
2994
+ }
2995
+ catch { /* ignore, will retry */ }
2996
+ }, interval);
2997
+ const cleanup = () => {
2998
+ settled = true;
2999
+ clearTimeout(timer);
3000
+ clearInterval(safetyPoll);
3001
+ this.ws.off(types_1.EventType.OperationUpdated, handler);
3002
+ this.ws.unwatchPath('/');
3003
+ };
3004
+ const handler = async () => {
3005
+ if (settled)
3006
+ return;
3007
+ try {
3008
+ pendingCount = await checkPending();
3009
+ if (pendingCount === 0) {
3010
+ cleanup();
3011
+ resolve(polls);
3012
+ }
3013
+ }
3014
+ catch { /* ignore */ }
3015
+ };
3016
+ this.ws.on(types_1.EventType.OperationUpdated, handler);
3017
+ if (Date.now() - start > timeout) {
3018
+ cleanup();
3019
+ reject(new Error(`Timed out waiting for quiescence after ${timeout}ms. ` +
3020
+ `${pendingCount} operations still pending.`));
3021
+ }
3022
+ });
3023
+ }
3024
+ _resolutionStats = { ws: 0, poll: 0, initial: 0 };
3025
+ /**
3026
+ * Returns how many operations were resolved via each path.
3027
+ * Useful for benchmarking and diagnostics — a high `poll` count
3028
+ * indicates WebSocket events are being missed.
3029
+ */
3030
+ getResolutionStats() {
3031
+ return { ...this._resolutionStats };
3032
+ }
3033
+ /** Resets the resolution stats counters to zero. */
3034
+ resetResolutionStats() {
3035
+ this._resolutionStats = { ws: 0, poll: 0, initial: 0 };
3036
+ }
3037
+ /**
3038
+ * Wait for a specific operation to reach a terminal state (completed or failed).
3039
+ *
3040
+ * Auto-connects the WebSocket and subscribes to the operations channel
3041
+ * so callers don't need to manage the connection manually.
3042
+ * If the WS event arrives without embedded operation data (enrichment failure),
3043
+ * fetches the operation via HTTP as a fallback.
3044
+ *
3045
+ * @param operationId - The operation ID to wait for
3046
+ * @param timeoutMs - Maximum time to wait (default 30s)
3047
+ * @throws {OperationFailedError} if the operation reaches a failed state
3048
+ */
3049
+ async waitForOperation(operationId, timeoutMs = 30000) {
3050
+ await this.ready();
3051
+ this.ws.ensureConnected();
3052
+ this.ws.watchPath('/').catch(() => { });
3053
+ const RECONCILIATION_INTERVAL = 5000;
3054
+ return new Promise((resolve, reject) => {
3055
+ let settled = false;
3056
+ let resolvedVia = 'initial';
3057
+ // Tracks the most recent operation snapshot we've seen so that on a
3058
+ // timeout we can surface the in-flight state (e.g. last activity, error
3059
+ // code from a partial outcome) via OperationStalledError. Without this,
3060
+ // the legacy timeout error gave callers no signal beyond "timed out".
3061
+ let lastOperation = null;
3062
+ const timeout = setTimeout(() => {
3063
+ if (settled)
3064
+ return;
3065
+ cleanup();
3066
+ // Best-effort final fetch: surfaces the operation row as it exists
3067
+ // server-side at the moment the SDK gives up. If the fetch fails or
3068
+ // the operation no longer exists, we fall back to whatever snapshot
3069
+ // we last cached from the WS/poll path.
3070
+ this.getOperation(operationId)
3071
+ .then(detail => {
3072
+ reject(new errors_1.OperationStalledError(operationId, timeoutMs, detail.operation ?? lastOperation));
3073
+ })
3074
+ .catch(() => {
3075
+ reject(new errors_1.OperationStalledError(operationId, timeoutMs, lastOperation));
3076
+ });
3077
+ }, timeoutMs);
3078
+ const reconciliationPoll = setInterval(() => {
3079
+ if (settled)
3080
+ return;
3081
+ resolvedVia = 'poll';
3082
+ fetchAndResolve();
3083
+ }, RECONCILIATION_INTERVAL);
3084
+ const cleanup = () => {
3085
+ settled = true;
3086
+ clearTimeout(timeout);
3087
+ clearInterval(reconciliationPoll);
3088
+ this.ws.off(types_1.EventType.OperationUpdated, handler);
3089
+ this.ws.unwatchPath('/');
3090
+ };
3091
+ const isTerminal = (s) => s !== 'pending';
3092
+ const tryResolve = (op) => {
3093
+ if (settled)
3094
+ return;
3095
+ lastOperation = op;
3096
+ if (isTerminal(op.state)) {
3097
+ this._resolutionStats[resolvedVia]++;
3098
+ cleanup();
3099
+ if (op.state === 'failed' || op.state === 'expired') {
3100
+ reject(new errors_1.OperationFailedError(op));
3101
+ }
3102
+ else {
3103
+ resolve(op);
3104
+ }
3105
+ }
3106
+ };
3107
+ const fetchAndResolve = () => {
3108
+ if (settled)
3109
+ return;
3110
+ this.getOperation(operationId)
3111
+ .then(detail => {
3112
+ tryResolve(detail.operation);
3113
+ })
3114
+ .catch(() => { });
3115
+ };
3116
+ const handler = (event) => {
3117
+ if (event.entityId !== operationId)
3118
+ return;
3119
+ resolvedVia = 'ws';
3120
+ if (event.operation) {
3121
+ tryResolve(event.operation);
3122
+ }
3123
+ else {
3124
+ fetchAndResolve();
3125
+ }
3126
+ };
3127
+ this.ws.on(types_1.EventType.OperationUpdated, handler);
3128
+ this.getOperation(operationId)
3129
+ .then(detail => {
3130
+ tryResolve(detail.operation);
3131
+ })
3132
+ .catch(() => {
3133
+ setTimeout(fetchAndResolve, 2000);
3134
+ });
3135
+ });
3136
+ }
3137
+ // ---- Custody ----
3138
+ /**
3139
+ * Get the custody status for this realm, including contract address,
3140
+ * total balance, all boundaries, exchange arcas, and venue halts.
3141
+ */
3142
+ async getCustodyStatus() {
3143
+ await this.ready();
3144
+ return this.client.get('/custody/status', {
3145
+ realmId: this.realmId(),
3146
+ });
3147
+ }
3148
+ /**
3149
+ * Get a single isolation boundary by ID.
3150
+ */
3151
+ async getBoundary(boundaryId) {
3152
+ await this.ready();
3153
+ return this.client.get(`/custody/boundaries/${boundaryId}`, {
3154
+ realmId: this.realmId(),
3155
+ });
3156
+ }
3157
+ /**
3158
+ * List all isolation boundaries for this realm.
3159
+ */
3160
+ async listBoundaries() {
3161
+ await this.ready();
3162
+ const resp = await this.client.get('/custody/boundaries', {
3163
+ realmId: this.realmId(),
3164
+ });
3165
+ return resp.boundaries;
3166
+ }
3167
+ /**
3168
+ * List exchange arcas, optionally filtered to a specific boundary.
3169
+ */
3170
+ async listExchangeArcas(boundaryId) {
3171
+ await this.ready();
3172
+ const params = { realmId: this.realmId() };
3173
+ if (boundaryId)
3174
+ params.boundaryId = boundaryId;
3175
+ const resp = await this.client.get('/custody/exchange-arcas', params);
3176
+ return resp.exchangeArcas;
3177
+ }
3178
+ /**
3179
+ * Register a recovery key for an isolation boundary.
3180
+ * This is an operator-initiated action (valid only when no recovery key is set).
3181
+ * After registration, only the recovery key holder can lock/unlock/withdraw.
3182
+ *
3183
+ * The wallet address is typically generated client-side via `Arca.generateRecoveryKey()`
3184
+ * or provided by the user from an existing wallet.
3185
+ */
3186
+ async registerRecoveryKey(opts) {
3187
+ await this.ready();
3188
+ return this.client.post('/custody/recovery-key', {
3189
+ realmId: this.realmId(),
3190
+ boundaryId: opts.boundaryId,
3191
+ walletAddress: opts.walletAddress,
3192
+ });
3193
+ }
3194
+ /**
3195
+ * Prepare an unsigned `lockBoundary` transaction.
3196
+ * The caller signs and submits this transaction from their recovery key wallet.
3197
+ * Locking freezes all operator fund movement and cancels any pending exit.
3198
+ */
3199
+ prepareLockBoundary(contractAddress, chainId, boundaryId) {
3200
+ return {
3201
+ to: contractAddress,
3202
+ data: encodeCustodyCall('lockBoundary(bytes32)', [boundaryId]),
3203
+ chainId,
3204
+ value: '0',
3205
+ };
3206
+ }
3207
+ /**
3208
+ * Prepare an unsigned `unlockBoundary` transaction.
3209
+ * Only the actor who locked the boundary can unlock it.
3210
+ */
3211
+ prepareUnlockBoundary(contractAddress, chainId, boundaryId) {
3212
+ return {
3213
+ to: contractAddress,
3214
+ data: encodeCustodyCall('unlockBoundary(bytes32)', [boundaryId]),
3215
+ chainId,
3216
+ value: '0',
3217
+ };
3218
+ }
3219
+ /**
3220
+ * Prepare an unsigned `withdraw` transaction.
3221
+ * Withdraws the entire boundary balance to the recovery key holder.
3222
+ * Requires: boundary is locked by the caller, caller is recovery key holder.
3223
+ */
3224
+ prepareWithdraw(contractAddress, chainId, boundaryId) {
3225
+ return {
3226
+ to: contractAddress,
3227
+ data: encodeCustodyCall('withdraw(bytes32)', [boundaryId]),
3228
+ chainId,
3229
+ value: '0',
3230
+ };
3231
+ }
3232
+ /**
3233
+ * Prepare an unsigned `assignRecoveryKey` transaction for changing an existing key.
3234
+ * When the boundary already has a recovery key, only the current holder can change it.
3235
+ * For initial assignment (no existing key), use `registerRecoveryKey()` instead.
3236
+ */
3237
+ prepareAssignRecoveryKey(contractAddress, chainId, boundaryId, newRecoveryKey) {
3238
+ return {
3239
+ to: contractAddress,
3240
+ data: encodeCustodyCall('assignRecoveryKey(bytes32,address)', [boundaryId, newRecoveryKey]),
3241
+ chainId,
3242
+ value: '0',
3243
+ };
3244
+ }
3245
+ /**
3246
+ * Prepare an unsigned `setTimeLock` transaction.
3247
+ * Recovery key holders can only increase the time lock; never decrease.
3248
+ */
3249
+ prepareSetTimeLock(contractAddress, chainId, boundaryId, durationSeconds) {
3250
+ return {
3251
+ to: contractAddress,
3252
+ data: encodeCustodyCall('setTimeLock(bytes32,uint256)', [boundaryId, durationSeconds.toString()]),
3253
+ chainId,
3254
+ value: '0',
3255
+ };
3256
+ }
3257
+ /**
3258
+ * Prepare an unsigned `cancelPendingExit` transaction.
3259
+ * Can be called by recovery key holder or operator.
3260
+ */
3261
+ prepareCancelPendingExit(contractAddress, chainId, boundaryId) {
3262
+ return {
3263
+ to: contractAddress,
3264
+ data: encodeCustodyCall('cancelPendingExit(bytes32)', [boundaryId]),
3265
+ chainId,
3266
+ value: '0',
3267
+ };
3268
+ }
3269
+ /**
3270
+ * Prepare an unsigned `recoveryWithdrawAccount` transaction.
3271
+ * Sweeps an exchange arca's balance back to its boundary.
3272
+ * Requires: boundary is locked by the recovery key holder.
3273
+ */
3274
+ prepareRecoveryWithdrawAccount(contractAddress, chainId, arcaId) {
3275
+ return {
3276
+ to: contractAddress,
3277
+ data: encodeCustodyCall('recoveryWithdrawAccount(bytes32)', [arcaId]),
3278
+ chainId,
3279
+ value: '0',
3280
+ };
3281
+ }
3282
+ /**
3283
+ * Generate a recovery key pair entirely client-side.
3284
+ *
3285
+ * Creates a 12-word BIP-39 mnemonic using the platform CSPRNG
3286
+ * (`crypto.getRandomValues`) and derives the Ethereum address at the
3287
+ * standard BIP-44 path (`m/44'/60'/0'/0/0`). No network call is made;
3288
+ * the mnemonic never leaves the caller's process.
3289
+ *
3290
+ * All intermediate cryptographic material (seed, private key bytes) is
3291
+ * zeroed after derivation. The mnemonic itself is a JavaScript string and
3292
+ * cannot be reliably erased from memory — for environments requiring
3293
+ * guaranteed zeroization, generate the key in a native module or secure
3294
+ * enclave and pass only the derived address to {@link registerRecoveryKey}.
3295
+ *
3296
+ * **Two-path UX recommendation**: most users already have an Ethereum
3297
+ * wallet (MetaMask, Phantom, Ledger, etc.). Prefer letting them paste or
3298
+ * connect an existing address via {@link registerRecoveryKey}. Reserve
3299
+ * this method for users who need a new wallet generated for them.
3300
+ *
3301
+ * @example
3302
+ * ```typescript
3303
+ * // Path A: user already has a wallet — just register the address
3304
+ * await arca.registerRecoveryKey({
3305
+ * boundaryId: 'b0',
3306
+ * walletAddress: '0x1234...abcd', // from WalletConnect, paste, etc.
3307
+ * });
3308
+ *
3309
+ * // Path B: generate a new recovery wallet
3310
+ * const recovery = Arca.generateRecoveryKey();
3311
+ * // Show recovery.mnemonic to the user — they MUST back it up
3312
+ * await arca.registerRecoveryKey({
3313
+ * boundaryId: 'b0',
3314
+ * walletAddress: recovery.address,
3315
+ * });
3316
+ * ```
3317
+ */
3318
+ static generateRecoveryKey() {
3319
+ return (0, recovery_1.generateRecoveryKeyPair)();
3320
+ }
3321
+ // ---- Internal ----
3322
+ /**
3323
+ * Wrap a mutation HTTP call in an OperationHandle.
3324
+ * Defers ready() + throwIfOperationFailed into the promise chain.
3325
+ */
3326
+ op(httpCall, predicted, defaultTimeoutMs) {
3327
+ const call = this.ready().then(() => httpCall()).then(response => {
3328
+ this.throwIfOperationFailed(response.operation);
3329
+ return response;
3330
+ });
3331
+ const handle = new operation_handle_1.OperationHandle(call, (id, timeout) => this.waitForOperation(id, timeout ?? defaultTimeoutMs), predicted);
3332
+ if (this._autoTrackOps) {
3333
+ this._autoTrackOps.trackSubmission(handle);
3334
+ }
3335
+ if (this._autoTrackBal && predicted?.balanceChanges) {
3336
+ this._autoTrackBal.applyPrediction(handle);
3337
+ }
3338
+ return handle;
3339
+ }
3340
+ realmId() {
3341
+ if (!this.resolvedRealmId) {
3342
+ throw new Error('Arca SDK not initialized. Call await arca.ready() first.');
3343
+ }
3344
+ return this.resolvedRealmId;
3345
+ }
3346
+ throwIfOperationFailed(operation) {
3347
+ if (!operation)
3348
+ return;
3349
+ if (operation.state === 'failed' || operation.state === 'expired') {
3350
+ throw new errors_1.OperationFailedError(operation);
3351
+ }
3352
+ }
3353
+ // ---- Token lifecycle ----
3354
+ extractRealmAndScheduleRefresh(token) {
3355
+ if (!this.realmInput && !this.resolvedRealmId) {
3356
+ try {
3357
+ const claims = decodeJwtPayload(token);
3358
+ if (typeof claims.realmId === 'string') {
3359
+ this.resolvedRealmId = claims.realmId;
3360
+ }
3361
+ }
3362
+ catch {
3363
+ // If we can't decode, we'll try to resolve via API later
3364
+ }
3365
+ }
3366
+ this.scheduleProactiveRefresh(token);
3367
+ }
3368
+ /**
3369
+ * Call the token provider, deduplicate concurrent calls, apply the new token,
3370
+ * and schedule the next proactive refresh.
3371
+ */
3372
+ refreshTokenFromProvider() {
3373
+ if (this.pendingRefresh)
3374
+ return this.pendingRefresh;
3375
+ this.pendingRefresh = this.tokenProvider()
3376
+ .then(token => {
3377
+ this.pendingRefresh = null;
3378
+ this.applyNewToken(token);
3379
+ return token;
3380
+ })
3381
+ .catch(err => {
3382
+ this.pendingRefresh = null;
3383
+ throw err;
3384
+ });
3385
+ return this.pendingRefresh;
3386
+ }
3387
+ applyNewToken(token) {
3388
+ this.client.updateCredential(token);
3389
+ this.ws.updateToken(token);
3390
+ this.scheduleProactiveRefresh(token);
3391
+ }
3392
+ scheduleProactiveRefresh(token) {
3393
+ if (this.refreshTimer) {
3394
+ clearTimeout(this.refreshTimer);
3395
+ this.refreshTimer = null;
3396
+ }
3397
+ if (!this.tokenProvider)
3398
+ return;
3399
+ try {
3400
+ const claims = decodeJwtPayload(token);
3401
+ if (typeof claims.exp === 'number') {
3402
+ const expiresAtMs = claims.exp * 1000;
3403
+ const delay = Math.max(0, expiresAtMs - Date.now() - REFRESH_BUFFER_MS);
3404
+ this.refreshTimer = setTimeout(() => {
3405
+ this.refreshTokenFromProvider().catch(err => {
3406
+ this.emitAuthError(err instanceof Error ? err : new Error(String(err)));
3407
+ });
3408
+ }, delay);
3409
+ }
3410
+ }
3411
+ catch {
3412
+ // Can't decode exp claim — skip proactive refresh
3413
+ }
3414
+ }
3415
+ /**
3416
+ * Release resources associated with this Arca client.
3417
+ * Clears any proactive token refresh timers and disconnects the WebSocket.
3418
+ * Useful for teardown in short-lived processes or tests.
3419
+ */
3420
+ dispose() {
3421
+ if (this.refreshTimer) {
3422
+ clearTimeout(this.refreshTimer);
3423
+ this.refreshTimer = null;
3424
+ }
3425
+ this.ws.disconnect();
3426
+ }
3427
+ emitAuthError(error) {
3428
+ this.authErrorListeners.forEach(cb => cb(error));
3429
+ }
3430
+ // ---- Realm resolution ----
3431
+ async resolveRealm() {
3432
+ // If already resolved (e.g., from token claims), we're done
3433
+ if (this.resolvedRealmId)
3434
+ return;
3435
+ // If no realm input was provided (and token didn't contain one), error
3436
+ if (!this.realmInput) {
3437
+ throw new Error('No realm specified. Provide a realm in the config or use a scoped token that contains a realmId claim.');
3438
+ }
3439
+ // If it looks like a UUID or a TypeID (e.g. rlm_01h2xcejqtf2nbrexx3vqjhp41), use directly
3440
+ if (isIdFormat(this.realmInput)) {
3441
+ this.resolvedRealmId = this.realmInput;
3442
+ return;
3443
+ }
3444
+ // Otherwise, resolve slug/name/id to ID by listing realms
3445
+ const result = await this.client.get('/realms');
3446
+ const realm = result.realms.find((r) => r.slug === this.realmInput || r.name === this.realmInput || r.id === this.realmInput);
3447
+ if (!realm) {
3448
+ throw new errors_1.NotFoundError(`Realm '${this.realmInput}' not found. Available realms: ${result.realms.map((r) => r.slug).join(', ')}`);
3449
+ }
3450
+ this.resolvedRealmId = realm.id;
3451
+ }
3452
+ }
3453
+ exports.Arca = Arca;
3454
+ //# sourceMappingURL=arca.js.map