@metamask-previews/perps-controller 24.1.0-preview-1a6714ed3 → 24.1.0-preview-4ba073b3a

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 (147) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +115 -5
  3. package/dist/PerpsController-method-action-types.d.ts +2 -2
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +19 -6
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +302 -64
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/aggregation/SubscriptionMultiplexer.d.ts +13 -2
  10. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
  11. package/dist/aggregation/SubscriptionMultiplexer.js +27 -13
  12. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +2 -0
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +2 -0
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/lighterConfig.d.ts +17 -0
  18. package/dist/constants/lighterConfig.d.ts.map +1 -1
  19. package/dist/constants/lighterConfig.js +31 -8
  20. package/dist/constants/lighterConfig.js.map +1 -1
  21. package/dist/errors.d.ts +16 -0
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +13 -0
  24. package/dist/errors.js.map +1 -1
  25. package/dist/index.d.ts +7 -4
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +3 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +3 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +4 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/AggregatedPerpsProvider.d.ts +33 -1
  34. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  35. package/dist/providers/AggregatedPerpsProvider.js +688 -41
  36. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  37. package/dist/providers/HyperLiquidProvider.d.ts +2 -1
  38. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  39. package/dist/providers/HyperLiquidProvider.js +410 -132
  40. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  41. package/dist/providers/LighterProvider.d.ts +9 -2
  42. package/dist/providers/LighterProvider.d.ts.map +1 -1
  43. package/dist/providers/LighterProvider.js +334 -111
  44. package/dist/providers/LighterProvider.js.map +1 -1
  45. package/dist/services/AccountService.d.ts.map +1 -1
  46. package/dist/services/AccountService.js +14 -1
  47. package/dist/services/AccountService.js.map +1 -1
  48. package/dist/services/DepositService.d.ts +8 -1
  49. package/dist/services/DepositService.d.ts.map +1 -1
  50. package/dist/services/DepositService.js +47 -6
  51. package/dist/services/DepositService.js.map +1 -1
  52. package/dist/services/HyperLiquidClientService.d.ts +1 -1
  53. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  54. package/dist/services/HyperLiquidClientService.js +5 -2
  55. package/dist/services/HyperLiquidClientService.js.map +1 -1
  56. package/dist/services/HyperLiquidSubscriptionService.d.ts +19 -14
  57. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  58. package/dist/services/HyperLiquidSubscriptionService.js +612 -191
  59. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  60. package/dist/services/HyperLiquidWalletService.d.ts +7 -0
  61. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
  62. package/dist/services/HyperLiquidWalletService.js +16 -0
  63. package/dist/services/HyperLiquidWalletService.js.map +1 -1
  64. package/dist/services/LighterClientService.d.ts.map +1 -1
  65. package/dist/services/LighterClientService.js +3 -1
  66. package/dist/services/LighterClientService.js.map +1 -1
  67. package/dist/services/RewardsIntegrationService.d.ts +2 -1
  68. package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
  69. package/dist/services/RewardsIntegrationService.js +9 -2
  70. package/dist/services/RewardsIntegrationService.js.map +1 -1
  71. package/dist/services/ServiceContext.d.ts +3 -3
  72. package/dist/services/ServiceContext.d.ts.map +1 -1
  73. package/dist/services/ServiceContext.js.map +1 -1
  74. package/dist/services/TradingService.d.ts.map +1 -1
  75. package/dist/services/TradingService.js +340 -88
  76. package/dist/services/TradingService.js.map +1 -1
  77. package/dist/types/index.d.ts +321 -14
  78. package/dist/types/index.d.ts.map +1 -1
  79. package/dist/types/index.js.map +1 -1
  80. package/dist/types/lighter-types.d.ts +1 -1
  81. package/dist/types/lighter-types.d.ts.map +1 -1
  82. package/dist/types/lighter-types.js.map +1 -1
  83. package/dist/utils/accountAggregation.d.ts +58 -0
  84. package/dist/utils/accountAggregation.d.ts.map +1 -0
  85. package/dist/utils/accountAggregation.js +117 -0
  86. package/dist/utils/accountAggregation.js.map +1 -0
  87. package/dist/utils/accountUtils.d.ts +18 -0
  88. package/dist/utils/accountUtils.d.ts.map +1 -1
  89. package/dist/utils/accountUtils.js +69 -66
  90. package/dist/utils/accountUtils.js.map +1 -1
  91. package/dist/utils/batchOperationStatus.d.ts +18 -0
  92. package/dist/utils/batchOperationStatus.d.ts.map +1 -0
  93. package/dist/utils/batchOperationStatus.js +26 -0
  94. package/dist/utils/batchOperationStatus.js.map +1 -0
  95. package/dist/utils/cancelOrders.d.ts +32 -0
  96. package/dist/utils/cancelOrders.d.ts.map +1 -0
  97. package/dist/utils/cancelOrders.js +53 -0
  98. package/dist/utils/cancelOrders.js.map +1 -0
  99. package/dist/utils/closePositions.d.ts +24 -0
  100. package/dist/utils/closePositions.d.ts.map +1 -0
  101. package/dist/utils/closePositions.js +20 -0
  102. package/dist/utils/closePositions.js.map +1 -0
  103. package/dist/utils/feeSupport.d.ts +9 -0
  104. package/dist/utils/feeSupport.d.ts.map +1 -0
  105. package/dist/utils/feeSupport.js +11 -0
  106. package/dist/utils/feeSupport.js.map +1 -0
  107. package/dist/utils/hyperLiquidAdapter.d.ts +9 -1
  108. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  109. package/dist/utils/hyperLiquidAdapter.js +37 -1
  110. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  111. package/dist/utils/hyperLiquidPositionPreview.d.ts +46 -0
  112. package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
  113. package/dist/utils/hyperLiquidPositionPreview.js +98 -6
  114. package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
  115. package/dist/utils/index.d.ts +5 -0
  116. package/dist/utils/index.d.ts.map +1 -1
  117. package/dist/utils/index.js +3 -0
  118. package/dist/utils/index.js.map +1 -1
  119. package/dist/utils/lighterAdapter.d.ts +2 -1
  120. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  121. package/dist/utils/lighterAdapter.js +32 -16
  122. package/dist/utils/lighterAdapter.js.map +1 -1
  123. package/dist/utils/orderBookGrouping.d.ts +38 -0
  124. package/dist/utils/orderBookGrouping.d.ts.map +1 -0
  125. package/dist/utils/orderBookGrouping.js +101 -0
  126. package/dist/utils/orderBookGrouping.js.map +1 -0
  127. package/dist/utils/orderTypes.d.ts +2 -0
  128. package/dist/utils/orderTypes.d.ts.map +1 -1
  129. package/dist/utils/orderTypes.js +11 -4
  130. package/dist/utils/orderTypes.js.map +1 -1
  131. package/dist/utils/perpsClientCopy.d.ts +33 -0
  132. package/dist/utils/perpsClientCopy.d.ts.map +1 -0
  133. package/dist/utils/perpsClientCopy.js +509 -0
  134. package/dist/utils/perpsClientCopy.js.map +1 -0
  135. package/dist/utils/standaloneInfoClient.d.ts +20 -3
  136. package/dist/utils/standaloneInfoClient.d.ts.map +1 -1
  137. package/dist/utils/standaloneInfoClient.js +35 -10
  138. package/dist/utils/standaloneInfoClient.js.map +1 -1
  139. package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
  140. package/dist/utils/subscriptionFeeWaiver.js +5 -3
  141. package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
  142. package/docs/README.md +1 -0
  143. package/docs/architecture.md +16 -12
  144. package/docs/client-contract.md +89 -0
  145. package/docs/contracts/events.md +1 -1
  146. package/docs/tpsl.md +1 -0
  147. package/package.json +2 -2
