@polyester/sdk 0.35.0-devnet-20261108182734 → 0.35.0-devnet-20261110160258

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 (58) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/core-client.d.ts +3 -3
  3. package/dist/core-client.d.ts.map +1 -1
  4. package/dist/core-client.js +4 -1
  5. package/dist/core-client.js.map +1 -1
  6. package/dist/index.d.ts +3 -2
  7. package/dist/index.js +2 -1
  8. package/dist/realtime/client.d.ts +5 -0
  9. package/dist/realtime/client.d.ts.map +1 -1
  10. package/dist/realtime/client.js +3 -2
  11. package/dist/realtime/client.js.map +1 -1
  12. package/dist/services/auth/account-signer-auth.d.ts +3 -0
  13. package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
  14. package/dist/services/auth/account-signer-auth.js +2 -1
  15. package/dist/services/auth/account-signer-auth.js.map +1 -1
  16. package/dist/services/auth/auth.d.ts +26 -2
  17. package/dist/services/auth/auth.d.ts.map +1 -1
  18. package/dist/services/auth/auth.js +6 -3
  19. package/dist/services/auth/auth.js.map +1 -1
  20. package/dist/services/balances/balances.schemas.d.ts +8 -2
  21. package/dist/services/balances/balances.schemas.d.ts.map +1 -1
  22. package/dist/services/balances/balances.schemas.js +5 -1
  23. package/dist/services/balances/balances.schemas.js.map +1 -1
  24. package/dist/services/candles/candles.schemas.d.ts +10 -10
  25. package/dist/services/changelog/changelog.schemas.d.ts +17 -17
  26. package/dist/services/checkpoints/checkpoints.schemas.d.ts +2 -2
  27. package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
  28. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts +6 -0
  29. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts.map +1 -0
  30. package/dist/services/internal-transfers/internal-transfers.codecs.js +8 -1
  31. package/dist/services/internal-transfers/internal-transfers.codecs.js.map +1 -1
  32. package/dist/services/internal-transfers/internal-transfers.d.ts +1 -1
  33. package/dist/services/internal-transfers/internal-transfers.js +1 -1
  34. package/dist/services/internal-transfers/internal-transfers.js.map +1 -1
  35. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +3 -0
  36. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts.map +1 -1
  37. package/dist/services/internal-transfers/internal-transfers.schemas.js +4 -2
  38. package/dist/services/internal-transfers/internal-transfers.schemas.js.map +1 -1
  39. package/dist/services/internal-transfers/internal-transfers.types.d.ts +2 -1
  40. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  41. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  42. package/dist/services/orders/order-errors.schemas.d.ts +2 -2
  43. package/dist/services/orders/orders-batch.schemas.d.ts +54 -54
  44. package/dist/services/orders/orders-input.schemas.d.ts +6 -6
  45. package/dist/services/orders/orders-output.schemas.d.ts +17 -17
  46. package/dist/services/rewards/rewards.schemas.d.ts +3 -3
  47. package/dist/services/subaccounts/subaccounts.schemas.d.ts +4 -4
  48. package/dist/services/trades/trades.schemas.d.ts +2 -2
  49. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  50. package/dist/services/triggers/triggers-output.schemas.d.ts +30 -30
  51. package/dist/services/triggers/triggers.d.ts +10 -4
  52. package/dist/services/triggers/triggers.d.ts.map +1 -1
  53. package/dist/services/triggers/triggers.js +8 -0
  54. package/dist/services/triggers/triggers.js.map +1 -1
  55. package/dist/shared/rate-limit.schemas.d.ts +1 -1
  56. package/dist/shared/transports.js +27 -8
  57. package/dist/shared/transports.js.map +1 -1
  58. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @polyester/sdk
2
2
 
3
- ## 0.35.0-devnet-20261108182734
3
+ ## 0.35.0-devnet-20261110160258
4
4
 
5
5
  ### Minor Changes
6
6
 
@@ -12,6 +12,8 @@
12
12
 
13
13
  ### Patch Changes
14
14
 
15
+ - `createApiKeyEd25519AuthHeaders` now builds the same canonical string as the server's API-key verifier, so requests with escaped or unusual URLs stop failing signature checks. It signs the upper-cased method and the percent-decoded path, sorts query pairs by their decoded bytes (key, then value), and escapes everything outside `A-Z a-z 0-9 - . _ ~`, keeping bytes that are not UTF-8. A URL with a `;` in its query or a malformed percent-escape now throws `ConfigurationError` before signing, because the server rejects those requests whatever the signature. The tests pin the signing vectors shared with the Go, Python and Rust SDKs. ([#238](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/238))
16
+
15
17
  - API-key auth takes an optional `recvWindow`: a whole number of milliseconds from 1 to 60000, sent as `X-API-RECV-WINDOW` and signed on the line after the timestamp. The backend processes a request only until its timestamp plus the window, which defaults to 10000 when omitted. A value outside the range throws `ConfigurationError` before the request is sent. An `AUTH_RECV_WINDOW_INVALID` refusal maps to a non-retryable `ValidationError` rather than `AuthenticationError`, because the credentials are not at fault. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
16
18
 
17
19
  - The `orders.batchCreate` JSDoc now gives the batch's 15-minute idempotency window. It previously said 60 seconds, which is the `batchReplace` window. Within 15 minutes, a retry with the same `requestId` and payload returns each decided item's original result and retries the unresolved ones. After that the ID is free, and a repeat can place its orders again. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
@@ -24,10 +26,20 @@
24
26
 
