@lifi/perps-sdk-provider-ondo 36.0.0 → 36.2.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 (72) hide show
  1. package/README.md +34 -9
  2. package/dist/cjs/OndoProvider.d.ts.map +1 -1
  3. package/dist/cjs/OndoProvider.js +7 -4
  4. package/dist/cjs/OndoProvider.js.map +1 -1
  5. package/dist/cjs/auth/OndoTokenStore.d.ts +1 -1
  6. package/dist/cjs/auth/OndoTokenStore.d.ts.map +1 -1
  7. package/dist/cjs/auth/OndoTokenStore.js +9 -2
  8. package/dist/cjs/auth/OndoTokenStore.js.map +1 -1
  9. package/dist/cjs/utils/buildFee.d.ts +4 -0
  10. package/dist/cjs/utils/buildFee.d.ts.map +1 -0
  11. package/dist/cjs/utils/buildFee.js +22 -0
  12. package/dist/cjs/utils/buildFee.js.map +1 -0
  13. package/dist/cjs/utils/fillLeverages.d.ts +4 -0
  14. package/dist/cjs/utils/fillLeverages.d.ts.map +1 -0
  15. package/dist/cjs/utils/fillLeverages.js +39 -0
  16. package/dist/cjs/utils/fillLeverages.js.map +1 -0
  17. package/dist/cjs/utils/mapFill.d.ts.map +1 -1
  18. package/dist/cjs/utils/mapFill.js +4 -7
  19. package/dist/cjs/utils/mapFill.js.map +1 -1
  20. package/dist/cjs/utils/mapPortfolioHistory.d.ts.map +1 -1
  21. package/dist/cjs/utils/mapPortfolioHistory.js +18 -3
  22. package/dist/cjs/utils/mapPortfolioHistory.js.map +1 -1
  23. package/dist/cjs/websocket/OndoWsProvider.d.ts +8 -1
  24. package/dist/cjs/websocket/OndoWsProvider.d.ts.map +1 -1
  25. package/dist/cjs/websocket/OndoWsProvider.js +122 -9
  26. package/dist/cjs/websocket/OndoWsProvider.js.map +1 -1
  27. package/dist/esm/OndoProvider.d.ts.map +1 -1
  28. package/dist/esm/OndoProvider.js +8 -5
  29. package/dist/esm/OndoProvider.js.map +1 -1
  30. package/dist/esm/auth/OndoTokenStore.d.ts +1 -1
  31. package/dist/esm/auth/OndoTokenStore.d.ts.map +1 -1
  32. package/dist/esm/auth/OndoTokenStore.js +9 -2
  33. package/dist/esm/auth/OndoTokenStore.js.map +1 -1
  34. package/dist/esm/utils/buildFee.d.ts +8 -0
  35. package/dist/esm/utils/buildFee.d.ts.map +1 -0
  36. package/dist/esm/utils/buildFee.js +22 -0
  37. package/dist/esm/utils/buildFee.js.map +1 -0
  38. package/dist/esm/utils/fillLeverages.d.ts +12 -0
  39. package/dist/esm/utils/fillLeverages.d.ts.map +1 -0
  40. package/dist/esm/utils/fillLeverages.js +43 -0
  41. package/dist/esm/utils/fillLeverages.js.map +1 -0
  42. package/dist/esm/utils/mapFill.d.ts +2 -1
  43. package/dist/esm/utils/mapFill.d.ts.map +1 -1
  44. package/dist/esm/utils/mapFill.js +7 -10
  45. package/dist/esm/utils/mapFill.js.map +1 -1
  46. package/dist/esm/utils/mapPortfolioHistory.d.ts.map +1 -1
  47. package/dist/esm/utils/mapPortfolioHistory.js +19 -4
  48. package/dist/esm/utils/mapPortfolioHistory.js.map +1 -1
  49. package/dist/esm/websocket/OndoWsProvider.d.ts +18 -2
  50. package/dist/esm/websocket/OndoWsProvider.d.ts.map +1 -1
  51. package/dist/esm/websocket/OndoWsProvider.js +136 -11
  52. package/dist/esm/websocket/OndoWsProvider.js.map +1 -1
  53. package/dist/types/OndoProvider.d.ts.map +1 -1
  54. package/dist/types/auth/OndoTokenStore.d.ts +1 -1
  55. package/dist/types/auth/OndoTokenStore.d.ts.map +1 -1
  56. package/dist/types/utils/buildFee.d.ts +8 -0
  57. package/dist/types/utils/buildFee.d.ts.map +1 -0
  58. package/dist/types/utils/fillLeverages.d.ts +12 -0
  59. package/dist/types/utils/fillLeverages.d.ts.map +1 -0
  60. package/dist/types/utils/mapFill.d.ts +2 -1
  61. package/dist/types/utils/mapFill.d.ts.map +1 -1
  62. package/dist/types/utils/mapPortfolioHistory.d.ts.map +1 -1
  63. package/dist/types/websocket/OndoWsProvider.d.ts +18 -2
  64. package/dist/types/websocket/OndoWsProvider.d.ts.map +1 -1
  65. package/package.json +3 -3
  66. package/src/OndoProvider.ts +15 -4
  67. package/src/auth/OndoTokenStore.ts +13 -2
  68. package/src/utils/buildFee.ts +35 -0
  69. package/src/utils/fillLeverages.ts +67 -0
  70. package/src/utils/mapFill.ts +27 -30
  71. package/src/utils/mapPortfolioHistory.ts +29 -4
  72. package/src/websocket/OndoWsProvider.ts +192 -12
@@ -1,4 +1,5 @@
1
1
  import {
2
+ buildFill,
2
3
  DecodeChain,
3
4
  getMarketRegistry,
4
5
  isDecimalString,
@@ -21,6 +22,7 @@ import {
21
22
  wsLog,
22
23
  } from '@lifi/perps-sdk'
23
24
  import {
25
+ type Fill,
24
26
  type MarketContext,
25
27
  type MarketDisplay,
26
28
  type OndoAccountBalance,
@@ -28,7 +30,7 @@ import {
28
30
  type PerpsMarketDisplay,
29
31
  type Subscription,
30
32
  } from '@lifi/perps-types'
31
- import type { Address } from 'viem'
33
+ import { type Address, isAddress } from 'viem'
32
34
  import { OndoTokenStore } from '../auth/OndoTokenStore.js'
33
35
  import { ondoSessionRejectedError } from '../auth/sessionToken.js'
34
36
  import {
@@ -51,6 +53,7 @@ import type {
51
53
  OndoWsMessage,
52
54
  OndoWsTrade,
53
55
  } from '../types/index.js'
56
+ import { fetchFillLeverages } from '../utils/fillLeverages.js'
54
57
  import {
55
58
  isOpenPosition,
56
59
  mapFill,
@@ -90,6 +93,9 @@ const ONDO_AUTH_FANOUT: readonly string[] = [
90
93
  'accountSummary',
91
94
  ]
92
95
 
96
+ /** Bound on the venue's answer to a `login` op. An unmapped error leaves no other exit. */
97
+ const ONDO_LOGIN_ACK_TIMEOUT_MS = 10_000
98
+
93
99
  const isAuthChannel = (
94
100
  channel: Subscription['channel']
95
101
  ): channel is AuthChannel => channel in ONDO_AUTH_CHANNEL
@@ -159,6 +165,11 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
159
165
  wsLog.handlerFailure(this.providerKey, err)
160
166
  )
161
167
 
168
+ // A closing fill waits for a leverage read, so fills frames emit in order.
169
+ private readonly fillChain = new DecodeChain('every', (err) =>
170
+ wsLog.handlerFailure(this.providerKey, err)
171
+ )
172
+
162
173
  /** Complete (mark-price-bearing) contexts, keyed by venue market symbol. */
163
174
  private contexts: Record<string, MarketContext> = {}
164
175
  /** Funding seen before the market's first mark price. */
@@ -170,6 +181,17 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
170
181
  /** The single address this connection's login is bound to. */
171
182
  private accountAddress: string | undefined
172
183
  private loginPromise: Promise<void> | undefined
184
+ private loginAttempt:
185
+ | {
186
+ address: Address
187
+ token: string
188
+ accepted: boolean
189
+ timer: ReturnType<typeof setTimeout>
190
+ resolve: () => void
191
+ reject: (error: unknown) => void
192
+ }
193
+ | undefined
194
+ private readonly rejectedTokens = new Set<string>()
173
195
  private authGeneration = 0
174
196
  private authBindingRefs = 0
175
197
  private closeGeneration = 0
@@ -194,6 +216,9 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
194
216
  // The venue's login lives and dies with the connection, so a drop must
195
217
  // forget both the in-flight login and the address it bound.
196
218
  this.rws.on('close', () => {
219
+ this.takeLoginAttempt()?.reject(
220
+ new Error('Ondo WebSocket closed during login')
221
+ )
197
222
  this.loginPromise = undefined
198
223
  this.accountAddress = undefined
199
224
  })
@@ -387,24 +412,49 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
387
412
  if (bound === undefined) {
388
413
  return true
389
414
  }
390
- for (const channel of ONDO_AUTH_FANOUT) {
391
- if (!this.closeChannelIfIdle(`${channel}:${bound}`)) {
415
+ for (const key of this.authChannelKeys(bound)) {
416
+ if (!this.closeChannelIfIdle(key)) {
392
417
  return false
393
418
  }
394
419
  }
395
420
  return true
396
421
  }
397
422
 
398
- /** Release a channel's binding reservation, including one still opening. */
423
+ /**
424
+ * Release a channel's binding reservation, including one still opening.
425
+ * The last release cycles the connection only when a login was sent on it,
426
+ * because the venue holds that login until the socket closes.
427
+ */
399
428
  private releaseBinding(): void {
400
429
  this.authBindingRefs -= 1
401
430
  if (this.authBindingRefs > 0) {
402
431
  return
403
432
  }
404
433
  this.accountAddress = undefined
434
+ const login = this.loginPromise
405
435
  this.loginPromise = undefined
406
436
  this.authGeneration += 1
407
- this.rws.reconnect()
437
+ if (login !== undefined) {
438
+ this.rws.reconnect()
439
+ }
440
+ }
441
+
442
+ private authChannelKeys(address: string): string[] {
443
+ return ONDO_AUTH_FANOUT.map((channel) => `${channel}:${address}`)
444
+ }
445
+
446
+ /**
447
+ * The venue login is per connection, so one credential failure stops every
448
+ * private channel of the address.
449
+ */
450
+ protected override resolveChannelKeys(
451
+ key: string,
452
+ state: SubState
453
+ ): string[] {
454
+ if (!state.needsAuth || state.address === undefined) {
455
+ return super.resolveChannelKeys(key, state)
456
+ }
457
+ return this.authChannelKeys(state.address.toLowerCase())
408
458
  }
409
459
 
410
460
  /** Register a wire sub, ref-counting the shared authenticated channels. */
@@ -473,12 +523,16 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
473
523
  this.contexts = {}
474
524
  this.pendingFunding.clear()
475
525
  this.loginPromise = undefined
526
+ this.takeLoginAttempt()?.reject(
527
+ new Error('Ondo WebSocket closed during login')
528
+ )
476
529
  this.accountAddress = undefined
477
530
  this.authGeneration += 1
478
531
  this.closeGeneration += 1
479
532
  this.authWireRefs.clear()
480
533
  this.authBindingRefs = 0
481
534
  this.clearAccountSummary()
535
+ this.fillChain.reset()
482
536
  }
483
537
 
484
538
  /** Wire subs for `sub`, keyed uniquely for the base's replay registry. */
@@ -602,6 +656,12 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
602
656
  `No Ondo session for ${address}. Run the SIWE login before subscribing to account channels.`
603
657
  )
604
658
  }
659
+ if (this.rejectedTokens.has(token.token)) {
660
+ throw ondoSessionRejectedError(
661
+ 'WebSocket subscription',
662
+ new OndoSessionExpiredError('Ondo rejected the session token')
663
+ )
664
+ }
605
665
  return token
606
666
  }
607
667
 
@@ -614,11 +674,36 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
614
674
  if (this.loginPromise === undefined) {
615
675
  const login: Promise<void> = this.requireSession(address).then(
616
676
  (token) => {
617
- if (this.loginPromise === login) {
677
+ if (this.loginPromise !== login) {
678
+ return
679
+ }
680
+ return new Promise<void>((resolve, reject) => {
618
681
  this.rws.send(
619
682
  JSON.stringify({ op: 'login', args: { token: token.token } })
620
683
  )
621
- }
684
+ const attempt = {
685
+ address,
686
+ token: token.token,
687
+ accepted: false,
688
+ timer: setTimeout(() => {
689
+ if (this.loginAttempt !== attempt) {
690
+ return
691
+ }
692
+ this.rejectLogin(
693
+ new PerpsError(
694
+ PerpsErrorCode.TimeoutError,
695
+ 'Ondo did not acknowledge the WebSocket login.'
696
+ ),
697
+ false
698
+ )
699
+ // The venue may still hold a half-open login on this socket.
700
+ this.rws.reconnect()
701
+ }, ONDO_LOGIN_ACK_TIMEOUT_MS),
702
+ resolve,
703
+ reject,
704
+ }
705
+ this.loginAttempt = attempt
706
+ })
622
707
  }
623
708
  )
624
709
  this.loginPromise = login
@@ -631,8 +716,9 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
631
716
  return this.loginPromise
632
717
  }
633
718
 
634
- private restClient(): OndoApiClient {
719
+ private restClient(signal?: AbortSignal): OndoApiClient {
635
720
  return new OndoApiClient(this.apiUrl, {
721
+ signal,
636
722
  fetchImpl: this.client?.config.fetch,
637
723
  })
638
724
  }
@@ -708,7 +794,7 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
708
794
  if (!(err instanceof OndoSessionExpiredError)) {
709
795
  throw err
710
796
  }
711
- await this.tokenStore.remove(address)
797
+ await this.tokenStore.remove(address, token.token)
712
798
  throw ondoSessionRejectedError('account summary', err)
713
799
  }
714
800
  return {
@@ -738,6 +824,50 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
738
824
  })
739
825
  }
740
826
 
827
+ /** Detach the pending login attempt, if any, and stop its acknowledgement timer. */
828
+ private takeLoginAttempt(): typeof this.loginAttempt {
829
+ const attempt = this.loginAttempt
830
+ if (attempt !== undefined) {
831
+ clearTimeout(attempt.timer)
832
+ this.loginAttempt = undefined
833
+ }
834
+ return attempt
835
+ }
836
+
837
+ private rejectLogin(error: PerpsError, unauthorized: boolean): void {
838
+ const attempt = this.takeLoginAttempt()
839
+ if (attempt === undefined) {
840
+ wsLog.serverError(
841
+ this.providerKey,
842
+ `Login error without a pending login: ${error.message}`
843
+ )
844
+ return
845
+ }
846
+ this.loginPromise = undefined
847
+ const address = attempt.address.toLowerCase()
848
+ if (unauthorized) {
849
+ this.rejectedTokens.add(attempt.token)
850
+ void this.tokenStore
851
+ .remove(attempt.address, attempt.token)
852
+ .catch((cause) => wsLog.handlerFailure(this.providerKey, cause))
853
+ }
854
+ for (const [key, state] of this.wireSubs) {
855
+ if (state.needsAuth) {
856
+ this.unregisterSub(key)
857
+ this.rws.send(JSON.stringify({ op: 'unsubscribe', ...state.frame }))
858
+ }
859
+ }
860
+ this.authWireRefs.clear()
861
+ this.authBindingRefs = 0
862
+ this.authGeneration += 1
863
+ this.accountAddress = undefined
864
+ this.clearAccountSummary()
865
+ attempt.reject(error)
866
+ for (const key of this.authChannelKeys(address)) {
867
+ this.rejectChannel(key, error)
868
+ }
869
+ }
870
+
741
871
  protected handleMessage(raw: string): void {
742
872
  let msg: OndoWsMessage
743
873
  try {
@@ -746,8 +876,38 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
746
876
  wsLog.parseFailure(this.providerKey, raw)
747
877
  return
748
878
  }
879
+ if (msg.type === 'loggedIn') {
880
+ if (this.loginAttempt !== undefined) {
881
+ clearTimeout(this.loginAttempt.timer)
882
+ this.loginAttempt.accepted = true
883
+ this.loginAttempt.resolve()
884
+ }
885
+ return
886
+ }
749
887
  if (msg.type === 'error') {
750
- wsLog.serverError(this.providerKey, msg.msg ?? 'unknown error')
888
+ if (msg.msg?.startsWith('error parsing jwt: ')) {
889
+ this.rejectLogin(
890
+ ondoSessionRejectedError(
891
+ 'WebSocket subscription',
892
+ new OndoSessionExpiredError('Ondo rejected the session token')
893
+ ),
894
+ true
895
+ )
896
+ return
897
+ }
898
+ if (
899
+ this.loginAttempt !== undefined &&
900
+ !this.loginAttempt.accepted &&
901
+ (msg.msg === 'already logged in on this connection' ||
902
+ msg.msg === 'account already has too many connections')
903
+ ) {
904
+ this.rejectLogin(
905
+ new PerpsError(PerpsErrorCode.ThirdPartyError, msg.msg),
906
+ false
907
+ )
908
+ return
909
+ }
910
+ wsLog.serverError(this.providerKey, 'Venue rejected a WebSocket request')
751
911
  return
752
912
  }
753
913
  if (msg.type !== 'update') {
@@ -957,7 +1117,7 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
957
1117
  if (address === undefined) {
958
1118
  return
959
1119
  }
960
- const mapped = []
1120
+ const mapped: Fill[] = []
961
1121
  for (const fill of fills) {
962
1122
  const market = this.resolveMarket(fill.market)
963
1123
  const mappedFill = market && mapFill(fill, market)
@@ -965,7 +1125,27 @@ export class OndoWsProvider extends WsProviderBase<SubState> {
965
1125
  mapped.push(mappedFill)
966
1126
  }
967
1127
  }
968
- this.emit(`fills:${address}`, { channel: 'fills', data: mapped })
1128
+ this.fillChain.push(async () => {
1129
+ const leverages = isAddress(address, { strict: false })
1130
+ ? await this.readFrameEnrichment('fill leverage', async (signal) => {
1131
+ const token = await this.tokenStore.get(address)
1132
+ return token === null
1133
+ ? undefined
1134
+ : fetchFillLeverages(
1135
+ this.restClient(signal),
1136
+ token.token,
1137
+ mapped,
1138
+ signal
1139
+ )
1140
+ })
1141
+ : undefined
1142
+ this.emit(`fills:${address}`, {
1143
+ channel: 'fills',
1144
+ data: mapped.map((fill) =>
1145
+ buildFill(fill, leverages?.get(fill.market.id))
1146
+ ),
1147
+ })
1148
+ })
969
1149
  if (this.accountSummary !== undefined) {
970
1150
  const generation = this.accountSummaryGeneration
971
1151
  this.accountSummaryChain.push(() =>