@@ -15,13 +15,16 @@
15
15
  */
16
16
  import { SubscriptionMultiplexer } from '../aggregation/SubscriptionMultiplexer.js';
17
17
  import { PERPS_CONSTANTS } from '../constants/perpsConfig.js';
18
- import { createTpslLegReplaceUnsupportedError } from '../errors.js';
18
+ import { createTpslLegReplaceUnsupportedError, OrderDiscoveryError, } from '../errors.js';
19
19
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
20
20
  import { ProviderRouter } from '../routing/ProviderRouter.js';
21
21
  import { isProviderOnTestnet } from '../services/providerNetwork.js';
22
22
  import { WebSocketConnectionState } from '../types/index.js';
23
+ import { buildAggregatedAccountState, getAccountAggregateMetadata, } from '../utils/accountAggregation.js';
24
+ import { resolveCloseSelection } from '../utils/closePositions.js';
23
25
  import { carryProviderErrorCause } from '../utils/errorContext.js';
24
26
  import { ensureError } from '../utils/errorUtils.js';
27
+ import { hasFeeSetter } from '../utils/feeSupport.js';
25
28
  /** Error returned when only some providers suspend their Chase orders. */
26
29
  export class ChaseOrderSuspensionError extends Error {
27
30
  suspendedOrders;
@@ -302,14 +305,43 @@ export class AggregatedPerpsProvider {
302
305
  });
303
306
  return successful;
304
307
  }
308
+ /**
309
+ * Values of a read across venues. A venue whose read failed leaves the
310
+ * merged list unknown, never shorter: the first failure is rethrown when it
311
+ * is already classified, else wrapped in `failureCode` with the cause.
312
+ *
313
+ * @param results - Results from Promise.allSettled
314
+ * @param failureCode - Error code for an unclassified venue failure.
315
+ * @returns Every venue's values
316
+ */
317
+ #requireAllVenueResults(results, failureCode) {
318
+ const failure = results.find((result) => result.status === 'rejected');
319
+ if (failure) {
320
+ const reason = failure.reason;
321
+ if (reason instanceof Error &&
322
+ (reason.message === failureCode ||
323
+ reason.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE)) {
324
+ throw reason;
325
+ }
326
+ throw new Error(failureCode, { cause: reason });
327
+ }
328
+ return results.flatMap((result) => result.status === 'fulfilled' ? [result.value] : []);
329
+ }
305
330
  // ============================================================================
306
331
  // Asset Routes (Synchronous - delegate to default provider)
307
332
  // ============================================================================
308
333
  getDepositRoutes(params) {
309
- return this.#getDefaultProvider().getDepositRoutes(params);
334
+ // Routes name the venue that actually settles the movement: identical
335
+ // asset/chain routes from different venues are distinct entries and are
336
+ // never collapsed.
337
+ return this.#getActiveProviders().flatMap(([providerId, provider]) => provider
338
+ .getDepositRoutes(params)
339
+ .map((route) => ({ ...route, providerId })));
310
340
  }
311
341
  getWithdrawalRoutes(params) {
312
- return this.#getDefaultProvider().getWithdrawalRoutes(params);
342
+ return this.#getActiveProviders().flatMap(([providerId, provider]) => provider
343
+ .getWithdrawalRoutes(params)
344
+ .map((route) => ({ ...route, providerId })));
313
345
  }