25
27
  - `expandColumnarTimestampsSec` and `columnarTimestampSecAt` now end at `endTsSec`, so the last columnar history point is no longer one bucket early. ([#233](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/233))
26
28
 
29
+ - `formatLedgerBalance` is now exported from the package root. It converts a `ledger.read.v1.AssetBalance` message to the `LedgerBalance` that `balances.list` returns. Its U128 amounts are always at the 18-decimal ledger scale, whatever the asset's own decimals, so callers holding these messages from other APIs no longer convert them by hand. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
30
+
31
+ - `internalTransfers.create()` results now carry `status`: `"accepted"`, `"rejected"`, `"failed"`, or `"unspecified"` for a value this SDK version doesn't know. The response field was previously dropped. Rejected and failed transfers, such as insufficient funds or a missing step-up, still raise errors rather than returning a result. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
32
+
27
33
  - `lifecycle.listFlows` with an `accountSelector` now also returns the transfers the account received from other accounts, such as transfers from other users or subaccounts and reward payouts. Each row carries `participation`: `"owner"` for a flow the account owns, including a transfer it sent, and `"recipient"` for a received transfer. Rows are `"unspecified"` without an account selector and in flow detail and realtime updates. Pass `participation: "owner"` to keep the previous owner-only list or `"recipient"` for received transfers only. `participation` requires `accountSelector` and throws `ValidationError` without one. A `pageToken` now resumes only the request it came from, so change nothing but `limit` between pages. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
28
34
 
35
+ - `auth.login()` and `auth.refreshSession()` results now carry `session`, the issued token's assurance details (`sessionId`, `sessionLevel`, `authenticationMethods`, `authTimeMs`) in the same shape as `auth.me().session`. The wallet login response sent them, but the SDK dropped them. `session` is `undefined` when the response omits it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
36
+
37
+ - `auth.me()` now returns `rootSmartAccountAddress`, the caller's root smart-account address as lowercase `0x` hex, or `""` when the account has none. It was previously dropped. A new account can read `""` for a moment right after its first login, until the backend records the address. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
38
+
29
39
  - A ConnectRPC `resource_exhausted` that carries a `RateLimitDetail`, as wallet sign-in and the public catalog calls now send, maps to a `RateLimitError` with `rateLimit` set and `retryAfterMs` taken from the detail. Its `detail` is `{ service: "rate_limit", code: "RATE_LIMIT_EXCEEDED", rateLimit }`. The gateway's own refusal has no detail: `retryAfterMs` comes from `Retry-After` when present and is `undefined` for a concurrency refusal, so back off without a server hint. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
30
40
 
41
+ - Realtime token requests (`/v1/rt/token` and `/v1/rt/subscribe`) now go through the `fetch` passed to `PolyesterClient`, like every other SDK request. They used the global `fetch` before, so proxies, mocks and request logging never saw them. `RealtimeClient` takes the same optional `fetch`. Without one, both keep using the global `fetch`. ([#238](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/238))
42
+
31
43
  - Realtime token requests honor `Retry-After`. When the connection or subscription token endpoint answers 429 with a `Retry-After` header, the `RateLimitError` carries it as `retryAfterMs`, and the realtime client sends no further token request until it has passed (at most 60 seconds), even when the socket retries sooner. This covers public, private and private order stream sockets. ([#232](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/232))
32
44
 
33
45
  - A signed request refused with `AUTH_REPLAY_CAPACITY_EXHAUSTED` maps to a retryable `RateLimitError` without `retryAfterMs`. Before, a full replay store answered `SIGNATURE_INVALID`. Now each API key and account holds a fixed share, so only the key or account at its share is refused. Back off briefly and retry, which signs again. A shorter `recvWindow` frees room sooner. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
@@ -44,6 +56,8 @@
44
56
 
45
57
  - `tradeWsPb` in `@polyester/sdk/unstable/gen` adds the `cancelAllAfter` client command and acknowledgement, which arm, refresh or disarm the account's dead-man switch, plus the `ClientFrame` fields `timestampMs` and `recvWindowMs`, which set a per-command receive window. The SDK has no trading WebSocket client yet. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
46
58
 
59
+ - `triggers.fromProto(trigger)` converts a `triggers.v1.Trigger` message received from another API into the same `Trigger` record that `triggers.get`, `list`, and `subscribe` return, with quantities and prices scaled by the client's catalog. It waits for the catalog and throws when the trigger's market isn't in it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
60
+
47
61
  - A wallet login refused with `AUTH_WALLET_ALREADY_LINKED` maps to a non-retryable `AlreadyExistsError`. The wallet already belongs to another account, so the same login fails again. Log in with the account address the wallet already uses. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
48
62
 
49
63
  ## 0.34.0
@@ -23,9 +23,9 @@ interface PolyesterClientCommonConfig {
23
23
  */
24
24
  wireFormat?: "binary" | "json";
25
25
  /**
26
- * Custom fetch implementation for SDK HTTP requests. Defaults to the global
27
- * `fetch`, resolved on each request. Ignored when `transports` is
28
- * provided.
26
+ * Custom fetch implementation for SDK HTTP requests, realtime token requests
27
+ * included. Defaults to the global `fetch`, resolved on each request. Injected
28
+ * `transports` and `realtimeClient` ignore it.
29
29
  */
30
30
  fetch?: typeof fetch;
31
31
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.d.ts","names":[],"sources":["../src/core-client.ts"],"mappings":";;;;;;;;;;;;;KA8DY,8BAA8B,KAAK;UAErC;EACN,aAAa;EACb,eAAe;EACf,OAAO,kBAAkB;EACzB,WAAW;;;;;EAKX;;;;;;EAMA,eAAe;;;;;;;EAOf,aAAa;;;;;;EAMb,iBAAiB;;KAGhB;;EAGK,SAAS;EACT;EACA;;EAGA;;;;;;EAMA,kBAAkB;;;;;EAKlB,cAAc;;;KAIZ,4BAA4B,8BAA8B;;KAG1D,wBAAwB;UAc1B;EACN,YAAY;EACZ,UAAU;EACV,aAAa;;EAEb,uBAAuB,QAAQ;;UAGzB;EACN,cAAc,SAAS,8BAA8B;;;;;;;;;;;cA0E5C;;qBACU,YAAY;EAkBnB,YAAA,QAAQ,uBAAuB,UAAS;MAsChD,YAAY;MAqBZ,WAAW;MA2CX,QAAQ;;;;;YAqBF,4BAA4B"}
1
+ {"version":3,"file":"core-client.d.ts","names":[],"sources":["../src/core-client.ts"],"mappings":";;;;;;;;;;;;;KA8DY,8BAA8B,KAAK;UAErC;EACN,aAAa;EACb,eAAe;EACf,OAAO,kBAAkB;EACzB,WAAW;;;;;EAKX;;;;;;EAMA,eAAe;;;;;;;EAOf,aAAa;;;;;;EAMb,iBAAiB;;KAGhB;;EAGK,SAAS;EACT;EACA;;EAGA;;;;;;EAMA,kBAAkB;;;;;EAKlB,cAAc;;;KAIZ,4BAA4B,8BAA8B;;KAG1D,wBAAwB;UAc1B;EACN,YAAY;EACZ,UAAU;EACV,aAAa;;EAEb,uBAAuB,QAAQ;;UAGzB;EACN,cAAc,SAAS,8BAA8B;;;;;;;;;;;cA0E5C;;qBACU,YAAY;EAmBnB,YAAA,QAAQ,uBAAuB,UAAS;MAuChD,YAAY;MAsBZ,WAAW;MA2CX,QAAQ;;;;;YAqBF,4BAA4B"}
@@ -88,6 +88,7 @@ var PolyesterCore = class {
88
88
  #authProvider;
89
89
  #realtimeConfig;
90
90
  #configRealtimeClient;
91
+ #fetch;
91
92
  #configCatalog;
92
93
  #configCatalogSnapshot;
93
94
  #configCatalogCell;
@@ -113,6 +114,7 @@ var PolyesterCore = class {
113
114
  this.#authProvider = config.auth;
114
115
  this.#realtimeConfig = config.realtime;
115
116
  this.#configRealtimeClient = config.realtimeClient;
117
+ this.#fetch = config.fetch;
116
118
  this.#configCatalog = config.catalog;
117
119
  this.#configCatalogSnapshot = config.catalogSnapshot;
118
120
  this.#configCatalogCell = config.catalogCell;
@@ -139,7 +141,8 @@ var PolyesterCore = class {
139
141
  subscribeEndpoint: `${environment.apiUrl}/v1/rt/subscribe`,
140
142
  privateWsUrl: `${environment.apiUrl.replace(/^http/, "ws")}/v1/ws/private`,
141
143
  getAuthHeaders: this.#realtimeConfig?.getAuthHeaders ?? realtimeAuth.getAuthHeaders,
142
- hasAuth: this.#realtimeConfig?.hasAuth ?? realtimeAuth.hasAuth
144
+ hasAuth: this.#realtimeConfig?.hasAuth ?? realtimeAuth.hasAuth,
145
+ fetch: this.#fetch
143
146
  });
144
147
  }
145
148
  return this.#realtime;
@@ -1 +1 @@
1
- {"version":3,"file":"core-client.js","names":["#environment","#authProvider","#realtimeConfig","#configRealtimeClient","#configCatalog","#configCatalogSnapshot","#configCatalogCell","#createAuth","#getScales","#getResolver","#realtime","#catalog","#scales","#resolverInitialized","#resolver","#auth"],"sources":["../src/core-client.ts"],"sourcesContent":["import type { Interceptor } from \"@connectrpc/connect\";\nimport { ConfigurationError } from \"./shared/errors.js\";\nimport {\n createApiKeyEd25519AuthHeaders,\n createTransports,\n resolveJwtToken,\n type AuthAndPublicApiTransports,\n type Transports,\n type JwtAuthProvider,\n type ApiKeyEd25519AuthProvider,\n} from \"./shared/transports.js\";\nimport { parsePolyesterEnvironment, type PolyesterEnvironment } from \"./environment.js\";\nimport { AuthService } from \"./services/auth/auth.js\";\nimport type { SubaccountsService } from \"./services/subaccounts/subaccounts.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport {\n createPolyesterCatalog,\n type CatalogSnapshot,\n type CatalogSnapshotCell,\n type ClientCatalog,\n} from \"./catalogs/index.js\";\nimport { createCatalogSdkScales, type SdkScales } from \"./shared/decimal-surface.js\";\nimport { RealtimeClient, type PolyesterRealtime, type RealtimeConfig } from \"./realtime/index.js\";\n\nfunction realtimeAuthFromProvider(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider | undefined,\n): Pick<RealtimeConfig, \"getAuthHeaders\" | \"hasAuth\"> {\n if (!auth) return {};\n if (auth.kind === \"jwt\") {\n return {\n getAuthHeaders: async () => {\n const token = await resolveJwtToken(auth);\n const headers: Record<string, string> = {};\n if (token) headers.authorization = `Bearer ${token}`;\n return headers;\n },\n hasAuth: () => {\n try {\n const token = auth.getToken();\n if (token !== null && typeof token !== \"string\") {\n // Async credentials are validated by the token request.\n void token.catch(() => {});\n return true;\n }\n return token !== null && token.length > 0;\n } catch {\n // Let the token request report provider failures as AuthenticationError.\n return true;\n }\n },\n };\n }\n return {\n getAuthHeaders: (request) =>\n createApiKeyEd25519AuthHeaders(auth, {\n url: request.url,\n method: request.method,\n }),\n hasAuth: () => true,\n };\n}\n\nexport type PolyesterRealtimeAuthConfig = Pick<RealtimeConfig, \"getAuthHeaders\" | \"hasAuth\">;\n\ninterface PolyesterClientCommonConfig {\n environment: PolyesterEnvironment;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n realtime?: PolyesterRealtimeAuthConfig;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for human-readable debugging.\n */\n wireFormat?: \"binary\" | \"json\";\n /**\n * Custom fetch implementation for SDK HTTP requests. Defaults to the global\n * `fetch`, resolved on each request. Ignored when `transports` is\n * provided.\n */\n fetch?: typeof fetch;\n /**\n * Advanced: inject pre-built Connect transports (in-memory mocks, custom\n * stacks). When provided, the SDK does not build its own transports and the\n * built-in auth/error-mapping interceptors are NOT applied — the injected\n * transports own their full interceptor chain.\n */\n transports?: Transports;\n /**\n * Advanced: inject a realtime implementation (in-memory mocks, custom\n * stacks). When provided, the SDK skips constructing its Centrifuge-backed\n * realtime client and the `realtime` auth config is ignored.\n */\n realtimeClient?: PolyesterRealtime;\n}\n\ntype PolyesterCatalogConfig =\n | {\n /** Client-owned catalog store. */\n catalog: ClientCatalog;\n catalogSnapshot?: never;\n catalogCell?: never;\n }\n | {\n catalog?: never;\n /**\n * Explicit initial catalog snapshot, commonly hydrated from server-rendered data.\n * Combines with `catalogCell` as the cell's initial value without clobbering a\n * pre-populated cell.\n */\n catalogSnapshot?: CatalogSnapshot;\n /**\n * External snapshot storage for the client-built catalog. A cell backed by a\n * reactive source makes every catalog read reactive.\n */\n catalogCell?: CatalogSnapshotCell;\n };\n\n/** Configuration shared by every Polyester client. */\nexport type PolyesterClientBaseConfig = PolyesterClientCommonConfig & PolyesterCatalogConfig;\n\n/** Configuration for the base Polyester client. */\nexport type PolyesterClientConfig = PolyesterClientBaseConfig;\n\n/** Preserves the exclusive catalog configuration while projecting client config fields. */\nexport function pickPolyesterCatalogConfig(\n config: PolyesterClientBaseConfig,\n): PolyesterCatalogConfig {\n return config.catalog === undefined\n ? {\n catalogSnapshot: config.catalogSnapshot,\n catalogCell: config.catalogCell,\n }\n : { catalog: config.catalog };\n}\n\ninterface AuthServiceFactoryContext {\n transports: AuthAndPublicApiTransports;\n realtime: PolyesterRealtime;\n environment: PolyesterEnvironment;\n /** Loads this client's subaccounts service on demand, keeping it out of the core bundle. */\n loadSubaccounts: () => Promise<SubaccountsService>;\n}\n\ninterface PolyesterClientRuntimeConfig {\n createAuth?: (context: AuthServiceFactoryContext) => AuthService;\n}\n\n/**\n * Parses the configuration shared by every public client constructor.\n */\nexport function parsePolyesterClientConfig<TConfig extends PolyesterClientBaseConfig>(\n config: TConfig,\n): TConfig {\n if (typeof config !== \"object\" || config === null || Array.isArray(config)) {\n throw new ConfigurationError(\"Client configuration must be an object.\");\n }\n const environment = parsePolyesterEnvironment(config.environment);\n if (\n config.wireFormat !== undefined &&\n config.wireFormat !== \"binary\" &&\n config.wireFormat !== \"json\"\n ) {\n throw new ConfigurationError('wireFormat must be either \"binary\" or \"json\".');\n }\n if (config.fetch !== undefined && typeof config.fetch !== \"function\") {\n throw new ConfigurationError(\"fetch must be a function.\");\n }\n if (config.catalog && config.catalogSnapshot) {\n throw new ConfigurationError(\"Provide either catalog or catalogSnapshot, not both.\");\n }\n if (config.catalog && config.catalogCell) {\n throw new ConfigurationError(\"Provide either catalog or catalogCell, not both.\");\n }\n\n return Object.assign({}, config, { environment });\n}\n\n/** Client internals handed to service factories created with {@link defineService}. */\nexport interface ServiceContext {\n readonly transports: Transports;\n readonly environment: PolyesterEnvironment;\n readonly realtime: PolyesterRealtime;\n readonly catalog: ClientCatalog;\n readonly scales: SdkScales;\n readonly resolver: SubaccountResolver | undefined;\n}\n\nconst serviceContexts = new WeakMap<PolyesterCore, ServiceContext>();\n\n/**\n * Defines a service accessor that lazily creates one service instance per client.\n * Accessors live in their own modules, so bundles only include the services they call.\n */\nexport function defineService<TService>(\n create: (context: ServiceContext) => TService,\n): (client: PolyesterCore) => TService {\n const instances = new WeakMap<PolyesterCore, TService>();\n return (client) => {\n let service = instances.get(client);\n if (service === undefined) {\n const context = serviceContexts.get(client);\n if (!context) throw new ConfigurationError(\"Expected a Polyester client.\");\n service = create(context);\n instances.set(client, service);\n }\n return service;\n };\n}\n\n/**\n * Tree-shakable SDK client core: wires transports, realtime, catalogs, and auth\n * for a Polyester environment. Other services are reached through their\n * `@polyester/sdk/services/*` accessors, e.g. `ordersService(core)`, so bundles\n * only include the services they use. `PolyesterClient` adds a getter for every service.\n *\n * Everything is constructed lazily on first access (and memoized) so that creating a\n * client — which happens for every SSR request in server hooks — stays cheap.\n */\nexport class PolyesterCore {\n protected readonly transports: Transports;\n\n readonly #environment: PolyesterEnvironment;\n readonly #authProvider: JwtAuthProvider | ApiKeyEd25519AuthProvider | undefined;\n readonly #realtimeConfig: PolyesterRealtimeAuthConfig | undefined;\n readonly #configRealtimeClient: PolyesterRealtime | undefined;\n readonly #configCatalog: ClientCatalog | undefined;\n readonly #configCatalogSnapshot: CatalogSnapshot | undefined;\n readonly #configCatalogCell: CatalogSnapshotCell | undefined;\n readonly #createAuth: PolyesterClientRuntimeConfig[\"createAuth\"];\n\n #realtime: PolyesterRealtime | undefined;\n #catalog: ClientCatalog | undefined;\n #scales: SdkScales | undefined;\n #resolver: SubaccountResolver | undefined;\n #resolverInitialized = false;\n #auth: AuthService | undefined;\n\n constructor(config: PolyesterClientConfig, runtime: PolyesterClientRuntimeConfig = {}) {\n const parsedConfig = parsePolyesterClientConfig(config);\n config = parsedConfig;\n const interceptors = config.interceptors ?? [];\n const { environment } = config;\n\n this.transports =\n config.transports ??\n createTransports({\n apiUrl: environment.apiUrl,\n interceptors,\n auth: config.auth,\n wireFormat: config.wireFormat,\n fetch: config.fetch,\n });\n\n this.#environment = environment;\n this.#authProvider = config.auth;\n this.#realtimeConfig = config.realtime;\n this.#configRealtimeClient = config.realtimeClient;\n this.#configCatalog = config.catalog;\n this.#configCatalogSnapshot = config.catalogSnapshot;\n this.#configCatalogCell = config.catalogCell;\n this.#createAuth = runtime.createAuth;\n\n // Getters keep realtime, catalog, and scales lazy until a service needs them.\n const context = { transports: this.transports, environment } as ServiceContext;\n serviceContexts.set(\n this,\n Object.defineProperties(context, {\n realtime: { get: () => this.realtime },\n catalog: { get: () => this.catalog },\n scales: { get: () => this.#getScales() },\n resolver: { get: () => this.#getResolver() },\n }),\n );\n }\n\n get realtime(): PolyesterRealtime {\n if (!this.#realtime) {\n if (this.#configRealtimeClient) {\n this.#realtime = this.#configRealtimeClient;\n } else {\n const environment = this.#environment;\n const realtimeAuth = realtimeAuthFromProvider(this.#authProvider);\n this.#realtime = new RealtimeClient({\n wsUrl: environment.websocketUrl,\n tokenEndpoint: `${environment.apiUrl}/v1/rt/token`,\n subscribeEndpoint: `${environment.apiUrl}/v1/rt/subscribe`,\n privateWsUrl: `${environment.apiUrl.replace(/^http/, \"ws\")}/v1/ws/private`,\n getAuthHeaders:\n this.#realtimeConfig?.getAuthHeaders ?? realtimeAuth.getAuthHeaders,\n hasAuth: this.#realtimeConfig?.hasAuth ?? realtimeAuth.hasAuth,\n });\n }\n }\n return this.#realtime;\n }\n\n get catalog(): ClientCatalog {\n if (!this.#catalog) {\n if (this.#configCatalog) {\n this.#catalog = this.#configCatalog;\n } else {\n // Refresh is async and rare, so its services load on demand rather\n // than pinning market data and zipper into every bundle.\n this.#catalog = createPolyesterCatalog({\n snapshot: this.#configCatalogSnapshot,\n cell: this.#configCatalogCell,\n refresh: {\n market: async () => {\n const { marketDataService } =\n await import(\"./services/market-data/service.js\");\n return marketDataService(this).getSpotConfig();\n },\n zipper: async () => {\n const { zipperService } = await import(\"./services/zipper/service.js\");\n return zipperService(this).getDepositWithdrawConfig();\n },\n },\n });\n }\n }\n return this.#catalog;\n }\n\n #getScales(): SdkScales {\n // Lazy catalog binding: the resolver only dereferences `this.catalog` at\n // call time. getSpotConfig() (the catalog's own refresh source) never\n // awaits scale readiness.\n this.#scales ??= createCatalogSdkScales(() => this.catalog);\n return this.#scales;\n }\n\n #getResolver(): SubaccountResolver | undefined {\n if (!this.#resolverInitialized) {\n this.#resolverInitialized = true;\n this.#resolver = this.createSubaccountResolver();\n }\n return this.#resolver;\n }\n\n get auth(): AuthService {\n if (!this.#auth) {\n this.#auth =\n this.#createAuth?.({\n transports: this.transports,\n realtime: this.realtime,\n environment: this.#environment,\n loadSubaccounts: async () => {\n const { subaccountsService } =\n await import(\"./services/subaccounts/service.js\");\n return subaccountsService(this);\n },\n }) ?? new AuthService(this.transports, this.realtime);\n }\n return this.#auth;\n }\n\n /**\n * Override in subclasses to provide a subaccount resolver.\n * The resolver is called lazily when service methods are invoked.\n */\n protected createSubaccountResolver(): SubaccountResolver | undefined {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;AAwBA,SAAS,yBACL,MACkD;CAClD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,IAAI,KAAK,SAAS,OACd,OAAO;EACH,gBAAgB,YAAY;GACxB,MAAM,QAAQ,MAAM,gBAAgB,IAAI;GACxC,MAAM,UAAkC,CAAC;GACzC,IAAI,OAAO,QAAQ,gBAAgB,UAAU;GAC7C,OAAO;EACX;EACA,eAAe;GACX,IAAI;IACA,MAAM,QAAQ,KAAK,SAAS;IAC5B,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;KAE7C,MAAW,YAAY,CAAC,CAAC;KACzB,OAAO;IACX;IACA,OAAO,UAAU,QAAQ,MAAM,SAAS;GAC5C,QAAQ;IAEJ,OAAO;GACX;EACJ;CACJ;CAEJ,OAAO;EACH,iBAAiB,YACb,+BAA+B,MAAM;GACjC,KAAK,QAAQ;GACb,QAAQ,QAAQ;EACpB,CAAC;EACL,eAAe;CACnB;AACJ;;AAgEA,SAAgB,2BACZ,QACsB;CACtB,OAAO,OAAO,YAAY,KAAA,IACpB;EACI,iBAAiB,OAAO;EACxB,aAAa,OAAO;CACxB,IACA,EAAE,SAAS,OAAO,QAAQ;AACpC;;;;AAiBA,SAAgB,2BACZ,QACO;CACP,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GACrE,MAAM,IAAI,mBAAmB,yCAAyC;CAE1E,MAAM,cAAc,0BAA0B,OAAO,WAAW;CAChE,IACI,OAAO,eAAe,KAAA,KACtB,OAAO,eAAe,YACtB,OAAO,eAAe,QAEtB,MAAM,IAAI,mBAAmB,mDAA+C;CAEhF,IAAI,OAAO,UAAU,KAAA,KAAa,OAAO,OAAO,UAAU,YACtD,MAAM,IAAI,mBAAmB,2BAA2B;CAE5D,I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B,KAAKC,YAAY,KAAK,yBAAyB;EACnD;EACA,OAAO,KAAKA;CAChB;CAEA,IAAI,OAAoB;EACpB,IAAI,CAAC,KAAKC,OACN,KAAKA,QACD,KAAKR,cAAc;GACf,YAAY,KAAK;GACjB,UAAU,KAAK;GACf,aAAa,KAAKP;GAClB,iBAAiB,YAAY;IACzB,MAAM,EAAE,uBACJ,MAAM,OAAO;IACjB,OAAO,mBAAmB,IAAI;GAClC;EACJ,CAAC,KAAK,IAAI,YAAY,KAAK,YAAY,KAAK,QAAQ;EAE5D,OAAO,KAAKe;CAChB;;;;;CAMA,2BAAqE,CAErE;AACJ"}
1
+ {"version":3,"file":"core-client.js","names":["#environment","#authProvider","#realtimeConfig","#configRealtimeClient","#fetch","#configCatalog","#configCatalogSnapshot","#configCatalogCell","#createAuth","#getScales","#getResolver","#realtime","#catalog","#scales","#resolverInitialized","#resolver","#auth"],"sources":["../src/core-client.ts"],"sourcesContent":["import type { Interceptor } from \"@connectrpc/connect\";\nimport { ConfigurationError } from \"./shared/errors.js\";\nimport {\n createApiKeyEd25519AuthHeaders,\n createTransports,\n resolveJwtToken,\n type AuthAndPublicApiTransports,\n type Transports,\n type JwtAuthProvider,\n type ApiKeyEd25519AuthProvider,\n} from \"./shared/transports.js\";\nimport { parsePolyesterEnvironment, type PolyesterEnvironment } from \"./environment.js\";\nimport { AuthService } from \"./services/auth/auth.js\";\nimport type { SubaccountsService } from \"./services/subaccounts/subaccounts.js\";\nimport type { SubaccountResolver } from \"./services/subaccount-resolver.js\";\nimport {\n createPolyesterCatalog,\n type CatalogSnapshot,\n type CatalogSnapshotCell,\n type ClientCatalog,\n} from \"./catalogs/index.js\";\nimport { createCatalogSdkScales, type SdkScales } from \"./shared/decimal-surface.js\";\nimport { RealtimeClient, type PolyesterRealtime, type RealtimeConfig } from \"./realtime/index.js\";\n\nfunction realtimeAuthFromProvider(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider | undefined,\n): Pick<RealtimeConfig, \"getAuthHeaders\" | \"hasAuth\"> {\n if (!auth) return {};\n if (auth.kind === \"jwt\") {\n return {\n getAuthHeaders: async () => {\n const token = await resolveJwtToken(auth);\n const headers: Record<string, string> = {};\n if (token) headers.authorization = `Bearer ${token}`;\n return headers;\n },\n hasAuth: () => {\n try {\n const token = auth.getToken();\n if (token !== null && typeof token !== \"string\") {\n // Async credentials are validated by the token request.\n void token.catch(() => {});\n return true;\n }\n return token !== null && token.length > 0;\n } catch {\n // Let the token request report provider failures as AuthenticationError.\n return true;\n }\n },\n };\n }\n return {\n getAuthHeaders: (request) =>\n createApiKeyEd25519AuthHeaders(auth, {\n url: request.url,\n method: request.method,\n }),\n hasAuth: () => true,\n };\n}\n\nexport type PolyesterRealtimeAuthConfig = Pick<RealtimeConfig, \"getAuthHeaders\" | \"hasAuth\">;\n\ninterface PolyesterClientCommonConfig {\n environment: PolyesterEnvironment;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n realtime?: PolyesterRealtimeAuthConfig;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for human-readable debugging.\n */\n wireFormat?: \"binary\" | \"json\";\n /**\n * Custom fetch implementation for SDK HTTP requests, realtime token requests\n * included. Defaults to the global `fetch`, resolved on each request. Injected\n * `transports` and `realtimeClient` ignore it.\n */\n fetch?: typeof fetch;\n /**\n * Advanced: inject pre-built Connect transports (in-memory mocks, custom\n * stacks). When provided, the SDK does not build its own transports and the\n * built-in auth/error-mapping interceptors are NOT applied — the injected\n * transports own their full interceptor chain.\n */\n transports?: Transports;\n /**\n * Advanced: inject a realtime implementation (in-memory mocks, custom\n * stacks). When provided, the SDK skips constructing its Centrifuge-backed\n * realtime client and the `realtime` auth config is ignored.\n */\n realtimeClient?: PolyesterRealtime;\n}\n\ntype PolyesterCatalogConfig =\n | {\n /** Client-owned catalog store. */\n catalog: ClientCatalog;\n catalogSnapshot?: never;\n catalogCell?: never;\n }\n | {\n catalog?: never;\n /**\n * Explicit initial catalog snapshot, commonly hydrated from server-rendered data.\n * Combines with `catalogCell` as the cell's initial value without clobbering a\n * pre-populated cell.\n */\n catalogSnapshot?: CatalogSnapshot;\n /**\n * External snapshot storage for the client-built catalog. A cell backed by a\n * reactive source makes every catalog read reactive.\n */\n catalogCell?: CatalogSnapshotCell;\n };\n\n/** Configuration shared by every Polyester client. */\nexport type PolyesterClientBaseConfig = PolyesterClientCommonConfig & PolyesterCatalogConfig;\n\n/** Configuration for the base Polyester client. */\nexport type PolyesterClientConfig = PolyesterClientBaseConfig;\n\n/** Preserves the exclusive catalog configuration while projecting client config fields. */\nexport function pickPolyesterCatalogConfig(\n config: PolyesterClientBaseConfig,\n): PolyesterCatalogConfig {\n return config.catalog === undefined\n ? {\n catalogSnapshot: config.catalogSnapshot,\n catalogCell: config.catalogCell,\n }\n : { catalog: config.catalog };\n}\n\ninterface AuthServiceFactoryContext {\n transports: AuthAndPublicApiTransports;\n realtime: PolyesterRealtime;\n environment: PolyesterEnvironment;\n /** Loads this client's subaccounts service on demand, keeping it out of the core bundle. */\n loadSubaccounts: () => Promise<SubaccountsService>;\n}\n\ninterface PolyesterClientRuntimeConfig {\n createAuth?: (context: AuthServiceFactoryContext) => AuthService;\n}\n\n/**\n * Parses the configuration shared by every public client constructor.\n */\nexport function parsePolyesterClientConfig<TConfig extends PolyesterClientBaseConfig>(\n config: TConfig,\n): TConfig {\n if (typeof config !== \"object\" || config === null || Array.isArray(config)) {\n throw new ConfigurationError(\"Client configuration must be an object.\");\n }\n const environment = parsePolyesterEnvironment(config.environment);\n if (\n config.wireFormat !== undefined &&\n config.wireFormat !== \"binary\" &&\n config.wireFormat !== \"json\"\n ) {\n throw new ConfigurationError('wireFormat must be either \"binary\" or \"json\".');\n }\n if (config.fetch !== undefined && typeof config.fetch !== \"function\") {\n throw new ConfigurationError(\"fetch must be a function.\");\n }\n if (config.catalog && config.catalogSnapshot) {\n throw new ConfigurationError(\"Provide either catalog or catalogSnapshot, not both.\");\n }\n if (config.catalog && config.catalogCell) {\n throw new ConfigurationError(\"Provide either catalog or catalogCell, not both.\");\n }\n\n return Object.assign({}, config, { environment });\n}\n\n/** Client internals handed to service factories created with {@link defineService}. */\nexport interface ServiceContext {\n readonly transports: Transports;\n readonly environment: PolyesterEnvironment;\n readonly realtime: PolyesterRealtime;\n readonly catalog: ClientCatalog;\n readonly scales: SdkScales;\n readonly resolver: SubaccountResolver | undefined;\n}\n\nconst serviceContexts = new WeakMap<PolyesterCore, ServiceContext>();\n\n/**\n * Defines a service accessor that lazily creates one service instance per client.\n * Accessors live in their own modules, so bundles only include the services they call.\n */\nexport function defineService<TService>(\n create: (context: ServiceContext) => TService,\n): (client: PolyesterCore) => TService {\n const instances = new WeakMap<PolyesterCore, TService>();\n return (client) => {\n let service = instances.get(client);\n if (service === undefined) {\n const context = serviceContexts.get(client);\n if (!context) throw new ConfigurationError(\"Expected a Polyester client.\");\n service = create(context);\n instances.set(client, service);\n }\n return service;\n };\n}\n\n/**\n * Tree-shakable SDK client core: wires transports, realtime, catalogs, and auth\n * for a Polyester environment. Other services are reached through their\n * `@polyester/sdk/services/*` accessors, e.g. `ordersService(core)`, so bundles\n * only include the services they use. `PolyesterClient` adds a getter for every service.\n *\n * Everything is constructed lazily on first access (and memoized) so that creating a\n * client — which happens for every SSR request in server hooks — stays cheap.\n */\nexport class PolyesterCore {\n protected readonly transports: Transports;\n\n readonly #environment: PolyesterEnvironment;\n readonly #authProvider: JwtAuthProvider | ApiKeyEd25519AuthProvider | undefined;\n readonly #realtimeConfig: PolyesterRealtimeAuthConfig | undefined;\n readonly #configRealtimeClient: PolyesterRealtime | undefined;\n readonly #fetch: typeof fetch | undefined;\n readonly #configCatalog: ClientCatalog | undefined;\n readonly #configCatalogSnapshot: CatalogSnapshot | undefined;\n readonly #configCatalogCell: CatalogSnapshotCell | undefined;\n readonly #createAuth: PolyesterClientRuntimeConfig[\"createAuth\"];\n\n #realtime: PolyesterRealtime | undefined;\n #catalog: ClientCatalog | undefined;\n #scales: SdkScales | undefined;\n #resolver: SubaccountResolver | undefined;\n #resolverInitialized = false;\n #auth: AuthService | undefined;\n\n constructor(config: PolyesterClientConfig, runtime: PolyesterClientRuntimeConfig = {}) {\n const parsedConfig = parsePolyesterClientConfig(config);\n config = parsedConfig;\n const interceptors = config.interceptors ?? [];\n const { environment } = config;\n\n this.transports =\n config.transports ??\n createTransports({\n apiUrl: environment.apiUrl,\n interceptors,\n auth: config.auth,\n wireFormat: config.wireFormat,\n fetch: config.fetch,\n });\n\n this.#environment = environment;\n this.#authProvider = config.auth;\n this.#realtimeConfig = config.realtime;\n this.#configRealtimeClient = config.realtimeClient;\n this.#fetch = config.fetch;\n this.#configCatalog = config.catalog;\n this.#configCatalogSnapshot = config.catalogSnapshot;\n this.#configCatalogCell = config.catalogCell;\n this.#createAuth = runtime.createAuth;\n\n // Getters keep realtime, catalog, and scales lazy until a service needs them.\n const context = { transports: this.transports, environment } as ServiceContext;\n serviceContexts.set(\n this,\n Object.defineProperties(context, {\n realtime: { get: () => this.realtime },\n catalog: { get: () => this.catalog },\n scales: { get: () => this.#getScales() },\n resolver: { get: () => this.#getResolver() },\n }),\n );\n }\n\n get realtime(): PolyesterRealtime {\n if (!this.#realtime) {\n if (this.#configRealtimeClient) {\n this.#realtime = this.#configRealtimeClient;\n } else {\n const environment = this.#environment;\n const realtimeAuth = realtimeAuthFromProvider(this.#authProvider);\n this.#realtime = new RealtimeClient({\n wsUrl: environment.websocketUrl,\n tokenEndpoint: `${environment.apiUrl}/v1/rt/token`,\n subscribeEndpoint: `${environment.apiUrl}/v1/rt/subscribe`,\n privateWsUrl: `${environment.apiUrl.replace(/^http/, \"ws\")}/v1/ws/private`,\n getAuthHeaders:\n this.#realtimeConfig?.getAuthHeaders ?? realtimeAuth.getAuthHeaders,\n hasAuth: this.#realtimeConfig?.hasAuth ?? realtimeAuth.hasAuth,\n fetch: this.#fetch,\n });\n }\n }\n return this.#realtime;\n }\n\n get catalog(): ClientCatalog {\n if (!this.#catalog) {\n if (this.#configCatalog) {\n this.#catalog = this.#configCatalog;\n } else {\n // Refresh is async and rare, so its services load on demand rather\n // than pinning market data and zipper into every bundle.\n this.#catalog = createPolyesterCatalog({\n snapshot: this.#configCatalogSnapshot,\n cell: this.#configCatalogCell,\n refresh: {\n market: async () => {\n const { marketDataService } =\n await import(\"./services/market-data/service.js\");\n return marketDataService(this).getSpotConfig();\n },\n zipper: async () => {\n const { zipperService } = await import(\"./services/zipper/service.js\");\n return zipperService(this).getDepositWithdrawConfig();\n },\n },\n });\n }\n }\n return this.#catalog;\n }\n\n #getScales(): SdkScales {\n // Lazy catalog binding: the resolver only dereferences `this.catalog` at\n // call time. getSpotConfig() (the catalog's own refresh source) never\n // awaits scale readiness.\n this.#scales ??= createCatalogSdkScales(() => this.catalog);\n return this.#scales;\n }\n\n #getResolver(): SubaccountResolver | undefined {\n if (!this.#resolverInitialized) {\n this.#resolverInitialized = true;\n this.#resolver = this.createSubaccountResolver();\n }\n return this.#resolver;\n }\n\n get auth(): AuthService {\n if (!this.#auth) {\n this.#auth =\n this.#createAuth?.({\n transports: this.transports,\n realtime: this.realtime,\n environment: this.#environment,\n loadSubaccounts: async () => {\n const { subaccountsService } =\n await import(\"./services/subaccounts/service.js\");\n return subaccountsService(this);\n },\n }) ?? new AuthService(this.transports, this.realtime);\n }\n return this.#auth;\n }\n\n /**\n * Override in subclasses to provide a subaccount resolver.\n * The resolver is called lazily when service methods are invoked.\n */\n protected createSubaccountResolver(): SubaccountResolver | undefined {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;AAwBA,SAAS,yBACL,MACkD;CAClD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,IAAI,KAAK,SAAS,OACd,OAAO;EACH,gBAAgB,YAAY;GACxB,MAAM,QAAQ,MAAM,gBAAgB,IAAI;GACxC,MAAM,UAAkC,CAAC;GACzC,IAAI,OAAO,QAAQ,gBAAgB,UAAU;GAC7C,OAAO;EACX;EACA,eAAe;GACX,IAAI;IACA,MA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B;;;;;CAMA,2BAAqE,CAErE;AACJ"}
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ import { ApiKeyPolicy, ApiKeyPolicyApplyInput, ApiKeyPolicyCreateInput, ApiKeyPo
19
19
  import { ApiKey, ApiKeyIdInput, ApiKeyStatus, ApiKeysCreateInput, ApiKeysListInput, ApiKeysUpdateInput } from "./services/api-keys/api-keys.schemas.js";
20
20
  import { SubaccountPolicy, SubaccountPolicyApplyInput, SubaccountPolicyCreateInput, SubaccountPolicyUpdateInput } from "./services/policies/subaccount-policies/subaccount-policies.schemas.js";
21
21
  import { AccountCodeValue, TransferCodeValue } from "./shared/ledger-codes.js";
22
- import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse } from "./services/balances/balances.schemas.js";
22
+ import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse, formatLedgerBalance } from "./services/balances/balances.schemas.js";
23
23
  import { CreateSubaccountChallengeInput, CreateSubaccountInput, CreateSubaccountResult as CreateSubaccountResult$1, EffectiveSubaccountPermissions, GetSubaccountInput, InviteSubaccountMemberInput, ListSubaccountInvitesInput, RemoveSubaccountMemberInput, RespondSubaccountInviteInput, SetSubaccountMemberMfaRequirementInput, Subaccount, SubaccountActivityInput, SubaccountChallenge, SubaccountEvent, SubaccountIdInput, SubaccountInvite, SubaccountInviteStatus, SubaccountMember, SubaccountPermission, SubaccountPermissionDefinition, SubaccountRole, SubaccountRoleCatalog, SubaccountRoleDefinition, SubaccountStatus, UpdateSubaccountInput, UpdateSubaccountMemberRoleInput } from "./services/subaccounts/subaccounts.schemas.js";
24
24
  import { Candle, CandleColumnar, CandleColumnarInt, CandleInt, GetCandlesColumnsInput, GetCandlesInput, Timeframe } from "./services/candles/candles.schemas.js";
25
25
  import { ChainAnalyticsRange, GetUnifiedAssetBalancesInput, GetZippedAssetSupplyGroupInput, GetZippedAssetSupplyInput, UnifiedAssetBalancesResponse, ZippedAssetSupplyGroupResponse, ZippedAssetSupplyResponse, ZippedAssetSupplySeries } from "./services/chain-analytics/chain-analytics.schemas.js";
@@ -101,6 +101,7 @@ import "./services/deposit/deposit.types.js";
101
101
  import "./services/fees/fees.types.js";
102
102
  import "./services/guard-signer/guard-signer.types.js";
103
103
  import "./services/heatmap/heatmap.types.js";
104
+ import { InternalTransferStatus } from "./services/internal-transfers/internal-transfers.codecs.js";
104
105
  import "./services/internal-transfers/internal-transfers.types.js";
105
106
  import "./services/lifecycle/lifecycle.types.js";
106
107
  import "./services/market-data/market-data.types.js";
@@ -124,4 +125,4 @@ import "./services/transfers/transfers.types.js";
124
125
  import "./services/triggers/triggers.types.js";
125
126
  import "./services/vip/vip.types.js";
126
127
  import "./services/zipper/zipper.types.js";
127
- 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 AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, 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 ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, 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 CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, 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 GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, 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 ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, 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 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 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, OutcomeUnknownError, 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 PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, 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 SetAutoWithdrawRuleInput, 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 SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, 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 TradeBackfill, 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, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, 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, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
128
+ 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 AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, 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 ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, 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 CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, 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 GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferStatus, 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 ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, 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 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 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, OutcomeUnknownError, 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 PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, 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 SetAutoWithdrawRuleInput, 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 SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, 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 TradeBackfill, 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, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, 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, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_TESTNET_ENVIRONMENT, createPoly
6
6
  import { tsObjToNsString } from "./utils/time.js";
7
7
  import { PolyesterCore } from "./core-client.js";
8
8
  import { validateCreateAddressBookEntryInput } from "./services/address-book/address-book.schemas.js";
9
+ import { formatLedgerBalance } from "./services/balances/balances.schemas.js";
9
10
  import { formatConnectError, formatUserFacingError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError } from "./utils/errors.js";
10
11
  import { PolyesterClient } from "./client.js";
11
12
  import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, resolveAuthCookieName } from "./services/auth/cookie-constants.js";
@@ -18,4 +19,4 @@ import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFact
18
19
  import { columnarTimestampSecAt, expandColumnarTimestampsSec } from "./utils/columnar-time.js";
19
20
  import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "./shared/reconciliation.js";
20
21
  import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
21
- export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, OutcomeUnknownError, 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, RequestDeadlineExceededError, RequestError, RequestTooLargeError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, ValidationError, WithdrawDeadlineExpiredError, 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, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
22
+ export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, OutcomeUnknownError, 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, RequestDeadlineExceededError, RequestError, RequestTooLargeError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, ValidationError, WithdrawDeadlineExpiredError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -15,6 +15,11 @@ interface RealtimeConfig {
15
15
  privateWsUrl: string;
16
16
  getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;
17
17
  hasAuth?: () => boolean;
18
+ /**
19
+ * Custom fetch implementation for realtime token requests. Defaults to the
20
+ * global `fetch`, resolved on each request.
21
+ */
22
+ fetch?: typeof fetch;
18
23
  }
19
24
  //#endregion
20
25
  export { type ConnectChannelParams, RealtimeAuthRequest, RealtimeConfig, type SubscribeHandlers };
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;;UAwFiB;EACb,cAAc;EACd;;UAGa;EACb;EACA;EACA;;EAEA;EACA,kBAAkB,SAAS,wBAAwB,QAAQ,eAAe;EAC1E"}
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;;UAuFiB;EACb,cAAc;EACd;;UAGa;EACb;EACA;EACA;;EAEA;EACA,kBAAkB,SAAS,wBAAwB,QAAQ,eAAe;EAC1E;;;;;EAKA,eAAe"}
@@ -6,7 +6,6 @@ import { createSdkSubscriptionErrorContext, fromCentrifugeSubscriptionError } fr
6
6
  import { decodeProtoFrame } from "../utils/streams.js";
7
7
  import { fromBinary } from "@bufbuild/protobuf";
8
8
  //#region src/realtime/client.ts
9
- const realtimeFetch = makeFetch();
10
9
  const MAX_RETRY_AFTER_MS = 6e4;
11
10
  const defaultCentrifugeModuleLoader = () => import("centrifuge/build/protobuf");
12
11
  let centrifugeCtorPromise = null;
@@ -60,7 +59,9 @@ var RealtimeClient = class {
60
59
  /** Token requests wait until then after a 429 with `Retry-After`. */
61
60
  #tokenRetryAt = 0;
62
61
  #config;
62
+ #fetch;
63
63
  constructor(config) {
64
+ this.#fetch = makeFetch(config.fetch);
64
65
  this.#config = {
65
66
  wsUrl: config.wsUrl,
66
67
  tokenEndpoint: config.tokenEndpoint,
@@ -87,7 +88,7 @@ var RealtimeClient = class {
87
88
  method: "GET"
88
89
  });
89
90
  } while (this.#tokenRetryAt > Date.now());
90
- const res = await realtimeFetch(url, { headers });
91
+ const res = await this.#fetch(url, { headers });
91
92
  if (!res.ok) {
92
93
  const retryAfterMs = parseRetryAfterHeader(res.headers.get("retry-after"));
93
94
  if (res.status === 429 && retryAfterMs !== void 0) this.#tokenRetryAt = Math.max(this.#tokenRetryAt, Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS));