@polyester/sdk 0.36.0-devnet-20261118141710 → 0.36.0-devnet-20261118184607
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.
- package/CHANGELOG.md +5 -1
- package/dist/realtime/ready-gated-subscription.js +1 -1
- package/dist/realtime/snapshot-then-stream.js +2 -0
- package/dist/realtime/snapshot-then-stream.js.map +1 -1
- package/dist/services/account-activity/account-activity.schemas.d.ts +2 -2
- package/dist/services/assistant/assistant-events.schemas.d.ts +27 -27
- package/dist/services/assistant/assistant.schemas.d.ts +1 -1
- package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +3 -3
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/changelog/changelog.schemas.d.ts +38 -38
- package/dist/services/checkpoints/checkpoints.schemas.d.ts +1 -1
- package/dist/services/claims/claims.schemas.d.ts +2 -2
- package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +2 -2
- package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
- package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +6 -6
- package/dist/services/lifecycle/lifecycle.js +1 -1
- package/dist/services/lifecycle/lifecycle.js.map +1 -1
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +39 -39
- package/dist/services/orderbook/orderbook.js +1 -1
- package/dist/services/orders/order-errors.schemas.d.ts +9 -9
- package/dist/services/orders/orders-batch.schemas.d.ts +102 -102
- package/dist/services/orders/orders-input.schemas.d.ts +15 -15
- package/dist/services/orders/orders-output.schemas.d.ts +14 -14
- package/dist/services/orders/orders.d.ts.map +1 -1
- package/dist/services/orders/orders.js +47 -43
- package/dist/services/orders/orders.js.map +1 -1
- package/dist/services/rewards/rewards.schemas.d.ts +4 -4
- package/dist/services/statement-exports/statement-exports.schemas.d.ts +6 -6
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +4 -4
- package/dist/services/system/system.schemas.d.ts +13 -13
- package/dist/services/trades/trades.d.ts.map +1 -1
- package/dist/services/trades/trades.js +12 -4
- package/dist/services/trades/trades.js.map +1 -1
- package/dist/services/trades/trades.schemas.d.ts +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +50 -50
- package/dist/services/triggers/triggers.d.ts.map +1 -1
- package/dist/services/triggers/triggers.js +14 -10
- package/dist/services/triggers/triggers.js.map +1 -1
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +4 -1
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/decimal-surface.d.ts +6 -0
- package/dist/shared/decimal-surface.d.ts.map +1 -1
- package/dist/shared/decimal-surface.js +65 -1
- package/dist/shared/decimal-surface.js.map +1 -1
- package/dist/shared/rate-limit.schemas.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"triggers.d.ts","names":[],"sources":["../../../src/services/triggers/triggers.ts"],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"triggers.d.ts","names":[],"sources":["../../../src/services/triggers/triggers.ts"],"mappings":";;;;;;;;;;;;UA8EiB;EACb,UAAU;EACV;;UAGM,+BAA+B,mBAAmB;EACxD;;UAGM,oCAAoC,mBAAmB;EAC7D;;;;;cAMS;;EAYL,YAAA,YAAY,mBACZ,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;EAgBN,OACF,OAAO,oBACP,UAAU,2BACX,QAAQ;;;;;;;EAcL,UACF,OAAO,gBACP,UAAU,2BACX,QAAQ;;;;;EAeL,UACF,OAAO,gBACP,UAAU,2BACX,QAAQ;;;;EAaL,IAAI,OAAO,iBAAiB,UAAU,0BAA0B,QAAQ;;;;;EAkBxE,UAAU,SAAS,UAAgB,QAAQ;;;;EAQ3C,KACF,QAAO,mBACP,UAAU,0BACX,QAAQ;;;;;;EAqBL,OACF,OAAO,oBACP,UAAU,2BACX,QAAQ;;;;;;;;EAiBL,YACF,OAAO,0BACP,UAAU,2BACX,QAAQ;;;;EAsBL,OACF,OAAO,oBACP,UAAU,2BACX,QAAQ;;;;EAWL,MACF,OAAO,mBACP,UAAU,2BACX,QAAQ;;;;EAaL,OACF,OAAO,oBACP,UAAU,2BACX,QAAQ;;;;EAaL,WACF,OAAO,wBACP,UAAU,0BACX,QAAQ;;;;;;EA2BX,UAAU,OAAO;;;;;;EA2BjB,gBAAgB,OAAO"}
|
|
@@ -2,6 +2,7 @@ import { parse } from "../../shared/validation.js";
|
|
|
2
2
|
import { removeUndefined } from "../../utils/remove-undefined.js";
|
|
3
3
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
4
4
|
import { deliverBatch } from "../../shared/subscription-errors.js";
|
|
5
|
+
import { createCatalogRefreshQueue, hasKnownSymbol, withCatalogRefresh } from "../../shared/decimal-surface.js";
|
|
5
6
|
import { resolveAccountScopedInput } from "../subaccount-resolver.js";
|
|
6
7
|
import { TriggerEventBatchSchema, TriggerSchema, TriggersService as TriggersService$1 } from "../../gen/triggers/v1/triggers_pb.js";
|
|
7
8
|
import { BatchCancelTriggersResultSchema, CancelOcoResultSchema, CancelTriggerResultSchema, CreateOcoResultSchema, CreateTriggerResultSchema, ModifyTriggerResultSchema, PauseTriggerResultSchema, ResumeTriggerResultSchema, createTriggerEventSchema, createTriggerSchema } from "./triggers-output.schemas.js";
|
|
@@ -75,9 +76,9 @@ var TriggersService = class {
|
|
|
75
76
|
await this.#scales.ready();
|
|
76
77
|
const resolved = resolveAccountScopedInput(input, this.#resolver);
|
|
77
78
|
const validated = parse(GetTriggerInputSchema, resolved);
|
|
78
|
-
const
|
|
79
|
-
if (!
|
|
80
|
-
return parse(this.#triggerSchema,
|
|
79
|
+
const trigger = (await this.#client.getTrigger(removeUndefined(validated), toConnectCallOptions(options))).trigger;
|
|
80
|
+
if (!trigger) return null;
|
|
81
|
+
return withCatalogRefresh(this.#scales, () => parse(this.#triggerSchema, trigger));
|
|
81
82
|
}
|
|
82
83
|
/**
|
|
83
84
|
* Converts a `triggers.v1.Trigger` message received from another API into the same `Trigger`
|
|
@@ -85,7 +86,7 @@ var TriggersService = class {
|
|
|
85
86
|
*/
|
|
86
87
|
async fromProto(trigger) {
|
|
87
88
|
await this.#scales.ready();
|
|
88
|
-
return parse(this.#triggerSchema, trigger);
|
|
89
|
+
return withCatalogRefresh(this.#scales, () => parse(this.#triggerSchema, trigger));
|
|
89
90
|
}
|
|
90
91
|
/**
|
|
91
92
|
* Lists triggers for the resolved account scope with optional symbol ID, status, trigger type, parent order, OCO (`orderListId` or `clientListId`), limit, and page-token filters. Results are returned newest-first.
|
|
@@ -96,7 +97,7 @@ var TriggersService = class {
|
|
|
96
97
|
const validated = parse(ListTriggersInputSchema, resolved);
|
|
97
98
|
const res = await this.#client.listTriggers(removeUndefined(validated), toConnectCallOptions(options));
|
|
98
99
|
return {
|
|
99
|
-
triggers: parse(v.array(this.#triggerSchema), res.triggers),
|
|
100
|
+
triggers: await withCatalogRefresh(this.#scales, () => parse(v.array(this.#triggerSchema), res.triggers)),
|
|
100
101
|
nextPageToken: res.nextPageToken
|
|
101
102
|
};
|
|
102
103
|
}
|
|
@@ -183,18 +184,21 @@ var TriggersService = class {
|
|
|
183
184
|
*/
|
|
184
185
|
subscribe(input) {
|
|
185
186
|
const channel = `private:spot:triggers:${input.accountId}:proto`;
|
|
186
|
-
|
|
187
|
+
let open = true;
|
|
188
|
+
const queue = createCatalogRefreshQueue(this.#scales, channel, input.onError, () => open);
|
|
189
|
+
const stop = connectReadyGatedProtoChannel(this.#realtime, {
|
|
187
190
|
channel,
|
|
188
191
|
schema: TriggerSchema,
|
|
189
192
|
ready: () => this.#scales.ready(),
|
|
190
|
-
onPublication: (data) =>
|
|
191
|
-
const trigger = parse(this.#triggerSchema, data);
|
|
192
|
-
input.onEvent(trigger);
|
|
193
|
-
},
|
|
193
|
+
onPublication: (data) => queue(!hasKnownSymbol(this.#scales, data.symbolId), () => input.onEvent(parse(this.#triggerSchema, data))),
|
|
194
194
|
onConnected: () => input.onOpen?.(),
|
|
195
195
|
onDisconnected: () => input.onClose?.(),
|
|
196
196
|
onError: input.onError
|
|
197
197
|
});
|
|
198
|
+
return () => {
|
|
199
|
+
open = false;
|
|
200
|
+
stop();
|
|
201
|
+
};
|
|
198
202
|
}
|
|
199
203
|
/**
|
|
200
204
|
* Subscribes to private trigger lifecycle events on private:spot:triggers:events:{accountId}:proto and emits parsed trigger event records.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"triggers.js","names":["#client","Proto.TriggersService","#realtime","#resolver","#scales","#createTriggerInputSchema","#createOcoInputSchema","#modifyTriggerInputSchema","#triggerSchema","#triggerEventSchema","Proto.TriggerSchema","Proto.TriggerEventBatchSchema"],"sources":["../../../src/services/triggers/triggers.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { connectReadyGatedProtoChannel } from \"../../realtime/ready-gated-subscription.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { createMutationRequestId } from \"../../shared/request-id.js\";\nimport {\n createCreateOcoInputSchema,\n createCreateTriggerInputSchema,\n createModifyTriggerInputSchema,\n ListTriggersInputSchema,\n BatchCancelTriggersInputSchema,\n CancelOcoInputSchema,\n CancelTriggerInputSchema,\n PauseTriggerInputSchema,\n ResumeTriggerInputSchema,\n GetTriggerInputSchema,\n ListTriggerEventsInputSchema,\n CreateTriggerResultSchema,\n CreateOcoResultSchema,\n CancelOcoResultSchema,\n BatchCancelTriggersResultSchema,\n CancelTriggerResultSchema,\n ModifyTriggerResultSchema,\n PauseTriggerResultSchema,\n ResumeTriggerResultSchema,\n createTriggerSchema,\n createTriggerEventSchema,\n type Trigger,\n type CreateTriggerInput,\n type CreateOcoInput,\n type CreateOcoResult,\n type CancelOcoInput,\n type CancelOcoResult,\n type BatchCancelTriggersInput,\n type BatchCancelTriggersResult,\n type ListTriggersInput,\n type CancelTriggerInput,\n type GetTriggerInput,\n type ModifyTriggerInput,\n type PauseTriggerInput,\n type ResumeTriggerInput,\n type ListTriggerEventsInput,\n type CreateTriggerResult,\n type CancelTriggerResult,\n type ModifyTriggerResult,\n type PauseTriggerResult,\n type ResumeTriggerResult,\n type ListTriggerEventsResult,\n type TriggerEvent,\n} from \"./triggers.schemas.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\n\nexport type {\n CreateTriggerResult,\n CancelTriggerResult,\n ModifyTriggerResult,\n PauseTriggerResult,\n ResumeTriggerResult,\n ListTriggerEventsResult,\n};\n\nexport interface ListTriggersResult {\n triggers: Trigger[];\n nextPageToken: string;\n}\n\ninterface SubscribeTriggersInput extends BaseSubscribeInput<Trigger> {\n accountId: string;\n}\n\ninterface SubscribeTriggerEventsInput extends BaseSubscribeInput<TriggerEvent> {\n accountId: string;\n}\n\n/**\n * Manages standalone order triggers and their realtime lifecycle/event streams.\n */\nexport class TriggersService {\n #client: Client<typeof Proto.TriggersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #createTriggerInputSchema: ReturnType<typeof createCreateTriggerInputSchema>;\n #createOcoInputSchema: ReturnType<typeof createCreateOcoInputSchema>;\n #modifyTriggerInputSchema: ReturnType<typeof createModifyTriggerInputSchema>;\n #triggerSchema: ReturnType<typeof createTriggerSchema>;\n #triggerEventSchema: ReturnType<typeof createTriggerEventSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.TriggersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#createTriggerInputSchema = createCreateTriggerInputSchema(scales);\n this.#createOcoInputSchema = createCreateOcoInputSchema(scales);\n this.#modifyTriggerInputSchema = createModifyTriggerInputSchema(scales);\n this.#triggerSchema = createTriggerSchema(scales);\n this.#triggerEventSchema = createTriggerEventSchema(scales);\n }\n\n /**\n * Creates a standalone trigger for a symbol ID, using that market's catalog quantity scale.\n */\n async create(\n input: CreateTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#createTriggerInputSchema, resolved);\n const res = await this.#client.createTrigger(validatedInput, toConnectCallOptions(options));\n return parse(CreateTriggerResultSchema, res);\n }\n\n /**\n * Creates an OCO: a take-profit and a stop-loss over a quantity the account already holds, which\n * cancel each other. Returns the OCO's `orderListId` and both legs' trigger IDs; read the legs\n * with `list({ orderListId })`. An `OutcomeUnknownError` means the OCO may exist: list by\n * `clientListId` before retrying.\n */\n async createOco(\n input: CreateOcoInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOcoResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#createOcoInputSchema, resolved);\n const res = await this.#client.createOco(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CreateOcoResultSchema, res);\n }\n\n /**\n * Cancels both legs of an OCO by its `orderListId` and releases its reserved quantity. Canceling\n * either leg with `cancel` does the same.\n */\n async cancelOco(\n input: CancelOcoInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOcoResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelOcoInputSchema, resolved);\n const res = await this.#client.cancelOco(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelOcoResultSchema, res);\n }\n\n /**\n * Fetches one trigger by id in the resolved account scope and returns null when the backend response contains no trigger.\n */\n async get(input: GetTriggerInput, options?: PolyesterRequestOptions): Promise<Trigger | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(GetTriggerInputSchema, resolved);\n const res = await this.#client.getTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n\n if (!res.trigger) return null;\n return parse(this.#triggerSchema, res.trigger);\n }\n\n /**\n * Converts a `triggers.v1.Trigger` message received from another API into the same `Trigger`\n * record that `get`, `list`, and `subscribe` return, scaled with this client's catalog.\n */\n async fromProto(trigger: Proto.Trigger): Promise<Trigger> {\n await this.#scales.ready();\n return parse(this.#triggerSchema, trigger);\n }\n\n /**\n * Lists triggers for the resolved account scope with optional symbol ID, status, trigger type, parent order, OCO (`orderListId` or `clientListId`), limit, and page-token filters. Results are returned newest-first.\n */\n async list(\n input: ListTriggersInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggersResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggersInputSchema, resolved);\n const res = await this.#client.listTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return {\n triggers: parse(v.array(this.#triggerSchema), res.triggers),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Cancels an active trigger by id in the resolved account scope and returns the trigger id, resulting status, and server timestamp.\n * A trigger that has ended, including one a previous cancel already canceled, throws with code\n * `TRIGGER_STATUS_INVALID` for at least 60 s, and `TRIGGER_NOT_FOUND` after that: treat either as done.\n */\n async cancel(\n input: CancelTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelTriggerInputSchema, resolved);\n const res = await this.#client.cancelTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelTriggerResultSchema, res);\n }\n\n /**\n * Cancels 1–50 distinct triggers in one best-effort request; results follow `triggerIds` order.\n * `accepted` means the cancellation was requested. A `rejected` item's `code` says why:\n * `TRIGGER_STATUS_INVALID` has already ended, and `RATE_LIMIT_EXCEEDED`, `PAIR_BACKLOGGED` and\n * `TRIGGER_CONTROL_IN_PROGRESS` can be retried in a new batch. A requestId is generated when\n * omitted; retry a timed-out batch unchanged with the same requestId within 2 minutes.\n */\n async batchCancel(\n input: BatchCancelTriggersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelTriggersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(BatchCancelTriggersInputSchema, resolved);\n const res = await this.#client.batchCancelTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelTriggersResultSchema, res);\n if (result.results.length !== validated.triggerIds.length) {\n throw new Error(\n `batchCancel returned ${result.results.length} results for ${validated.triggerIds.length} requested triggers.`,\n );\n }\n return result;\n }\n\n /**\n * Applies a limited patch to an existing trigger. Omit activationPrice or maxSlippage to leave it unchanged, or pass `{ kind: \"none\" }` to clear it. Once a trailing stop has started tracking, a new or different activation price rejects the whole patch with `TRIGGER_ACTIVATION_PRICE_NOT_MODIFIABLE`; clearing it or repeating the current price is still accepted. To wait for a new activation price, cancel the trigger and create another. An optional symbol ID must name the trigger's own market. An API key limited to specific markets gets `API_KEY_MARKET_DENY` when the trigger's market is outside them.\n */\n async modify(\n input: ModifyTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#modifyTriggerInputSchema, resolved);\n const res = await this.#client.modifyTrigger(validated, toConnectCallOptions(options));\n return parse(ModifyTriggerResultSchema, res);\n }\n\n /**\n * Pauses an active trigger without discarding its immutable strategy configuration.\n */\n async pause(\n input: PauseTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<PauseTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(PauseTriggerInputSchema, resolved);\n const res = await this.#client.pauseTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(PauseTriggerResultSchema, res);\n }\n\n /**\n * Resumes a paused trigger. An optional symbol ID must name the trigger's own market. An API key limited to specific markets gets `API_KEY_MARKET_DENY` when the trigger's market is outside them.\n */\n async resume(\n input: ResumeTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ResumeTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ResumeTriggerInputSchema, resolved);\n const res = await this.#client.resumeTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ResumeTriggerResultSchema, res);\n }\n\n /**\n * Returns newest-first historical lifecycle events for one trigger, optionally filtered by event type. Fired events enumerate child-order actions. The SDK defaults limit to 50.\n */\n async listEvents(\n input: ListTriggerEventsInput,\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggerEventsResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggerEventsInputSchema, resolved);\n\n const res = await this.#client.listTriggerEvents(\n removeUndefined({\n triggerId: validated.triggerId,\n subaccountId: validated.subaccountId,\n limit: validated.limit ?? 50,\n eventType: validated.eventType,\n pageToken: validated.pageToken ?? \"\",\n }),\n toConnectCallOptions(options),\n );\n\n return {\n events: parse(v.array(this.#triggerEventSchema), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private trigger state updates on private:spot:triggers:{accountId}:proto and emits parsed trigger records.\n * Keep the copy of each trigger with the highest `version`, across list reads and updates, and ignore any copy whose\n * version is not higher than the one you hold: a reconnect can repeat an earlier state, and list results can lag.\n */\n subscribe(input: SubscribeTriggersInput): () => void {\n const channel = `private:spot:triggers:${input.accountId}:proto`;\n return connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.TriggerSchema,\n ready: () => this.#scales.ready(),\n onPublication: (data) => {\n const trigger = parse(this.#triggerSchema, data);\n input.onEvent(trigger);\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n\n /**\n * Subscribes to private trigger lifecycle events on private:spot:triggers:events:{accountId}:proto and emits parsed trigger event records.\n * Each publication batches events, emitted one at a time; `(triggerId, eventType, childSeq,\n * tsNs)` identifies an event, and a repeated identity replaces the earlier copy.\n */\n subscribeEvents(input: SubscribeTriggerEventsInput): () => void {\n const channel = `private:spot:triggers:events:${input.accountId}:proto`;\n return connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.TriggerEventBatchSchema,\n ready: () => this.#scales.ready(),\n onPublication: (batch) =>\n deliverBatch(\n channel,\n batch.events,\n (event) => input.onEvent(parse(this.#triggerEventSchema, event)),\n input.onError,\n ),\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyFA,IAAa,kBAAb,MAA6B;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACI,YACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAuB,WAAW,OAAO;EACrE,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,4BAA4B,+BAA+B,MAAM;EACtE,KAAKC,wBAAwB,2BAA2B,MAAM;EAC9D,KAAKC,4BAA4B,+BAA+B,MAAM;EACtE,KAAKC,iBAAiB,oBAAoB,MAAM;EAChD,KAAKC,sBAAsB,yBAAyB,MAAM;CAC9D;;;;CAKA,MAAM,OACF,OACA,SAC4B;EAC5B,MAAM,KAAKL,QAAQ,MAAM;EACzB,MAAM,WAAW,0BAA0B,OAAO,KAAKD,SAAS;EAChE,MAAM,iBAAiB,MAAM,KAAKE,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;;;;CAOA,gBAAgB,OAAgD;EAC5D,MAAM,UAAU,gCAAgC,MAAM,UAAU;EAChE,OAAO,8BAA8B,KAAKN,WAAW;GACjD;GACA,QAAQS;GACR,aAAa,KAAKP,QAAQ,MAAM;GAChC,gBAAgB,UACZ,aACI,SACA,MAAM,SACL,UAAU,MAAM,QAAQ,MAAM,KAAKK,qBAAqB,KAAK,CAAC,GAC/D,MAAM,OACV;GACJ,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
|
|
1
|
+
{"version":3,"file":"triggers.js","names":["#client","Proto.TriggersService","#realtime","#resolver","#scales","#createTriggerInputSchema","#createOcoInputSchema","#modifyTriggerInputSchema","#triggerSchema","#triggerEventSchema","Proto.TriggerSchema","Proto.TriggerEventBatchSchema"],"sources":["../../../src/services/triggers/triggers.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport {\n createCatalogRefreshQueue,\n hasKnownSymbol,\n withCatalogRefresh,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { connectReadyGatedProtoChannel } from \"../../realtime/ready-gated-subscription.js\";\nimport { createMutationRequestId } from \"../../shared/request-id.js\";\nimport {\n createCreateOcoInputSchema,\n createCreateTriggerInputSchema,\n createModifyTriggerInputSchema,\n ListTriggersInputSchema,\n BatchCancelTriggersInputSchema,\n CancelOcoInputSchema,\n CancelTriggerInputSchema,\n PauseTriggerInputSchema,\n ResumeTriggerInputSchema,\n GetTriggerInputSchema,\n ListTriggerEventsInputSchema,\n CreateTriggerResultSchema,\n CreateOcoResultSchema,\n CancelOcoResultSchema,\n BatchCancelTriggersResultSchema,\n CancelTriggerResultSchema,\n ModifyTriggerResultSchema,\n PauseTriggerResultSchema,\n ResumeTriggerResultSchema,\n createTriggerSchema,\n createTriggerEventSchema,\n type Trigger,\n type CreateTriggerInput,\n type CreateOcoInput,\n type CreateOcoResult,\n type CancelOcoInput,\n type CancelOcoResult,\n type BatchCancelTriggersInput,\n type BatchCancelTriggersResult,\n type ListTriggersInput,\n type CancelTriggerInput,\n type GetTriggerInput,\n type ModifyTriggerInput,\n type PauseTriggerInput,\n type ResumeTriggerInput,\n type ListTriggerEventsInput,\n type CreateTriggerResult,\n type CancelTriggerResult,\n type ModifyTriggerResult,\n type PauseTriggerResult,\n type ResumeTriggerResult,\n type ListTriggerEventsResult,\n type TriggerEvent,\n} from \"./triggers.schemas.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\n\nexport type {\n CreateTriggerResult,\n CancelTriggerResult,\n ModifyTriggerResult,\n PauseTriggerResult,\n ResumeTriggerResult,\n ListTriggerEventsResult,\n};\n\nexport interface ListTriggersResult {\n triggers: Trigger[];\n nextPageToken: string;\n}\n\ninterface SubscribeTriggersInput extends BaseSubscribeInput<Trigger> {\n accountId: string;\n}\n\ninterface SubscribeTriggerEventsInput extends BaseSubscribeInput<TriggerEvent> {\n accountId: string;\n}\n\n/**\n * Manages standalone order triggers and their realtime lifecycle/event streams.\n */\nexport class TriggersService {\n #client: Client<typeof Proto.TriggersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #createTriggerInputSchema: ReturnType<typeof createCreateTriggerInputSchema>;\n #createOcoInputSchema: ReturnType<typeof createCreateOcoInputSchema>;\n #modifyTriggerInputSchema: ReturnType<typeof createModifyTriggerInputSchema>;\n #triggerSchema: ReturnType<typeof createTriggerSchema>;\n #triggerEventSchema: ReturnType<typeof createTriggerEventSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.TriggersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#createTriggerInputSchema = createCreateTriggerInputSchema(scales);\n this.#createOcoInputSchema = createCreateOcoInputSchema(scales);\n this.#modifyTriggerInputSchema = createModifyTriggerInputSchema(scales);\n this.#triggerSchema = createTriggerSchema(scales);\n this.#triggerEventSchema = createTriggerEventSchema(scales);\n }\n\n /**\n * Creates a standalone trigger for a symbol ID, using that market's catalog quantity scale.\n */\n async create(\n input: CreateTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#createTriggerInputSchema, resolved);\n const res = await this.#client.createTrigger(validatedInput, toConnectCallOptions(options));\n return parse(CreateTriggerResultSchema, res);\n }\n\n /**\n * Creates an OCO: a take-profit and a stop-loss over a quantity the account already holds, which\n * cancel each other. Returns the OCO's `orderListId` and both legs' trigger IDs; read the legs\n * with `list({ orderListId })`. An `OutcomeUnknownError` means the OCO may exist: list by\n * `clientListId` before retrying.\n */\n async createOco(\n input: CreateOcoInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOcoResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#createOcoInputSchema, resolved);\n const res = await this.#client.createOco(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CreateOcoResultSchema, res);\n }\n\n /**\n * Cancels both legs of an OCO by its `orderListId` and releases its reserved quantity. Canceling\n * either leg with `cancel` does the same.\n */\n async cancelOco(\n input: CancelOcoInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOcoResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelOcoInputSchema, resolved);\n const res = await this.#client.cancelOco(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelOcoResultSchema, res);\n }\n\n /**\n * Fetches one trigger by id in the resolved account scope and returns null when the backend response contains no trigger.\n */\n async get(input: GetTriggerInput, options?: PolyesterRequestOptions): Promise<Trigger | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(GetTriggerInputSchema, resolved);\n const res = await this.#client.getTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n\n const trigger = res.trigger;\n if (!trigger) return null;\n return withCatalogRefresh(this.#scales, () => parse(this.#triggerSchema, trigger));\n }\n\n /**\n * Converts a `triggers.v1.Trigger` message received from another API into the same `Trigger`\n * record that `get`, `list`, and `subscribe` return, scaled with this client's catalog.\n */\n async fromProto(trigger: Proto.Trigger): Promise<Trigger> {\n await this.#scales.ready();\n return withCatalogRefresh(this.#scales, () => parse(this.#triggerSchema, trigger));\n }\n\n /**\n * Lists triggers for the resolved account scope with optional symbol ID, status, trigger type, parent order, OCO (`orderListId` or `clientListId`), limit, and page-token filters. Results are returned newest-first.\n */\n async list(\n input: ListTriggersInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggersResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggersInputSchema, resolved);\n const res = await this.#client.listTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return {\n triggers: await withCatalogRefresh(this.#scales, () =>\n parse(v.array(this.#triggerSchema), res.triggers),\n ),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Cancels an active trigger by id in the resolved account scope and returns the trigger id, resulting status, and server timestamp.\n * A trigger that has ended, including one a previous cancel already canceled, throws with code\n * `TRIGGER_STATUS_INVALID` for at least 60 s, and `TRIGGER_NOT_FOUND` after that: treat either as done.\n */\n async cancel(\n input: CancelTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelTriggerInputSchema, resolved);\n const res = await this.#client.cancelTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelTriggerResultSchema, res);\n }\n\n /**\n * Cancels 1–50 distinct triggers in one best-effort request; results follow `triggerIds` order.\n * `accepted` means the cancellation was requested. A `rejected` item's `code` says why:\n * `TRIGGER_STATUS_INVALID` has already ended, and `RATE_LIMIT_EXCEEDED`, `PAIR_BACKLOGGED` and\n * `TRIGGER_CONTROL_IN_PROGRESS` can be retried in a new batch. A requestId is generated when\n * omitted; retry a timed-out batch unchanged with the same requestId within 2 minutes.\n */\n async batchCancel(\n input: BatchCancelTriggersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelTriggersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(BatchCancelTriggersInputSchema, resolved);\n const res = await this.#client.batchCancelTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelTriggersResultSchema, res);\n if (result.results.length !== validated.triggerIds.length) {\n throw new Error(\n `batchCancel returned ${result.results.length} results for ${validated.triggerIds.length} requested triggers.`,\n );\n }\n return result;\n }\n\n /**\n * Applies a limited patch to an existing trigger. Omit activationPrice or maxSlippage to leave it unchanged, or pass `{ kind: \"none\" }` to clear it. Once a trailing stop has started tracking, a new or different activation price rejects the whole patch with `TRIGGER_ACTIVATION_PRICE_NOT_MODIFIABLE`; clearing it or repeating the current price is still accepted. To wait for a new activation price, cancel the trigger and create another. An optional symbol ID must name the trigger's own market. An API key limited to specific markets gets `API_KEY_MARKET_DENY` when the trigger's market is outside them.\n */\n async modify(\n input: ModifyTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#modifyTriggerInputSchema, resolved);\n const res = await this.#client.modifyTrigger(validated, toConnectCallOptions(options));\n return parse(ModifyTriggerResultSchema, res);\n }\n\n /**\n * Pauses an active trigger without discarding its immutable strategy configuration.\n */\n async pause(\n input: PauseTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<PauseTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(PauseTriggerInputSchema, resolved);\n const res = await this.#client.pauseTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(PauseTriggerResultSchema, res);\n }\n\n /**\n * Resumes a paused trigger. An optional symbol ID must name the trigger's own market. An API key limited to specific markets gets `API_KEY_MARKET_DENY` when the trigger's market is outside them.\n */\n async resume(\n input: ResumeTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ResumeTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ResumeTriggerInputSchema, resolved);\n const res = await this.#client.resumeTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ResumeTriggerResultSchema, res);\n }\n\n /**\n * Returns newest-first historical lifecycle events for one trigger, optionally filtered by event type. Fired events enumerate child-order actions. The SDK defaults limit to 50.\n */\n async listEvents(\n input: ListTriggerEventsInput,\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggerEventsResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggerEventsInputSchema, resolved);\n\n const res = await this.#client.listTriggerEvents(\n removeUndefined({\n triggerId: validated.triggerId,\n subaccountId: validated.subaccountId,\n limit: validated.limit ?? 50,\n eventType: validated.eventType,\n pageToken: validated.pageToken ?? \"\",\n }),\n toConnectCallOptions(options),\n );\n\n return {\n events: parse(v.array(this.#triggerEventSchema), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private trigger state updates on private:spot:triggers:{accountId}:proto and emits parsed trigger records.\n * Keep the copy of each trigger with the highest `version`, across list reads and updates, and ignore any copy whose\n * version is not higher than the one you hold: a reconnect can repeat an earlier state, and list results can lag.\n */\n subscribe(input: SubscribeTriggersInput): () => void {\n const channel = `private:spot:triggers:${input.accountId}:proto`;\n let open = true;\n const queue = createCatalogRefreshQueue(this.#scales, channel, input.onError, () => open);\n const stop = connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.TriggerSchema,\n ready: () => this.#scales.ready(),\n onPublication: (data) =>\n queue(!hasKnownSymbol(this.#scales, data.symbolId), () =>\n input.onEvent(parse(this.#triggerSchema, data)),\n ),\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n return () => {\n open = false;\n stop();\n };\n }\n\n /**\n * Subscribes to private trigger lifecycle events on private:spot:triggers:events:{accountId}:proto and emits parsed trigger event records.\n * Each publication batches events, emitted one at a time; `(triggerId, eventType, childSeq,\n * tsNs)` identifies an event, and a repeated identity replaces the earlier copy.\n */\n subscribeEvents(input: SubscribeTriggerEventsInput): () => void {\n const channel = `private:spot:triggers:events:${input.accountId}:proto`;\n return connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.TriggerEventBatchSchema,\n ready: () => this.#scales.ready(),\n onPublication: (batch) =>\n deliverBatch(\n channel,\n batch.events,\n (event) => input.onEvent(parse(this.#triggerEventSchema, event)),\n input.onError,\n ),\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8FA,IAAa,kBAAb,MAA6B;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACI,YACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAuB,WAAW,OAAO;EACrE,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,4BAA4B,+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KS,mBAAmB,GAAG,IAAI,MAAM;GAC3D,eAAe,IAAI;EACvB;CACJ;;;;;;CAOA,UAAU,OAA2C;EACjD,MAAM,UAAU,yBAAyB,MAAM,UAAU;EACzD,IAAI,OAAO;EACX,MAAM,QAAQ,0BAA0B,KAAKL,SAAS,SAAS,MAAM,eAAe,IAAI;EACxF,MAAM,OAAO,8BAA8B,KAAKF,WAAW;GACvD;GACA,QAAQQ;GACR,aAAa,KAAKN,QAAQ,MAAM;GAChC,gBAAgB,SACZ,MAAM,CAAC,eAAe,KAAKA,SAAS,KAAK,QAAQ,SAC7C,MAAM,QAAQ,MAAM,KAAKI,gBAAgB,IAAI,CAAC,CAClD;GACJ,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;EACD,aAAa;GACT,OAAO;GACP,KAAK;EACT;CACJ;;;;;;CAOA,gBAAgB,OAAgD;EAC5D,MAAM,UAAU,gCAAgC,MAAM,UAAU;EAChE,OAAO,8BAA8B,KAAKN,WAAW;GACjD;GACA,QAAQS;GACR,aAAa,KAAKP,QAAQ,MAAM;GAChC,gBAAgB,UACZ,aACI,SACA,MAAM,SACL,UAAU,MAAM,QAAQ,MAAM,KAAKK,qBAAqB,KAAK,CAAC,GAC/D,MAAM,OACV;GACJ,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAwMgB,6BAA6B,IAAI,eAAe;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAwMgB,6BAA6B,IAAI,eAAe;;;;;;;;;iBAkThD,iBAAiB;;;;;;iBAyDjB,iCAAiC"}
|
|
@@ -175,7 +175,10 @@ function connectErrorToPolyesterError(ce) {
|
|
|
175
175
|
case Code.Aborted: return new TransientError(withFallback("Operation aborted by the backend."), options);
|
|
176
176
|
default:
|
|
177
177
|
if (ce.code === Code.Unknown && isFetchNetworkError(ce.cause)) return new NetworkError("Transport request failed", options);
|
|
178
|
-
if (/service temporarily unavailable/i.test(message)) return new ServiceUnavailableError(withFallback("Service unavailable."),
|
|
178
|
+
if (/service temporarily unavailable/i.test(message)) return new ServiceUnavailableError(withFallback("Service unavailable."), {
|
|
179
|
+
...options,
|
|
180
|
+
retryAfterMs: parseRetryAfterMs(ce)
|
|
181
|
+
});
|
|
179
182
|
return new InternalServerError(withFallback("Internal server error."), options);
|
|
180
183
|
}
|
|
181
184
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n ClaimOutcomeUnknownError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isFetchNetworkError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n NetworkError,\n normalizeErrorMessage,\n OutcomeUnknownError,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n RequestDeadlineExceededError,\n RequestTooLargeError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\n// A body over the API's size limit arrives as ResourceExhausted with no detail; match its message.\nconst REQUEST_TOO_LARGE_MESSAGE = \"request too large\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\n);\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_NOT_ENROLLED\") return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n return parseRetryAfterHeader(ce.metadata.get(\"retry-after\"));\n}\n\n/** Parses an HTTP `Retry-After` value (delay seconds or HTTP date) into milliseconds. */\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (!value) return undefined;\n if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n // Not a rate limit: the same request is refused again, so it must not read as retryable.\n if (\n ce.code === Code.ResourceExhausted &&\n !detail &&\n ce.rawMessage === REQUEST_TOO_LARGE_MESSAGE\n ) {\n return new RequestTooLargeError(\n \"Request is over the API's size limit. Send a smaller one.\",\n options,\n );\n }\n\n // A malformed X-API-RECV-WINDOW arrives as unauthenticated, but the\n // credentials are fine: the request is wrong, so do not log the caller out.\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RECV_WINDOW_INVALID\") {\n return new ValidationError(\n withFallback(\"API key receive window must be 1 to 60000 milliseconds.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n // Arrives as Aborted, which would otherwise map to a retryable TransientError.\n if (detail?.service === \"alerts\" && detail.code === \"REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Price alert changed since it was last read.\"),\n options,\n );\n }\n\n // Arrives as ResourceExhausted, which would otherwise map to a retryable RateLimitError;\n // it clears only when one of the account's exports finishes.\n if (detail?.service === \"ledger\" && detail.code === \"STATEMENT_EXPORT_LIMIT_REACHED\") {\n return new PreconditionFailedError(\n withFallback(\n \"The account already has the most statement exports queued or in progress. Wait for one to finish (statementExports.list shows their status), then create a new one.\",\n ),\n options,\n );\n }\n\n // Arrive as ResourceExhausted, but clear only after the account's 6 hour conversion window\n // or the target's daily limit, not on a quick retry. DUST_BUSY stays a RateLimitError.\n if (detail?.service === \"internal_transfer\" && detail.code === \"DUST_WINDOW_ACTIVE\") {\n return new PreconditionFailedError(\n withFallback(\n \"The account converted dust in the last 6 hours, or a conversion is still processing. Try again once 6 hours have passed since the last conversion.\",\n ),\n options,\n );\n }\n if (detail?.service === \"internal_transfer\" && detail.code === \"DUST_DAILY_LIMIT\") {\n return new PreconditionFailedError(\n withFallback(\n \"The target asset reached its daily dust conversion limit. Try again tomorrow or pick another target asset.\",\n ),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_WALLET_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Wallet is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_SCOPE_MISMATCH\") {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_LAST_FACTOR_REQUIRED\") {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n // Arrives as Unavailable; mapped on its own so callers get the claim ID.\n if (detail?.service === \"claims\" && detail.code === \"CLAIM_OUTCOME_UNKNOWN\") {\n return new ClaimOutcomeUnknownError(\n withFallback(\"Daily claim payout is not confirmed yet; check the claim status.\"),\n { ...options, claimId: detail.claimId },\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"REQUEST_DEADLINE_EXCEEDED\") {\n return new RequestDeadlineExceededError(\n withFallback(\"Request receive window ended before admission; nothing changed.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit =\n detail?.service === \"orders\" || detail?.service === \"rate_limit\"\n ? detail.rateLimit\n : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Connect reads 200 bodies outside the SDK fetch wrapper, so a connection\n // dropped mid-body arrives as Unknown with the raw fetch TypeError as cause.\n if (ce.code === Code.Unknown && isFetchNetworkError(ce.cause)) {\n return new NetworkError(\"Transport request failed\", options);\n }\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_VERIFY_FAILED\")\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-canceled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n await loadErrorDetailDecoders(err);\n throw toPolyesterError(err);\n }\n };\n}\n\n// Non-idempotent writes the contract answers with `deadline_exceeded` / 504 when the write may\n// already have been applied (changes/2026-11-15T2309Z-orders-v1.md); a retry could apply it twice.\nconst UNKNOWN_OUTCOME_ON_SERVER_TIMEOUT = new Set([\n \"auth.v1.ApiKeyService.CreateApiKey\",\n \"auth.v1.PolicyService.CreateApiPolicy\",\n \"auth.v1.PolicyService.CreateSubaccountPolicy\",\n \"auth.v1.MFAService.RegenerateRecoveryCodes\",\n]);\n\nfunction withUnknownWriteOutcome(\n method: { name: string; parent: { typeName: string } },\n err: unknown,\n): unknown {\n if (!(err instanceof TimeoutError || err instanceof ServiceUnavailableError)) return err;\n // Only a server-sent 504; a client-side timeout carries no status.\n if (err.status !== 504) return err;\n if (!UNKNOWN_OUTCOME_ON_SERVER_TIMEOUT.has(`${method.parent.typeName}.${method.name}`)) {\n return err;\n }\n return new OutcomeUnknownError(\n \"Outcome unknown; the write may have been applied. Read the current state before retrying.\",\n { cause: err, status: 504 },\n );\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw withUnknownWriteOutcome(method, await toTransportError(error, signal));\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AAiDA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAG1C,MAAM,4BAA4B;AAElC,SAAS,yBAAyB,QAAmD;CACjF,IAAI,QAAQ,YAAY,YACpB,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,qBACpB,OAAO;EACH;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,UACpB,OAAO,CAAC,uBAAuB,+BAA+B,CAAC,CAAC,SAAS,OAAO,IAAI;CAGxF,IAAI,QAAQ,YAAY,QACpB,OAAO,OAAO,SAAS;CAE3B,OAAO;AACX;AAEA,SAAS,iBAAiB,WAA4D;CAClF,IAAI,WAAW,iBAAiB,KAAA,GAAW,OAAO,KAAA;CAClD,MAAM,QAAQ,OAAO,UAAU,YAAY;CAC3C,OAAO,SAAS,OAAO,OAAO,gBAAgB,IAAI,OAAO,KAAK,IAAI,KAAA;AACtE;AAEA,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,aAAa;AACnB,MAAM,eAAe,IAAI,OACrB,OAAO,aAAa,WAAW,WAAW,mCAAmC,kBAAkB,WAAW,WAAW,mCAAmC,aAAa,GAAG,WAAW,+CACnL,GACJ;;;;;;AAOA,SAAgB,4BAA4B,KAAsB;CAE9D,MAAM,MADK,aAAa,KAAK,GAChB,CAAC,CAAC,WAAW;CAC1B,OAAO,sBAAsB,GAAG;AACpC;AAaA,SAAS,aAAa,QAA+D;CACjF,IA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
|
+
{"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n ClaimOutcomeUnknownError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isFetchNetworkError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n NetworkError,\n normalizeErrorMessage,\n OutcomeUnknownError,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n RequestDeadlineExceededError,\n RequestTooLargeError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\n// A body over the API's size limit arrives as ResourceExhausted with no detail; match its message.\nconst REQUEST_TOO_LARGE_MESSAGE = \"request too large\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\n);\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_NOT_ENROLLED\") return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n return parseRetryAfterHeader(ce.metadata.get(\"retry-after\"));\n}\n\n/** Parses an HTTP `Retry-After` value (delay seconds or HTTP date) into milliseconds. */\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (!value) return undefined;\n if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n // Not a rate limit: the same request is refused again, so it must not read as retryable.\n if (\n ce.code === Code.ResourceExhausted &&\n !detail &&\n ce.rawMessage === REQUEST_TOO_LARGE_MESSAGE\n ) {\n return new RequestTooLargeError(\n \"Request is over the API's size limit. Send a smaller one.\",\n options,\n );\n }\n\n // A malformed X-API-RECV-WINDOW arrives as unauthenticated, but the\n // credentials are fine: the request is wrong, so do not log the caller out.\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RECV_WINDOW_INVALID\") {\n return new ValidationError(\n withFallback(\"API key receive window must be 1 to 60000 milliseconds.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n // Arrives as Aborted, which would otherwise map to a retryable TransientError.\n if (detail?.service === \"alerts\" && detail.code === \"REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Price alert changed since it was last read.\"),\n options,\n );\n }\n\n // Arrives as ResourceExhausted, which would otherwise map to a retryable RateLimitError;\n // it clears only when one of the account's exports finishes.\n if (detail?.service === \"ledger\" && detail.code === \"STATEMENT_EXPORT_LIMIT_REACHED\") {\n return new PreconditionFailedError(\n withFallback(\n \"The account already has the most statement exports queued or in progress. Wait for one to finish (statementExports.list shows their status), then create a new one.\",\n ),\n options,\n );\n }\n\n // Arrive as ResourceExhausted, but clear only after the account's 6 hour conversion window\n // or the target's daily limit, not on a quick retry. DUST_BUSY stays a RateLimitError.\n if (detail?.service === \"internal_transfer\" && detail.code === \"DUST_WINDOW_ACTIVE\") {\n return new PreconditionFailedError(\n withFallback(\n \"The account converted dust in the last 6 hours, or a conversion is still processing. Try again once 6 hours have passed since the last conversion.\",\n ),\n options,\n );\n }\n if (detail?.service === \"internal_transfer\" && detail.code === \"DUST_DAILY_LIMIT\") {\n return new PreconditionFailedError(\n withFallback(\n \"The target asset reached its daily dust conversion limit. Try again tomorrow or pick another target asset.\",\n ),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_WALLET_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Wallet is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_SCOPE_MISMATCH\") {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_LAST_FACTOR_REQUIRED\") {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n // Arrives as Unavailable; mapped on its own so callers get the claim ID.\n if (detail?.service === \"claims\" && detail.code === \"CLAIM_OUTCOME_UNKNOWN\") {\n return new ClaimOutcomeUnknownError(\n withFallback(\"Daily claim payout is not confirmed yet; check the claim status.\"),\n { ...options, claimId: detail.claimId },\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"REQUEST_DEADLINE_EXCEEDED\") {\n return new RequestDeadlineExceededError(\n withFallback(\"Request receive window ended before admission; nothing changed.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit =\n detail?.service === \"orders\" || detail?.service === \"rate_limit\"\n ? detail.rateLimit\n : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Connect reads 200 bodies outside the SDK fetch wrapper, so a connection\n // dropped mid-body arrives as Unknown with the raw fetch TypeError as cause.\n if (ce.code === Code.Unknown && isFetchNetworkError(ce.cause)) {\n return new NetworkError(\"Transport request failed\", options);\n }\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_VERIFY_FAILED\")\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-canceled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n await loadErrorDetailDecoders(err);\n throw toPolyesterError(err);\n }\n };\n}\n\n// Non-idempotent writes the contract answers with `deadline_exceeded` / 504 when the write may\n// already have been applied (changes/2026-11-15T2309Z-orders-v1.md); a retry could apply it twice.\nconst UNKNOWN_OUTCOME_ON_SERVER_TIMEOUT = new Set([\n \"auth.v1.ApiKeyService.CreateApiKey\",\n \"auth.v1.PolicyService.CreateApiPolicy\",\n \"auth.v1.PolicyService.CreateSubaccountPolicy\",\n \"auth.v1.MFAService.RegenerateRecoveryCodes\",\n]);\n\nfunction withUnknownWriteOutcome(\n method: { name: string; parent: { typeName: string } },\n err: unknown,\n): unknown {\n if (!(err instanceof TimeoutError || err instanceof ServiceUnavailableError)) return err;\n // Only a server-sent 504; a client-side timeout carries no status.\n if (err.status !== 504) return err;\n if (!UNKNOWN_OUTCOME_ON_SERVER_TIMEOUT.has(`${method.parent.typeName}.${method.name}`)) {\n return err;\n }\n return new OutcomeUnknownError(\n \"Outcome unknown; the write may have been applied. Read the current state before retrying.\",\n { cause: err, status: 504 },\n );\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw withUnknownWriteOutcome(method, await toTransportError(error, signal));\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AAiDA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAG1C,MAAM,4BAA4B;AAElC,SAAS,yBAAyB,QAAmD;CACjF,IAAI,QAAQ,YAAY,YACpB,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ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CAC/B,IAAI,CAAC,kCAAkC,IAAI,GAAG,OAAO,OAAO,SAAS,GAAG,OAAO,MAAM,GACjF,OAAO;CAEX,OAAO,IAAI,oBACP,6FACA;EAAE,OAAO;EAAK,QAAQ;CAAI,CAC9B;AACJ;;;;;AAMA,SAAgB,4BAA4B,WAAiC;CACzE,OAAO;EACH,MAAM,MAAM,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GACjE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,OAAO,MAAM,UAAU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,wBAAwB,QAAQ,MAAM,iBAAiB,OAAO,MAAM,CAAC;GAC/E;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;CACJ;AACJ"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PairCatalogKey } from "../catalogs/types.js";
|
|
2
|
+
import "./subscription-errors.js";
|
|
2
3
|
//#region src/shared/decimal-surface.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Resolves wire scales for the SDK's internal decimal conversion. Backed by
|
|
@@ -16,6 +17,11 @@ interface SdkScales {
|
|
|
16
17
|
referencePrice(pair: PairCatalogKey): number;
|
|
17
18
|
ledgerAmount(ledgerAssetId: number): number;
|
|
18
19
|
zippedAssetAmount(zippedAssetId: number): number;
|
|
20
|
+
/**
|
|
21
|
+
* Refreshes the catalog after a lookup miss, so a pair listed after startup resolves.
|
|
22
|
+
* Misses within {@link CATALOG_MISS_REFRESH_INTERVAL_MS} share one refresh; never rejects.
|
|
23
|
+
*/
|
|
24
|
+
refreshAfterMiss?(): Promise<void>;
|
|
19
25
|
}
|
|
20
26
|
//#endregion
|
|
21
27
|
export { SdkScales };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decimal-surface.d.ts","names":[],"sources":["../../src/shared/decimal-surface.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"decimal-surface.d.ts","names":[],"sources":["../../src/shared/decimal-surface.ts"],"mappings":";;;;;;;;UA6CiB;EACb,SAAS;EACT;EACA,QAAQ,MAAM;EACd,YAAY,MAAM;;EAElB,iBAAiB,MAAM;;EAEvB,eAAe,MAAM;EACrB,aAAa;EACb,kBAAkB;;;;;EAKlB,qBAAqB"}
|
|
@@ -1,13 +1,77 @@
|
|
|
1
1
|
import "./wire-bounds.js";
|
|
2
2
|
import { scaledToDecimal, tryDecimalToScaled } from "../catalogs/decimal.js";
|
|
3
3
|
import { CatalogConversionError, CatalogLookupError, CatalogNotReadyError } from "../catalogs/types.js";
|
|
4
|
+
import { publicationHandlerErrorContext } from "./subscription-errors.js";
|
|
4
5
|
import { U128_MAX } from "../utils/u128.js";
|
|
6
|
+
/** Least time between catalog refreshes that lookup misses start. */
|
|
7
|
+
const CATALOG_MISS_REFRESH_INTERVAL_MS = 3e4;
|
|
8
|
+
/** Longest a lookup miss waits for its catalog refresh before it fails with the current catalog. */
|
|
9
|
+
const CATALOG_MISS_REFRESH_TIMEOUT_MS = 1e4;
|
|
10
|
+
/** Runs `read`; on a catalog miss, refreshes the catalog and runs it once more, so a second miss throws. */
|
|
11
|
+
async function withCatalogRefresh(scales, read) {
|
|
12
|
+
try {
|
|
13
|
+
return read();
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (!(error instanceof CatalogLookupError) || !scales.refreshAfterMiss) throw error;
|
|
16
|
+
await scales.refreshAfterMiss();
|
|
17
|
+
return read();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** True when the catalog can scale quantities of `symbolId`. */
|
|
21
|
+
function hasKnownSymbol(scales, symbolId) {
|
|
22
|
+
try {
|
|
23
|
+
scales.baseQty(symbolId);
|
|
24
|
+
return true;
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Keeps a stream's publications in order across catalog refreshes. Call the returned function
|
|
31
|
+
* with each publication's handler: one naming a symbol the catalog lacks waits for a refresh,
|
|
32
|
+
* and every later one waits behind it. A symbol still missing then fails in the handler, which
|
|
33
|
+
* reports it to `onError`; nothing runs after the subscription closed.
|
|
34
|
+
*/
|
|
35
|
+
function createCatalogRefreshQueue(scales, channel, onError, isOpen) {
|
|
36
|
+
let tail;
|
|
37
|
+
return (missesCatalog, handle) => {
|
|
38
|
+
const wait = tail ?? (missesCatalog ? scales.refreshAfterMiss?.() : void 0);
|
|
39
|
+
if (!wait) return handle();
|
|
40
|
+
const next = wait.then(() => {
|
|
41
|
+
if (!isOpen()) return;
|
|
42
|
+
try {
|
|
43
|
+
handle();
|
|
44
|
+
} catch (error) {
|
|
45
|
+
try {
|
|
46
|
+
onError?.(publicationHandlerErrorContext(channel, error));
|
|
47
|
+
} catch {}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
tail = next;
|
|
51
|
+
next.then(() => {
|
|
52
|
+
if (tail === next) tail = void 0;
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
}
|
|
5
56
|
/**
|
|
6
57
|
* Catalog-backed scale resolver. Takes a getter so it can be constructed
|
|
7
58
|
* before the owning client has assigned its catalog.
|
|
8
59
|
*/
|
|
9
60
|
function createCatalogSdkScales(getCatalog) {
|
|
61
|
+
let lastMissRefresh;
|
|
10
62
|
return {
|
|
63
|
+
refreshAfterMiss: () => {
|
|
64
|
+
if (lastMissRefresh && Date.now() - lastMissRefresh.at < 3e4) return lastMissRefresh.done;
|
|
65
|
+
let timer;
|
|
66
|
+
const done = Promise.race([getCatalog().refresh(), new Promise((resolve) => {
|
|
67
|
+
timer = setTimeout(resolve, CATALOG_MISS_REFRESH_TIMEOUT_MS);
|
|
68
|
+
})]).then(() => clearTimeout(timer), () => clearTimeout(timer));
|
|
69
|
+
lastMissRefresh = {
|
|
70
|
+
at: Date.now(),
|
|
71
|
+
done
|
|
72
|
+
};
|
|
73
|
+
return done;
|
|
74
|
+
},
|
|
11
75
|
ready: async () => {
|
|
12
76
|
await getCatalog().ensureReady();
|
|
13
77
|
},
|
|
@@ -124,6 +188,6 @@ function createReadyGate(ready, handlers) {
|
|
|
124
188
|
};
|
|
125
189
|
}
|
|
126
190
|
//#endregion
|
|
127
|
-
export { createCatalogSdkScales, createReadyGate, decimalInputToScaled, positiveDecimalInputToScaled, quantityInputToE18, scaledToDecimalOutput };
|
|
191
|
+
export { CATALOG_MISS_REFRESH_INTERVAL_MS, CATALOG_MISS_REFRESH_TIMEOUT_MS, createCatalogRefreshQueue, createCatalogSdkScales, createReadyGate, decimalInputToScaled, hasKnownSymbol, positiveDecimalInputToScaled, quantityInputToE18, scaledToDecimalOutput, withCatalogRefresh };
|
|
128
192
|
|
|
129
193
|
//# sourceMappingURL=decimal-surface.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decimal-surface.js","names":[],"sources":["../../src/shared/decimal-surface.ts"],"sourcesContent":["/**\n * Internal scaled⇄decimal bridge for the SDK's public decimal-string surface.\n *\n * The wire protocol carries scaled integers (price ticks, per-asset scaled\n * quantities); the public SDK surface carries plain decimal strings. Output\n * schemas convert exactly (no rounding, trailing zeros trimmed); input schemas\n * accept zero padding but reject fractional precision that remains above the\n * scale after trailing zeros are removed. Scaled integers must not escape\n * through any service input or output.\n */\nimport {\n scaledToDecimal,\n tryDecimalToScaled,\n type DecimalToScaledFailure,\n} from \"../catalogs/decimal.js\";\nimport {\n CatalogConversionError,\n CatalogLookupError,\n CatalogNotReadyError,\n type ClientCatalog,\n type PairCatalogKey,\n} from \"../catalogs/types.js\";\nimport { PRICE_SCALE } from \"../catalogs/readers.js\";\nimport { PROTOBUF_INT64_MAX } from \"./wire-bounds.js\";\nimport { U128_MAX } from \"../utils/u128.js\";\n\n/** On-chain unified-asset amounts (`amountE18`) are always 18-decimal scaled. */\nexport const E18_SCALE = 18;\n\n/**\n * Policy notional caps (`max_order_notional`) are canonical quote microunits:\n * one unit is 0.000001 USDT, per the `auth.v1` policy contract. Fixed by the\n * protocol rather than per-pair, so it needs no catalog lookup.\n */\nexport const QUOTE_NOTIONAL_SCALE = 6;\n\n/**\n * Resolves wire scales for the SDK's internal decimal conversion. Backed by\n * the client catalog; `ready()` must be awaited before the synchronous lookups\n * are used so the catalog can answer them.\n */\nexport interface SdkScales {\n ready(): Promise<void>;\n price(): number;\n baseQty(pair: PairCatalogKey): number;\n quoteAmount(pair: PairCatalogKey): number;\n /** Base volume in public candles and market overview; falls back to the base quantity scale. */\n marketDataVolume(pair: PairCatalogKey): number;\n /** Composite reference candle prices; falls back to the primary price scale. */\n referencePrice(pair: PairCatalogKey): number;\n ledgerAmount(ledgerAssetId: number): number;\n zippedAssetAmount(zippedAssetId: number): number;\n}\n\n/**\n * Catalog-backed scale resolver. Takes a getter so it can be constructed\n * before the owning client has assigned its catalog.\n */\nexport function createCatalogSdkScales(getCatalog: () => ClientCatalog): SdkScales {\n return {\n ready: async () => {\n await getCatalog().ensureReady();\n },\n price: () => PRICE_SCALE,\n baseQty: (pair) => requirePair(getCatalog(), pair).baseAsset.quantityScale,\n quoteAmount: (pair) => requirePair(getCatalog(), pair).quoteAsset.quantityScale,\n marketDataVolume: (pair) => {\n const { baseAsset } = requirePair(getCatalog(), pair);\n return baseAsset.marketDataVolumeScale ?? baseAsset.quantityScale;\n },\n referencePrice: (pair) =>\n requirePair(getCatalog(), pair).referencePriceScale ?? PRICE_SCALE,\n ledgerAmount: (ledgerAssetId) => {\n const ledger = getCatalog().ledger;\n if (!ledger.isKnownAssetId(ledgerAssetId)) {\n throw new CatalogLookupError(\"ledger\", \"ledgerId\", ledgerAssetId);\n }\n return ledger.requireAssetByLedgerId(ledgerAssetId).quantityScale;\n },\n zippedAssetAmount: (zippedAssetId) =>\n getCatalog().zipper.requireAssetChainByZippedAssetId(zippedAssetId).asset.quantityScale,\n };\n}\n\nfunction requirePair(catalog: ClientCatalog, pair: PairCatalogKey) {\n return typeof pair === \"string\" || (typeof pair === \"object\" && \"symbol\" in pair)\n ? catalog.market.requirePairBySymbol(typeof pair === \"string\" ? pair : pair.symbol)\n : catalog.market.requirePairBySymbolId(typeof pair === \"number\" ? pair : pair.symbolId);\n}\n\n/** Output direction: exact scaled→decimal conversion (`1500000n`@6 → `\"1.5\"`). */\nexport function scaledToDecimalOutput(value: bigint, scale: number): string {\n return scaledToDecimal(value, scale);\n}\n\nfunction conversionFailureMessage(\n field: string,\n value: string,\n failure: DecimalToScaledFailure,\n): string {\n return failure.reason === \"precision\"\n ? `${field} supports at most ${failure.maxDecimals} decimal places: ${value}`\n : `${field} must be a non-negative decimal number: ${value}`;\n}\n\n/**\n * Input direction: strict decimal→scaled conversion. Throws\n * CatalogConversionError for non-decimal input or inexact excess precision.\n */\nexport function decimalInputToScaled(field: string, value: string, scale: number): bigint {\n const result = tryDecimalToScaled(value.trim(), scale);\n if (!result.ok) {\n throw new CatalogConversionError(\n field,\n conversionFailureMessage(field, value, result.failure),\n );\n }\n return result.scaled;\n}\n\nfunction unboundedPositiveDecimalInputToScaled(\n field: string,\n value: string,\n scale: number,\n): bigint {\n const scaled = decimalInputToScaled(field, value, scale);\n if (scaled <= 0n) {\n throw new CatalogConversionError(field, `${field} must be greater than 0: ${value}`);\n }\n return scaled;\n}\n\n/**\n * Converts a positive decimal input to a scaled protobuf `int64` value.\n * Rejects values above the wire-format ceiling before serialization.\n */\nexport function positiveDecimalInputToScaled(field: string, value: string, scale: number): bigint {\n const scaled = unboundedPositiveDecimalInputToScaled(field, value, scale);\n if (scaled > PROTOBUF_INT64_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${value}`,\n );\n }\n return scaled;\n}\n\n/**\n * Decimal quantity → PolyesterChain E18 ledger units.\n * Input precision is capped at the asset's quantityScale; the wire value is\n * always upscaled to E18 (trading balances / amount_e18 convention).\n */\nexport function quantityInputToE18(params: {\n scales: SdkScales;\n assetId: number;\n quantity: string;\n field?: string;\n}): bigint {\n const field = params.field ?? \"quantity\";\n const assetScale = params.scales.ledgerAmount(params.assetId);\n if (assetScale > E18_SCALE) {\n throw new CatalogConversionError(\n field,\n `${field} asset quantityScale ${assetScale} exceeds E18 ledger scale`,\n );\n }\n const scaled =\n unboundedPositiveDecimalInputToScaled(field, params.quantity, assetScale) *\n 10n ** BigInt(E18_SCALE - assetScale);\n if (scaled > U128_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${params.quantity}`,\n );\n }\n return scaled;\n}\n\nexport interface ReadyGate {\n /** Queues or delivers one transition while the gate remains active. */\n run(deliver: () => void): void;\n /** Drops pending transitions and permanently prevents future delivery. */\n close(): void;\n}\n\ninterface ReadyGateHandlers {\n onDeliveryError?: (error: unknown) => void;\n onTerminalError: (error: unknown) => void;\n}\n\nconst READY_GATE_MAX_PENDING_DELIVERIES = 1_024;\n\n/**\n * Transition event delivery behind catalog readiness. Events arriving before the\n * catalog can resolve scales are queued and flushed in arrival order once it\n * is ready. Delivery errors are isolated from the transport. Readiness failure\n * or queue overflow is terminal because dropping an event would break stream\n * continuity; the owning subscription must visibly terminate when notified.\n */\nexport function createReadyGate(\n ready: () => Promise<void>,\n handlers: ReadyGateHandlers,\n): ReadyGate {\n let state: \"pending\" | \"open\" | \"closed\" = \"pending\";\n const queue: Array<() => void> = [];\n\n const deliverIsolated = (deliver: () => void) => {\n try {\n deliver();\n } catch (error) {\n handlers.onDeliveryError?.(error);\n }\n };\n\n const closeWithError = (error: unknown) => {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n handlers.onTerminalError(error);\n };\n\n Promise.resolve()\n .then(ready)\n .then(\n () => {\n if (state !== \"pending\") return;\n state = \"open\";\n for (const deliver of queue.splice(0)) deliverIsolated(deliver);\n },\n (error) => {\n if (state !== \"pending\") return;\n closeWithError(error);\n },\n );\n\n return {\n run(deliver) {\n if (state === \"open\") deliverIsolated(deliver);\n else if (state === \"pending\") {\n if (queue.length === READY_GATE_MAX_PENDING_DELIVERIES) {\n closeWithError(new CatalogNotReadyError());\n return;\n }\n queue.push(deliver);\n }\n },\n close() {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;AA0DA,SAAgB,uBAAuB,YAA4C;CAC/E,OAAO;EACH,OAAO,YAAY;GACf,MAAM,WAAW,CAAC,CAAC,YAAY;EACnC;EACA,aAAA;EACA,UAAU,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,UAAU;EAC7D,cAAc,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,WAAW;EAClE,mBAAmB,SAAS;GACxB,MAAM,EAAE,cAAc,YAAY,WAAW,GAAG,IAAI;GACpD,OAAO,UAAU,yBAAyB,UAAU;EACxD;EACA,iBAAiB,SACb,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,uBAAA;EACpC,eAAe,kBAAkB;GAC7B,MAAM,SAAS,WAAW,CAAC,CAAC;GAC5B,IAAI,CAAC,OAAO,eAAe,aAAa,GACpC,MAAM,IAAI,mBAAmB,UAAU,YAAY,aAAa;GAEpE,OAAO,OAAO,uBAAuB,aAAa,CAAC,CAAC;EACxD;EACA,oBAAoB,kBAChB,WAAW,CAAC,CAAC,OAAO,iCAAiC,aAAa,CAAC,CAAC,MAAM;CAClF;AACJ;AAEA,SAAS,YAAY,SAAwB,MAAsB;CAC/D,OAAO,OAAO,SAAS,YAAa,OAAO,SAAS,YAAY,YAAY,OACtE,QAAQ,OAAO,oBAAoB,OAAO,SAAS,WAAW,OAAO,KAAK,MAAM,IAChF,QAAQ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C;;;;;;;;AAS1C,SAAgB,gBACZ,OACA,UACS;CACT,IAAI,QAAuC;CAC3C,MAAM,QAA2B,CAAC;CAElC,MAAM,mBAAmB,YAAwB;EAC7C,IAAI;GACA,QAAQ;EACZ,SAAS,OAAO;GACZ,SAAS,kBAAkB,KAAK;EACpC;CACJ;CAEA,MAAM,kBAAkB,UAAmB;EACvC,IAAI,UAAU,UAAU;EACxB,QAAQ;EACR,MAAM,SAAS;EACf,SAAS,gBAAgB,KAAK;CAClC;CAEA,QAAQ,QAAQ,CAAC,CACZ,KAAK,KAAK,CAAC,CACX,WACS;EACF,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,KAAK,MAAM,WAAW,MAAM,OAAO,CAAC,GAAG,gBAAgB,OAAO;CAClE,IACC,UAAU;EACP,IAAI,UAAU,WAAW;EACzB,eAAe,KAAK;CACxB,CACJ;CAEJ,OAAO;EACH,IAAI,SAAS;GACT,IAAI,UAAU,QAAQ,gBAAgB,OAAO;QACxC,IAAI,UAAU,WAAW;IAC1B,IAAI,MAAM,WAAW,mCAAmC;KACpD,eAAe,IAAI,qBAAqB,CAAC;KACzC;IACJ;IACA,MAAM,KAAK,OAAO;GACtB;EACJ;EACA,QAAQ;GACJ,IAAI,UAAU,UAAU;GACxB,QAAQ;GACR,MAAM,SAAS;EACnB;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"decimal-surface.js","names":[],"sources":["../../src/shared/decimal-surface.ts"],"sourcesContent":["/**\n * Internal scaled⇄decimal bridge for the SDK's public decimal-string surface.\n *\n * The wire protocol carries scaled integers (price ticks, per-asset scaled\n * quantities); the public SDK surface carries plain decimal strings. Output\n * schemas convert exactly (no rounding, trailing zeros trimmed); input schemas\n * accept zero padding but reject fractional precision that remains above the\n * scale after trailing zeros are removed. Scaled integers must not escape\n * through any service input or output.\n */\nimport {\n scaledToDecimal,\n tryDecimalToScaled,\n type DecimalToScaledFailure,\n} from \"../catalogs/decimal.js\";\nimport {\n CatalogConversionError,\n CatalogLookupError,\n CatalogNotReadyError,\n type ClientCatalog,\n type PairCatalogKey,\n} from \"../catalogs/types.js\";\nimport { PRICE_SCALE } from \"../catalogs/readers.js\";\nimport { PROTOBUF_INT64_MAX } from \"./wire-bounds.js\";\nimport {\n publicationHandlerErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"./subscription-errors.js\";\nimport { U128_MAX } from \"../utils/u128.js\";\n\n/** On-chain unified-asset amounts (`amountE18`) are always 18-decimal scaled. */\nexport const E18_SCALE = 18;\n\n/**\n * Policy notional caps (`max_order_notional`) are canonical quote microunits:\n * one unit is 0.000001 USDT, per the `auth.v1` policy contract. Fixed by the\n * protocol rather than per-pair, so it needs no catalog lookup.\n */\nexport const QUOTE_NOTIONAL_SCALE = 6;\n\n/**\n * Resolves wire scales for the SDK's internal decimal conversion. Backed by\n * the client catalog; `ready()` must be awaited before the synchronous lookups\n * are used so the catalog can answer them.\n */\nexport interface SdkScales {\n ready(): Promise<void>;\n price(): number;\n baseQty(pair: PairCatalogKey): number;\n quoteAmount(pair: PairCatalogKey): number;\n /** Base volume in public candles and market overview; falls back to the base quantity scale. */\n marketDataVolume(pair: PairCatalogKey): number;\n /** Composite reference candle prices; falls back to the primary price scale. */\n referencePrice(pair: PairCatalogKey): number;\n ledgerAmount(ledgerAssetId: number): number;\n zippedAssetAmount(zippedAssetId: number): number;\n /**\n * Refreshes the catalog after a lookup miss, so a pair listed after startup resolves.\n * Misses within {@link CATALOG_MISS_REFRESH_INTERVAL_MS} share one refresh; never rejects.\n */\n refreshAfterMiss?(): Promise<void>;\n}\n\n/** Least time between catalog refreshes that lookup misses start. */\nexport const CATALOG_MISS_REFRESH_INTERVAL_MS = 30_000;\n\n/** Longest a lookup miss waits for its catalog refresh before it fails with the current catalog. */\nexport const CATALOG_MISS_REFRESH_TIMEOUT_MS = 10_000;\n\n/** Runs `read`; on a catalog miss, refreshes the catalog and runs it once more, so a second miss throws. */\nexport async function withCatalogRefresh<T>(scales: SdkScales, read: () => T): Promise<T> {\n try {\n return read();\n } catch (error) {\n if (!(error instanceof CatalogLookupError) || !scales.refreshAfterMiss) throw error;\n await scales.refreshAfterMiss();\n return read();\n }\n}\n\n/** True when the catalog can scale quantities of `symbolId`. */\nexport function hasKnownSymbol(scales: SdkScales, symbolId: number): boolean {\n try {\n scales.baseQty(symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Keeps a stream's publications in order across catalog refreshes. Call the returned function\n * with each publication's handler: one naming a symbol the catalog lacks waits for a refresh,\n * and every later one waits behind it. A symbol still missing then fails in the handler, which\n * reports it to `onError`; nothing runs after the subscription closed.\n */\nexport function createCatalogRefreshQueue(\n scales: SdkScales,\n channel: string,\n onError: ((error: SdkSubscriptionErrorContext) => void) | undefined,\n isOpen: () => boolean,\n): (missesCatalog: boolean, handle: () => void) => void {\n let tail: Promise<void> | undefined;\n return (missesCatalog, handle) => {\n const wait = tail ?? (missesCatalog ? scales.refreshAfterMiss?.() : undefined);\n if (!wait) return handle();\n const next = wait.then(() => {\n if (!isOpen()) return;\n try {\n handle();\n } catch (error) {\n try {\n onError?.(publicationHandlerErrorContext(channel, error));\n } catch {\n // The caller's onError threw; keep later publications flowing.\n }\n }\n });\n tail = next;\n void next.then(() => {\n if (tail === next) tail = undefined;\n });\n };\n}\n\n/**\n * Catalog-backed scale resolver. Takes a getter so it can be constructed\n * before the owning client has assigned its catalog.\n */\nexport function createCatalogSdkScales(getCatalog: () => ClientCatalog): SdkScales {\n let lastMissRefresh: { at: number; done: Promise<void> } | undefined;\n return {\n refreshAfterMiss: () => {\n if (\n lastMissRefresh &&\n Date.now() - lastMissRefresh.at < CATALOG_MISS_REFRESH_INTERVAL_MS\n ) {\n return lastMissRefresh.done;\n }\n // A failed or stalled refresh leaves the catalog as it was, so the retried lookup\n // misses again instead of holding a stream behind it.\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = Promise.race([\n getCatalog().refresh(),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CATALOG_MISS_REFRESH_TIMEOUT_MS);\n }),\n ]).then(\n () => clearTimeout(timer),\n () => clearTimeout(timer),\n );\n lastMissRefresh = { at: Date.now(), done };\n return done;\n },\n ready: async () => {\n await getCatalog().ensureReady();\n },\n price: () => PRICE_SCALE,\n baseQty: (pair) => requirePair(getCatalog(), pair).baseAsset.quantityScale,\n quoteAmount: (pair) => requirePair(getCatalog(), pair).quoteAsset.quantityScale,\n marketDataVolume: (pair) => {\n const { baseAsset } = requirePair(getCatalog(), pair);\n return baseAsset.marketDataVolumeScale ?? baseAsset.quantityScale;\n },\n referencePrice: (pair) =>\n requirePair(getCatalog(), pair).referencePriceScale ?? PRICE_SCALE,\n ledgerAmount: (ledgerAssetId) => {\n const ledger = getCatalog().ledger;\n if (!ledger.isKnownAssetId(ledgerAssetId)) {\n throw new CatalogLookupError(\"ledger\", \"ledgerId\", ledgerAssetId);\n }\n return ledger.requireAssetByLedgerId(ledgerAssetId).quantityScale;\n },\n zippedAssetAmount: (zippedAssetId) =>\n getCatalog().zipper.requireAssetChainByZippedAssetId(zippedAssetId).asset.quantityScale,\n };\n}\n\nfunction requirePair(catalog: ClientCatalog, pair: PairCatalogKey) {\n return typeof pair === \"string\" || (typeof pair === \"object\" && \"symbol\" in pair)\n ? catalog.market.requirePairBySymbol(typeof pair === \"string\" ? pair : pair.symbol)\n : catalog.market.requirePairBySymbolId(typeof pair === \"number\" ? pair : pair.symbolId);\n}\n\n/** Output direction: exact scaled→decimal conversion (`1500000n`@6 → `\"1.5\"`). */\nexport function scaledToDecimalOutput(value: bigint, scale: number): string {\n return scaledToDecimal(value, scale);\n}\n\nfunction conversionFailureMessage(\n field: string,\n value: string,\n failure: DecimalToScaledFailure,\n): string {\n return failure.reason === \"precision\"\n ? `${field} supports at most ${failure.maxDecimals} decimal places: ${value}`\n : `${field} must be a non-negative decimal number: ${value}`;\n}\n\n/**\n * Input direction: strict decimal→scaled conversion. Throws\n * CatalogConversionError for non-decimal input or inexact excess precision.\n */\nexport function decimalInputToScaled(field: string, value: string, scale: number): bigint {\n const result = tryDecimalToScaled(value.trim(), scale);\n if (!result.ok) {\n throw new CatalogConversionError(\n field,\n conversionFailureMessage(field, value, result.failure),\n );\n }\n return result.scaled;\n}\n\nfunction unboundedPositiveDecimalInputToScaled(\n field: string,\n value: string,\n scale: number,\n): bigint {\n const scaled = decimalInputToScaled(field, value, scale);\n if (scaled <= 0n) {\n throw new CatalogConversionError(field, `${field} must be greater than 0: ${value}`);\n }\n return scaled;\n}\n\n/**\n * Converts a positive decimal input to a scaled protobuf `int64` value.\n * Rejects values above the wire-format ceiling before serialization.\n */\nexport function positiveDecimalInputToScaled(field: string, value: string, scale: number): bigint {\n const scaled = unboundedPositiveDecimalInputToScaled(field, value, scale);\n if (scaled > PROTOBUF_INT64_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${value}`,\n );\n }\n return scaled;\n}\n\n/**\n * Decimal quantity → PolyesterChain E18 ledger units.\n * Input precision is capped at the asset's quantityScale; the wire value is\n * always upscaled to E18 (trading balances / amount_e18 convention).\n */\nexport function quantityInputToE18(params: {\n scales: SdkScales;\n assetId: number;\n quantity: string;\n field?: string;\n}): bigint {\n const field = params.field ?? \"quantity\";\n const assetScale = params.scales.ledgerAmount(params.assetId);\n if (assetScale > E18_SCALE) {\n throw new CatalogConversionError(\n field,\n `${field} asset quantityScale ${assetScale} exceeds E18 ledger scale`,\n );\n }\n const scaled =\n unboundedPositiveDecimalInputToScaled(field, params.quantity, assetScale) *\n 10n ** BigInt(E18_SCALE - assetScale);\n if (scaled > U128_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${params.quantity}`,\n );\n }\n return scaled;\n}\n\nexport interface ReadyGate {\n /** Queues or delivers one transition while the gate remains active. */\n run(deliver: () => void): void;\n /** Drops pending transitions and permanently prevents future delivery. */\n close(): void;\n}\n\ninterface ReadyGateHandlers {\n onDeliveryError?: (error: unknown) => void;\n onTerminalError: (error: unknown) => void;\n}\n\nconst READY_GATE_MAX_PENDING_DELIVERIES = 1_024;\n\n/**\n * Transition event delivery behind catalog readiness. Events arriving before the\n * catalog can resolve scales are queued and flushed in arrival order once it\n * is ready. Delivery errors are isolated from the transport. Readiness failure\n * or queue overflow is terminal because dropping an event would break stream\n * continuity; the owning subscription must visibly terminate when notified.\n */\nexport function createReadyGate(\n ready: () => Promise<void>,\n handlers: ReadyGateHandlers,\n): ReadyGate {\n let state: \"pending\" | \"open\" | \"closed\" = \"pending\";\n const queue: Array<() => void> = [];\n\n const deliverIsolated = (deliver: () => void) => {\n try {\n deliver();\n } catch (error) {\n handlers.onDeliveryError?.(error);\n }\n };\n\n const closeWithError = (error: unknown) => {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n handlers.onTerminalError(error);\n };\n\n Promise.resolve()\n .then(ready)\n .then(\n () => {\n if (state !== \"pending\") return;\n state = \"open\";\n for (const deliver of queue.splice(0)) deliverIsolated(deliver);\n },\n (error) => {\n if (state !== \"pending\") return;\n closeWithError(error);\n },\n );\n\n return {\n run(deliver) {\n if (state === \"open\") deliverIsolated(deliver);\n else if (state === \"pending\") {\n if (queue.length === READY_GATE_MAX_PENDING_DELIVERIES) {\n closeWithError(new CatalogNotReadyError());\n return;\n }\n queue.push(deliver);\n }\n },\n close() {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;AAgEA,MAAa,mCAAmC;;AAGhD,MAAa,kCAAkC;;AAG/C,eAAsB,mBAAsB,QAAmB,MAA2B;CACtF,IAAI;EACA,OAAO,KAAK;CAChB,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,uBAAuB,CAAC,OAAO,kBAAkB,MAAM;EAC9E,MAAM,OAAO,iBAAiB;EAC9B,OAAO,KAAK;CAChB;AACJ;;AAGA,SAAgB,eAAe,QAAmB,UAA2B;CACzE,IAAI;EACA,OAAO,QAAQ,QAAQ;EACvB,OAAO;CACX,QAAQ;EACJ,OAA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AAU;GACxB,QAAQ;GACR,MAAM,SAAS;EACnB;CACJ;AACJ"}
|
|
@@ -21,7 +21,7 @@ declare const RateLimitDetailSchema: v.ObjectSchema<{
|
|
|
21
21
|
readonly policyVersion: v.SchemaWithPipe<readonly [v.OptionalSchema<v.BigintSchema<undefined>, undefined>, v.TransformAction<bigint | undefined, string | undefined>]>;
|
|
22
22
|
readonly operationId: v.StringSchema<undefined>;
|
|
23
23
|
readonly policyClass: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "auth_public" | "trading_place" | "trading_cancel" | "trading_read" | "account_admin" | "public_read" | "account_security" | "deposit_create" | "internal_transfer" | "withdraw_submit" | "withdraw_validate" | "guard_sign" | "social_provider" | "assistant_message" | "assistant_control" | "assistant_read">]>;
|
|
24
|
-
readonly scope: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "symbol" | "unspecified" | "
|
|
24
|
+
readonly scope: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "symbol" | "unspecified" | "subaccount" | "client_ip" | "api_key" | "account" | "connection" | "service" | "region" | "auth_subject">]>;
|
|
25
25
|
readonly refillModel: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "continuous" | "fixed_window" | "rolling_window">]>;
|
|
26
26
|
}, undefined>;
|
|
27
27
|
/** Structured quota state exposed by order rejections and {@link RateLimitError}. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polyester/sdk",
|
|
3
|
-
"version": "0.36.0-devnet-
|
|
3
|
+
"version": "0.36.0-devnet-20261118184607",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "TypeScript SDK providing access to APIs on Polyester Exchange.",
|
|
6
6
|
"homepage": "https://github.com/Fabric-Labs/polyester-sdk-typescript#readme",
|