314
346
  /**
315
347
  * Route account support through the same explicit-provider/default-provider
@@ -452,20 +484,100 @@ export class AggregatedPerpsProvider {
452
484
  // Read Operations (Aggregate from all providers)
453
485
  // ============================================================================
454
486
  async getPositions(params) {
455
- const results = await Promise.allSettled(this.#getActiveProviders().map(async ([id, provider]) => {
487
+ const requests = this.#getActiveProviders().map(async ([id, provider]) => {
456
488
  const positions = await provider.getPositions(params);
457
489
  return positions.map((pos) => ({ ...pos, providerId: id }));
490
+ });
491
+ if (params?.throwOnUnavailable) {
492
+ return (await Promise.all(requests)).flat();
493
+ }
494
+ const results = await Promise.allSettled(requests);
495
+ return this.#requireAllVenueResults(results, PERPS_ERROR_CODES.POSITIONS_FAILED).flat();
496
+ }
497
+ /**
498
+ * Read positions for batch-close fee pricing. Each venue supplies its own
499
+ * notional independently, so an unavailable venue cannot affect another.
500
+ *
501
+ * @internal
502
+ * @param providerIds - Venues targeted by the batch close.
503
+ * @returns Positions from the targeted venues that answered.
504
+ */
505
+ async getPositionsForBatchClose(providerIds) {
506
+ const results = await Promise.allSettled(this.#getActiveProviders()
507
+ .filter(([id]) => providerIds.has(id))
508
+ .map(async ([id, provider]) => {
509
+ const positions = await provider.getPositions({
510
+ throwOnUnavailable: true,
511
+ includeProtection: false,
512
+ });
513
+ return positions.map((position) => ({ ...position, providerId: id }));
458
514
  }));
459
- return this.#extractSuccessfulResults(results, 'getPositions').flat();
515
+ return this.#extractSuccessfulResults(results, 'getPositionsForBatchClose').flat();
460
516
  }
461
517
  async getAccountState(params) {
462
- // Capture the route before awaiting: `setDefaultProvider` can run while
463
- // the venue request is in flight, and the response must stay attributed to
464
- // the provider that served it (the user-data preloader buckets by this id).
465
- const providerId = this.#defaultProvider;
466
- const provider = this.#getDefaultProvider();
467
- const state = await provider.getAccountState(params);
468
- return { ...state, providerId };
518
+ // Single-venue aggregation (for example a fallback when one venue failed
519
+ // to load) keeps the direct result shape: there is nothing to combine and
520
+ // no completeness question to answer.
521
+ if (this.#providers.size === 1) {
522
+ const [[providerId, provider]] = this.#getActiveProviders();
523
+ const state = await provider.getAccountState(params);
524
+ return { ...state, providerId };
525
+ }
526
+ // Capture each entry's venue before awaiting: `setDefaultProvider` and
527
+ // `addProvider` can run while requests are in flight, and a response must
528
+ // stay attributed to the provider that actually served it.
529
+ // Aggregation opts into strict reads: a venue adapter that answers an
530
+ // infrastructure failure with a zero-valued state (Lighter's lenient
531
+ // default) would otherwise be classified here as `{ status: 'available' }`
532
+ // with confirmed zero balances. Only a genuine rejection becomes an
533
+ // `unavailable` entry. Direct and single-venue callers keep each adapter's
534
+ // own default.
535
+ const activeProviders = this.#getActiveProviders();
536
+ const results = await Promise.allSettled(activeProviders.map(async ([providerId, provider]) => {
537
+ const state = await provider.getAccountState({
538
+ ...params,
539
+ throwOnUnavailable: true,
540
+ });
541
+ const entry = {
542
+ status: 'available',
543
+ state: { ...state, providerId },
544
+ providerId,
545
+ };
546
+ return entry;
547
+ }));
548
+ const entries = [];
549
+ const failures = [];
550
+ results.forEach((result, index) => {
551
+ const [providerId] = activeProviders[index];
552
+ if (result.status === 'fulfilled') {
553
+ entries.push(result.value);
554
+ }
555
+ else {
556
+ failures.push({ providerId, reason: result.reason });
557
+ entries.push({
558
+ status: 'unavailable',
559
+ error: ensureError(result.reason).message,
560
+ providerId,
561
+ });
562
+ }
563
+ });
564
+ if (failures.length > 0) {
565
+ this.#deps.debugLogger.log('[AggregatedPerpsProvider] getAccountState partial failure', {
566
+ failedProviders: failures.map((failure) => failure.providerId),
567
+ });
568
+ }
569
+ // No venue reported usable data: refuse to manufacture an all-zero
570
+ // successful total. The first failure is the most specific cause.
571
+ const account = buildAggregatedAccountState({ entries });
572
+ if (!account) {
573
+ const firstFailure = failures[0]?.reason;
574
+ throw firstFailure instanceof Error
575
+ ? firstFailure
576
+ : new Error(failures
577
+ .map((failure) => `${failure.providerId}: ${String(failure.reason)}`)
578
+ .join('; ') || 'No perps provider reported an account state');
579
+ }
580
+ return account;
469
581
  }
470
582
  async getMarkets(params) {
471
583
  const results = await Promise.allSettled(this.#getActiveProviders().map(async ([id, provider]) => {
@@ -511,14 +623,43 @@ export class AggregatedPerpsProvider {
511
623
  const orders = await provider.getOrders(params, options);
512
624
  return orders.map((order) => ({ ...order, providerId: id }));
513
625
  }));
514
- return this.#extractSuccessfulResults(results, 'getOrders').flat();
626
+ return this.#requireAllVenueResults(results, PERPS_ERROR_CODES.ORDERS_FAILED).flat();
515
627
  }
516
628
  async getOpenOrders(params) {
517
- const results = await Promise.allSettled(this.#getActiveProviders().map(async ([id, provider]) => {
629
+ const providers = this.#getActiveProviders();
630
+ const results = await Promise.allSettled(providers.map(async ([id, provider]) => {
518
631
  const orders = await provider.getOpenOrders(params);
519
632
  return orders.map((order) => ({ ...order, providerId: id }));
520
633
  }));
521
- return this.#extractSuccessfulResults(results, 'getOpenOrders').flat();
634
+ if (params?.throwOnUnavailable) {
635
+ const orders = [];
636
+ const failures = [];
637
+ results.forEach((result, index) => {
638
+ if (result.status === 'fulfilled') {
639
+ orders.push(...result.value);
640
+ }
641
+ else if (result.reason instanceof OrderDiscoveryError) {
642
+ // A venue may itself aggregate DEXs (e.g. HyperLiquid HIP-3) and
643
+ // report the orders it did fetch; keep them usable.
644
+ orders.push(...result.reason.orders.map((order) => ({
645
+ ...order,
646
+ providerId: providers[index][0],
647
+ })));
648
+ failures.push(...result.reason.failures);
649
+ }
650
+ else {
651
+ failures.push({
652
+ providerId: providers[index][0],
653
+ error: ensureError(result.reason).message,
654
+ });
655
+ }
656
+ });
657
+ if (failures.length > 0) {
658
+ throw new OrderDiscoveryError({ orders, failures });
659
+ }
660
+ return orders;
661
+ }
662
+ return this.#requireAllVenueResults(results, PERPS_ERROR_CODES.ORDERS_FAILED).flat();
522
663
  }
523
664
  async getFunding(params, options) {
524
665
  const results = await Promise.allSettled(this.#getActiveProviders().map(async ([_providerId, provider]) => {
@@ -722,22 +863,165 @@ export class AggregatedPerpsProvider {
722
863
  return carryProviderErrorCause(result, { ...result, providerId });
723
864
  }
724
865
  async cancelOrders(params) {
725
- // Batch cancel delegates to default provider
726
- const provider = this.#getDefaultProvider();
727
- if (!provider.cancelOrders) {
728
- return {
729
- success: false,
730
- successCount: 0,
731
- failureCount: params.length,
732
- results: params.map((param) => ({
733
- orderId: param.orderId,
734
- symbol: param.symbol,
866
+ // Single-venue aggregation keeps the direct passthrough for that venue's
867
+ // own targets, but venue identity is still execution identity: a target
868
+ // tagged for another venue is not forwardable to the one loaded provider
869
+ // (it could cancel a colliding local ID or be read as its own), and it is
870
+ // not silently dropped either. Foreign-venue targets fail on their own.
871
+ if (this.#providers.size <= 1) {
872
+ const [active] = this.#getActiveProviders();
873
+ const onlyProviderId = active?.[0];
874
+ const onlyProvider = active?.[1];
875
+ const routed = [];
876
+ const misrouted = [];
877
+ for (const param of params) {
878
+ if (param.providerId === undefined ||
879
+ param.providerId === onlyProviderId) {
880
+ routed.push(param);
881
+ }
882
+ else {
883
+ // An unregistered venue was named explicitly: refuse that target
884
+ // rather than executing it on (or losing it to) another venue.
885
+ misrouted.push({
886
+ orderId: param.orderId,
887
+ symbol: param.symbol,
888
+ success: false,
889
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_FOUND,
890
+ providerId: param.providerId,
891
+ });
892
+ }
893
+ }
894
+ if (routed.length === 0) {
895
+ return {
735
896
  success: false,
736
- error: 'Batch cancel not supported',
897
+ successCount: 0,
898
+ failureCount: misrouted.length,
899
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_FOUND,
900
+ results: misrouted,
901
+ };
902
+ }
903
+ if (!onlyProvider) {
904
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
905
+ }
906
+ const result = await this.#cancelOrdersOnProvider(onlyProvider, routed);
907
+ return {
908
+ ...result,
909
+ failureCount: result.failureCount + misrouted.length,
910
+ results: [
911
+ ...result.results.map((item) => ({
912
+ ...item,
913
+ providerId: item.providerId ?? onlyProviderId,
914
+ })),
915
+ ...misrouted,
916
+ ],
917
+ };
918
+ }
919
+ // Venue identity is execution identity: a target without one is ambiguous
920
+ // the moment two venues are registered, and is refused rather than
921
+ // resolved against the default provider.
922
+ // Group targets by venue and use its batch or individual cancel API.
923
+ const byProvider = new Map();
924
+ for (const param of params) {
925
+ const venue = param.providerId;
926
+ if (venue === undefined) {
927
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_ROUTE_REQUIRED);
928
+ }
929
+ const group = byProvider.get(venue);
930
+ if (group) {
931
+ group.push(param);
932
+ }
933
+ else {
934
+ byProvider.set(venue, [param]);
935
+ }
936
+ }
937
+ const grouped = Array.from(byProvider.entries());
938
+ const results = await Promise.allSettled(grouped.map(async ([providerId, targets]) => {
939
+ const provider = this.#providers.get(providerId);
940
+ if (!provider) {
941
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
942
+ }
943
+ const result = await this.#cancelOrdersOnProvider(provider, targets);
944
+ // Attach venue identity to every per-order outcome.
945
+ return {
946
+ ...result,
947
+ results: result.results.map((item) => ({
948
+ ...item,
949
+ providerId,
737
950
  })),
738
951
  };
952
+ }));
953
+ const merged = {
954
+ success: false,
955
+ successCount: 0,
956
+ failureCount: 0,
957
+ results: [],
958
+ };
959
+ const failures = [];
960
+ results.forEach((result, index) => {
961
+ const [providerId, targets] = grouped[index];
962
+ if (result.status === 'fulfilled') {
963
+ merged.successCount += result.value.successCount;
964
+ merged.failureCount += result.value.failureCount;
965
+ merged.results.push(...result.value.results);
966
+ if (result.value.error !== undefined) {
967
+ failures.push({ providerId, error: result.value.error });
968
+ }
969
+ }
970
+ else {
971
+ // The venue's batch threw (or the venue is missing): its targets
972
+ // fail explicitly instead of silently disappearing from the outcome.
973
+ const { message } = ensureError(result.reason);
974
+ failures.push({ providerId, error: message });
975
+ merged.failureCount += targets.length;
976
+ merged.results.push(...targets.map((target) => ({
977
+ orderId: target.orderId,
978
+ symbol: target.symbol,
979
+ success: false,
980
+ error: message,
981
+ providerId,
982
+ })));
983
+ }
984
+ });
985
+ if (failures.length > 0) {
986
+ merged.error = PERPS_ERROR_CODES.BATCH_INCOMPLETE;
987
+ merged.failures = failures;
739
988
  }
740
- return provider.cancelOrders(params);
989
+ merged.success = merged.successCount > 0;
990
+ return merged;
991
+ }
992
+ /**
993
+ * Cancel on one venue, retaining per-order outcomes when it has no batch API.
994
+ *
995
+ * @param provider - The venue that owns every target.
996
+ * @param targets - Orders to cancel on that venue.
997
+ * @returns The batch or individual cancellation results.
998
+ */
999
+ async #cancelOrdersOnProvider(provider, targets) {
1000
+ if (provider.cancelOrders) {
1001
+ return provider.cancelOrders(targets);
1002
+ }
1003
+ const settled = await Promise.allSettled(targets.map(async (target) => provider.cancelOrder(target)));
1004
+ const results = settled.map((result, index) => {
1005
+ if (result.status === 'fulfilled') {
1006
+ return {
1007
+ ...targets[index],
1008
+ success: result.value.success,
1009
+ error: result.value.error,
1010
+ };
1011
+ }
1012
+ return {
1013
+ ...targets[index],
1014
+ success: false,
1015
+ error: ensureError(result.reason).message,
1016
+ };
1017
+ });
1018
+ const successCount = results.filter((result) => result.success).length;
1019
+ return {
1020
+ success: successCount > 0,
1021
+ successCount,
1022
+ failureCount: results.length - successCount,
1023
+ results,
1024
+ };
741
1025
  }
742
1026
  async closePosition(params) {
743
1027
  const [providerId, provider] = this.#getProviderOrDefault(params.providerId);
@@ -745,17 +1029,260 @@ export class AggregatedPerpsProvider {
745
1029
  return carryProviderErrorCause(result, { ...result, providerId });
746
1030
  }
747
1031
  async closePositions(params) {
748
- // Batch close delegates to default provider
749
- const provider = this.#getDefaultProvider();
750
- if (!provider.closePositions) {
1032
+ // Single-venue aggregation keeps the direct passthrough for legacy
1033
+ // `symbols` / `closeAll` calls: there is no cross-venue ambiguity to
1034
+ // resolve. Tagged targets are not part of that legacy contract — a venue
1035
+ // that only reads `symbols` and `closeAll` would treat a missing symbol
1036
+ // list as close-every-position.
1037
+ const selection = resolveCloseSelection(params);
1038
+ // An explicit empty target list closes nothing; it never falls through
1039
+ // to the close-all fan-out below.
1040
+ if (selection.kind === 'none') {
1041
+ return { success: false, successCount: 0, failureCount: 0, results: [] };
1042
+ }
1043
+ if (this.#providers.size <= 1) {
1044
+ if (selection.kind === 'targets') {
1045
+ const active = this.#getActiveProviders();
1046
+ const only = active[0];
1047
+ if (!only) {
1048
+ return {
1049
+ success: false,
1050
+ successCount: 0,
1051
+ failureCount: selection.targets.length,
1052
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_FOUND,
1053
+ results: selection.targets.map((target) => ({
1054
+ symbol: target.symbol,
1055
+ success: false,
1056
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_FOUND,
1057
+ providerId: target.providerId,
1058
+ })),
1059
+ };
1060
+ }
1061
+ return this.#closeSingleVenueTargets(only[0], only[1], selection.targets);
1062
+ }
1063
+ const [, provider] = this.#getProviderOrDefault();
1064
+ if (!provider.closePositions) {
1065
+ return {
1066
+ success: false,
1067
+ successCount: 0,
1068
+ failureCount: 0,
1069
+ results: [],
1070
+ };
1071
+ }
1072
+ return provider.closePositions(params);
1073
+ }
1074
+ // Group explicit targets by venue. Identical symbols on different venues
1075
+ // are independent closes; each result keeps its venue identity.
1076
+ if (selection.kind === 'targets') {
1077
+ const byProvider = new Map();
1078
+ for (const target of selection.targets) {
1079
+ const group = byProvider.get(target.providerId);
1080
+ if (group) {
1081
+ group.push(target.symbol);
1082
+ }
1083
+ else {
1084
+ byProvider.set(target.providerId, [target.symbol]);
1085
+ }
1086
+ }
1087
+ const batches = Array.from(byProvider.entries()).map(([providerId, symbols]) => ({ providerId, symbols }));
1088
+ return this.#mergeCloseResults(await Promise.allSettled(batches.map(async ({ providerId, symbols }) => {
1089
+ const provider = this.#providers.get(providerId);
1090
+ if (!provider) {
1091
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
1092
+ }
1093
+ const result = await this.#closePositionsOnProvider(provider, {
1094
+ symbols,
1095
+ });
1096
+ return {
1097
+ ...result,
1098
+ results: result.results.map((item) => ({
1099
+ ...item,
1100
+ providerId,
1101
+ })),
1102
+ };
1103
+ })), batches);
1104
+ }
1105
+ // `closeAll` outranks a legacy `symbols` list, matching the controller
1106
+ // guard and the direct/HyperLiquid path: `{ closeAll: true, symbols:
1107
+ // ['BTC'] }` closes every position on every venue. Only a symbols-only
1108
+ // request (no `closeAll`) is ambiguous once two venues are registered,
1109
+ // and is refused rather than resolved against the default.
1110
+ if (selection.kind === 'symbols') {
1111
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_ROUTE_REQUIRED);
1112
+ }
1113
+ // `closeAll`, or an empty request, means every position, so it fans out
1114
+ // to every enabled venue. Capture the venue list once so a thrown batch
1115
+ // is attributed to the provider that was actually called.
1116
+ const activeProviders = this.#getActiveProviders();
1117
+ return this.#mergeCloseResults(await Promise.allSettled(activeProviders.map(async ([providerId, provider]) => {
1118
+ const result = await this.#closePositionsOnProvider(provider, {
1119
+ closeAll: true,
1120
+ });
751
1121
  return {
1122
+ ...result,
1123
+ results: result.results.map((item) => ({
1124
+ ...item,
1125
+ providerId,
1126
+ })),
1127
+ };
1128
+ })), activeProviders.map(([providerId]) => ({ providerId })));
1129
+ }
1130
+ /**
1131
+ * Close tagged targets when only one venue is registered.
1132
+ *
1133
+ * Targets for that venue become a symbol list. Targets for any other venue
1134
+ * fail on their own and are not forwarded, so they cannot be read as a
1135
+ * request to close every position on the venue that is actually loaded.
1136
+ *
1137
+ * @param providerId - The only registered venue.
1138
+ * @param provider - That venue's provider.
1139
+ * @param targets - The caller's tagged close targets.
1140
+ * @returns The close result, including per-target failures for other venues.
1141
+ */
1142
+ async #closeSingleVenueTargets(providerId, provider, targets) {
1143
+ const symbols = [];
1144
+ const misrouted = [];
1145
+ for (const target of targets) {
1146
+ if (target.providerId === providerId) {
1147
+ symbols.push(target.symbol);
1148
+ }
1149
+ else {
1150
+ misrouted.push({
1151
+ symbol: target.symbol,
1152
+ success: false,
1153
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_FOUND,
1154
+ providerId: target.providerId,
1155
+ });
1156
+ }
1157
+ }
1158
+ const local = symbols.length === 0
1159
+ ? {
752
1160
  success: false,
753
1161
  successCount: 0,
754
1162
  failureCount: 0,
755
1163
  results: [],
1164
+ }
1165
+ : await this.#closePositionsOnProvider(provider, { symbols });
1166
+ return {
1167
+ success: local.successCount > 0,
1168
+ successCount: local.successCount,
1169
+ failureCount: local.failureCount + misrouted.length,
1170
+ ...(local.error !== undefined && { error: local.error }),
1171
+ results: [
1172
+ ...local.results.map((item) => ({
1173
+ ...item,
1174
+ providerId: item.providerId ?? providerId,
1175
+ })),
1176
+ ...misrouted,
1177
+ ],
1178
+ };
1179
+ }
1180
+ /**
1181
+ * Run one venue's optional batch close, falling back to that same venue's
1182
+ * per-position close when it has no batch method. Never invents an
1183
+ * execution strategy the venue does not expose.
1184
+ *
1185
+ * @param provider - The venue to close on.
1186
+ * @param params - Venue-local close parameters (symbols or closeAll).
1187
+ * @returns The venue's close result.
1188
+ */
1189
+ async #closePositionsOnProvider(provider, params) {
1190
+ if (provider.closePositions) {
1191
+ return provider.closePositions(params);
1192
+ }
1193
+ let targets = (params.symbols ?? []).map((symbol) => ({ symbol }));
1194
+ if (params.closeAll === true) {
1195
+ targets = provider.getClosePositionTargets
1196
+ ? await provider.getClosePositionTargets()
1197
+ : (await provider.getPositions({ throwOnUnavailable: true })).map(({ symbol }) => ({ symbol }));
1198
+ }
1199
+ if (targets.length === 0) {
1200
+ return { success: false, successCount: 0, failureCount: 0, results: [] };
1201
+ }
1202
+ const settled = await Promise.allSettled(targets.map((target) => provider.closePosition(target)));
1203
+ const results = settled.map((result, index) => {
1204
+ const failed = result.status === 'rejected';
1205
+ let success;
1206
+ let error;
1207
+ if (failed) {
1208
+ success = false;
1209
+ error = ensureError(result.reason).message;
1210
+ }
1211
+ else {
1212
+ success = result.value.success === true;
1213
+ error = result.value.error;
1214
+ }
1215
+ return {
1216
+ symbol: targets[index].symbol,
1217
+ success,
1218
+ error,
756
1219
  };
1220
+ });
1221
+ const successCount = results.filter((item) => item.success).length;
1222
+ return {
1223
+ success: successCount > 0,
1224
+ successCount,
1225
+ failureCount: results.length - successCount,
1226
+ results,
1227
+ };
1228
+ }
1229
+ /**
1230
+ * Merge per-venue close results into one batch outcome. Successful work on
1231
+ * one venue is never hidden by another venue's rejection: a thrown venue
1232
+ * batch contributes an explicit venue-attributed error, and when the caller
1233
+ * named the symbols that batch was closing, each of them is a failed result
1234
+ * so a partial close cannot look complete. `success` stays true when at
1235
+ * least one close landed.
1236
+ *
1237
+ * @param results - Settled per-venue results.
1238
+ * @param batches - The venues, in the same order as the settled results.
1239
+ * `symbols` is set for a tagged close, where the failed positions are known
1240
+ * without another read. A `closeAll` throw has no symbol list.
1241
+ * @returns The merged close result.
1242
+ */
1243
+ #mergeCloseResults(results, batches) {
1244
+ const merged = {
1245
+ success: false,
1246
+ successCount: 0,
1247
+ failureCount: 0,
1248
+ results: [],
1249
+ };
1250
+ const failures = [];
1251
+ results.forEach((result, index) => {
1252
+ const batch = batches[index];
1253
+ const { providerId } = batch;
1254
+ if (result.status === 'fulfilled') {
1255
+ merged.successCount += result.value.successCount;
1256
+ merged.failureCount += result.value.failureCount;
1257
+ merged.results.push(...result.value.results);
1258
+ if (result.value.error !== undefined) {
1259
+ failures.push({ providerId, error: result.value.error });
1260
+ }
1261
+ }
1262
+ else {
1263
+ const { message } = ensureError(result.reason);
1264
+ failures.push({ providerId, error: message });
1265
+ const symbols = batch.symbols ?? [];
1266
+ if (symbols.length > 0) {
1267
+ merged.failureCount += symbols.length;
1268
+ merged.results.push(...symbols.map((symbol) => ({
1269
+ symbol,
1270
+ success: false,
1271
+ error: message,
1272
+ providerId,
1273
+ })));
1274
+ }
1275
+ else {
1276
+ merged.failureCount += 1;
1277
+ }
1278
+ }
1279
+ });
1280
+ if (failures.length > 0) {
1281
+ merged.error = PERPS_ERROR_CODES.BATCH_INCOMPLETE;
1282
+ merged.failures = failures;
757
1283
  }
758
- return provider.closePositions(params);
1284
+ merged.success = merged.successCount > 0;
1285
+ return merged;
759
1286
  }
760
1287
  async updatePositionTPSL(params) {
761
1288
  const [providerId, provider] = this.#getProviderOrDefault(params.providerId);
@@ -1043,28 +1570,109 @@ export class AggregatedPerpsProvider {
1043
1570
  },
1044
1571
  });
1045
1572
  }
1573
+ /**
1574
+ * Stream account updates from every enabled venue.
1575
+ *
1576
+ * With more than one venue registered, each venue is subscribed through
1577
+ * the multiplexer, and every emission carries the same contract as a REST
1578
+ * read: combined totals over the venues with data, one `providerStates`
1579
+ * entry per enabled venue (available, pending or unavailable), and
1580
+ * `aggregate` completeness metadata. Before a venue's first snapshot, even
1581
+ * a `null` leaves it pending. A subsequent `null` makes it unavailable.
1582
+ * When no venue has usable data, the consumer gets `null` plus completeness
1583
+ * metadata — never an all-zero total.
1584
+ *
1585
+ * This is venue fan-out, not default routing: changing the routing default
1586
+ * neither re-subscribes these streams nor invalidates the still-valid
1587
+ * all-venue total.
1588
+ *
1589
+ * With a single venue registered, the direct stream is passed through
1590
+ * unchanged (venue identity stamped), matching the one-provider read.
1591
+ *
1592
+ * @param params - Subscription parameters including callback and account ID.
1593
+ * @returns A cleanup function covering every venue subscription.
1594
+ */
1046
1595
  subscribeToAccount(params) {
1047
- // Account, candles, order book and OI caps have no per-venue route of
1048
- // their own, so they follow the routing default and move with it.
1049
- return this.#trackDefaultRoutedSubscription({
1050
- open: (provider) => provider.subscribeToAccount(params),
1051
- // Emit an unavailable snapshot so a consumer that caches the balance
1052
- // (for example Mobile's account stream channel) does not keep showing
1053
- // the previous venue's value while the new venue's first update pends.
1054
- onInvalidate: () => params.callback(null),
1596
+ // Single-venue aggregation keeps the direct stream shape: the emission
1597
+ // carries top-level `providerId` and venue-local fields, so a REST read
1598
+ // and a stream update have the same contract when one venue is loaded
1599
+ // (for example while the other recovers). Building an aggregate here
1600
+ // would move `crossMarginSummary` and `subAccountBreakdown` under
1601
+ // `providerStates` and strip the top-level venue identity.
1602
+ if (this.#providers.size === 1) {
1603
+ const [[providerId, provider]] = this.#getActiveProviders();
1604
+ return provider.subscribeToAccount({
1605
+ ...(params.accountId !== undefined && {
1606
+ accountId: params.accountId,
1607
+ }),
1608
+ callback: (account) => {
1609
+ if (account === null) {
1610
+ // Same semantics as the read path: no venue data is no data,
1611
+ // never a zero-valued total.
1612
+ params.callback(null);
1613
+ return;
1614
+ }
1615
+ params.callback({ ...account, providerId });
1616
+ },
1617
+ });
1618
+ }
1619
+ // A null before the first snapshot leaves the venue pending. After a
1620
+ // snapshot (even an invalid one), a null means it became unavailable.
1621
+ // Like the strict REST read, each venue must report its whole account or
1622
+ // null: a partial venue snapshot would otherwise count as complete.
1623
+ const lastReport = new Set();
1624
+ const unavailable = new Set();
1625
+ return this.#subscriptionMux.subscribeToAccount({
1626
+ ...(params.accountId !== undefined && { accountId: params.accountId }),
1627
+ requireCompleteAccount: true,
1628
+ providers: this.#getActiveProviders(),
1629
+ onError: (_error, providerId) => {
1630
+ unavailable.add(providerId);
1631
+ },
1632
+ callback: (accounts) => {
1633
+ const entries = this.#getActiveProviders().map(([providerId]) => {
1634
+ const state = accounts.find((account) => account.providerId === providerId);
1635
+ if (state) {
1636
+ lastReport.add(providerId);
1637
+ return { status: 'available', state, providerId };
1638
+ }
1639
+ // Reported before and its latest update was null: no current
1640
+ // balance is known for this venue. Never seen: it simply has
1641
+ // not reported yet.
1642
+ return unavailable.has(providerId) || lastReport.has(providerId)
1643
+ ? { status: 'unavailable', providerId }
1644
+ : { status: 'pending', providerId };
1645
+ });
1646
+ const account = buildAggregatedAccountState({ entries });
1647
+ params.callback(account, account?.aggregate ?? getAccountAggregateMetadata(entries));
1648
+ },
1055
1649
  });
