@polyester/sdk 0.30.1 → 0.31.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 (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/browser-core.d.ts.map +1 -1
  3. package/dist/browser-core.js +24 -2
  4. package/dist/browser-core.js.map +1 -1
  5. package/dist/catalogs/snapshot-validation.js +6 -1
  6. package/dist/catalogs/snapshot-validation.js.map +1 -1
  7. package/dist/catalogs/zipper-supply.d.ts.map +1 -1
  8. package/dist/catalogs/zipper-supply.js +3 -3
  9. package/dist/catalogs/zipper-supply.js.map +1 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +2 -2
  12. package/dist/realtime/snapshot-then-stream.js +1 -1
  13. package/dist/realtime/snapshot-then-stream.js.map +1 -1
  14. package/dist/services/address-book/address-book.schemas.d.ts +2 -2
  15. package/dist/services/auth/account-signer-auth.d.ts +6 -0
  16. package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
  17. package/dist/services/auth/account-signer-auth.js +19 -0
  18. package/dist/services/auth/account-signer-auth.js.map +1 -1
  19. package/dist/services/candles/candles.schemas.d.ts +10 -10
  20. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  21. package/dist/services/lifecycle/lifecycle.schemas.d.ts +42 -42
  22. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  23. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  24. package/dist/services/orders/order-errors.schemas.d.ts +1 -1
  25. package/dist/services/orders/orders-batch.schemas.d.ts +32 -32
  26. package/dist/services/orders/orders-input.schemas.d.ts +3 -3
  27. package/dist/services/orders/orders-output.schemas.d.ts +6 -6
  28. package/dist/services/subaccounts/subaccounts.schemas.d.ts +11 -11
  29. package/dist/services/trades/trades.schemas.d.ts +1 -1
  30. package/dist/services/trading-withdraws/trading-withdraws.d.ts +7 -0
  31. package/dist/services/trading-withdraws/trading-withdraws.d.ts.map +1 -1
  32. package/dist/services/trading-withdraws/trading-withdraws.js +13 -4
  33. package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
  34. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  35. package/dist/services/triggers/triggers-output.schemas.d.ts +15 -15
  36. package/dist/services/whiteboard/whiteboard.schemas.d.ts +49 -49
  37. package/dist/shared/errors.d.ts +21 -3
  38. package/dist/shared/errors.d.ts.map +1 -1
  39. package/dist/shared/errors.js +17 -1
  40. package/dist/shared/errors.js.map +1 -1
  41. package/dist/shared/rate-limit.schemas.d.ts +1 -1
  42. package/dist/shared/subscription-errors.d.ts +6 -6
  43. package/dist/shared/subscription-errors.d.ts.map +1 -1
  44. package/dist/shared/subscription-errors.js +20 -29
  45. package/dist/shared/subscription-errors.js.map +1 -1
  46. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @polyester/sdk
2
2
 
3
+ ## 0.31.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Realtime `onError` contexts now always carry an `Error`. Server and websocket failures arrive as the new `RealtimeError` (code `REALTIME_ERROR`) with the Centrifugo code on `realtimeCode`, instead of plain `{ code, message }` objects. `retryable` is true for errors the realtime client is already retrying on its own, such as code 109 (token expired), so callers can skip reporting them. Snapshot failures keep their original typed SDK error. ([#193](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/193))
8
+
9
+ Browser clients end the session and emit `loggedOut` when an authenticated RPC is rejected as unauthenticated with the current token, for example when the backend revoked it or the device clock lags. Rejections of a token that has since been replaced, and those arriving while a login or refresh is in flight, are ignored. `AccountSignerAuthService.handleRejectedToken` exposes the same check.
10
+
11
+ `PreparedTradingWithdraw` exposes the signed `deadline` and `isExpired()`, which turns true a minute before the deadline. Prepare again before resubmitting an expired withdraw, for example after a slow MFA enrollment.
12
+
13
+ ## 0.30.2
14
+
15
+ ### Patch Changes
16
+
17
+ - `patchZipperCatalogSupply` caches the snapshot it returns as already validated, so passing it to `catalog.setSnapshot` no longer re-validates the whole catalog on every supply update. ([#191](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/191))
18
+
3
19
  ## 0.30.1
4
20
 
5
21
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"browser-core.d.ts","names":[],"sources":["../src/browser-core.ts"],"mappings":";;;;;;KAeK,wBAAwB,WAAW,gBAAgB,4BAClD,KAAK;;KAIC,+BAA+B,wBAAwB;;;;;EAK/D,gBAAgB;;;;;EAKhB,eAAe;;;;;;;cAQN,6BAA6B;MAIzB,QAAQ;EAIT,YAAA,QAAQ;;;;;YA0CD,4BAA4B;;;;EAiB/C,iBAAiB,eAAe"}
1
+ {"version":3,"file":"browser-core.d.ts","names":[],"sources":["../src/browser-core.ts"],"mappings":";;;;;;KA2CK,wBAAwB,WAAW,gBAAgB,4BAClD,KAAK;;KAIC,+BAA+B,wBAAwB;;;;;EAK/D,gBAAgB;;;;;EAKhB,eAAe;;;;;;;cAQN,6BAA6B;MAIzB,QAAQ;EAIT,YAAA,QAAQ;;;;;YA8CD,4BAA4B;;;;EAiB/C,iBAAiB,eAAe"}
@@ -1,9 +1,30 @@
1
+ import { AuthenticationError } from "./shared/errors.js";
2
+ import { loadErrorDetailDecoders } from "./shared/error-detail.js";
3
+ import { toPolyesterError } from "./shared/connect-error-mapping.js";
1
4
  import { PolyesterCore, parsePolyesterClientConfig, pickPolyesterCatalogConfig } from "./core-client.js";
2
5
  import { AuthSessionStore } from "./services/auth/session.js";
3
6
  import { createMemoryAuthTokenStorage } from "./services/auth/token-storage.js";
4
7
  import { AccountSignerAuthService } from "./services/auth/account-signer-auth.js";
5
8
  //#region src/browser-core.ts
6
9
  /**
10
+ * Ends the session when the backend rejects the bearer token a request actually sent.
11
+ * Sits just inside the JWT auth interceptor so it sees the attached header.
12
+ */
13
+ function createRejectedTokenInterceptor(getAuth) {
14
+ return (next) => async (req) => {
15
+ try {
16
+ return await next(req);
17
+ } catch (error) {
18
+ const token = req.header.get("Authorization")?.replace(/^Bearer /u, "");
19
+ if (token) {
20
+ await loadErrorDetailDecoders(error);
21
+ if (toPolyesterError(error) instanceof AuthenticationError) getAuth()?.handleRejectedToken(token);
22
+ }
23
+ throw error;
24
+ }
25
+ };
26
+ }
27
+ /**
7
28
  * Tree-shakable browser client core: account-signer auth plus transports, realtime,
8
29
  * and catalogs. Reach other services through `@polyester/sdk/services/*` accessors,
9
30
  * or use `PolyesterBrowserClient` for a getter per service.
@@ -17,9 +38,10 @@ var PolyesterBrowserCore = class extends PolyesterCore {
17
38
  const tokenStorage = config.tokenStorage ?? createMemoryAuthTokenStorage();
18
39
  const sessionStore = new AuthSessionStore({ environmentFingerprint: config.environment.fingerprint });
19
40
  const getToken = () => sessionStore.getEnvironmentBoundToken(tokenStorage);
41
+ let auth;
20
42
  super({
21
43
  environment: config.environment,
22
- interceptors: config.interceptors,
44
+ interceptors: [createRejectedTokenInterceptor(() => auth), ...config.interceptors ?? []],
23
45
  auth: {
24
46
  kind: "jwt",
25
47
  getToken
@@ -33,7 +55,7 @@ var PolyesterBrowserCore = class extends PolyesterCore {
33
55
  hasAuth: () => !!getToken(),
34
56
  ...config.realtime
35
57
  }
36
- }, { createAuth: ({ transports, realtime, loadSubaccounts, environment }) => new AccountSignerAuthService({
58
+ }, { createAuth: ({ transports, realtime, loadSubaccounts, environment }) => auth = new AccountSignerAuthService({
37
59
  transports,
38
60
  accountSignerConfig: config.accountSigner,
39
61
  environment,
@@ -1 +1 @@
1
- {"version":3,"file":"browser-core.js","names":[],"sources":["../src/browser-core.ts"],"sourcesContent":["import {\n parsePolyesterClientConfig,\n pickPolyesterCatalogConfig,\n PolyesterCore,\n type PolyesterClientBaseConfig,\n} from \"./core-client.js\";\nimport { AccountSignerAuthService } from \"./services/auth/account-signer-auth.js\";\nimport type { AccountSignerConfig, AccountSigner } from \"./account-signer/types.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport {\n createMemoryAuthTokenStorage,\n type AuthTokenStorage,\n} from \"./services/auth/token-storage.js\";\nimport { AuthSessionStore } from \"./services/auth/session.js\";\n\ntype BrowserClientBaseConfig<TConfig> = TConfig extends PolyesterClientBaseConfig\n ? Omit<TConfig, \"auth\">\n : never;\n\n/** Configuration for the browser Polyester client. */\nexport type PolyesterBrowserClientConfig = BrowserClientBaseConfig<PolyesterClientBaseConfig> & {\n /**\n * Account signer interface for authentication.\n * Pass a signer object or a factory function for lazy initialization.\n */\n accountSigner?: AccountSignerConfig;\n /**\n * Storage for browser bearer tokens. Defaults to per-client memory storage.\n * Use createCookieAuthTokenStorage() to opt into reload/SSR persistence.\n */\n tokenStorage?: AuthTokenStorage;\n};\n\n/**\n * Tree-shakable browser client core: account-signer auth plus transports, realtime,\n * and catalogs. Reach other services through `@polyester/sdk/services/*` accessors,\n * or use `PolyesterBrowserClient` for a getter per service.\n */\nexport class PolyesterBrowserCore extends PolyesterCore {\n // The base class builds `auth` through the `createAuth` runtime factory we\n // pass below, so the lazily-constructed instance is always an\n // AccountSignerAuthService — this override only narrows the type.\n override get auth(): AccountSignerAuthService {\n return super.auth as AccountSignerAuthService;\n }\n\n constructor(config: PolyesterBrowserClientConfig) {\n config = parsePolyesterClientConfig(config);\n const tokenStorage = config.tokenStorage ?? createMemoryAuthTokenStorage();\n const sessionStore = new AuthSessionStore({\n environmentFingerprint: config.environment.fingerprint,\n });\n const getToken = () => sessionStore.getEnvironmentBoundToken(tokenStorage);\n\n super(\n {\n environment: config.environment,\n interceptors: config.interceptors,\n auth: { kind: \"jwt\", getToken },\n wireFormat: config.wireFormat,\n fetch: config.fetch,\n ...pickPolyesterCatalogConfig(config),\n transports: config.transports,\n realtimeClient: config.realtimeClient,\n realtime: {\n hasAuth: () => !!getToken(),\n ...config.realtime,\n },\n },\n {\n createAuth: ({ transports, realtime, loadSubaccounts, environment }) =>\n new AccountSignerAuthService({\n transports,\n accountSignerConfig: config.accountSigner,\n environment,\n subaccounts: loadSubaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n }),\n },\n );\n }\n\n /**\n * Creates a resolver that defaults subaccountId to the active subaccount.\n * The getter is called lazily when service methods are invoked.\n */\n protected override createSubaccountResolver(): SubaccountResolver {\n return {\n getDefaultSubaccountId: () => {\n const state = this.auth.getState();\n if (state.activeAccount && !state.activeAccount.isMain) {\n return state.activeAccount.accountId;\n }\n return null;\n },\n getActiveAccountId: () => this.auth.getState().activeAccount?.accountId ?? null,\n getMainAccountId: () => this.auth.getState().mainAccountId ?? null,\n };\n }\n\n /**\n * Sets the account signer used for authenticated browser requests.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n this.auth.setAccountSigner(accountSigner);\n }\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,uBAAb,cAA0C,cAAc;CAIpD,IAAa,OAAiC;EAC1C,OAAO,MAAM;CACjB;CAEA,YAAY,QAAsC;EAC9C,SAAS,2BAA2B,MAAM;EAC1C,MAAM,eAAe,OAAO,gBAAgB,6BAA6B;EACzE,MAAM,eAAe,IAAI,iBAAiB,EACtC,wBAAwB,OAAO,YAAY,YAC/C,CAAC;EACD,MAAM,iBAAiB,aAAa,yBAAyB,YAAY;EAEzE,MACI;GACI,aAAa,OAAO;GACpB,cAAc,OAAO;GACrB,MAAM;IAAE,MAAM;IAAO;GAAS;GAC9B,YAAY,OAAO;GACnB,OAAO,OAAO;GACd,GAAG,2BAA2B,MAAM;GACpC,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB,UAAU;IACN,eAAe,CAAC,CAAC,SAAS;IAC1B,GAAG,OAAO;GACd;EACJ,GACA,EACI,aAAa,EAAE,YAAY,UAAU,iBAAiB,kBAClD,IAAI,yBAAyB;GACzB;GACA,qBAAqB,OAAO;GAC5B;GACA,aAAa;GACb;GACA;GACA;EACJ,CAAC,EACT,CACJ;CACJ;;;;;CAMA,2BAAkE;EAC9D,OAAO;GACH,8BAA8B;IAC1B,MAAM,QAAQ,KAAK,KAAK,SAAS;IACjC,IAAI,MAAM,iBAAiB,CAAC,MAAM,cAAc,QAC5C,OAAO,MAAM,cAAc;IAE/B,OAAO;GACX;GACA,0BAA0B,KAAK,KAAK,SAAS,CAAC,CAAC,eAAe,aAAa;GAC3E,wBAAwB,KAAK,KAAK,SAAS,CAAC,CAAC,iBAAiB;EAClE;CACJ;;;;CAKA,iBAAiB,eAA2C;EACxD,KAAK,KAAK,iBAAiB,aAAa;CAC5C;AACJ"}
1
+ {"version":3,"file":"browser-core.js","names":[],"sources":["../src/browser-core.ts"],"sourcesContent":["import {\n parsePolyesterClientConfig,\n pickPolyesterCatalogConfig,\n PolyesterCore,\n type PolyesterClientBaseConfig,\n} from \"./core-client.js\";\nimport { AccountSignerAuthService } from \"./services/auth/account-signer-auth.js\";\nimport type { AccountSignerConfig, AccountSigner } from \"./account-signer/types.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport {\n createMemoryAuthTokenStorage,\n type AuthTokenStorage,\n} from \"./services/auth/token-storage.js\";\nimport { AuthSessionStore } from \"./services/auth/session.js\";\nimport type { Interceptor } from \"@connectrpc/connect\";\nimport { toPolyesterError } from \"./shared/connect-error-mapping.js\";\nimport { loadErrorDetailDecoders } from \"./shared/error-detail.js\";\nimport { AuthenticationError } from \"./shared/errors.js\";\n\n/**\n * Ends the session when the backend rejects the bearer token a request actually sent.\n * Sits just inside the JWT auth interceptor so it sees the attached header.\n */\nfunction createRejectedTokenInterceptor(\n getAuth: () => AccountSignerAuthService | undefined,\n): Interceptor {\n return (next) => async (req) => {\n try {\n return await next(req);\n } catch (error) {\n const token = req.header.get(\"Authorization\")?.replace(/^Bearer /u, \"\");\n if (token) {\n // Decoders let MFA and other auth-detail rejections map to their own classes.\n await loadErrorDetailDecoders(error);\n if (toPolyesterError(error) instanceof AuthenticationError) {\n getAuth()?.handleRejectedToken(token);\n }\n }\n throw error;\n }\n };\n}\n\ntype BrowserClientBaseConfig<TConfig> = TConfig extends PolyesterClientBaseConfig\n ? Omit<TConfig, \"auth\">\n : never;\n\n/** Configuration for the browser Polyester client. */\nexport type PolyesterBrowserClientConfig = BrowserClientBaseConfig<PolyesterClientBaseConfig> & {\n /**\n * Account signer interface for authentication.\n * Pass a signer object or a factory function for lazy initialization.\n */\n accountSigner?: AccountSignerConfig;\n /**\n * Storage for browser bearer tokens. Defaults to per-client memory storage.\n * Use createCookieAuthTokenStorage() to opt into reload/SSR persistence.\n */\n tokenStorage?: AuthTokenStorage;\n};\n\n/**\n * Tree-shakable browser client core: account-signer auth plus transports, realtime,\n * and catalogs. Reach other services through `@polyester/sdk/services/*` accessors,\n * or use `PolyesterBrowserClient` for a getter per service.\n */\nexport class PolyesterBrowserCore extends PolyesterCore {\n // The base class builds `auth` through the `createAuth` runtime factory we\n // pass below, so the lazily-constructed instance is always an\n // AccountSignerAuthService — this override only narrows the type.\n override get auth(): AccountSignerAuthService {\n return super.auth as AccountSignerAuthService;\n }\n\n constructor(config: PolyesterBrowserClientConfig) {\n config = parsePolyesterClientConfig(config);\n const tokenStorage = config.tokenStorage ?? createMemoryAuthTokenStorage();\n const sessionStore = new AuthSessionStore({\n environmentFingerprint: config.environment.fingerprint,\n });\n const getToken = () => sessionStore.getEnvironmentBoundToken(tokenStorage);\n let auth: AccountSignerAuthService | undefined;\n\n super(\n {\n environment: config.environment,\n interceptors: [\n createRejectedTokenInterceptor(() => auth),\n ...(config.interceptors ?? []),\n ],\n auth: { kind: \"jwt\", getToken },\n wireFormat: config.wireFormat,\n fetch: config.fetch,\n ...pickPolyesterCatalogConfig(config),\n transports: config.transports,\n realtimeClient: config.realtimeClient,\n realtime: {\n hasAuth: () => !!getToken(),\n ...config.realtime,\n },\n },\n {\n createAuth: ({ transports, realtime, loadSubaccounts, environment }) =>\n (auth = new AccountSignerAuthService({\n transports,\n accountSignerConfig: config.accountSigner,\n environment,\n subaccounts: loadSubaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n })),\n },\n );\n }\n\n /**\n * Creates a resolver that defaults subaccountId to the active subaccount.\n * The getter is called lazily when service methods are invoked.\n */\n protected override createSubaccountResolver(): SubaccountResolver {\n return {\n getDefaultSubaccountId: () => {\n const state = this.auth.getState();\n if (state.activeAccount && !state.activeAccount.isMain) {\n return state.activeAccount.accountId;\n }\n return null;\n },\n getActiveAccountId: () => this.auth.getState().activeAccount?.accountId ?? null,\n getMainAccountId: () => this.auth.getState().mainAccountId ?? null,\n };\n }\n\n /**\n * Sets the account signer used for authenticated browser requests.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n this.auth.setAccountSigner(accountSigner);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,SAAS,+BACL,SACW;CACX,QAAQ,SAAS,OAAO,QAAQ;EAC5B,IAAI;GACA,OAAO,MAAM,KAAK,GAAG;EACzB,SAAS,OAAO;GACZ,MAAM,QAAQ,IAAI,OAAO,IAAI,eAAe,CAAC,EAAE,QAAQ,aAAa,EAAE;GACtE,IAAI,OAAO;IAEP,MAAM,wBAAwB,KAAK;IACnC,IAAI,iBAAiB,KAAK,aAAa,qBACnC,QAAQ,CAAC,EAAE,oBAAoB,KAAK;GAE5C;GACA,MAAM;EACV;CACJ;AACJ;;;;;;AAyBA,IAAa,uBAAb,cAA0C,cAAc;CAIpD,IAAa,OAAiC;EAC1C,OAAO,MAAM;CACjB;CAEA,YAAY,QAAsC;EAC9C,SAAS,2BAA2B,MAAM;EAC1C,MAAM,eAAe,OAAO,gBAAgB,6BAA6B;EACzE,MAAM,eAAe,IAAI,iBAAiB,EACtC,wBAAwB,OAAO,YAAY,YAC/C,CAAC;EACD,MAAM,iBAAiB,aAAa,yBAAyB,YAAY;EACzE,IAAI;EAEJ,MACI;GACI,aAAa,OAAO;GACpB,cAAc,CACV,qCAAqC,IAAI,GACzC,GAAI,OAAO,gBAAgB,CAAC,CAChC;GACA,MAAM;IAAE,MAAM;IAAO;GAAS;GAC9B,YAAY,OAAO;GACnB,OAAO,OAAO;GACd,GAAG,2BAA2B,MAAM;GACpC,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB,UAAU;IACN,eAAe,CAAC,CAAC,SAAS;IAC1B,GAAG,OAAO;GACd;EACJ,GACA,EACI,aAAa,EAAE,YAAY,UAAU,iBAAiB,kBACjD,OAAO,IAAI,yBAAyB;GACjC;GACA,qBAAqB,OAAO;GAC5B;GACA,aAAa;GACb;GACA;GACA;EACJ,CAAC,EACT,CACJ;CACJ;;;;;CAMA,2BAAkE;EAC9D,OAAO;GACH,8BAA8B;IAC1B,MAAM,QAAQ,KAAK,KAAK,SAAS;IACjC,IAAI,MAAM,iBAAiB,CAAC,MAAM,cAAc,QAC5C,OAAO,MAAM,cAAc;IAE/B,OAAO;GACX;GACA,0BAA0B,KAAK,KAAK,SAAS,CAAC,CAAC,eAAe,aAAa;GAC3E,wBAAwB,KAAK,KAAK,SAAS,CAAC,CAAC,iBAAiB;EAClE;CACJ;;;;CAKA,iBAAiB,eAA2C;EACxD,KAAK,KAAK,iBAAiB,aAAa;CAC5C;AACJ"}
@@ -124,6 +124,11 @@ function parseCatalogSnapshot(value) {
124
124
  parsedSnapshots.set(snapshot, snapshot);
125
125
  return snapshot;
126
126
  }
127
+ /** Caches a snapshot built only from already-parsed parts so later parses skip validation. */
128
+ function markCatalogSnapshotParsed(snapshot) {
129
+ parsedSnapshots.set(snapshot, snapshot);
130
+ return snapshot;
131
+ }
127
132
  /** Parses supply updates before they can advance a snapshot's version or timestamp. */
128
133
  function parseZippedAssetSupplyCatalogUpdates(value) {
129
134
  const result = v.safeParse(ZippedAssetSupplyCatalogUpdatesSchema, value);
@@ -131,6 +136,6 @@ function parseZippedAssetSupplyCatalogUpdates(value) {
131
136
  return result.output;
132
137
  }
133
138
  //#endregion
134
- export { CatalogSnapshotShapeSchema, parseCatalogSnapshot, parseZippedAssetSupplyCatalogUpdates };
139
+ export { CatalogSnapshotShapeSchema, markCatalogSnapshotParsed, parseCatalogSnapshot, parseZippedAssetSupplyCatalogUpdates };
135
140
 
136
141
  //# sourceMappingURL=snapshot-validation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-validation.js","names":[],"sources":["../../src/catalogs/snapshot-validation.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { ValidationError } from \"../shared/errors.js\";\nimport { PAIR_STATUSES } from \"../shared/catalog-config.js\";\nimport type { CatalogSnapshot } from \"./types.js\";\nimport type { ZippedAssetSupplyCatalogUpdate } from \"./zipper-supply.js\";\n\nconst FiniteNumberSchema = v.pipe(v.number(), v.finite());\nconst IntegerSchema = v.pipe(FiniteNumberSchema, v.safeInteger());\n\nconst AssetConfigSchema = v.object({\n symbol: v.string(),\n ledgerId: IntegerSchema,\n name: v.string(),\n quantityDisplayDecimals: IntegerSchema,\n quantityScale: IntegerSchema,\n marketDataVolumeScale: v.optional(IntegerSchema),\n});\n\nconst PairMarketDataConfigSchema = v.object({\n orderbookPriceBuckets: v.array(FiniteNumberSchema),\n});\n\nconst EnrichedPairConfigSchema = v.object({\n symbolId: IntegerSchema,\n symbol: v.string(),\n baseAsset: AssetConfigSchema,\n quoteAsset: AssetConfigSchema,\n tickSize: v.string(),\n stepSize: v.string(),\n minNotionalQuote: v.string(),\n minQtyBase: v.string(),\n allowBuyFeeFromBase: v.boolean(),\n defaultMarketSlippagePctBuy: FiniteNumberSchema,\n defaultMarketSlippagePctSell: FiniteNumberSchema,\n maxClientRefDriftPct: FiniteNumberSchema,\n baseQuantityScale: v.optional(IntegerSchema),\n quoteQuantityScale: v.optional(IntegerSchema),\n referencePriceScale: v.optional(IntegerSchema),\n marketdata: v.optional(PairMarketDataConfigSchema),\n listingAt: v.nullable(FiniteNumberSchema),\n delistingAt: v.nullable(FiniteNumberSchema),\n status: v.picklist([...PAIR_STATUSES, \"unknown\"]),\n});\n\nconst ZipperChainConfigSchema = v.object({\n chainId: IntegerSchema,\n code: v.string(),\n name: v.string(),\n nativeChainId: v.string(),\n nativeCurrencySymbol: v.string(),\n explorerUrl: v.string(),\n icon: v.string(),\n requiredConfirmations: IntegerSchema,\n confirmationTimeSeconds: IntegerSchema,\n isCaseSensitive: v.boolean(),\n minAddressLength: IntegerSchema,\n maxAddressLength: IntegerSchema,\n});\n\nconst ZipperTokenConfigSchema = v.object({\n address: v.string(),\n decimals: IntegerSchema,\n});\n\nconst ZipperEnrichedAssetChainSchema = v.object({\n ...ZipperChainConfigSchema.entries,\n zippedAssetId: IntegerSchema,\n isNativeAsset: v.boolean(),\n networkFee: v.optional(v.string()),\n networkFeeTsSec: v.optional(FiniteNumberSchema),\n depositMinAmount: v.optional(v.string()),\n withdrawMinAmount: v.optional(v.string()),\n supply: v.optional(v.string()),\n sourceToken: ZipperTokenConfigSchema,\n zToken: ZipperTokenConfigSchema,\n});\n\nconst ZipperEnrichedAssetConfigSchema = v.object({\n asset: v.string(),\n ledgerId: IntegerSchema,\n name: v.string(),\n icon: v.string(),\n quantityScale: IntegerSchema,\n quantityDisplayDecimals: IntegerSchema,\n uAssetId: v.string(),\n chains: v.array(ZipperEnrichedAssetChainSchema),\n});\n\nconst ZipperChainContractConfigSchema = v.object({\n name: v.string(),\n address: v.string(),\n type: v.string(),\n description: v.string(),\n version: IntegerSchema,\n});\n\nexport const CatalogSnapshotShapeSchema = v.object({\n source: v.picklist([\"api\", \"snapshot\"]),\n tsMs: FiniteNumberSchema,\n version: IntegerSchema,\n market: v.object({\n assets: v.array(AssetConfigSchema),\n pairs: v.array(EnrichedPairConfigSchema),\n tsSec: v.optional(FiniteNumberSchema),\n }),\n zipper: v.object({\n chains: v.array(ZipperChainConfigSchema),\n assets: v.array(ZipperEnrichedAssetConfigSchema),\n contracts: v.array(ZipperChainContractConfigSchema),\n tsMs: v.optional(FiniteNumberSchema),\n }),\n});\n\nconst ZippedAssetSupplyCatalogUpdatesSchema = v.array(\n v.object({\n zippedAssetId: IntegerSchema,\n supply: v.string(),\n }),\n);\n\nconst parsedSnapshots = new WeakMap<object, CatalogSnapshot>();\n\nfunction hasValidRelationships(\n snapshot: v.InferOutput<typeof CatalogSnapshotShapeSchema>,\n): boolean {\n const assetSymbols = new Set(snapshot.market.assets.map((asset) => asset.symbol));\n if (\n snapshot.market.pairs.some(\n (pair) =>\n !assetSymbols.has(pair.baseAsset.symbol) ||\n !assetSymbols.has(pair.quoteAsset.symbol),\n )\n ) {\n return false;\n }\n\n const chainIds = new Set(snapshot.zipper.chains.map((chain) => chain.chainId));\n return snapshot.zipper.assets.every((asset) =>\n asset.chains.every((chain) => chainIds.has(chain.chainId)),\n );\n}\n\nconst CatalogSnapshotSchema = v.custom<CatalogSnapshot>((value) => {\n const result = v.safeParse(CatalogSnapshotShapeSchema, value);\n return result.success && hasValidRelationships(result.output);\n});\n\n/** Parses and caches untrusted SSR or JavaScript input as a catalog snapshot. */\nexport function parseCatalogSnapshot(value: unknown): CatalogSnapshot {\n if (typeof value !== \"object\" || value === null) {\n throw new ValidationError(\"Catalog snapshot is malformed.\");\n }\n\n const cached = parsedSnapshots.get(value);\n if (cached) return cached;\n\n const result = v.safeParse(CatalogSnapshotSchema, value);\n if (!result.success) {\n throw new ValidationError(\"Catalog snapshot is malformed.\");\n }\n\n const snapshot: CatalogSnapshot = result.output;\n parsedSnapshots.set(value, snapshot);\n parsedSnapshots.set(snapshot, snapshot);\n return snapshot;\n}\n\n/** Parses supply updates before they can advance a snapshot's version or timestamp. */\nexport function parseZippedAssetSupplyCatalogUpdates(\n value: unknown,\n): readonly ZippedAssetSupplyCatalogUpdate[] {\n const result = v.safeParse(ZippedAssetSupplyCatalogUpdatesSchema, value);\n if (!result.success) {\n throw new ValidationError(\"Zipper catalog supply updates are malformed.\");\n }\n return result.output;\n}\n"],"mappings":";;;;AAMA,MAAM,qBAAqB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AACxD,MAAM,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,YAAY,CAAC;AAEhE,MAAM,oBAAoB,EAAE,OAAO;CAC/B,QAAQ,EAAE,OAAO;CACjB,UAAU;CACV,MAAM,EAAE,OAAO;CACf,yBAAyB;CACzB,eAAe;CACf,uBAAuB,EAAE,SAAS,aAAa;A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CAGX,MAAM,WAAW,IAAI,IAAI,SAAS,OAAO,OAAO,KAAK,UAAU,MAAM,OAAO,CAAC;CAC7E,OAAO,SAAS,OAAO,OAAO,OAAO,UACjC,MAAM,OAAO,OAAO,UAAU,SAAS,IAAI,MAAM,OAAO,CAAC,CAC7D;AACJ;AAEA,MAAM,wBAAwB,EAAE,QAAyB,UAAU;CAC/D,MAAM,SAAS,EAAE,UAAU,4BAA4B,KAAK;CAC5D,OAAO,OAAO,WAAW,sBAAsB,OAAO,MAAM;AAChE,CAAC;;AAGD,SAAgB,qBAAqB,OAAiC;CAClE,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,MAAM,IAAI,gBAAgB,gCAAgC;CAG9D,MAAM,SAAS,gBAAgB,IAAI,KAAK;CACxC,IAAI,QAAQ,OAAO;CAEnB,MAAM,SAAS,EAAE,UAAU,uBAAuB,KAAK;CACvD,IAAI,CAAC,OAAO,SACR,MAAM,IAAI,gBAAgB,gCAAgC;CAG9D,MAAM,WAA4B,OAAO;CACzC,gBAAgB,IAAI,OAAO,QAAQ;CACnC,gBAAgB,IAAI,UAAU,QAAQ;CACtC,OAAO;AACX;;AAGA,SAAgB,qCACZ,OACyC;CACzC,MAAM,SAAS,EAAE,UAAU,uCAAuC,KAAK;CACvE,IAAI,CAAC,OAAO,SACR,MAAM,IAAI,gBAAgB,8CAA8C;CAE5E,OAAO,OAAO;AAClB"}
1
+ {"version":3,"file":"snapshot-validation.js","names":[],"sources":["../../src/catalogs/snapshot-validation.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { ValidationError } from \"../shared/errors.js\";\nimport { PAIR_STATUSES } from \"../shared/catalog-config.js\";\nimport type { CatalogSnapshot } from \"./types.js\";\nimport type { ZippedAssetSupplyCatalogUpdate } from \"./zipper-supply.js\";\n\nconst FiniteNumberSchema = v.pipe(v.number(), v.finite());\nconst IntegerSchema = v.pipe(FiniteNumberSchema, v.safeInteger());\n\nconst AssetConfigSchema = v.object({\n symbol: v.string(),\n ledgerId: IntegerSchema,\n name: v.string(),\n quantityDisplayDecimals: IntegerSchema,\n quantityScale: IntegerSchema,\n marketDataVolumeScale: v.optional(IntegerSchema),\n});\n\nconst PairMarketDataConfigSchema = v.object({\n orderbookPriceBuckets: v.array(FiniteNumberSchema),\n});\n\nconst EnrichedPairConfigSchema = v.object({\n symbolId: IntegerSchema,\n symbol: v.string(),\n baseAsset: AssetConfigSchema,\n quoteAsset: AssetConfigSchema,\n tickSize: v.string(),\n stepSize: v.string(),\n minNotionalQuote: v.string(),\n minQtyBase: v.string(),\n allowBuyFeeFromBase: v.boolean(),\n defaultMarketSlippagePctBuy: FiniteNumberSchema,\n defaultMarketSlippagePctSell: FiniteNumberSchema,\n maxClientRefDriftPct: FiniteNumberSchema,\n baseQuantityScale: v.optional(IntegerSchema),\n quoteQuantityScale: v.optional(IntegerSchema),\n referencePriceScale: v.optional(IntegerSchema),\n marketdata: v.optional(PairMarketDataConfigSchema),\n listingAt: v.nullable(FiniteNumberSchema),\n delistingAt: v.nullable(FiniteNumberSchema),\n status: v.picklist([...PAIR_STATUSES, \"unknown\"]),\n});\n\nconst ZipperChainConfigSchema = v.object({\n chainId: IntegerSchema,\n code: v.string(),\n name: v.string(),\n nativeChainId: v.string(),\n nativeCurrencySymbol: v.string(),\n explorerUrl: v.string(),\n icon: v.string(),\n requiredConfirmations: IntegerSchema,\n confirmationTimeSeconds: IntegerSchema,\n isCaseSensitive: v.boolean(),\n minAddressLength: IntegerSchema,\n maxAddressLength: IntegerSchema,\n});\n\nconst ZipperTokenConfigSchema = v.object({\n address: v.string(),\n decimals: IntegerSchema,\n});\n\nconst ZipperEnrichedAssetChainSchema = v.object({\n ...ZipperChainConfigSchema.entries,\n zippedAssetId: IntegerSchema,\n isNativeAsset: v.boolean(),\n networkFee: v.optional(v.string()),\n networkFeeTsSec: v.optional(FiniteNumberSchema),\n depositMinAmount: v.optional(v.string()),\n withdrawMinAmount: v.optional(v.string()),\n supply: v.optional(v.string()),\n sourceToken: ZipperTokenConfigSchema,\n zToken: ZipperTokenConfigSchema,\n});\n\nconst ZipperEnrichedAssetConfigSchema = v.object({\n asset: v.string(),\n ledgerId: IntegerSchema,\n name: v.string(),\n icon: v.string(),\n quantityScale: IntegerSchema,\n quantityDisplayDecimals: IntegerSchema,\n uAssetId: v.string(),\n chains: v.array(ZipperEnrichedAssetChainSchema),\n});\n\nconst ZipperChainContractConfigSchema = v.object({\n name: v.string(),\n address: v.string(),\n type: v.string(),\n description: v.string(),\n version: IntegerSchema,\n});\n\nexport const CatalogSnapshotShapeSchema = v.object({\n source: v.picklist([\"api\", \"snapshot\"]),\n tsMs: FiniteNumberSchema,\n version: IntegerSchema,\n market: v.object({\n assets: v.array(AssetConfigSchema),\n pairs: v.array(EnrichedPairConfigSchema),\n tsSec: v.optional(FiniteNumberSchema),\n }),\n zipper: v.object({\n chains: v.array(ZipperChainConfigSchema),\n assets: v.array(ZipperEnrichedAssetConfigSchema),\n contracts: v.array(ZipperChainContractConfigSchema),\n tsMs: v.optional(FiniteNumberSchema),\n }),\n});\n\nconst ZippedAssetSupplyCatalogUpdatesSchema = v.array(\n v.object({\n zippedAssetId: IntegerSchema,\n supply: v.string(),\n }),\n);\n\nconst parsedSnapshots = new WeakMap<object, CatalogSnapshot>();\n\nfunction hasValidRelationships(\n snapshot: v.InferOutput<typeof CatalogSnapshotShapeSchema>,\n): boolean {\n const assetSymbols = new Set(snapshot.market.assets.map((asset) => asset.symbol));\n if (\n snapshot.market.pairs.some(\n (pair) =>\n !assetSymbols.has(pair.baseAsset.symbol) ||\n !assetSymbols.has(pair.quoteAsset.symbol),\n )\n ) {\n return false;\n }\n\n const chainIds = new Set(snapshot.zipper.chains.map((chain) => chain.chainId));\n return snapshot.zipper.assets.every((asset) =>\n asset.chains.every((chain) => chainIds.has(chain.chainId)),\n );\n}\n\nconst CatalogSnapshotSchema = v.custom<CatalogSnapshot>((value) => {\n const result = v.safeParse(CatalogSnapshotShapeSchema, value);\n return result.success && hasValidRelationships(result.output);\n});\n\n/** Parses and caches untrusted SSR or JavaScript input as a catalog snapshot. */\nexport function parseCatalogSnapshot(value: unknown): CatalogSnapshot {\n if (typeof value !== \"object\" || value === null) {\n throw new ValidationError(\"Catalog snapshot is malformed.\");\n }\n\n const cached = parsedSnapshots.get(value);\n if (cached) return cached;\n\n const result = v.safeParse(CatalogSnapshotSchema, value);\n if (!result.success) {\n throw new ValidationError(\"Catalog snapshot is malformed.\");\n }\n\n const snapshot: CatalogSnapshot = result.output;\n parsedSnapshots.set(value, snapshot);\n parsedSnapshots.set(snapshot, snapshot);\n return snapshot;\n}\n\n/** Caches a snapshot built only from already-parsed parts so later parses skip validation. */\nexport function markCatalogSnapshotParsed(snapshot: CatalogSnapshot): CatalogSnapshot {\n parsedSnapshots.set(snapshot, snapshot);\n return snapshot;\n}\n\n/** Parses supply updates before they can advance a snapshot's version or timestamp. */\nexport function parseZippedAssetSupplyCatalogUpdates(\n value: unknown,\n): readonly ZippedAssetSupplyCatalogUpdate[] {\n const result = v.safeParse(ZippedAssetSupplyCatalogUpdatesSchema, value);\n if (!result.success) {\n throw new ValidationError(\"Zipper catalog supply updates are malformed.\");\n }\n return result.output;\n}\n"],"mappings":";;;;AAMA,MAAM,qBAAqB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AACxD,MAAM,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,YAAY,CAAC;AAEhE,MAAM,oBAAoB,EAAE,OAAO;CAC/B,QAAQ,EAAE,OAAO;CACjB,UAAU;CACV,MAAM,EAAE,OAAO;CACf,yBAAyB;CACzB,eAAe;CACf,uBAAuB,EAAE,SAAS,aAAa;AACnD,CAAC;AAED,MAAM,6BAA6B,EAAE,OAAO,EACxC,uBAAuB,EAAE,MAAM,kBAAkB,EACrD,CAAC;AAED,MAAM,2BAA2B,EAAE,OAAO;CACtC,UAAU;CACV,QAAQ,EAAE,OAAO;CACjB,WAAW;CACX,YAAY;CACZ,UAAU,EAAE,OAAO;CACn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B,EAAE,QAAyB,UAAU;CAC/D,MAAM,SAAS,EAAE,UAAU,4BAA4B,KAAK;CAC5D,OAAO,OAAO,WAAW,sBAAsB,OAAO,MAAM;AAChE,CAAC;;AAGD,SAAgB,qBAAqB,OAAiC;CAClE,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,MAAM,IAAI,gBAAgB,gCAAgC;CAG9D,MAAM,SAAS,gBAAgB,IAAI,KAAK;CACxC,IAAI,QAAQ,OAAO;CAEnB,MAAM,SAAS,EAAE,UAAU,uBAAuB,KAAK;CACvD,IAAI,CAAC,OAAO,SACR,MAAM,IAAI,gBAAgB,gCAAgC;CAG9D,MAAM,WAA4B,OAAO;CACzC,gBAAgB,IAAI,OAAO,QAAQ;CACnC,gBAAgB,IAAI,UAAU,QAAQ;CACtC,OAAO;AACX;;AAGA,SAAgB,0BAA0B,UAA4C;CAClF,gBAAgB,IAAI,UAAU,QAAQ;CACtC,OAAO;AACX;;AAGA,SAAgB,qCACZ,OACyC;CACzC,MAAM,SAAS,EAAE,UAAU,uCAAuC,KAAK;CACvE,IAAI,CAAC,OAAO,SACR,MAAM,IAAI,gBAAgB,8CAA8C;CAE5E,OAAO,OAAO;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"zipper-supply.d.ts","names":[],"sources":["../../src/catalogs/zipper-supply.ts"],"mappings":";;KAMY;EACR;EACA;;iBAGY,yBACZ,UAAU,iBACV,kBAAkB,mCACnB"}
1
+ {"version":3,"file":"zipper-supply.d.ts","names":[],"sources":["../../src/catalogs/zipper-supply.ts"],"mappings":";;KAOY;EACR;EACA;;iBAGY,yBACZ,UAAU,iBACV,kBAAkB,mCACnB"}
@@ -1,4 +1,4 @@
1
- import { parseCatalogSnapshot, parseZippedAssetSupplyCatalogUpdates } from "./snapshot-validation.js";
1
+ import { markCatalogSnapshotParsed, parseCatalogSnapshot, parseZippedAssetSupplyCatalogUpdates } from "./snapshot-validation.js";
2
2
  //#region src/catalogs/zipper-supply.ts
3
3
  function patchZipperCatalogSupply(snapshot, updates) {
4
4
  const parsedSnapshot = parseCatalogSnapshot(snapshot);
@@ -26,7 +26,7 @@ function patchZipperCatalogSupply(snapshot, updates) {
26
26
  });
27
27
  if (!changed) return parsedSnapshot;
28
28
  const nowMs = Date.now();
29
- return {
29
+ return markCatalogSnapshotParsed({
30
30
  ...parsedSnapshot,
31
31
  tsMs: nowMs,
32
32
  version: parsedSnapshot.version + 1,
@@ -35,7 +35,7 @@ function patchZipperCatalogSupply(snapshot, updates) {
35
35
  tsMs: nowMs,
36
36
  assets
37
37
  }
38
- };
38
+ });
39
39
  }
40
40
  //#endregion
41
41
  export { patchZipperCatalogSupply };
@@ -1 +1 @@
1
- {"version":3,"file":"zipper-supply.js","names":[],"sources":["../../src/catalogs/zipper-supply.ts"],"sourcesContent":["import type { CatalogSnapshot } from \"./types.js\";\nimport {\n parseCatalogSnapshot,\n parseZippedAssetSupplyCatalogUpdates,\n} from \"./snapshot-validation.js\";\n\nexport type ZippedAssetSupplyCatalogUpdate = {\n zippedAssetId: number;\n supply: string;\n};\n\nexport function patchZipperCatalogSupply(\n snapshot: CatalogSnapshot,\n updates: readonly ZippedAssetSupplyCatalogUpdate[],\n): CatalogSnapshot {\n const parsedSnapshot = parseCatalogSnapshot(snapshot);\n const parsedUpdates = parseZippedAssetSupplyCatalogUpdates(updates);\n if (parsedUpdates.length === 0) return parsedSnapshot;\n\n const supplyByZippedAssetId = new Map<number, string>();\n for (const update of parsedUpdates) {\n supplyByZippedAssetId.set(update.zippedAssetId, update.supply);\n }\n\n let changed = false;\n const assets = parsedSnapshot.zipper.assets.map((asset) => {\n let assetChanged = false;\n const chains = asset.chains.map((chain) => {\n const supply = supplyByZippedAssetId.get(chain.zippedAssetId);\n if (supply === undefined || supply === chain.supply) return chain;\n assetChanged = true;\n changed = true;\n return { ...chain, supply };\n });\n\n return assetChanged ? { ...asset, chains } : asset;\n });\n\n if (!changed) return parsedSnapshot;\n const nowMs = Date.now();\n\n return {\n ...parsedSnapshot,\n tsMs: nowMs,\n version: parsedSnapshot.version + 1,\n zipper: {\n ...parsedSnapshot.zipper,\n tsMs: nowMs,\n assets,\n },\n };\n}\n"],"mappings":";;AAWA,SAAgB,yBACZ,UACA,SACe;CACf,MAAM,iBAAiB,qBAAqB,QAAQ;CACpD,MAAM,gBAAgB,qCAAqC,OAAO;CAClE,IAAI,cAAc,WAAW,GAAG,OAAO;CAEvC,MAAM,wCAAwB,IAAI,IAAoB;CACtD,KAAK,MAAM,UAAU,eACjB,sBAAsB,IAAI,OAAO,eAAe,OAAO,MAAM;CAGjE,IAAI,UAAU;CACd,MAAM,SAAS,eAAe,OAAO,OAAO,KAAK,UAAU;EACvD,IAAI,eAAe;EACnB,MAAM,SAAS,MAAM,OAAO,KAAK,UAAU;GACvC,MAAM,SAAS,sBAAsB,IAAI,MAAM,aAAa;GAC5D,IAAI,WAAW,KAAA,KAAa,WAAW,MAAM,QAAQ,OAAO;GAC5D,eAAe;GACf,UAAU;GACV,OAAO;IAAE,GAAG;IAAO;GAAO;EAC9B,CAAC;EAED,OAAO,eAAe;GAAE,GAAG;GAAO;EAAO,IAAI;CACjD,CAAC;CAED,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,QAAQ,KAAK,IAAI;CAEvB,OAAO;EACH,GAAG;EACH,MAAM;EACN,SAAS,eAAe,UAAU;EAClC,QAAQ;GACJ,GAAG,eAAe;GAClB,MAAM;GACN;EACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"zipper-supply.js","names":[],"sources":["../../src/catalogs/zipper-supply.ts"],"sourcesContent":["import type { CatalogSnapshot } from \"./types.js\";\nimport {\n markCatalogSnapshotParsed,\n parseCatalogSnapshot,\n parseZippedAssetSupplyCatalogUpdates,\n} from \"./snapshot-validation.js\";\n\nexport type ZippedAssetSupplyCatalogUpdate = {\n zippedAssetId: number;\n supply: string;\n};\n\nexport function patchZipperCatalogSupply(\n snapshot: CatalogSnapshot,\n updates: readonly ZippedAssetSupplyCatalogUpdate[],\n): CatalogSnapshot {\n const parsedSnapshot = parseCatalogSnapshot(snapshot);\n const parsedUpdates = parseZippedAssetSupplyCatalogUpdates(updates);\n if (parsedUpdates.length === 0) return parsedSnapshot;\n\n const supplyByZippedAssetId = new Map<number, string>();\n for (const update of parsedUpdates) {\n supplyByZippedAssetId.set(update.zippedAssetId, update.supply);\n }\n\n let changed = false;\n const assets = parsedSnapshot.zipper.assets.map((asset) => {\n let assetChanged = false;\n const chains = asset.chains.map((chain) => {\n const supply = supplyByZippedAssetId.get(chain.zippedAssetId);\n if (supply === undefined || supply === chain.supply) return chain;\n assetChanged = true;\n changed = true;\n return { ...chain, supply };\n });\n\n return assetChanged ? { ...asset, chains } : asset;\n });\n\n if (!changed) return parsedSnapshot;\n const nowMs = Date.now();\n\n return markCatalogSnapshotParsed({\n ...parsedSnapshot,\n tsMs: nowMs,\n version: parsedSnapshot.version + 1,\n zipper: {\n ...parsedSnapshot.zipper,\n tsMs: nowMs,\n assets,\n },\n });\n}\n"],"mappings":";;AAYA,SAAgB,yBACZ,UACA,SACe;CACf,MAAM,iBAAiB,qBAAqB,QAAQ;CACpD,MAAM,gBAAgB,qCAAqC,OAAO;CAClE,IAAI,cAAc,WAAW,GAAG,OAAO;CAEvC,MAAM,wCAAwB,IAAI,IAAoB;CACtD,KAAK,MAAM,UAAU,eACjB,sBAAsB,IAAI,OAAO,eAAe,OAAO,MAAM;CAGjE,IAAI,UAAU;CACd,MAAM,SAAS,eAAe,OAAO,OAAO,KAAK,UAAU;EACvD,IAAI,eAAe;EACnB,MAAM,SAAS,MAAM,OAAO,KAAK,UAAU;GACvC,MAAM,SAAS,sBAAsB,IAAI,MAAM,aAAa;GAC5D,IAAI,WAAW,KAAA,KAAa,WAAW,MAAM,QAAQ,OAAO;GAC5D,eAAe;GACf,UAAU;GACV,OAAO;IAAE,GAAG;IAAO;GAAO;EAC9B,CAAC;EAED,OAAO,eAAe;GAAE,GAAG;GAAO;EAAO,IAAI;CACjD,CAAC;CAED,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,QAAQ,KAAK,IAAI;CAEvB,OAAO,0BAA0B;EAC7B,GAAG;EACH,MAAM;EACN,SAAS,eAAe,UAAU;EAClC,QAAQ;GACJ,GAAG,eAAe;GAClB,MAAM;GACN;EACJ;CACJ,CAAC;AACL"}
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ import { AssetConfig, DepositWithdrawConfig, PairConfig, PairStatus, SpotConfig,
6
6
  import { OrderErrorCode, OrderErrorDetail } from "./services/orders/order-errors.schemas.js";
7
7
  import { PolyesterErrorDetail, loadErrorDetailDecoders } from "./shared/error-detail.js";
8
8
  import { RateLimitDetail, RateLimitFailureReason, RateLimitPolicyClass, RateLimitRefillModel, RateLimitScope } from "./shared/rate-limit.schemas.js";
9
- import { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, MfaVerificationFailureReason, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PolyesterErrorCode, PolyesterErrorOptions, PreconditionFailedError, RateLimitError, RateLimitErrorOptions, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./shared/errors.js";
9
+ import { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, MfaVerificationFailureReason, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PolyesterErrorCode, PolyesterErrorOptions, PreconditionFailedError, RateLimitError, RateLimitErrorOptions, RealtimeError, RealtimeErrorOptions, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./shared/errors.js";
10
10
  import { ApiKeyEd25519AuthProvider, JwtAuthProvider, Transports } from "./shared/transports.js";
11
11
  import { PolyesterMutationOptions, PolyesterRequestOptions } from "./shared/request-options.js";
12
12
  import { ResolveAccountInput, ResolvedAccount } from "./services/accounts/accounts.schemas.js";
@@ -116,4 +116,4 @@ import "./services/triggers/triggers.types.js";
116
116
  import "./services/vip/vip.types.js";
117
117
  import "./services/whiteboard/whiteboard.types.js";
118
118
  import "./services/zipper/zipper.types.js";
119
- export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type ArchiveWhiteboardBoardInput, type ArchiveWhiteboardBoardResult, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ClaimCampaign, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CreateWhiteboardBoardInput, type CreateWhiteboardBoardResult, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWhiteboardBoardInput, type GetWhiteboardBoardResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type ListWhiteboardBoardsInput, type ListWhiteboardBoardsResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MintWhiteboardJoinTokenInput, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeRate, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, type UpdateWhiteboardBoardAclInput, type UpdateWhiteboardBoardAclResult, type UpdateWhiteboardBoardInput, type UpdateWhiteboardBoardResult, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, type WhiteboardAccess, type WhiteboardAclEntry, type WhiteboardAclEntryInput, type WhiteboardAclSubjectType, type WhiteboardAudience, type WhiteboardBoard, type WhiteboardBoardDetails, type WhiteboardBoardListItem, type WhiteboardJoinTokenResult, type WhiteboardPermissions, type WhiteboardPresencePayload, type WhiteboardResolvedRole, type WhiteboardSnapshot, type WhiteboardWritableRole, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
119
+ export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type ArchiveWhiteboardBoardInput, type ArchiveWhiteboardBoardResult, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ClaimCampaign, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CreateWhiteboardBoardInput, type CreateWhiteboardBoardResult, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetWhiteboardBoardInput, type GetWhiteboardBoardResult, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type ListWhiteboardBoardsInput, type ListWhiteboardBoardsResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MintWhiteboardJoinTokenInput, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeRate, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, type UpdateWhiteboardBoardAclInput, type UpdateWhiteboardBoardAclResult, type UpdateWhiteboardBoardInput, type UpdateWhiteboardBoardResult, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, type WhiteboardAccess, type WhiteboardAclEntry, type WhiteboardAclEntryInput, type WhiteboardAclSubjectType, type WhiteboardAudience, type WhiteboardBoard, type WhiteboardBoardDetails, type WhiteboardBoardListItem, type WhiteboardJoinTokenResult, type WhiteboardPermissions, type WhiteboardPresencePayload, type WhiteboardResolvedRole, type WhiteboardSnapshot, type WhiteboardWritableRole, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./shared/errors.js";
1
+ import { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PreconditionFailedError, RateLimitError, RealtimeError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./shared/errors.js";
2
2
  import { loadErrorDetailDecoders } from "./shared/error-detail.js";
3
3
  import { connectErrorToPolyesterError, createErrorMappingInterceptor, toPolyesterError } from "./shared/connect-error-mapping.js";
4
4
  import { checksumEvmAddress, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, isEvmAddress, isEvmAddressStrict, keccak256Hex } from "./utils/evm.js";
@@ -18,4 +18,4 @@ import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFact
18
18
  import { columnarTimestampSecAt, expandColumnarTimestampsSec } from "./utils/columnar-time.js";
19
19
  import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "./shared/reconciliation.js";
20
20
  import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
21
- export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterBrowserCore, PolyesterClient, PolyesterCore, PolyesterError, PolyesterServerClient, PolyesterServerCore, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
21
+ export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterBrowserCore, PolyesterClient, PolyesterCore, PolyesterError, PolyesterServerClient, PolyesterServerCore, PreconditionFailedError, RateLimitError, RealtimeError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -22,7 +22,7 @@ function snapshotThenStream(params) {
22
22
  let retryTimer = null;
23
23
  function reportSnapshotError(error) {
24
24
  if (isDev() && params.snapshotErrorLog) console.error(params.snapshotErrorLog, error);
25
- params.onError?.(createSdkSubscriptionErrorContext(params.channel, "snapshot", formatConnectError(error, "snapshot failed")));
25
+ params.onError?.(createSdkSubscriptionErrorContext(params.channel, "snapshot", error instanceof Error ? error : formatConnectError(error, "snapshot failed")));
26
26
  }
27
27
  function takePendingPublications() {
28
28
  const buffered = pendingPublications;
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n\n const delayMs = retry.delayMs * 2 ** retryAttempts;\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry();\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isRe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,MAAM,eAAe,OAAO,gBAAgB,OAAO;GACnD,IAAI,aAAa,WAAW,GAAG;GAE/B,IAAI,CAAC,OAAO;IACR,mBAAmB,YAAY;IAC/B;GACJ;GAEA,sBAAsB,YAAY;EACtC;EACA,mBAAmB;GACf,IAAI,UAAU;GACd,sBAAsB,CAAC;GACvB,gBAAgB;GAChB,OAAO,SAAS;EACpB;EACA,sBAAsB;GAClB,IAAI,UAAU;GACd,gBAAgB;GAChB;GACA,QAAQ;GACR,sBAAsB,CAAC;GACvB,OAAO,UAAU;EACrB;EACA,SAAS,OAAO;CACpB,CAAC;CAED,SAAS,cAAoB;EACzB,WAAW;EACX,gBAAgB;EAChB;EACA,sBAAsB,CAAC;EACvB,IAAI;GACA,oBAAoB;EACxB,QAAQ,CAER;CACJ;CAEA,OAAO;EACH;EACA;EACA,eAAe;EACf,kBAAkB;CACtB;AACJ"}
1
+ {"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n error instanceof Error ? error : formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n\n const delayMs = retry.delayMs * 2 ** retryAttempts;\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry();\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isReady: () => ready,\n isDisposed: () => disposed,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAgB,mBACZ,QAC8B;CAC9B,MAAM,0BAA0B,OAAO,2BAA2B;CAClE,IAAI,sBAAsB;CAE1B,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,oBAAoB;CACxB,IAAI,sBAAsC,CAAC;CAC3C,IAAI,gBAAgB;CACpB,IAAI,aAAmD;CAEvD,SAAS,oBAAoB,OAAsB;EAC/C,IAAI,MAAM,KAAK,OAAO,kBAClB,QAAQ,MAAM,OAAO,kBAAkB,KAAK;EAEhD,OAAO,UACH,kCACI,OAAO,SACP,YACA,iBAAiB,QAAQ,QAAQ,mBAAmB,OAAO,iBAAiB,CAChF,CACJ;CACJ;CAEA,SAAS,0BAA0C;EAC/C,MAAM,WAAW;EACjB,sBAAsB,CAAC;EACvB,OAAO;CACX;CAEA,SAAS,sBAA4B;EACjC,MAAM,WAAW,wBAAwB;EACzC,IAAI,SAAS,WAAW,GAAG;EAC3B,sBAAsB,QAAQ;CAClC;CAEA,SAAS,mBA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EAElC,MAAM,aAAa,EAAE;EACrB,QAAQ;EAER,QAAQ,QAAQ,CAAC,CACZ,WAAW,OAAO,cAAc,CAAC,CAAC,CAClC,MAAM,aAAa;GAChB,IAAI,YAAY,eAAe,mBAAmB;GAGlD,cAAc,UADG,wBACc,CAAC;GAEhC,IAAI,YAAY,eAAe,mBAAmB;GAClD,QAAQ;GACR,gBAAgB;EACpB,CAAC,CAAC,CACD,OAAO,UAAmB;GACvB,IAAI,YAAY,eAAe,mBAAmB;GAClD,oBAAoB,KAAK;GAKzB,KAHI,OAAO,OAAO,wBAAwB,aAChC,OAAO,oBAAoB,KAAK,IAChC,OAAO,yBACG,QAAQ;IACxB,QAAQ;IACR,oBAAoB;GACxB;GACA,sBAAsB;EAC1B,CAAC;CACT;CAEA,MAAM,sBAAsB,OAAO,SAAS,oBAAoB;EAC5D,SAAS,OAAO;EAChB,QAAQ,OAAO;EACf,gBAAgB,YAAY;GACxB,MAAM,eAAe,OAAO,gBAAgB,OAAO;GACnD,IAAI,aAAa,WAAW,GAAG;GAE/B,IAAI,CAAC,OAAO;IACR,mBAAmB,YAAY;IAC/B;GACJ;GAEA,sBAAsB,YAAY;EACtC;EACA,mBAAmB;GACf,IAAI,UAAU;GACd,sBAAsB,CAAC;GACvB,gBAAgB;GAChB,OAAO,SAAS;EACpB;EACA,sBAAsB;GAClB,IAAI,UAAU;GACd,gBAAgB;GAChB;GACA,QAAQ;GACR,sBAAsB,CAAC;GACvB,OAAO,UAAU;EACrB;EACA,SAAS,OAAO;CACpB,CAAC;CAED,SAAS,cAAoB;EACzB,WAAW;EACX,gBAAgB;EAChB;EACA,sBAAsB,CAAC;EACvB,IAAI;GACA,oBAAoB;EACxB,QAAQ,CAER;CACJ;CAEA,OAAO;EACH;EACA;EACA,eAAe;EACf,kBAAkB;CACtB;AACJ"}
@@ -297,7 +297,7 @@ declare const AddressBookSchema: v.ObjectSchema<{
297
297
  rootAccountId: string;
298
298
  subaccountId: bigint;
299
299
  }, AddressBookAccountScope>]>, undefined>;
300
- readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer" | "unspecified">]>;
300
+ readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer">]>;
301
301
  readonly label: v.StringSchema<undefined>;
302
302
  readonly ownerUsername: v.StringSchema<undefined>;
303
303
  readonly smartAccountAddress: v.StringSchema<undefined>;
@@ -1102,7 +1102,7 @@ declare const AddressBookViewSchema: v.ObjectSchema<{
1102
1102
  rootAccountId: string;
1103
1103
  subaccountId: bigint;
1104
1104
  }, AddressBookAccountScope>]>, undefined>;
1105
- readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer" | "unspecified">]>;
1105
+ readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer">]>;
1106
1106
  readonly label: v.StringSchema<undefined>;
1107
1107
  readonly ownerUsername: v.StringSchema<undefined>;
1108
1108
  readonly smartAccountAddress: v.StringSchema<undefined>;
@@ -106,6 +106,12 @@ declare class AccountSignerAuthService extends AuthService {
106
106
  * Clears stored auth state and removes the persisted auth token.
107
107
  */
108
108
  logout(): Promise<void>;
109
+ /**
110
+ * Ends the session after the backend rejected `token` as unauthenticated (revoked,
111
+ * or expired despite a lagging local clock). Ignored when the token has since been
112
+ * replaced or a login/refresh is in flight. Browser clients call this automatically.
113
+ */
114
+ handleRejectedToken(token: string): void;
109
115
  /**
110
116
  * Returns the remaining lifetime of the stored session token in milliseconds.
111
117
  */
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;;UAyBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb,UAAU;;EAEV;EACA,cAAc;;UAGD;;;;;;EAMb,eACM,kBACE,WAAW,wBAAwB,gBAAgB,QAAQ;;EAEnE;;EAEA;;EAEA,eAAe;;UAGF;EACb;EACA;EACA;;;KAIQ,2BAA2B,4BAA4B,QAAQ;;;;cAU9D,iCAAiC;;WACjC,QAAM,aAAA;EAoBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAWhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EAyF5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;EAqChB;;;;EASM,eAAe;;IAEjB;IACA,WAAW;IACX,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EA2DhE,YAAY"}
1
+ {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;;UAyBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb,UAAU;;EAEV;EACA,cAAc;;UAGD;;;;;;EAMb,eACM,kBACE,WAAW,wBAAwB,gBAAgB,QAAQ;;EAEnE;;EAEA;;EAEA,eAAe;;UAGF;EACb;EACA;EACA;;;KAIQ,2BAA2B,4BAA4B,QAAQ;;;;cAU9D,iCAAiC;;WACjC,QAAM,aAAA;EAuBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAWhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EAqG5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;;;EAsBhB,oBAAoB;;;;EA0BpB;;;;EASM,eAAe;;IAEjB;IACA,WAAW;IACX,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EA2DhE,YAAY"}
@@ -27,6 +27,7 @@ var AccountSignerAuthService = class extends AuthService {
27
27
  #sessionStore;
28
28
  #realtime;
29
29
  #authOperationGeneration = 0;
30
+ #loginsInFlight = 0;
30
31
  constructor({ transports, accountSignerConfig, environment, subaccounts, realtime, tokenStorage, sessionStore }) {
31
32
  super(transports, realtime);
32
33
  this.#accountSignerConfig = accountSignerConfig;
@@ -65,6 +66,14 @@ var AccountSignerAuthService = class extends AuthService {
65
66
  return this.#login(options);
66
67
  }
67
68
  async #login(options, previousActiveAccount) {
69
+ this.#loginsInFlight += 1;
70
+ try {
71
+ return await this.#performLogin(options, previousActiveAccount);
72
+ } finally {
73
+ this.#loginsInFlight -= 1;
74
+ }
75
+ }
76
+ async #performLogin(options, previousActiveAccount) {
68
77
  const generation = this.#beginAuthOperation();
69
78
  const startingToken = this.#tokenStorage.get();
70
79
  const { provider, loginMethod } = options;
@@ -217,6 +226,16 @@ var AccountSignerAuthService = class extends AuthService {
217
226
  this.#notifyStateChange();
218
227
  this.events.emit("loggedOut", void 0);
219
228
  }
229
+ /**
230
+ * Ends the session after the backend rejected `token` as unauthenticated (revoked,
231
+ * or expired despite a lagging local clock). Ignored when the token has since been
232
+ * replaced or a login/refresh is in flight. Browser clients call this automatically.
233
+ */
234
+ handleRejectedToken(token) {
235
+ if (this.#loginsInFlight > 0 || this.#getEnvironmentBoundToken() !== token) return;
236
+ this.#beginAuthOperation();
237
+ this.#clearExpiredSessionState();
238
+ }
220
239
  #clearExpiredSessionState() {
221
240
  const shouldEmitLoggedOut = this.#isAuthenticated;
222
241
  this.#realtime.disconnectPrivate();