@lifi/perps-sdk 0.0.0-preview-34f3bb2 → 0.0.0-preview-1ba1dc6

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 (126) hide show
  1. package/dist/cjs/client/PerpsClient.d.ts +9 -4
  2. package/dist/cjs/client/PerpsClient.d.ts.map +1 -1
  3. package/dist/cjs/client/PerpsClient.js +38 -4
  4. package/dist/cjs/client/PerpsClient.js.map +1 -1
  5. package/dist/cjs/index.d.ts +2 -2
  6. package/dist/cjs/index.d.ts.map +1 -1
  7. package/dist/cjs/index.js.map +1 -1
  8. package/dist/cjs/registry/assetRegistry.d.ts +1 -1
  9. package/dist/cjs/registry/assetRegistry.d.ts.map +1 -1
  10. package/dist/cjs/registry/assetRegistry.js +2 -2
  11. package/dist/cjs/registry/assetRegistry.js.map +1 -1
  12. package/dist/cjs/registry/marketRegistry.d.ts +1 -1
  13. package/dist/cjs/registry/marketRegistry.d.ts.map +1 -1
  14. package/dist/cjs/registry/marketRegistry.js +2 -2
  15. package/dist/cjs/registry/marketRegistry.js.map +1 -1
  16. package/dist/cjs/registry/referenceDataRegistry.d.ts +1 -3
  17. package/dist/cjs/registry/referenceDataRegistry.d.ts.map +1 -1
  18. package/dist/cjs/registry/referenceDataRegistry.js +3 -14
  19. package/dist/cjs/registry/referenceDataRegistry.js.map +1 -1
  20. package/dist/cjs/services/getMarket.d.ts.map +1 -1
  21. package/dist/cjs/services/getMarket.js +9 -1
  22. package/dist/cjs/services/getMarket.js.map +1 -1
  23. package/dist/cjs/types/api.d.ts +10 -1
  24. package/dist/cjs/types/api.d.ts.map +1 -1
  25. package/dist/cjs/types/config.d.ts +1 -0
  26. package/dist/cjs/types/config.d.ts.map +1 -1
  27. package/dist/cjs/utils/accountSummary.d.ts.map +1 -1
  28. package/dist/cjs/utils/accountSummary.js +2 -1
  29. package/dist/cjs/utils/accountSummary.js.map +1 -1
  30. package/dist/cjs/utils/switchChain.d.ts +5 -0
  31. package/dist/cjs/utils/switchChain.d.ts.map +1 -0
  32. package/dist/cjs/utils/switchChain.js +39 -0
  33. package/dist/cjs/utils/switchChain.js.map +1 -0
  34. package/dist/cjs/version.d.ts +1 -1
  35. package/dist/cjs/version.js +1 -1
  36. package/dist/cjs/websocket/ReconnectingWebSocket.d.ts.map +1 -1
  37. package/dist/cjs/websocket/ReconnectingWebSocket.js +4 -0
  38. package/dist/cjs/websocket/ReconnectingWebSocket.js.map +1 -1
  39. package/dist/cjs/websocket/WsProviderBase.d.ts.map +1 -1
  40. package/dist/cjs/websocket/WsProviderBase.js +9 -1
  41. package/dist/cjs/websocket/WsProviderBase.js.map +1 -1
  42. package/dist/esm/client/PerpsClient.d.ts +41 -7
  43. package/dist/esm/client/PerpsClient.d.ts.map +1 -1
  44. package/dist/esm/client/PerpsClient.js +76 -7
  45. package/dist/esm/client/PerpsClient.js.map +1 -1
  46. package/dist/esm/index.d.ts +2 -2
  47. package/dist/esm/index.d.ts.map +1 -1
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/esm/registry/assetRegistry.d.ts +1 -1
  50. package/dist/esm/registry/assetRegistry.d.ts.map +1 -1
  51. package/dist/esm/registry/assetRegistry.js +2 -2
  52. package/dist/esm/registry/assetRegistry.js.map +1 -1
  53. package/dist/esm/registry/marketRegistry.d.ts +1 -1
  54. package/dist/esm/registry/marketRegistry.d.ts.map +1 -1
  55. package/dist/esm/registry/marketRegistry.js +2 -2
  56. package/dist/esm/registry/marketRegistry.js.map +1 -1
  57. package/dist/esm/registry/referenceDataRegistry.d.ts +5 -11
  58. package/dist/esm/registry/referenceDataRegistry.d.ts.map +1 -1
  59. package/dist/esm/registry/referenceDataRegistry.js +6 -23
  60. package/dist/esm/registry/referenceDataRegistry.js.map +1 -1
  61. package/dist/esm/services/getMarket.d.ts +4 -3
  62. package/dist/esm/services/getMarket.d.ts.map +1 -1
  63. package/dist/esm/services/getMarket.js +13 -4
  64. package/dist/esm/services/getMarket.js.map +1 -1
  65. package/dist/esm/types/api.d.ts +24 -7
  66. package/dist/esm/types/api.d.ts.map +1 -1
  67. package/dist/esm/types/config.d.ts +11 -0
  68. package/dist/esm/types/config.d.ts.map +1 -1
  69. package/dist/esm/utils/accountSummary.d.ts +7 -3
  70. package/dist/esm/utils/accountSummary.d.ts.map +1 -1
  71. package/dist/esm/utils/accountSummary.js +5 -1
  72. package/dist/esm/utils/accountSummary.js.map +1 -1
  73. package/dist/esm/utils/switchChain.d.ts +21 -0
  74. package/dist/esm/utils/switchChain.d.ts.map +1 -0
  75. package/dist/esm/utils/switchChain.js +51 -0
  76. package/dist/esm/utils/switchChain.js.map +1 -0
  77. package/dist/esm/version.d.ts +1 -1
  78. package/dist/esm/version.js +1 -1
  79. package/dist/esm/websocket/ReconnectingWebSocket.d.ts +7 -4
  80. package/dist/esm/websocket/ReconnectingWebSocket.d.ts.map +1 -1
  81. package/dist/esm/websocket/ReconnectingWebSocket.js +11 -4
  82. package/dist/esm/websocket/ReconnectingWebSocket.js.map +1 -1
  83. package/dist/esm/websocket/WsProviderBase.d.ts.map +1 -1
  84. package/dist/esm/websocket/WsProviderBase.js +14 -1
  85. package/dist/esm/websocket/WsProviderBase.js.map +1 -1
  86. package/dist/esm/websocket/types.d.ts +3 -3
  87. package/dist/types/client/PerpsClient.d.ts +41 -7
  88. package/dist/types/client/PerpsClient.d.ts.map +1 -1
  89. package/dist/types/index.d.ts +2 -2
  90. package/dist/types/index.d.ts.map +1 -1
  91. package/dist/types/registry/assetRegistry.d.ts +1 -1
  92. package/dist/types/registry/assetRegistry.d.ts.map +1 -1
  93. package/dist/types/registry/marketRegistry.d.ts +1 -1
  94. package/dist/types/registry/marketRegistry.d.ts.map +1 -1
  95. package/dist/types/registry/referenceDataRegistry.d.ts +5 -11
  96. package/dist/types/registry/referenceDataRegistry.d.ts.map +1 -1
  97. package/dist/types/services/getMarket.d.ts +4 -3
  98. package/dist/types/services/getMarket.d.ts.map +1 -1
  99. package/dist/types/types/api.d.ts +24 -7
  100. package/dist/types/types/api.d.ts.map +1 -1
  101. package/dist/types/types/config.d.ts +11 -0
  102. package/dist/types/types/config.d.ts.map +1 -1
  103. package/dist/types/utils/accountSummary.d.ts +7 -3
  104. package/dist/types/utils/accountSummary.d.ts.map +1 -1
  105. package/dist/types/utils/switchChain.d.ts +21 -0
  106. package/dist/types/utils/switchChain.d.ts.map +1 -0
  107. package/dist/types/version.d.ts +1 -1
  108. package/dist/types/websocket/ReconnectingWebSocket.d.ts +7 -4
  109. package/dist/types/websocket/ReconnectingWebSocket.d.ts.map +1 -1
  110. package/dist/types/websocket/WsProviderBase.d.ts.map +1 -1
  111. package/dist/types/websocket/types.d.ts +3 -3
  112. package/package.json +2 -2
  113. package/src/client/PerpsClient.ts +96 -10
  114. package/src/index.ts +1 -2
  115. package/src/registry/assetRegistry.ts +4 -6
  116. package/src/registry/marketRegistry.ts +4 -6
  117. package/src/registry/referenceDataRegistry.ts +8 -32
  118. package/src/services/getMarket.ts +16 -4
  119. package/src/types/api.ts +29 -7
  120. package/src/types/config.ts +14 -0
  121. package/src/utils/accountSummary.ts +14 -4
  122. package/src/utils/switchChain.ts +73 -0
  123. package/src/version.ts +1 -1
  124. package/src/websocket/ReconnectingWebSocket.ts +11 -4
  125. package/src/websocket/WsProviderBase.ts +14 -1
  126. package/src/websocket/types.ts +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"WsProviderBase.d.ts","sourceRoot":"","sources":["../../../src/websocket/WsProviderBase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AACxE,OAAO,KAAK,EACV,sBAAsB,EACtB,aAAa,EACd,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AACvE,OAAO,KAAK,EACV,oBAAoB,EACpB,UAAU,EACV,gBAAgB,EACjB,MAAM,YAAY,CAAA;AAGnB;;;;;;;;GAQG;AAC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;IAgD5B,OAAO,CAAC,cAAc;CAwCvB"}