1056
1650
  }
1057
1651
  subscribeToOICaps(params) {
1652
+ // Explicit route: pinned to that venue. A venue without the stream never
1653
+ // silently falls back to a different venue's data.
1654
+ if (params.providerId !== undefined) {
1655
+ return (this.#resolveExplicitStreamRoute(params.providerId, undefined)?.subscribeToOICaps(params) ?? (() => undefined));
1656
+ }
1058
1657
  return this.#trackDefaultRoutedSubscription({
1059
1658
  open: (provider) => provider.subscribeToOICaps(params),
1060
1659
  });
1061
1660
  }
1062
1661
  subscribeToCandles(params) {
1662
+ // Explicit route: pinned to that venue — required when both venues list
1663
+ // the same symbol and the data must come from a specific one. A pinned
1664
+ // stream does not follow the routing default.
1665
+ if (params.providerId !== undefined) {
1666
+ return (this.#resolveExplicitStreamRoute(params.providerId, params.onError)?.subscribeToCandles(params) ?? (() => undefined));
1667
+ }
1063
1668
  return this.#trackDefaultRoutedSubscription({
1064
1669
  open: (provider) => provider.subscribeToCandles(params),
1065
1670
  });
1066
1671
  }
1067
1672
  subscribeToOrderBook(params) {
1673
+ if (params.providerId !== undefined) {
1674
+ return (this.#resolveExplicitStreamRoute(params.providerId, params.onError)?.subscribeToOrderBook(params) ?? (() => undefined));
1675
+ }
1068
1676
  return this.#trackDefaultRoutedSubscription({
1069
1677
  open: (provider) => provider.subscribeToOrderBook(params),
1070
1678
  });
@@ -1116,6 +1724,30 @@ export class AggregatedPerpsProvider {
1116
1724
  }
1117
1725
  return provider.subscribeToPublicTrades(params);
1118
1726
  }
1727
+ /**
1728
+ * Resolve an explicitly named stream venue.
1729
+ *
1730
+ * A route that is not registered is reported through the stream's
1731
+ * `onError` (or thrown when it has none) and never silently subscribes to a
1732
+ * different venue: no callback, no data, no fallback.
1733
+ *
1734
+ * @param providerId - The venue the caller named.
1735
+ * @param onError - The stream's error handler, when it has one.
1736
+ * @returns The provider, or undefined after reporting a missing route.
1737
+ */
1738
+ #resolveExplicitStreamRoute(providerId, onError) {
1739
+ const provider = this.#providers.get(providerId);
1740
+ if (!provider) {
1741
+ // A bare code, like every other refusal here, so clients can map it.
1742
+ const error = new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
1743
+ if (onError) {
1744
+ onError(error);
1745
+ return undefined;
1746
+ }
1747
+ throw error;
1748
+ }
1749
+ return provider;
1750
+ }
1119
1751
  /**
1120
1752
  * Stream available to trade from the explicit route, else the default
1121
1753
  * provider, as order placement routes. A route without support returns a
@@ -1164,8 +1796,23 @@ export class AggregatedPerpsProvider {
1164
1796
  }
1165
1797
  });
1166
1798
  }
1167
- setUserFeeResolution(resolution) {
1168
- this.#providers.forEach((provider) => {
1799
+ supportsFeeResolution(providerId) {
1800
+ const provider = this.#providers.get(providerId ?? this.#defaultProvider);
1801
+ return hasFeeSetter(provider);
1802
+ }
1803
+ setUserFeeResolution(resolution, providerId) {
1804
+ // A venue-scoped resolution reaches only that venue: a fan-out close
1805
+ // prices each venue against its own positions and fee route, and one
1806
+ // venue's resolution must not overwrite another's.
1807
+ let targets;
1808
+ if (providerId === undefined) {
1809
+ targets = Array.from(this.#providers.values());
1810
+ }
1811
+ else {
1812
+ const provider = this.#providers.get(providerId);
1813
+ targets = provider ? [provider] : [];
1814
+ }
1815
+ targets.forEach((provider) => {
1169
1816
  if (provider.setUserFeeResolution) {
1170
1817
  provider.setUserFeeResolution(resolution);
1171
1818
  }