@@ -21,9 +21,9 @@ export type SubscriptionListener = (event: SubscriptionEvent) => void;
21
21
  * - `connected` — socket open, live data flowing.
22
22
  * - `reconnecting` — socket dropped; auto-reconnect with backoff in progress.
23
23
  * Data may be stale until it returns to `connected`.
24
- * - `disconnected` — reconnection abandoned after the retry cap. The
25
- * connection is permanently dead and will not recover on its own; the
26
- * subscription's data is stale. Terminal.
24
+ * - `disconnected` — reconnection abandoned after the retry cap, or the
25
+ * connection was explicitly closed. The connection is permanently dead and
26
+ * will not recover on its own; the subscription's data is stale. Terminal.
27
27
  *
28
28
  * @public
29
29
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/perps-sdk",
3
- "version": "0.0.0-preview-34f3bb2",
3
+ "version": "0.0.0-preview-1ba1dc6",
4
4
  "description": "LI.FI Perps SDK for perpetuals trading",
5
5
  "homepage": "https://github.com/lifinance/perps-sdk",
6
6
  "bugs": {
@@ -44,7 +44,7 @@
44
44
  "@lifi/types": "17.82.1",
45
45
  "partysocket": "^1.1.19",
46
46
  "viem": "^2.48.8",
47
- "@lifi/perps-types": "^1.6.0"
47
+ "@lifi/perps-types": "^1.12.0"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"
@@ -30,14 +30,20 @@ import type {
30
30
  PlaceOrderParams,
31
31
  PlaceTriggerOrderParams,
32
32
  ProviderSetup,
33
+ SendAssetActionParams,
33
34
  WithdrawParams,
34
35
  } from '../types/api.js'
36
+ import type { PerpsClientSigner, SwitchChainHook } from '../types/config.js'
35
37
  import type {
36
38
  ActionSignerContribution,
37
39
  PerpsProvider,
38
40
  PerpsSDKClient,
39
41
  SignActionsContext,
40
42
  } from '../types/provider.js'
43
+ import {
44
+ switchSigningChain,
45
+ userEip712TargetChainId,
46
+ } from '../utils/switchChain.js'
41
47
  import { createPerpsClient } from './createPerpsClient.js'
42
48
  import { requireProvider as resolveProvider } from './requireProvider.js'
43
49
 
@@ -75,6 +81,7 @@ export class PerpsClient {
75
81
  private sdkClient: PerpsSDKClient
76
82
  private providerMetadataCache: Map<string, Provider> = new Map()
77
83
  private _userWallet: PerpsSDKClient['userWallet'] | undefined
84
+ private _switchChain: SwitchChainHook | undefined
78
85
 
79
86
  constructor(options: PerpsClientOptions) {
80
87
  this.sdkClient = createPerpsClient({
@@ -83,6 +90,7 @@ export class PerpsClient {
83
90
  apiUrl: options.apiUrl,
84
91
  providers: options.providers,
85
92
  })
93
+ this._switchChain = options.switchChain
86
94
  }
87
95
 
88
96
  /**
@@ -99,6 +107,17 @@ export class PerpsClient {
99
107
  })
100
108
  }
101
109
 
110
+ /**
111
+ * Set or replace the wallet chain-switch hook invoked before a USER-signed
112
+ * EIP-712 action is signed. Mirrors {@link setUserWallet}. Pass undefined to
113
+ * clear — cleared, a wallet on the wrong chain signs offline without a switch.
114
+ *
115
+ * @public
116
+ */
117
+ setSwitchChain(switchChain: SwitchChainHook | undefined): void {
118
+ this._switchChain = switchChain
119
+ }
120
+
102
121
  /**
103
122
  * The underlying low-level {@link PerpsSDKClient} (config, user wallet,
104
123
  * provider registry) backing this instance.
@@ -185,14 +204,37 @@ export class PerpsClient {
185
204
  `signingMethod '${descriptor.signingMethod}'.`
186
205
  )
187
206
  }
207
+ const userWallet = await this.resolveSigningWallet(descriptor, actions)
188
208
  return plugin.signActions(
189
209
  descriptor.signingMethod,
190
210
  actions,
191
211
  address,
192
- this.buildSignActionsContext(descriptor)
212
+ this.buildSignActionsContext(descriptor, userWallet)
193
213
  )
194
214
  }
195
215
 
216
+ /**
217
+ * Resolve the wallet that signs `actions`. For a USER-signed EIP-712 batch,
218
+ * switch the configured wallet to the action's target chain via the
219
+ * `switchChain` hook and return the switched client; the switch is transient
220
+ * — `sdkClient.userWallet` is never mutated. All other batches (agent-signed,
221
+ * non-EIP-712, or no configured wallet) return the configured wallet as-is.
222
+ */
223
+ private async resolveSigningWallet(
224
+ descriptor: ProviderAction,
225
+ actions: ActionStep[]
226
+ ): Promise<PerpsClientSigner | undefined> {
227
+ const wallet = this.sdkClient.userWallet
228
+ if (!wallet) {
229
+ return undefined
230
+ }
231
+ const targetChainId = userEip712TargetChainId(descriptor, actions)
232
+ if (targetChainId === undefined) {
233
+ return wallet
234
+ }
235
+ return switchSigningChain(wallet, targetChainId, this._switchChain)
236
+ }
237
+
196
238
  /**
197
239
  * Assemble the per-call context the provider plugin needs in order to sign:
198
240
  * the end-user's wallet and the descriptor's declared `signers`. Core
@@ -200,13 +242,19 @@ export class PerpsClient {
200
242
  * branch on them. Provider-owned session credentials (the Hyperliquid agent
201
243
  * keypair, Lighter's API key) are resolved inside the provider's
202
244
  * `signActions`, not threaded through here.
245
+ *
246
+ * `userWallet` overrides the configured wallet for this signing pass only —
247
+ * `resolveSigningWallet` supplies the chain-switched client without mutating
248
+ * `sdkClient.userWallet`.
203
249
  */
204
250
  private buildSignActionsContext(
205
- descriptor: ProviderAction
251
+ descriptor: ProviderAction,
252
+ userWallet?: PerpsClientSigner
206
253
  ): SignActionsContext {
207
254
  const ctx: SignActionsContext = { signers: descriptor.signers }
208
- if (this.sdkClient.userWallet !== undefined) {
209
- ctx.userWallet = this.sdkClient.userWallet
255
+ const wallet = userWallet ?? this.sdkClient.userWallet
256
+ if (wallet !== undefined) {
257
+ ctx.userWallet = wallet
210
258
  }
211
259
  return ctx
212
260
  }
@@ -217,14 +265,17 @@ export class PerpsClient {
217
265
  * consumers collect signed setup actions without embedding per-method
218
266
  * signing logic.
219
267
  *
268
+ * Returns `undefined` when the plugin executed the action entirely
269
+ * client-side (e.g. Lighter's token-authenticated venue mutations), leaving
270
+ * no backend-bound step to submit.
271
+ *
220
272
  * @throws {PerpsError} When the step's action is not declared by the provider.
221
- * @public
222
273
  */
223
- async signProviderSetupAction(
274
+ private async signProviderSetupAction(
224
275
  provider: string,
225
276
  address: Address,
226
277
  step: ActionStep
227
- ): Promise<SignedActionStep> {
278
+ ): Promise<SignedActionStep | undefined> {
228
279
  const metadata = await this.getProviderMetadata(provider)
229
280
  const descriptor = findActionDescriptor(metadata, step.action)
230
281
  const [signed] = await this.delegateSignActions(
@@ -404,10 +455,8 @@ export class PerpsClient {
404
455
  * caller / `signProviderSetupAction`). Routes the batch on the first step's
405
456
  * action and lets the plugin contribute that action's `signerAddress`.
406
457
  * Throws on any per-step venue rejection.
407
- *
408
- * @public
409
458
  */
410
- async executeProviderSetup(
459
+ private async executeProviderSetup(
411
460
  params: ExecuteProviderSetupParams
412
461
  ): Promise<ExecuteProviderSetupResult> {
413
462
  const { provider, address, setup, signedActions } = params
@@ -476,6 +525,14 @@ export class PerpsClient {
476
525
  }
477
526
 
478
527
  const signed = await this.signProviderSetupAction(provider, address, step)
528
+
529
+ // A client-executed setup action (Lighter SET_REFERRAL) produces no
530
+ // backend-bound step — it already ran during signing, so there is nothing
531
+ // to submit.
532
+ if (signed === undefined) {
533
+ return
534
+ }
535
+
479
536
  await this.executeProviderSetup({
480
537
  provider,
481
538
  address,
@@ -628,6 +685,28 @@ export class PerpsClient {
628
685
  })
629
686
  }
630
687
 
688
+ /**
689
+ * Move collateral between DEXes within the provider account. Convenience
690
+ * wrapper over {@link execute} with `ActionType.SEND_ASSET`; like
691
+ * {@link withdraw} it returns the raw {@link ExecuteActionResponse} and does
692
+ * not throw on a venue rejection.
693
+ *
694
+ * @throws {PerpsError} When the provider is unregistered or the action
695
+ * cannot be signed/submitted.
696
+ * @public
697
+ */
698
+ async sendAsset(
699
+ params: SendAssetActionParams
700
+ ): Promise<ExecuteActionResponse> {
701
+ const { provider, address, ...sendAsset } = params
702
+ return this.execute({
703
+ provider,
704
+ address,
705
+ action: ActionType.SEND_ASSET,
706
+ params: sendAsset,
707
+ })
708
+ }
709
+
631
710
  /**
632
711
  * Execute any action through the SDK's signing pipeline: fetch the unsigned
633
712
  * steps, delegate signing to the provider plugin (which branches on the
@@ -669,6 +748,13 @@ export class PerpsClient {
669
748
  actions
670
749
  )
671
750
 
751
+ // A plugin may execute an action entirely client-side (e.g. Lighter's
752
+ // token-authenticated venue mutations), leaving no backend-bound step. With
753
+ // nothing to submit, skip the `/executeAction` hop.
754
+ if (signedActions.length === 0) {
755
+ return { results: [] }
756
+ }
757
+
672
758
  return executeAction(this.sdkClient, {
673
759
  provider,
674
760
  address,
package/src/index.ts CHANGED
@@ -90,8 +90,6 @@ export {
90
90
  export type {
91
91
  BuildProviderSetupParams,
92
92
  CancelOrdersParams,
93
- ExecuteProviderSetupParams,
94
- ExecuteProviderSetupResult,
95
93
  GetAccountResult,
96
94
  GetSetupParams,
97
95
  ModifyOrdersParams,
@@ -109,6 +107,7 @@ export type {
109
107
  ProviderConfigs,
110
108
  RequestInterceptor,
111
109
  SDKRequestOptions,
110
+ SwitchChainHook,
112
111
  } from './types/config.js'
113
112
  export type {
114
113
  ActionSignerContribution,
@@ -21,15 +21,13 @@ export class AssetRegistry extends ReferenceDataRegistry<Asset> {
21
21
  return this.items
22
22
  }
23
23
 
24
- protected fetchItems(bypassHttpCache: boolean): Promise<Asset[]> {
24
+ protected fetchItems(): Promise<Asset[]> {
25
25
  const url = buildUrl(`${this.client.config.apiUrl}/assets`, {
26
26
  provider: this.provider,
27
27
  })
28
- return request<AssetsResponse>(
29
- this.client.config,
30
- url,
31
- bypassHttpCache ? { cache: 'no-cache' } : {}
32
- ).then((response) => response.assets)
28
+ return request<AssetsResponse>(this.client.config, url).then(
29
+ (response) => response.assets
30
+ )
33
31
  }
34
32
 
35
33
  protected keyOf(asset: Asset): string {
@@ -44,15 +44,13 @@ export class MarketRegistry extends ReferenceDataRegistry<Market> {
44
44
  return market
45
45
  }
46
46
 
47
- protected fetchItems(bypassHttpCache: boolean): Promise<Market[]> {
47
+ protected fetchItems(): Promise<Market[]> {
48
48
  const url = buildUrl(`${this.client.config.apiUrl}/markets`, {
49
49
  provider: this.provider,
50
50
  })
51
- return request<MarketsResponse>(
52
- this.client.config,
53
- url,
54
- bypassHttpCache ? { cache: 'no-cache' } : {}
55
- ).then((response) => response.markets)
51
+ return request<MarketsResponse>(this.client.config, url).then(
52
+ (response) => response.markets
53
+ )
56
54
  }
57
55
 
58
56
  protected keyOf(market: Market): string {
@@ -1,17 +1,13 @@
1
1
  import type { PerpsSDKClient } from '../types/provider.js'
2
2
 
3
- /** Minimum gap between unknown-id-triggered, HTTP-cache-bypassing refetches. */
4
- const REFRESH_COOLDOWN_MS = 60_000
5
-
6
3
  /**
7
4
  * Per-provider hash index over one of the provider's reference-data lists
8
5
  * (`/markets`, `/assets`), keyed by the list's own primary key.
9
6
  *
10
7
  * NOT a cache: it holds no freshness policy of its own. Every {@link sync}
11
8
  * refetches through the HTTP layer, whose `cache-control` headers decide
12
- * whether the response comes from disk or the network. A lookup miss
13
- * schedules a cooldown-gated background refetch that bypasses the HTTP
14
- * cache — the id may have listed after the cached snapshot.
9
+ * whether the response comes from disk or the network. A lookup miss warns
10
+ * once and returns `undefined`; the next {@link sync} reconciles the index.
15
11
  *
16
12
  * @internal
17
13
  */
@@ -20,7 +16,6 @@ export abstract class ReferenceDataRegistry<T> {
20
16
  private current: readonly T[] = []
21
17
  private inflight: Promise<readonly T[]> | undefined
22
18
  private warnedIds = new Set<string>()
23
- private refreshAfter = 0
24
19
 
25
20
  protected constructor(
26
21
  protected readonly client: PerpsSDKClient,
@@ -28,8 +23,8 @@ export abstract class ReferenceDataRegistry<T> {
28
23
  private readonly kind: string
29
24
  ) {}
30
25
 
31
- /** Fetch the provider's full list, bypassing the HTTP cache when asked. */
32
- protected abstract fetchItems(bypassHttpCache: boolean): Promise<T[]>
26
+ /** Fetch the provider's full list through the HTTP layer. */
27
+ protected abstract fetchItems(): Promise<T[]>
33
28
 
34
29
  /** The item's primary key — what {@link get} is keyed by. */
35
30
  protected abstract keyOf(item: T): string
@@ -41,7 +36,7 @@ export abstract class ReferenceDataRegistry<T> {
41
36
  */
42
37
  sync(): Promise<readonly T[]> {
43
38
  if (!this.inflight) {
44
- this.inflight = this.load(false).finally(() => {
39
+ this.inflight = this.load().finally(() => {
45
40
  this.inflight = undefined
46
41
  })
47
42
  }
@@ -53,10 +48,7 @@ export abstract class ReferenceDataRegistry<T> {
53
48
  return this.current
54
49
  }
55
50
 
56
- /**
57
- * O(1) lookup by primary key. A miss warns once per id and schedules the
58
- * cooldown-gated, cache-bypassing background refetch.
59
- */
51
+ /** O(1) lookup by primary key. A miss warns once per id. */
60
52
  get(id: string): T | undefined {
61
53
  const item = this.index.get(id)
62
54
  if (item !== undefined) {
@@ -66,30 +58,14 @@ export abstract class ReferenceDataRegistry<T> {
66
58
  this.warnedIds.add(id)
67
59
  console.warn(`[${this.provider}] unknown ${this.kind} id '${id}'`)
68
60
  }
69
- this.scheduleRefresh()
70
61
  return undefined
71
62
  }
72
63
 
73
- private async load(bypassHttpCache: boolean): Promise<readonly T[]> {
74
- const items = await this.fetchItems(bypassHttpCache)
64
+ private async load(): Promise<readonly T[]> {
65
+ const items = await this.fetchItems()
75
66
  this.index = new Map(items.map((item) => [this.keyOf(item), item]))
76
67
  this.current = items
77
68
  this.warnedIds.clear()
78
69
  return items
79
70
  }
80
-
81
- private scheduleRefresh(): void {
82
- const now = Date.now()
83
- if (now < this.refreshAfter) {
84
- return
85
- }
86
- // Set before any await so concurrent misses cannot trigger a refetch storm.
87
- this.refreshAfter = now + REFRESH_COOLDOWN_MS
88
- this.load(true).catch((error) =>
89
- console.error(
90
- `[${this.provider}] ${this.kind} registry refresh failed`,
91
- error
92
- )
93
- )
94
- }
95
71
  }
@@ -1,4 +1,6 @@
1
1
  import type { Market, MarketsResponse } from '@lifi/perps-types'
2
+ import { PerpsErrorCode } from '@lifi/perps-types'
3
+ import { PerpsError } from '../errors/PerpsError.js'
2
4
  import { buildUrl, request } from '../transport/request.js'
3
5
  import type { SDKRequestOptions } from '../types/config.js'
4
6
  import type { PerpsSDKClient } from '../types/provider.js'
@@ -21,10 +23,11 @@ export interface GetMarketParams {
21
23
  /**
22
24
  * Get a specific market by its opaque marketId. Requests the single market
23
25
  * from the backend `/markets` route (filtered by `marketIds`) and returns the
24
- * first match; the backend responds 404 (thrown as a {@link PerpsError}) when
25
- * nothing matches.
26
+ * first match; throws a `MarketNotFound` {@link PerpsError} both when the
27
+ * backend responds 404 and when it responds 200 with an empty list, matching
28
+ * `MarketRegistry.require`'s miss behaviour.
26
29
  *
27
- * @throws {PerpsError} On backend (e.g. 404), network, or parsing errors.
30
+ * @throws {PerpsError} On backend (e.g. 404 or empty match), network, or parsing errors.
28
31
  * @example
29
32
  * ```ts
30
33
  * const client = createPerpsClient({ integrator: 'my-app' })
@@ -48,5 +51,14 @@ export async function getMarket(
48
51
  {},
49
52
  options
50
53
  )
51
- return markets[0]
54
+ const market = markets[0]
55
+ if (market === undefined) {
56
+ const error = new PerpsError(
57
+ PerpsErrorCode.MarketNotFound,
58
+ `No ${params.provider} market found for marketId '${params.marketId}'`
59
+ )
60
+ error.tool = params.provider
61
+ throw error
62
+ }
63
+ return market
52
64
  }
package/src/types/api.ts CHANGED
@@ -14,7 +14,11 @@ import type {
14
14
  } from '@lifi/perps-types'
15
15
  import type { Account, Address, WalletClient } from 'viem'
16
16
  import type { RetryConfig } from '../transport/retryPolicy.js'
17
- import type { ProviderConfigs, RequestInterceptor } from './config.js'
17
+ import type {
18
+ ProviderConfigs,
19
+ RequestInterceptor,
20
+ SwitchChainHook,
21
+ } from './config.js'
18
22
  import type { PerpsProviderPlugin } from './provider.js'
19
23
 
20
24
  /**
@@ -85,6 +89,12 @@ export interface PerpsClientOptions {
85
89
  * a keyed `ProviderConfigs` map.
86
90
  */
87
91
  providers?: PerpsProviderPlugin[] | ProviderConfigs
92
+ /**
93
+ * Hook invoked before a USER-signed EIP-712 action is signed, to switch the
94
+ * user's wallet to the action's target chain. Also settable at runtime via
95
+ * `setSwitchChain`.
96
+ */
97
+ switchChain?: SwitchChainHook
88
98
  }
89
99
 
90
100
  /**
@@ -145,6 +155,22 @@ export interface WithdrawParams {
145
155
  withdrawal: WithdrawalParams
146
156
  }
147
157
 
158
+ /**
159
+ * Parameters for {@link PerpsClient.sendAsset}. The send-asset fields are held
160
+ * flat (not nested) to avoid colliding with `@lifi/perps-types`'
161
+ * `SendAssetParams`, which types the underlying action payload.
162
+ *
163
+ * @public
164
+ */
165
+ export interface SendAssetActionParams {
166
+ provider: string
167
+ address: Address
168
+ collateral: string
169
+ sourceDex: string
170
+ destinationDex: string
171
+ amount: string
172
+ }
173
+
148
174
  /**
149
175
  * Parameters for canceling orders.
150
176
  *
@@ -205,9 +231,7 @@ export interface ProviderSetup {
205
231
  }
206
232
 
207
233
  /**
208
- * Parameters for {@link PerpsClient.executeProviderSetup}.
209
- *
210
- * @public
234
+ * Parameters for the internal `PerpsClient.executeProviderSetup` batch submit.
211
235
  */
212
236
  export interface ExecuteProviderSetupParams {
213
237
  /** Provider to satisfy setup for */
@@ -221,9 +245,7 @@ export interface ExecuteProviderSetupParams {
221
245
  }
222
246
 
223
247
  /**
224
- * Result from {@link PerpsClient.executeProviderSetup}.
225
- *
226
- * @public
248
+ * Result from the internal `PerpsClient.executeProviderSetup` batch submit.
227
249
  */
228
250
  export interface ExecuteProviderSetupResult {
229
251
  results: ExecuteActionResponse
@@ -9,6 +9,20 @@ import type { RetryConfig } from '../transport/retryPolicy.js'
9
9
  */
10
10
  export type PerpsClientSigner = WalletClient<any, any, Account>
11
11
 
12
+ /**
13
+ * Consumer-supplied hook invoked at the SDK's signing choke point to switch the
14
+ * user's wallet to a USER-signed EIP-712 action's target chain. Modelled on
15
+ * `@lifi/sdk`'s switch-chain contract: a json-rpc wallet switches in place and
16
+ * resolves to the re-fetched client; a local/private-key signer resolves to a
17
+ * chain-bound client (or signs offline). Resolve to `undefined` to signal the
18
+ * switch could not be performed.
19
+ *
20
+ * @public
21
+ */
22
+ export type SwitchChainHook = (
23
+ chainId: number
24
+ ) => Promise<PerpsClientSigner | undefined>
25
+
12
26
  /**
13
27
  * Per-provider config — restricts which `markets` the WS client subscribes
14
28
  * to. Indexed by provider key.
@@ -13,11 +13,15 @@ const sumValueUsd = (balances: AccountResponse['balances']): number =>
13
13
  * positions' locked margin and unrealized PnL:
14
14
  *
15
15
  * - `'free'` — free collateral only; locked margin and unrealized PnL are
16
- * both carried by the positions.
16
+ * both carried by the positions. Available margin is the free collateral
17
+ * as-is; unrealized PnL is not counted toward it.
17
18
  * - `'gross'` — locked margin included, unrealized PnL carried by the
18
- * positions (e.g. spot holdings backing a unified account).
19
+ * positions (e.g. spot holdings backing a unified account). The venue
20
+ * counts unrealized PnL toward buying power, so it is added to available
21
+ * margin on top of the gross collateral.
19
22
  * - `'equity'` — total equity: locked margin AND unrealized PnL included
20
- * (e.g. a venue-reported account value).
23
+ * (e.g. a venue-reported account value). Unrealized PnL is thus already
24
+ * counted toward available margin.
21
25
  *
22
26
  * @public
23
27
  */
@@ -51,9 +55,15 @@ export function summarizeAccount(
51
55
  const equity =
52
56
  semantics === 'equity' ? grossCollateral : grossCollateral + unrealizedPnl
53
57
 
58
+ // Buying power is equity net of locked margin, so unrealized PnL counts
59
+ // toward it. The `'free'` rows exclude uPnL from available margin, holding
60
+ // it purely as free collateral.
61
+ const availableMargin =
62
+ semantics === 'free' ? grossCollateral - marginUsed : equity - marginUsed
63
+
54
64
  return {
55
65
  portfolioValue: (balances + equity).toString(),
56
- availableMargin: (grossCollateral - marginUsed).toString(),
66
+ availableMargin: availableMargin.toString(),
57
67
  marginUsed: marginUsed.toString(),
58
68
  unrealizedPnl: unrealizedPnl.toString(),
59
69
  }
@@ -0,0 +1,73 @@
1
+ import type {
2
+ ActionStep,
3
+ Eip712ActionStep,
4
+ ProviderAction,
5
+ } from '@lifi/perps-types'
6
+ import { PerpsErrorCode, PerpsSigner, SigningMethod } from '@lifi/perps-types'
7
+ import { getChainId } from 'viem/actions'
8
+ import { PerpsError } from '../errors/PerpsError.js'
9
+ import type { PerpsClientSigner, SwitchChainHook } from '../types/config.js'
10
+
11
+ /**
12
+ * The chain a batch of `actions` must be signed on, or `undefined` when no
13
+ * wallet chain switch applies. Only USER-signed EIP-712 batches carry a target
14
+ * (agent-signed batches sign with a chain-bound keypair; other schemes are not
15
+ * EIP-712). Reads the first numeric `typedData.domain.chainId`; a batch whose
16
+ * steps omit `chainId` yields `undefined`.
17
+ */
18
+ export function userEip712TargetChainId(
19
+ descriptor: ProviderAction,
20
+ actions: ActionStep[]
21
+ ): number | undefined {
22
+ if (
23
+ descriptor.signingMethod !== SigningMethod.EIP712 ||
24
+ !descriptor.signers.includes(PerpsSigner.USER)
25
+ ) {
26
+ return undefined
27
+ }
28
+ for (const step of actions) {
29
+ const chainId = (step as Eip712ActionStep).typedData?.domain?.chainId
30
+ if (typeof chainId === 'number') {
31
+ return chainId
32
+ }
33
+ }
34
+ return undefined
35
+ }
36
+
37
+ /**
38
+ * Ensure `wallet` is on `targetChainId` before signing, returning the wallet to
39
+ * sign with. Without a `switchChain` hook the wallet is returned unchanged (no
40
+ * throw, no RPC) — a local/private-key signer signs EIP-712 offline regardless
41
+ * of its transport chain. With a hook: probe the current chain via viem
42
+ * `getChainId`, return the wallet untouched when already on target, else invoke
43
+ * the hook and re-verify. Throws `PerpsErrorCode.SDKError` when the hook yields
44
+ * no client or a client still on the wrong chain.
45
+ */
46
+ export async function switchSigningChain(
47
+ wallet: PerpsClientSigner,
48
+ targetChainId: number,
49
+ switchChain?: SwitchChainHook
50
+ ): Promise<PerpsClientSigner> {
51
+ if (!switchChain) {
52
+ return wallet
53
+ }
54
+ const currentChainId = await getChainId(wallet)
55
+ if (currentChainId === targetChainId) {
56
+ return wallet
57
+ }
58
+ const switched = await switchChain(targetChainId)
59
+ if (!switched) {
60
+ throw new PerpsError(
61
+ PerpsErrorCode.SDKError,
62
+ `Wallet chain switch to ${targetChainId} was not completed.`
63
+ )
64
+ }
65
+ const switchedChainId = await getChainId(switched)
66
+ if (switchedChainId !== targetChainId) {
67
+ throw new PerpsError(
68
+ PerpsErrorCode.SDKError,
69
+ `Wallet is on chain ${switchedChainId} but chain ${targetChainId} is required to sign.`
70
+ )
71
+ }
72
+ return switched
73
+ }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export const name = '@lifi/perps-sdk'
2
- export const version = '0.0.0-preview-34f3bb2'
2
+ export const version = '0.0.0-preview-1ba1dc6'