@polyester/sdk 0.36.0-devnet-20261114152753 → 0.36.0-devnet-20261115165158
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 +25 -1
- package/dist/catalogs/readers.d.ts.map +1 -1
- package/dist/catalogs/readers.js +1 -1
- package/dist/catalogs/readers.js.map +1 -1
- package/dist/catalogs/snapshot-validation.js +8 -6
- package/dist/catalogs/snapshot-validation.js.map +1 -1
- package/dist/catalogs/unknown-asset.d.ts.map +1 -1
- package/dist/catalogs/unknown-asset.js +4 -4
- package/dist/catalogs/unknown-asset.js.map +1 -1
- package/dist/core-client.d.ts.map +1 -1
- package/dist/core-client.js +2 -1
- package/dist/core-client.js.map +1 -1
- package/dist/realtime/private-orders.d.ts +8 -0
- package/dist/realtime/private-orders.d.ts.map +1 -1
- package/dist/realtime/private-orders.js +38 -5
- package/dist/realtime/private-orders.js.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.js +4 -4
- package/dist/services/address-book/address-book.schemas.js.map +1 -1
- package/dist/services/assistant/assistant-events.schemas.d.ts +5 -5
- package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +19 -19
- package/dist/services/balances/balances.schemas.d.ts +6 -24
- package/dist/services/balances/balances.schemas.d.ts.map +1 -1
- package/dist/services/balances/balances.schemas.js +2 -2
- package/dist/services/balances/balances.schemas.js.map +1 -1
- 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/internal-transfers/internal-transfers.schemas.d.ts +3 -3
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +13 -13
- package/dist/services/orders/order-errors.schemas.d.ts +1 -1
- package/dist/services/orders/order-errors.schemas.d.ts.map +1 -1
- package/dist/services/orders/order-errors.schemas.js +7 -4
- package/dist/services/orders/order-errors.schemas.js.map +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +13 -13
- package/dist/services/orders/orders-batch.schemas.d.ts.map +1 -1
- package/dist/services/orders/orders-batch.schemas.js +3 -2
- package/dist/services/orders/orders-batch.schemas.js.map +1 -1
- package/dist/services/orders/orders-input.schemas.d.ts +3 -3
- package/dist/services/orders/orders-input.schemas.js +1 -1
- package/dist/services/orders/orders-modify.schemas.d.ts.map +1 -1
- package/dist/services/orders/orders-modify.schemas.js +2 -1
- package/dist/services/orders/orders-modify.schemas.js.map +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +6 -6
- package/dist/services/orders/orders-output.schemas.d.ts.map +1 -1
- package/dist/services/orders/orders-output.schemas.js +2 -10
- package/dist/services/orders/orders-output.schemas.js.map +1 -1
- package/dist/services/orders/orders.d.ts +6 -0
- package/dist/services/orders/orders.d.ts.map +1 -1
- package/dist/services/orders/orders.js +4 -0
- package/dist/services/orders/orders.js.map +1 -1
- package/dist/services/price-alerts/price-alerts.schemas.d.ts +10 -10
- package/dist/services/rewards/rewards.schemas.d.ts +4 -4
- 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.schemas.d.ts +1 -1
- package/dist/services/trading-withdraws/service.js +1 -1
- package/dist/services/trading-withdraws/service.js.map +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.d.ts +10 -12
- package/dist/services/trading-withdraws/trading-withdraws.d.ts.map +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.js +28 -20
- package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts +0 -5
- package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts.map +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js +0 -4
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js.map +1 -1
- package/dist/services/trading-withdraws/wallet-message.js +1 -1
- package/dist/services/trading-withdraws/wallet-message.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
- package/dist/services/triggers/trigger-input.schemas.d.ts.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.js +4 -3
- package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +2 -3
- package/dist/services/triggers/triggers-output.schemas.d.ts.map +1 -1
- package/dist/services/triggers/triggers-output.schemas.js +1 -1
- package/dist/services/vip/vip.schemas.d.ts +3 -3
- package/dist/shared/transports.d.ts +2 -1
- package/dist/shared/transports.d.ts.map +1 -1
- package/dist/shared/transports.js +52 -9
- package/dist/shared/transports.js.map +1 -1
- package/dist/utils/base58-id.js +1 -1
- package/dist/utils/base58-id.js.map +1 -1
- package/dist/utils/numbers.js +3 -2
- package/dist/utils/numbers.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders-modify.schemas.js","names":["ProtoWrite.RiskPolicySchema"],"sources":["../../../src/services/orders/orders-modify.schemas.ts"],"sourcesContent":["import * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { create } from \"@bufbuild/protobuf\";\nimport * as v from \"valibot\";\nimport { tsNsToMs } from \"../../utils/time.js\";\nimport { OptionalPublicIdSchema, PublicIdSchema } from \"../../shared/schemas.js\";\nimport { positiveDecimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { PROTOBUF_UINT32_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport { MODIFY_BEHAVIOR_VALUES, ModifyActionCodec, ModifyBehaviorCodec } from \"./orders.codecs.js\";\nimport { createRequiredRiskPolicyInputSchema } from \"./orders-risk.schemas.js\";\nimport {\n ClientOrderIdInputSchema,\n OrderIdInputSchema,\n OrderRequestIdInputSchema,\n} from \"./orders-identifiers.schemas.js\";\n\nconst ModifyBehaviorInputSchema = v.picklist(MODIFY_BEHAVIOR_VALUES);\n\nconst DecimalInputStringSchema = v.pipe(v.string(), v.trim(), v.minLength(1));\n\nconst ModifyOrderItemBaseInputSchema = v.object({\n symbolId: v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(PROTOBUF_UINT32_MAX)),\n behavior: v.optional(ModifyBehaviorInputSchema),\n newClientOrderId: v.optional(ClientOrderIdInputSchema),\n});\n\nconst ModifyOrderRequestInputSchema = v.object({\n ...AccountScopeInputEntries,\n requestId: v.optional(OrderRequestIdInputSchema),\n});\n\nconst ModifyOrderKeyInputSchema = v.union([\n v.pipe(\n v.object({\n orderId: OrderIdInputSchema,\n clientOrderId: v.optional(v.never()),\n }),\n v.transform(({ orderId }) => ({\n key: { case: \"orderId\" as const, value: orderId },\n })),\n ),\n v.pipe(\n v.object({\n orderId: v.optional(v.never()),\n clientOrderId: ClientOrderIdInputSchema,\n }),\n v.transform(({ clientOrderId }) => ({\n key: { case: \"clientOrderId\" as const, value: clientOrderId },\n })),\n ),\n]);\n\nconst ModifyOrderPricePatchInputSchema = v.object({\n newPrice: DecimalInputStringSchema,\n newQty: v.optional(DecimalInputStringSchema),\n});\n\nconst ModifyOrderQtyPatchInputSchema = v.object({\n newPrice: v.optional(DecimalInputStringSchema),\n newQty: DecimalInputStringSchema,\n});\n\nconst ModifyOrderNoPriceQtyPatchInputSchema = v.object({\n newPrice: v.optional(v.never()),\n newQty: v.optional(v.never()),\n});\n\nconst ModifyOrderClearRiskPatchInputSchema = v.object({\n risk: v.optional(v.never()),\n clearRisk: v.literal(true),\n});\n\nconst ModifyOrderNoRiskPatchInputSchema = v.object({\n risk: v.optional(v.never()),\n clearRisk: v.optional(v.literal(false)),\n});\n\nconst MODIFY_ORDER_ITEM_INPUT_KEYS = new Set<string>([\n ...Object.keys(ModifyOrderItemBaseInputSchema.entries),\n \"orderId\",\n \"clientOrderId\",\n \"newPrice\",\n \"newQty\",\n \"risk\",\n \"clearRisk\",\n]);\n\nconst MODIFY_ORDER_INPUT_KEYS = new Set<string>([\n ...MODIFY_ORDER_ITEM_INPUT_KEYS,\n ...Object.keys(ModifyOrderRequestInputSchema.entries),\n]);\n\n/**\n * The modify-order input is a v.intersect of partial object schemas, so its\n * members cannot use v.strictObject (each member would reject the other\n * members' keys). Unknown keys are rejected up front instead, matching the\n * strict-input behavior of every other mutating method.\n */\nexport function assertKnownModifyOrderInputKeys(input: object): void {\n for (const key of Object.keys(input)) {\n if (!MODIFY_ORDER_INPUT_KEYS.has(key)) {\n throw new Error(`Unknown key \"${key}\" in modify order input.`);\n }\n }\n}\n\nexport function createModifyOrderPatchInputSchema(scales: SdkScales) {\n const ModifyOrderSetRiskPatchInputSchema = v.object({\n risk: createRequiredRiskPolicyInputSchema(scales),\n clearRisk: v.optional(v.literal(false)),\n });\n\n const ModifyOrderAnyRiskPatchInputSchema = v.union([\n ModifyOrderSetRiskPatchInputSchema,\n ModifyOrderClearRiskPatchInputSchema,\n ModifyOrderNoRiskPatchInputSchema,\n ]);\n\n const ModifyOrderRequiredRiskPatchInputSchema = v.union([\n ModifyOrderSetRiskPatchInputSchema,\n ModifyOrderClearRiskPatchInputSchema,\n ]);\n\n return v.union([\n v.intersect([ModifyOrderPricePatchInputSchema, ModifyOrderAnyRiskPatchInputSchema]),\n v.intersect([ModifyOrderQtyPatchInputSchema, ModifyOrderAnyRiskPatchInputSchema]),\n v.intersect([\n ModifyOrderNoPriceQtyPatchInputSchema,\n ModifyOrderRequiredRiskPatchInputSchema,\n ]),\n ]);\n}\n\nfunction createModifyOrderItemObjectInputSchema(scales: SdkScales) {\n return v.intersect([\n ModifyOrderItemBaseInputSchema,\n ModifyOrderKeyInputSchema,\n createModifyOrderPatchInputSchema(scales),\n ]);\n}\n\ntype ParsedModifyOrderItemInput = v.InferOutput<\n ReturnType<typeof createModifyOrderItemObjectInputSchema>\n>;\n\nfunction toModifyOrderItem(\n input: ParsedModifyOrderItemInput,\n scales: SdkScales,\n defaultBehavior: ProtoWrite.ModifyBehavior,\n) {\n return {\n key: input.key,\n newPriceTicks:\n input.newPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\"newPrice\", input.newPrice, scales.price()),\n newQtyScaled:\n input.newQty === undefined\n ? undefined\n : positiveDecimalInputToScaled(\n \"newQty\",\n input.newQty,\n scales.baseQty(input.symbolId),\n ),\n newAttachedRisk:\n input.clearRisk === true ? create(ProtoWrite.RiskPolicySchema) : input.risk,\n behavior: input.behavior\n ? ModifyBehaviorCodec.inputToProto[input.behavior]\n : defaultBehavior,\n newClientOrderId: input.newClientOrderId ?? \"\",\n symbolId: input.symbolId,\n };\n}\n\nexport function createModifyOrderInputSchema(scales: SdkScales) {\n return v.pipe(\n v.intersect([\n ModifyOrderRequestInputSchema,\n createModifyOrderItemObjectInputSchema(scales),\n ]),\n v.transform((input) => ({\n subaccountId: accountScopeToSubaccountId(input.account),\n requestId: input.requestId,\n ...toModifyOrderItem(input, scales, ProtoWrite.ModifyBehavior.AMEND_OR_REPLACE),\n })),\n );\n}\n\nexport type ModifyOrderInput = v.InferInput<ReturnType<typeof createModifyOrderInputSchema>>;\n\nexport const ModifyOrderResultSchema = v.pipe(\n v.object({\n actionTaken: enumLabelSchema(ModifyActionCodec.protoToOutput),\n oldOrderId: PublicIdSchema,\n finalOrderId: PublicIdSchema,\n code: v.string(),\n takeProfitTriggerId: OptionalPublicIdSchema,\n stopLossTriggerId: OptionalPublicIdSchema,\n trailingStopTriggerId: OptionalPublicIdSchema,\n tsNs: v.bigint(),\n }),\n v.transform(({ tsNs, ...result }) => ({\n ...result,\n ts: tsNsToMs(tsNs),\n tsNs: tsNs.toString(),\n })),\n);\n\nexport type ModifyOrderResult = v.InferOutput<typeof ModifyOrderResultSchema>;\n"],"mappings":";;;;;;;;;;;;;AAoBA,MAAM,4BAA4B,EAAE,SAAS,sBAAsB;AAEnE,MAAM,2BAA2B,EAAE,KAAK,EAAE,OAAO,G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UACA,MAAM,QACN,OAAO,QAAQ,MAAM,QAAQ,CACjC;EACV,iBACI,MAAM,cAAc,OAAO,OAAOA,gBAA2B,IAAI,MAAM;EAC3E,UAAU,MAAM,WACV,oBAAoB,aAAa,MAAM,YACvC;EACN,kBAAkB,MAAM,oBAAoB;EAC5C,UAAU,MAAM;CACpB;AACJ;AAEA,SAAgB,6BAA6B,QAAmB;CAC5D,OAAO,EAAE,KACL,EAAE,UAAU,CACR,+BACA,uCAAuC,MAAM,CACjD,CAAC,GACD,EAAE,WAAW,WAAW;EACpB,cAAc,2BAA2B,MAAM,OAAO;EACtD,WAAW,MAAM;EACjB,GAAG,kBAAkB,OAAO,QAAA,CAAkD;CAClF,EAAE,CACN;AACJ;AAIA,MAAa,0BAA0B,EAAE,KACrC,EAAE,OAAO;CACL,aAAa,gBAAgB,kBAAkB,aAAa;CAC5D,YAAY;CACZ,cAAc;CACd,MAAM,EAAE,OAAO;CACf,qBAAqB;CACrB,mBAAmB;CACnB,uBAAuB;CACvB,MAAM,EAAE,OAAO;AACnB,CAAC,GACD,EAAE,WAAW,EAAE,MAAM,GAAG,cAAc;CAClC,GAAG;CACH,IAAI,SAAS,IAAI;CACjB,MAAM,KAAK,SAAS;AACxB,EAAE,CACN"}
|
|
1
|
+
{"version":3,"file":"orders-modify.schemas.js","names":["ProtoWrite.RiskPolicySchema"],"sources":["../../../src/services/orders/orders-modify.schemas.ts"],"sourcesContent":["import * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { create } from \"@bufbuild/protobuf\";\nimport * as v from \"valibot\";\nimport { tsNsToMs } from \"../../utils/time.js\";\nimport { OptionalPublicIdSchema, PublicIdSchema } from \"../../shared/schemas.js\";\nimport { positiveDecimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { ValidationError } from \"../../shared/errors.js\";\nimport { PROTOBUF_UINT32_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport { MODIFY_BEHAVIOR_VALUES, ModifyActionCodec, ModifyBehaviorCodec } from \"./orders.codecs.js\";\nimport { createRequiredRiskPolicyInputSchema } from \"./orders-risk.schemas.js\";\nimport {\n ClientOrderIdInputSchema,\n OrderIdInputSchema,\n OrderRequestIdInputSchema,\n} from \"./orders-identifiers.schemas.js\";\n\nconst ModifyBehaviorInputSchema = v.picklist(MODIFY_BEHAVIOR_VALUES);\n\nconst DecimalInputStringSchema = v.pipe(v.string(), v.trim(), v.minLength(1));\n\nconst ModifyOrderItemBaseInputSchema = v.object({\n symbolId: v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(PROTOBUF_UINT32_MAX)),\n behavior: v.optional(ModifyBehaviorInputSchema),\n newClientOrderId: v.optional(ClientOrderIdInputSchema),\n});\n\nconst ModifyOrderRequestInputSchema = v.object({\n ...AccountScopeInputEntries,\n requestId: v.optional(OrderRequestIdInputSchema),\n});\n\nconst ModifyOrderKeyInputSchema = v.union([\n v.pipe(\n v.object({\n orderId: OrderIdInputSchema,\n clientOrderId: v.optional(v.never()),\n }),\n v.transform(({ orderId }) => ({\n key: { case: \"orderId\" as const, value: orderId },\n })),\n ),\n v.pipe(\n v.object({\n orderId: v.optional(v.never()),\n clientOrderId: ClientOrderIdInputSchema,\n }),\n v.transform(({ clientOrderId }) => ({\n key: { case: \"clientOrderId\" as const, value: clientOrderId },\n })),\n ),\n]);\n\nconst ModifyOrderPricePatchInputSchema = v.object({\n newPrice: DecimalInputStringSchema,\n newQty: v.optional(DecimalInputStringSchema),\n});\n\nconst ModifyOrderQtyPatchInputSchema = v.object({\n newPrice: v.optional(DecimalInputStringSchema),\n newQty: DecimalInputStringSchema,\n});\n\nconst ModifyOrderNoPriceQtyPatchInputSchema = v.object({\n newPrice: v.optional(v.never()),\n newQty: v.optional(v.never()),\n});\n\nconst ModifyOrderClearRiskPatchInputSchema = v.object({\n risk: v.optional(v.never()),\n clearRisk: v.literal(true),\n});\n\nconst ModifyOrderNoRiskPatchInputSchema = v.object({\n risk: v.optional(v.never()),\n clearRisk: v.optional(v.literal(false)),\n});\n\nconst MODIFY_ORDER_ITEM_INPUT_KEYS = new Set<string>([\n ...Object.keys(ModifyOrderItemBaseInputSchema.entries),\n \"orderId\",\n \"clientOrderId\",\n \"newPrice\",\n \"newQty\",\n \"risk\",\n \"clearRisk\",\n]);\n\nconst MODIFY_ORDER_INPUT_KEYS = new Set<string>([\n ...MODIFY_ORDER_ITEM_INPUT_KEYS,\n ...Object.keys(ModifyOrderRequestInputSchema.entries),\n]);\n\n/**\n * The modify-order input is a v.intersect of partial object schemas, so its\n * members cannot use v.strictObject (each member would reject the other\n * members' keys). Unknown keys are rejected up front instead, matching the\n * strict-input behavior of every other mutating method.\n */\nexport function assertKnownModifyOrderInputKeys(input: object): void {\n for (const key of Object.keys(input)) {\n if (!MODIFY_ORDER_INPUT_KEYS.has(key)) {\n throw new ValidationError(`Unknown key \"${key}\" in modify order input.`);\n }\n }\n}\n\nexport function createModifyOrderPatchInputSchema(scales: SdkScales) {\n const ModifyOrderSetRiskPatchInputSchema = v.object({\n risk: createRequiredRiskPolicyInputSchema(scales),\n clearRisk: v.optional(v.literal(false)),\n });\n\n const ModifyOrderAnyRiskPatchInputSchema = v.union([\n ModifyOrderSetRiskPatchInputSchema,\n ModifyOrderClearRiskPatchInputSchema,\n ModifyOrderNoRiskPatchInputSchema,\n ]);\n\n const ModifyOrderRequiredRiskPatchInputSchema = v.union([\n ModifyOrderSetRiskPatchInputSchema,\n ModifyOrderClearRiskPatchInputSchema,\n ]);\n\n return v.union([\n v.intersect([ModifyOrderPricePatchInputSchema, ModifyOrderAnyRiskPatchInputSchema]),\n v.intersect([ModifyOrderQtyPatchInputSchema, ModifyOrderAnyRiskPatchInputSchema]),\n v.intersect([\n ModifyOrderNoPriceQtyPatchInputSchema,\n ModifyOrderRequiredRiskPatchInputSchema,\n ]),\n ]);\n}\n\nfunction createModifyOrderItemObjectInputSchema(scales: SdkScales) {\n return v.intersect([\n ModifyOrderItemBaseInputSchema,\n ModifyOrderKeyInputSchema,\n createModifyOrderPatchInputSchema(scales),\n ]);\n}\n\ntype ParsedModifyOrderItemInput = v.InferOutput<\n ReturnType<typeof createModifyOrderItemObjectInputSchema>\n>;\n\nfunction toModifyOrderItem(\n input: ParsedModifyOrderItemInput,\n scales: SdkScales,\n defaultBehavior: ProtoWrite.ModifyBehavior,\n) {\n return {\n key: input.key,\n newPriceTicks:\n input.newPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\"newPrice\", input.newPrice, scales.price()),\n newQtyScaled:\n input.newQty === undefined\n ? undefined\n : positiveDecimalInputToScaled(\n \"newQty\",\n input.newQty,\n scales.baseQty(input.symbolId),\n ),\n newAttachedRisk:\n input.clearRisk === true ? create(ProtoWrite.RiskPolicySchema) : input.risk,\n behavior: input.behavior\n ? ModifyBehaviorCodec.inputToProto[input.behavior]\n : defaultBehavior,\n newClientOrderId: input.newClientOrderId ?? \"\",\n symbolId: input.symbolId,\n };\n}\n\nexport function createModifyOrderInputSchema(scales: SdkScales) {\n return v.pipe(\n v.intersect([\n ModifyOrderRequestInputSchema,\n createModifyOrderItemObjectInputSchema(scales),\n ]),\n v.transform((input) => ({\n subaccountId: accountScopeToSubaccountId(input.account),\n requestId: input.requestId,\n ...toModifyOrderItem(input, scales, ProtoWrite.ModifyBehavior.AMEND_OR_REPLACE),\n })),\n );\n}\n\nexport type ModifyOrderInput = v.InferInput<ReturnType<typeof createModifyOrderInputSchema>>;\n\nexport const ModifyOrderResultSchema = v.pipe(\n v.object({\n actionTaken: enumLabelSchema(ModifyActionCodec.protoToOutput),\n oldOrderId: PublicIdSchema,\n finalOrderId: PublicIdSchema,\n code: v.string(),\n takeProfitTriggerId: OptionalPublicIdSchema,\n stopLossTriggerId: OptionalPublicIdSchema,\n trailingStopTriggerId: OptionalPublicIdSchema,\n tsNs: v.bigint(),\n }),\n v.transform(({ tsNs, ...result }) => ({\n ...result,\n ts: tsNsToMs(tsNs),\n tsNs: tsNs.toString(),\n })),\n);\n\nexport type ModifyOrderResult = v.InferOutput<typeof ModifyOrderResultSchema>;\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,4BAA4B,EAAE,SAAS,sBAAsB;AAEnE,MAAM,2BAA2B,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,CAAC,CAAC;AAE5E,MAAM,iCAAiC,EAAE,OAAO;CAC5C,UAAU,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,QAAQ,CAAC,GAAG,EAAE,SAAS,mBAAmB,CAAC;CACvF,UAAU,EAAE,SAAS,yBAAyB;CAC9C,kBAAkB,EAAE,SAAS,wBAAwB;AACzD,CAAC;AAED,MAAM,gCAAgC,EAAE,OAAO;CAC3C,GAAG;CACH,WAAW,EAAE,SAAS,yBAAyB;AACnD,CAAC;AAED,MAAM,4BAA4B,EAAE,MAAM,CACtC,EAAE,KACE,EAAE,OAAO;CACL,SAAS;CACT,eAAe,EAAE,SAAS,EAAE,MAAM,CAAC;AACvC,CAAC,GACD,EAAE,WAAW,EAAE,eAAe,EAC1B,KAAK;CAAE,MAAM;CAAoB,OAAO;AAAQ,EACpD,EAAE,CACN,GACA,EAAE,KACE,EAAE,OAAO;CACL,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;CAC7B,eAAe;AACnB,CAAC,GACD,EAAE,WAAW,EAAE,qBAAqB,EAChC,KAAK;CAAE,MAAM;CAA0B,OAAO;AAAc,EAChE,EAAE,CACN,CACJ,CAAC;AAED,MAAM,mCAAmC,EAAE,OAAO;CAC9C,UAAU;CACV,QAAQ,EAAE,SAAS,wBAAwB;AAC/C,CAAC;AAED,MAAM,iCAAiC,EAAE,OAAO;CAC5C,UAAU,EAAE,SAAS,wBAAwB;CAC7C,QAAQ;AACZ,CAAC;AAED,MAAM,wCAAwC,EAAE,OAAO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EACf;EACA;EACA,kCAAkC,MAAM;CAC5C,CAAC;AACL;AAMA,SAAS,kBACL,OACA,QACA,iBACF;CACE,OAAO;EACH,KAAK,MAAM;EACX,eACI,MAAM,aAAa,KAAA,IACb,KAAA,IACA,6BAA6B,YAAY,MAAM,UAAU,OAAO,MAAM,CAAC;EACjF,cACI,MAAM,WAAW,KAAA,IACX,KAAA,IACA,6BACI,UACA,MAAM,QACN,OAAO,QAAQ,MAAM,QAAQ,CACjC;EACV,iBACI,MAAM,cAAc,OAAO,OAAOA,gBAA2B,IAAI,MAAM;EAC3E,UAAU,MAAM,WACV,oBAAoB,aAAa,MAAM,YACvC;EACN,kBAAkB,MAAM,oBAAoB;EAC5C,UAAU,MAAM;CACpB;AACJ;AAEA,SAAgB,6BAA6B,QAAmB;CAC5D,OAAO,EAAE,KACL,EAAE,UAAU,CACR,+BACA,uCAAuC,MAAM,CACjD,CAAC,GACD,EAAE,WAAW,WAAW;EACpB,cAAc,2BAA2B,MAAM,OAAO;EACtD,WAAW,MAAM;EACjB,GAAG,kBAAkB,OAAO,QAAA,CAAkD;CAClF,EAAE,CACN;AACJ;AAIA,MAAa,0BAA0B,EAAE,KACrC,EAAE,OAAO;CACL,aAAa,gBAAgB,kBAAkB,aAAa;CAC5D,YAAY;CACZ,cAAc;CACd,MAAM,EAAE,OAAO;CACf,qBAAqB;CACrB,mBAAmB;CACnB,uBAAuB;CACvB,MAAM,EAAE,OAAO;AACnB,CAAC,GACD,EAAE,WAAW,EAAE,MAAM,GAAG,cAAc;CAClC,GAAG;CACH,IAAI,SAAS,IAAI;CACjB,MAAM,KAAK,SAAS;AACxB,EAAE,CACN"}
|
|
@@ -12,7 +12,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
|
|
|
12
12
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
13
13
|
readonly clientOrderId: v.StringSchema<undefined>;
|
|
14
14
|
readonly side: v.NumberSchema<undefined>;
|
|
15
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
15
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled">]>;
|
|
16
16
|
readonly orderType: v.NumberSchema<undefined>;
|
|
17
17
|
readonly timeInForce: v.NumberSchema<undefined>;
|
|
18
18
|
readonly selfTradePreventionMode: v.NumberSchema<undefined>;
|
|
@@ -149,7 +149,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
|
|
|
149
149
|
symbolId: number;
|
|
150
150
|
clientOrderId: string;
|
|
151
151
|
side: number;
|
|
152
|
-
status: "unspecified" | "
|
|
152
|
+
status: "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled";
|
|
153
153
|
orderType: number;
|
|
154
154
|
timeInForce: number;
|
|
155
155
|
selfTradePreventionMode: number;
|
|
@@ -375,7 +375,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
|
|
|
375
375
|
hiddenQty?: string | undefined;
|
|
376
376
|
symbolId: number;
|
|
377
377
|
clientOrderId: string;
|
|
378
|
-
status: "unspecified" | "
|
|
378
|
+
status: "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled" | "partial";
|
|
379
379
|
side: "buy" | "sell" | "unspecified";
|
|
380
380
|
orderType: "unspecified" | "limit" | "market";
|
|
381
381
|
timeInForce: "unspecified" | "gtc" | "ioc" | "fok" | "gtd";
|
|
@@ -442,7 +442,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
|
|
|
442
442
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
443
443
|
readonly clientOrderId: v.StringSchema<undefined>;
|
|
444
444
|
readonly side: v.NumberSchema<undefined>;
|
|
445
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
445
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled">]>;
|
|
446
446
|
readonly orderType: v.NumberSchema<undefined>;
|
|
447
447
|
readonly timeInForce: v.NumberSchema<undefined>;
|
|
448
448
|
readonly selfTradePreventionMode: v.NumberSchema<undefined>;
|
|
@@ -579,7 +579,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
|
|
|
579
579
|
symbolId: number;
|
|
580
580
|
clientOrderId: string;
|
|
581
581
|
side: number;
|
|
582
|
-
status: "unspecified" | "
|
|
582
|
+
status: "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled";
|
|
583
583
|
orderType: number;
|
|
584
584
|
timeInForce: number;
|
|
585
585
|
selfTradePreventionMode: number;
|
|
@@ -805,7 +805,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
|
|
|
805
805
|
hiddenQty?: string | undefined;
|
|
806
806
|
symbolId: number;
|
|
807
807
|
clientOrderId: string;
|
|
808
|
-
status: "unspecified" | "
|
|
808
|
+
status: "unspecified" | "rejected" | "canceled" | "pending" | "pending_cancel" | "working" | "filled" | "partial";
|
|
809
809
|
side: "buy" | "sell" | "unspecified";
|
|
810
810
|
orderType: "unspecified" | "limit" | "market";
|
|
811
811
|
timeInForce: "unspecified" | "gtc" | "ioc" | "fok" | "gtd";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders-output.schemas.d.ts","names":[],"sources":["../../../src/services/orders/orders-output.schemas.ts"],"mappings":";;;;;iBA+LgB,kBAAkB,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAU9C,eAAe,EAAE,YAAY,kBAAkB"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ErrorCode } from "../../gen/orders/v1/orders_pb.js";
|
|
2
1
|
import { parse } from "../../shared/validation.js";
|
|
3
2
|
import { formatId } from "../../utils/base58-id.js";
|
|
4
3
|
import { tsNsToMs, tsObjToMs } from "../../utils/time.js";
|
|
@@ -9,6 +8,7 @@ import { fromU128 } from "../../utils/u128.js";
|
|
|
9
8
|
import { AccountCodeCodec, TransferCodeCodec } from "../../shared/ledger-codes.js";
|
|
10
9
|
import { FeeAssetCodec, OrderSideCodec, OrderTypeCodec, SelfTradePreventionModeCodec, TimeInForceCodec } from "./order-enums.codecs.js";
|
|
11
10
|
import { OrderLineageSchema } from "./order-lineage.schemas.js";
|
|
11
|
+
import { orderErrorCodeName } from "./order-errors.schemas.js";
|
|
12
12
|
import { OrderCancelReasonCodec, OrderOriginScopeCodec, OrderStatusCodec, OrderTriggerTypeCodec } from "./orders.codecs.js";
|
|
13
13
|
import { createUserTradeSchema } from "../trades/trades.schemas.js";
|
|
14
14
|
import { ReadAttachedRiskSchema, formatAttachedRisk, formatMarketMaxSlippage } from "./orders-risk.schemas.js";
|
|
@@ -99,7 +99,7 @@ function toOrder(scales, o, n) {
|
|
|
99
99
|
price: scaledToDecimalOutput(o.priceTicks, scales.price()),
|
|
100
100
|
createdTs: tsNsToMs(o.createdTsNs),
|
|
101
101
|
terminalTs: tsNsToMs(o.terminalTsNs),
|
|
102
|
-
...o.rejectReason === 0 ? {} : { rejectReason:
|
|
102
|
+
...o.rejectReason === 0 ? {} : { rejectReason: orderErrorCodeName(o.rejectReason) },
|
|
103
103
|
...o.cancelReason === 0 ? {} : { cancelReason: enumLabel(OrderCancelReasonCodec.protoToOutput, o.cancelReason) },
|
|
104
104
|
attachedRisk: formatAttachedRisk(scales, n.attachedRisk),
|
|
105
105
|
...n.origin ? { origin: n.origin } : {},
|
|
@@ -129,14 +129,6 @@ function formatOrder(scales, o) {
|
|
|
129
129
|
expireAt: tsObjToMs(o.expireAt)
|
|
130
130
|
});
|
|
131
131
|
}
|
|
132
|
-
/**
|
|
133
|
-
* A REJECTED order's refusal, named like the error the Orders API returns for it. A code
|
|
134
|
-
* newer than this build reads as `"UNSPECIFIED"`: treat it as a generic refusal.
|
|
135
|
-
*/
|
|
136
|
-
function orderRejectReason(code) {
|
|
137
|
-
const name = ErrorCode[code];
|
|
138
|
-
return typeof name === "string" ? name : "UNSPECIFIED";
|
|
139
|
-
}
|
|
140
132
|
function createOrderTransferSchema() {
|
|
141
133
|
return v.pipe(v.object({
|
|
142
134
|
txId: v.string(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders-output.schemas.js","names":[],"sources":["../../../src/services/orders/orders-output.schemas.ts"],"sourcesContent":["import { ErrorCode } from \"../../gen/orders/v1/orders_pb.js\";\nimport { OrderLineageSchema } from \"./order-lineage.schemas.js\";\nimport type { OrderErrorCode } from \"./order-errors.schemas.js\";\nimport * as v from \"valibot\";\nimport { tsNsToMs, tsObjToMs } from \"../../utils/time.js\";\nimport type * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport {\n OptionalPublicIdSchema,\n OptionalTimestampMsSchema,\n U128Schema,\n} from \"../../shared/schemas.js\";\nimport { enumLabel, enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport { E18_SCALE, scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { createUserTradeSchema } from \"../trades/trades.schemas.js\";\nimport { fromU128 } from \"../../utils/u128.js\";\nimport { AccountCodeCodec, TransferCodeCodec } from \"../../shared/ledger-codes.js\";\nimport {\n FeeAssetCodec,\n OrderCancelReasonCodec,\n OrderOriginScopeCodec,\n OrderSideCodec,\n OrderStatusCodec,\n OrderTriggerTypeCodec,\n OrderTypeCodec,\n SelfTradePreventionModeCodec,\n TimeInForceCodec,\n} from \"./orders.codecs.js\";\nimport {\n ReadAttachedRiskSchema,\n formatAttachedRisk,\n formatMarketMaxSlippage,\n} from \"./orders-risk.schemas.js\";\n\nconst OrderStatusOutputSchema = enumLabelSchema(OrderStatusCodec.protoToOutput);\n\nconst ReadOrderOriginSchema = v.object({\n scope: enumLabelSchema(OrderOriginScopeCodec.protoToOutput),\n triggerType: enumLabelSchema(OrderTriggerTypeCodec.protoToOutput),\n triggerId: OptionalPublicIdSchema,\n parentOrderId: OptionalPublicIdSchema,\n childSeq: v.number(),\n});\n\nconst OrderFieldsSchema = v.object({\n orderId: v.bigint(),\n lineage: v.optional(OrderLineageSchema),\n symbolId: v.number(),\n clientOrderId: v.string(),\n side: v.number(),\n status: OrderStatusOutputSchema,\n orderType: v.number(),\n timeInForce: v.number(),\n selfTradePreventionMode: v.number(),\n feeAsset: v.number(),\n postOnly: v.boolean(),\n origQtyScaled: v.bigint(),\n cumQtyScaled: v.bigint(),\n inheritedCumQtyScaled: v.optional(v.bigint(), 0n),\n leavesQtyScaled: v.bigint(),\n displayQtyScaled: v.optional(v.bigint(), 0n),\n hiddenQtyScaled: v.optional(v.bigint(), 0n),\n avgPriceTicks: v.bigint(),\n avgPriceE18: v.optional(U128Schema),\n cumNotional: v.optional(U128Schema),\n feeTotal: v.optional(\n v.object({\n amountE18: v.optional(U128Schema),\n isRebate: v.boolean(),\n qtyScaled: v.bigint(),\n }),\n ),\n priceTicks: v.bigint(),\n createdTsNs: v.bigint(),\n terminalTsNs: v.bigint(),\n rejectReason: v.optional(v.number(), 0),\n cancelReason: v.optional(v.number(), 0),\n attachedRisk: v.optional(ReadAttachedRiskSchema),\n origin: v.optional(ReadOrderOriginSchema),\n marketClientRefPriceTicks: v.bigint(),\n marketMaxSlippageTicks: v.bigint(),\n marketMaxSlippageBps: v.number(),\n version: v.pipe(v.number(), v.integer(), v.minValue(0)),\n batchRequestId: v.bigint(),\n submittedMaxQuoteDebitScaled: v.optional(v.bigint()),\n submittedQuoteProceedsScaled: v.optional(v.bigint()),\n expireAt: OptionalTimestampMsSchema,\n});\n\ntype OrderFields = v.InferOutput<typeof OrderFieldsSchema>;\n/** Fields whose schemas transform or range-check, so the fast path still converts them. */\ntype OrderNestedFields = Pick<\n OrderFields,\n \"status\" | \"lineage\" | \"attachedRisk\" | \"origin\" | \"expireAt\"\n>;\n\n// `o` and `n` are separate so the fast path can pass a proto message without copying it:\n// spreading a protobuf-es message costs more than the validation it would skip.\nfunction toOrder(\n scales: SdkScales,\n o: Omit<OrderFields, keyof OrderNestedFields>,\n n: OrderNestedFields,\n) {\n const isPartial = n.status === \"working\" && o.cumQtyScaled > 0n;\n const baseQtyScale = scales.baseQty(o.symbolId);\n const marketClientRefPrice =\n o.marketClientRefPriceTicks > 0n\n ? scaledToDecimalOutput(o.marketClientRefPriceTicks, scales.price())\n : undefined;\n const marketMaxSlippage = formatMarketMaxSlippage(\n scales,\n o.marketMaxSlippageTicks,\n o.marketMaxSlippageBps,\n );\n return {\n orderId: formatId(o.orderId),\n ...(n.lineage === undefined ? {} : { lineage: n.lineage }),\n symbolId: o.symbolId,\n clientOrderId: o.clientOrderId,\n status: isPartial ? (\"partial\" as const) : n.status,\n side: enumLabel(OrderSideCodec.protoToOutput, o.side),\n orderType: enumLabel(OrderTypeCodec.protoToOutput, o.orderType),\n timeInForce: enumLabel(TimeInForceCodec.protoToOutput, o.timeInForce),\n selfTradePreventionMode: enumLabel(\n SelfTradePreventionModeCodec.protoToOutput,\n o.selfTradePreventionMode,\n ),\n feeAsset: enumLabel(FeeAssetCodec.protoToOutput, o.feeAsset),\n postOnly: o.postOnly,\n totalQty: scaledToDecimalOutput(o.origQtyScaled, baseQtyScale),\n cumQty: scaledToDecimalOutput(o.cumQtyScaled, baseQtyScale),\n inheritedCumQty: scaledToDecimalOutput(o.inheritedCumQtyScaled, baseQtyScale),\n leavesQty: scaledToDecimalOutput(o.leavesQtyScaled, baseQtyScale),\n // Iceberg only: the book shows at most displayQty, and leavesQty less hiddenQty now.\n ...(o.displayQtyScaled > 0n\n ? {\n displayQty: scaledToDecimalOutput(o.displayQtyScaled, baseQtyScale),\n hiddenQty: scaledToDecimalOutput(o.hiddenQtyScaled, baseQtyScale),\n }\n : {}),\n avgPx:\n o.avgPriceE18 === undefined\n ? scaledToDecimalOutput(o.avgPriceTicks, scales.price())\n : scaledToDecimalOutput(fromU128(o.avgPriceE18), E18_SCALE),\n cumQuote: scaledToDecimalOutput(fromU128(o.cumNotional), scales.price() + baseQtyScale),\n ...(o.feeTotal === undefined\n ? {}\n : {\n feeTotal: {\n amount: scaledToDecimalOutput(fromU128(o.feeTotal.amountE18), E18_SCALE),\n isRebate: o.feeTotal.isRebate,\n qty: scaledToDecimalOutput(o.feeTotal.qtyScaled, baseQtyScale),\n },\n }),\n price: scaledToDecimalOutput(o.priceTicks, scales.price()),\n createdTs: tsNsToMs(o.createdTsNs),\n terminalTs: tsNsToMs(o.terminalTsNs),\n ...(o.rejectReason === 0 ? {} : { rejectReason: orderRejectReason(o.rejectReason) }),\n ...(o.cancelReason === 0\n ? {}\n : {\n cancelReason: enumLabel(OrderCancelReasonCodec.protoToOutput, o.cancelReason),\n }),\n attachedRisk: formatAttachedRisk(scales, n.attachedRisk),\n ...(n.origin ? { origin: n.origin } : {}),\n ...(marketClientRefPrice ? { marketClientRefPrice } : {}),\n ...(marketMaxSlippage ? { marketMaxSlippage } : {}),\n ...(o.batchRequestId > 0n ? { batchRequestId: formatId(o.batchRequestId) } : {}),\n ...(o.submittedMaxQuoteDebitScaled === undefined\n ? {}\n : {\n submittedMaxQuoteDebit: scaledToDecimalOutput(\n o.submittedMaxQuoteDebitScaled,\n scales.quoteAmount(o.symbolId),\n ),\n }),\n // A quote-proceeds SELL: cumQuote is what it received before fees, never above this.\n ...(o.submittedQuoteProceedsScaled === undefined\n ? {}\n : {\n submittedQuoteProceeds: scaledToDecimalOutput(\n o.submittedQuoteProceedsScaled,\n scales.quoteAmount(o.symbolId),\n ),\n }),\n ...(n.expireAt === undefined ? {} : { expireAt: n.expireAt }),\n version: o.version,\n };\n}\n\nexport function createOrderSchema(scales: SdkScales) {\n return v.pipe(\n OrderFieldsSchema,\n v.transform((o) => toOrder(scales, o, o)),\n );\n}\n\n/**\n * Formats a protobuf-decoded order into the same payload as {@link createOrderSchema}\n * without re-validating fields protobuf already typed. Only nested fields whose schemas\n * transform or range-check are still parsed.\n */\nexport function formatOrder(scales: SdkScales, o: ProtoRead.Order): Order {\n return toOrder(scales, o, {\n status: enumLabel(OrderStatusCodec.protoToOutput, o.status),\n lineage: o.lineage && parse(OrderLineageSchema, o.lineage),\n attachedRisk: o.attachedRisk && parse(ReadAttachedRiskSchema, o.attachedRisk),\n origin: o.origin && parse(ReadOrderOriginSchema, o.origin),\n expireAt: tsObjToMs(o.expireAt),\n });\n}\n\n/**\n * A REJECTED order's refusal, named like the error the Orders API returns for it. A code\n * newer than this build reads as `\"UNSPECIFIED\"`: treat it as a generic refusal.\n */\nfunction orderRejectReason(code: number): OrderErrorCode {\n const name: unknown = ErrorCode[code];\n return typeof name === \"string\" ? (name as OrderErrorCode) : \"UNSPECIFIED\";\n}\n\nexport type Order = v.InferOutput<ReturnType<typeof createOrderSchema>>;\n\nexport function createOrderTransferSchema() {\n return v.pipe(\n v.object({\n txId: v.string(),\n matchId: v.pipe(\n v.bigint(),\n v.transform((value) => value.toString()),\n ),\n symbolId: v.number(),\n assetId: v.number(),\n amountE18: v.optional(\n v.object({\n hi: v.bigint(),\n lo: v.bigint(),\n }),\n ),\n isDebit: v.boolean(),\n transferCode: v.number(),\n accountCode: v.number(),\n tsNs: v.bigint(),\n }),\n v.transform((tr) => ({\n txId: tr.txId,\n matchId: tr.matchId,\n symbolId: tr.symbolId,\n assetId: tr.assetId,\n isDebit: tr.isDebit,\n timestamp: tsNsToMs(tr.tsNs),\n amount: scaledToDecimalOutput(fromU128(tr.amountE18), E18_SCALE),\n type: enumLabel(TransferCodeCodec.protoToOutput, tr.transferCode),\n accountCode: enumLabel(AccountCodeCodec.protoToOutput, tr.accountCode),\n })),\n );\n}\n\nexport type OrderTransfer = v.InferOutput<ReturnType<typeof createOrderTransferSchema>>;\n\nexport function createOrderDetailsSchema(scales: SdkScales) {\n return v.object({\n nextPageToken: v.optional(v.string(), \"\"),\n order: createOrderSchema(scales),\n trades: v.optional(v.array(createUserTradeSchema(scales)), []),\n transfers: v.optional(v.array(createOrderTransferSchema()), []),\n executionsComplete: v.optional(v.boolean(), false),\n });\n}\n\nexport type OrderDetails = v.InferOutput<ReturnType<typeof createOrderDetailsSchema>>;\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,MAAM,0BAA0B,gBAAgB,iBAAiB,aAAa;AAE9E,MAAM,wBAAwB,EAAE,OAAO;CACnC,OAAO,gBAAgB,sBAAsB,aAAa;CAC1D,aAAa,gBAAgB,sBAAsB,aAAa;CAChE,WAAW;CACX,eAAe;CACf,UAAU,EAAE,OAAO;AACvB,CAAC;AAED,MAAM,oBAAoB,EAAE,OAAO;CAC/B,SAAS,EAAE,OAAO;CAClB,SAAS,EAAE,SAAS,kBAAkB;CACtC,UAAU,EAAE,OAAO;CACnB,eAAe,EAAE,OAAO;CACxB,MAAM,EAAE,OAAO;CACf,QAAQ;CAC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,oBAAoB,EAAE,SAAS,EAAE,QAAQ,GAAG,KAAK;CACrD,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"orders-output.schemas.js","names":[],"sources":["../../../src/services/orders/orders-output.schemas.ts"],"sourcesContent":["import { OrderLineageSchema } from \"./order-lineage.schemas.js\";\nimport { orderErrorCodeName } from \"./order-errors.schemas.js\";\nimport * as v from \"valibot\";\nimport { tsNsToMs, tsObjToMs } from \"../../utils/time.js\";\nimport type * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport {\n OptionalPublicIdSchema,\n OptionalTimestampMsSchema,\n U128Schema,\n} from \"../../shared/schemas.js\";\nimport { enumLabel, enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport { E18_SCALE, scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { createUserTradeSchema } from \"../trades/trades.schemas.js\";\nimport { fromU128 } from \"../../utils/u128.js\";\nimport { AccountCodeCodec, TransferCodeCodec } from \"../../shared/ledger-codes.js\";\nimport {\n FeeAssetCodec,\n OrderCancelReasonCodec,\n OrderOriginScopeCodec,\n OrderSideCodec,\n OrderStatusCodec,\n OrderTriggerTypeCodec,\n OrderTypeCodec,\n SelfTradePreventionModeCodec,\n TimeInForceCodec,\n} from \"./orders.codecs.js\";\nimport {\n ReadAttachedRiskSchema,\n formatAttachedRisk,\n formatMarketMaxSlippage,\n} from \"./orders-risk.schemas.js\";\n\nconst OrderStatusOutputSchema = enumLabelSchema(OrderStatusCodec.protoToOutput);\n\nconst ReadOrderOriginSchema = v.object({\n scope: enumLabelSchema(OrderOriginScopeCodec.protoToOutput),\n triggerType: enumLabelSchema(OrderTriggerTypeCodec.protoToOutput),\n triggerId: OptionalPublicIdSchema,\n parentOrderId: OptionalPublicIdSchema,\n childSeq: v.number(),\n});\n\nconst OrderFieldsSchema = v.object({\n orderId: v.bigint(),\n lineage: v.optional(OrderLineageSchema),\n symbolId: v.number(),\n clientOrderId: v.string(),\n side: v.number(),\n status: OrderStatusOutputSchema,\n orderType: v.number(),\n timeInForce: v.number(),\n selfTradePreventionMode: v.number(),\n feeAsset: v.number(),\n postOnly: v.boolean(),\n origQtyScaled: v.bigint(),\n cumQtyScaled: v.bigint(),\n inheritedCumQtyScaled: v.optional(v.bigint(), 0n),\n leavesQtyScaled: v.bigint(),\n displayQtyScaled: v.optional(v.bigint(), 0n),\n hiddenQtyScaled: v.optional(v.bigint(), 0n),\n avgPriceTicks: v.bigint(),\n avgPriceE18: v.optional(U128Schema),\n cumNotional: v.optional(U128Schema),\n feeTotal: v.optional(\n v.object({\n amountE18: v.optional(U128Schema),\n isRebate: v.boolean(),\n qtyScaled: v.bigint(),\n }),\n ),\n priceTicks: v.bigint(),\n createdTsNs: v.bigint(),\n terminalTsNs: v.bigint(),\n rejectReason: v.optional(v.number(), 0),\n cancelReason: v.optional(v.number(), 0),\n attachedRisk: v.optional(ReadAttachedRiskSchema),\n origin: v.optional(ReadOrderOriginSchema),\n marketClientRefPriceTicks: v.bigint(),\n marketMaxSlippageTicks: v.bigint(),\n marketMaxSlippageBps: v.number(),\n version: v.pipe(v.number(), v.integer(), v.minValue(0)),\n batchRequestId: v.bigint(),\n submittedMaxQuoteDebitScaled: v.optional(v.bigint()),\n submittedQuoteProceedsScaled: v.optional(v.bigint()),\n expireAt: OptionalTimestampMsSchema,\n});\n\ntype OrderFields = v.InferOutput<typeof OrderFieldsSchema>;\n/** Fields whose schemas transform or range-check, so the fast path still converts them. */\ntype OrderNestedFields = Pick<\n OrderFields,\n \"status\" | \"lineage\" | \"attachedRisk\" | \"origin\" | \"expireAt\"\n>;\n\n// `o` and `n` are separate so the fast path can pass a proto message without copying it:\n// spreading a protobuf-es message costs more than the validation it would skip.\nfunction toOrder(\n scales: SdkScales,\n o: Omit<OrderFields, keyof OrderNestedFields>,\n n: OrderNestedFields,\n) {\n const isPartial = n.status === \"working\" && o.cumQtyScaled > 0n;\n const baseQtyScale = scales.baseQty(o.symbolId);\n const marketClientRefPrice =\n o.marketClientRefPriceTicks > 0n\n ? scaledToDecimalOutput(o.marketClientRefPriceTicks, scales.price())\n : undefined;\n const marketMaxSlippage = formatMarketMaxSlippage(\n scales,\n o.marketMaxSlippageTicks,\n o.marketMaxSlippageBps,\n );\n return {\n orderId: formatId(o.orderId),\n ...(n.lineage === undefined ? {} : { lineage: n.lineage }),\n symbolId: o.symbolId,\n clientOrderId: o.clientOrderId,\n status: isPartial ? (\"partial\" as const) : n.status,\n side: enumLabel(OrderSideCodec.protoToOutput, o.side),\n orderType: enumLabel(OrderTypeCodec.protoToOutput, o.orderType),\n timeInForce: enumLabel(TimeInForceCodec.protoToOutput, o.timeInForce),\n selfTradePreventionMode: enumLabel(\n SelfTradePreventionModeCodec.protoToOutput,\n o.selfTradePreventionMode,\n ),\n feeAsset: enumLabel(FeeAssetCodec.protoToOutput, o.feeAsset),\n postOnly: o.postOnly,\n totalQty: scaledToDecimalOutput(o.origQtyScaled, baseQtyScale),\n cumQty: scaledToDecimalOutput(o.cumQtyScaled, baseQtyScale),\n inheritedCumQty: scaledToDecimalOutput(o.inheritedCumQtyScaled, baseQtyScale),\n leavesQty: scaledToDecimalOutput(o.leavesQtyScaled, baseQtyScale),\n // Iceberg only: the book shows at most displayQty, and leavesQty less hiddenQty now.\n ...(o.displayQtyScaled > 0n\n ? {\n displayQty: scaledToDecimalOutput(o.displayQtyScaled, baseQtyScale),\n hiddenQty: scaledToDecimalOutput(o.hiddenQtyScaled, baseQtyScale),\n }\n : {}),\n avgPx:\n o.avgPriceE18 === undefined\n ? scaledToDecimalOutput(o.avgPriceTicks, scales.price())\n : scaledToDecimalOutput(fromU128(o.avgPriceE18), E18_SCALE),\n cumQuote: scaledToDecimalOutput(fromU128(o.cumNotional), scales.price() + baseQtyScale),\n ...(o.feeTotal === undefined\n ? {}\n : {\n feeTotal: {\n amount: scaledToDecimalOutput(fromU128(o.feeTotal.amountE18), E18_SCALE),\n isRebate: o.feeTotal.isRebate,\n qty: scaledToDecimalOutput(o.feeTotal.qtyScaled, baseQtyScale),\n },\n }),\n price: scaledToDecimalOutput(o.priceTicks, scales.price()),\n createdTs: tsNsToMs(o.createdTsNs),\n terminalTs: tsNsToMs(o.terminalTsNs),\n // A REJECTED order's refusal, named like the error the Orders API returns for it.\n ...(o.rejectReason === 0 ? {} : { rejectReason: orderErrorCodeName(o.rejectReason) }),\n ...(o.cancelReason === 0\n ? {}\n : {\n cancelReason: enumLabel(OrderCancelReasonCodec.protoToOutput, o.cancelReason),\n }),\n attachedRisk: formatAttachedRisk(scales, n.attachedRisk),\n ...(n.origin ? { origin: n.origin } : {}),\n ...(marketClientRefPrice ? { marketClientRefPrice } : {}),\n ...(marketMaxSlippage ? { marketMaxSlippage } : {}),\n ...(o.batchRequestId > 0n ? { batchRequestId: formatId(o.batchRequestId) } : {}),\n ...(o.submittedMaxQuoteDebitScaled === undefined\n ? {}\n : {\n submittedMaxQuoteDebit: scaledToDecimalOutput(\n o.submittedMaxQuoteDebitScaled,\n scales.quoteAmount(o.symbolId),\n ),\n }),\n // A quote-proceeds SELL: cumQuote is what it received before fees, never above this.\n ...(o.submittedQuoteProceedsScaled === undefined\n ? {}\n : {\n submittedQuoteProceeds: scaledToDecimalOutput(\n o.submittedQuoteProceedsScaled,\n scales.quoteAmount(o.symbolId),\n ),\n }),\n ...(n.expireAt === undefined ? {} : { expireAt: n.expireAt }),\n version: o.version,\n };\n}\n\nexport function createOrderSchema(scales: SdkScales) {\n return v.pipe(\n OrderFieldsSchema,\n v.transform((o) => toOrder(scales, o, o)),\n );\n}\n\n/**\n * Formats a protobuf-decoded order into the same payload as {@link createOrderSchema}\n * without re-validating fields protobuf already typed. Only nested fields whose schemas\n * transform or range-check are still parsed.\n */\nexport function formatOrder(scales: SdkScales, o: ProtoRead.Order): Order {\n return toOrder(scales, o, {\n status: enumLabel(OrderStatusCodec.protoToOutput, o.status),\n lineage: o.lineage && parse(OrderLineageSchema, o.lineage),\n attachedRisk: o.attachedRisk && parse(ReadAttachedRiskSchema, o.attachedRisk),\n origin: o.origin && parse(ReadOrderOriginSchema, o.origin),\n expireAt: tsObjToMs(o.expireAt),\n });\n}\n\nexport type Order = v.InferOutput<ReturnType<typeof createOrderSchema>>;\n\nexport function createOrderTransferSchema() {\n return v.pipe(\n v.object({\n txId: v.string(),\n matchId: v.pipe(\n v.bigint(),\n v.transform((value) => value.toString()),\n ),\n symbolId: v.number(),\n assetId: v.number(),\n amountE18: v.optional(\n v.object({\n hi: v.bigint(),\n lo: v.bigint(),\n }),\n ),\n isDebit: v.boolean(),\n transferCode: v.number(),\n accountCode: v.number(),\n tsNs: v.bigint(),\n }),\n v.transform((tr) => ({\n txId: tr.txId,\n matchId: tr.matchId,\n symbolId: tr.symbolId,\n assetId: tr.assetId,\n isDebit: tr.isDebit,\n timestamp: tsNsToMs(tr.tsNs),\n amount: scaledToDecimalOutput(fromU128(tr.amountE18), E18_SCALE),\n type: enumLabel(TransferCodeCodec.protoToOutput, tr.transferCode),\n accountCode: enumLabel(AccountCodeCodec.protoToOutput, tr.accountCode),\n })),\n );\n}\n\nexport type OrderTransfer = v.InferOutput<ReturnType<typeof createOrderTransferSchema>>;\n\nexport function createOrderDetailsSchema(scales: SdkScales) {\n return v.object({\n nextPageToken: v.optional(v.string(), \"\"),\n order: createOrderSchema(scales),\n trades: v.optional(v.array(createUserTradeSchema(scales)), []),\n transfers: v.optional(v.array(createOrderTransferSchema()), []),\n executionsComplete: v.optional(v.boolean(), false),\n });\n}\n\nexport type OrderDetails = v.InferOutput<ReturnType<typeof createOrderDetailsSchema>>;\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,0BAA0B,gBAAgB,iBAAiB,aAAa;AAE9E,MAAM,wBAAwB,EAAE,OAAO;CACnC,OAAO,gBAAgB,sBAAsB,aAAa;CAC1D,aAAa,gBAAgB,sBAAsB,aAAa;CAChE,WAAW;CACX,eAAe;CACf,UAAU,E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AAC,GAAG,CAAC,CAAC;EAC7D,WAAW,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC,GAAG,CAAC,CAAC;EAC9D,oBAAoB,EAAE,SAAS,EAAE,QAAQ,GAAG,KAAK;CACrD,CAAC;AACL"}
|
|
@@ -32,6 +32,12 @@ interface SubscribeOrdersInput extends BaseSubscribeInput<Order> {
|
|
|
32
32
|
* the rest of the view is current. A later call replaces the earlier one.
|
|
33
33
|
*/
|
|
34
34
|
onStale?: (stale: boolean, orderIds?: string[]) => void;
|
|
35
|
+
/**
|
|
36
|
+
* The stream reflects every order change acknowledged before it subscribed, including
|
|
37
|
+
* every order read made before then. Wait for it before relying on the stream. Called
|
|
38
|
+
* again after each resubscribe or reconnect.
|
|
39
|
+
*/
|
|
40
|
+
onReady?: () => void;
|
|
35
41
|
}
|
|
36
42
|
/**
|
|
37
43
|
* Manages account-scoped spot orders across read, write, and realtime order update surfaces.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders.d.ts","names":[],"sources":["../../../src/services/orders/orders.ts"],"mappings":";;;;;;;;;;;;;UA+FiB,6BAA6B,mBAAmB;;EAE7D;;;;;;;EAOA,cAAc,QAAQ;;;;;EAKtB,aAAa;;;;;;EAMb,WAAW,gBAAgB;;;;;
|
|
1
|
+
{"version":3,"file":"orders.d.ts","names":[],"sources":["../../../src/services/orders/orders.ts"],"mappings":";;;;;;;;;;;;;UA+FiB,6BAA6B,mBAAmB;;EAE7D;;;;;;;EAOA,cAAc,QAAQ;;;;;EAKtB,aAAa;;;;;;EAMb,WAAW,gBAAgB;;;;;;EAM3B;;;;;cAcS;;EAYL,YAAA,YAAY,mBACZ,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;EAgBN,SACF,QAAO,EAAE,kBAAkB,wBAC3B,UAAU,0BACX;IAAU,QAAQ;IAAS;;;;;EAmBxB,YACF,QAAO,EAAE,kBAAkB,0BAC3B,UAAU,0BACX;IAAU,QAAQ;IAAS;;;;;EAmBxB,QACF,OAAO,eACP,UAAU,0BACX,QAAQ;;;;EAiBL,OACF,OAAO,eACP,UAAU,2BACX,QAAQ;;;;EAkBL,YACF,OAAO,wBACP,UAAU,2BACX,QAAQ;;;;EAyBL,OACF,OAAO,EAAE,kBAAkB,yBAC3B,UAAU,2BACX,QAAQ;;;;EAmBL,YACF,OAAO,wBACP,UAAU,2BACX,QAAQ;;;;EAkBL,OACF,OAAO,kBACP,UAAU,2BACX,QAAQ;;;;;;;;EAsBL,aACF,OAAO,yBACP,UAAU,2BACX,QAAQ;;;;;;;;;;;;EA8BL,sBACF,OAAO,4BACP,UAAU,0BACX,QAAQ;;;;;;EAeL,UACF,OAAO,EAAE,kBAAkB,6BAC3B,UAAU,2BACX,QAAQ;;;;EAgBL,eACF,OAAO,qBACP,UAAU,2BACX,QAAQ;;;;;;;;;EAqBL,WACF,OAAO,EAAE,kBAAkB,6BAC3B,UAAU,0BACX,QAAQ;;;;;;;;EA2BX,UAAU,OAAO"}
|
|
@@ -264,6 +264,10 @@ var OrdersService = class {
|
|
|
264
264
|
channel,
|
|
265
265
|
ready: () => this.#scales.ready(),
|
|
266
266
|
onPublication: (event) => {
|
|
267
|
+
if (event.type === "ready") {
|
|
268
|
+
input.onReady?.();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
267
271
|
if (event.type === "stale") {
|
|
268
272
|
input.onStale?.(event.stale, event.orderIds?.map((id) => formatId(id)));
|
|
269
273
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders.js","names":["#readClient","ProtoRead.OrdersReadService","#writeClient","ProtoWrite.OrdersService","#realtime","#resolver","#scales","#orderDetailsSchema","#newOrderInputSchema","#modifyOrderInputSchema","#batchCreateOrdersInputSchema"],"sources":["../../../src/services/orders/orders.ts"],"sourcesContent":["import * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type * 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 { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { connectReadyGated } from \"../../realtime/ready-gated-subscription.js\";\nimport type { PrivateOrdersEvent } from \"../../realtime/private-orders.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { formatId, idToBigInt } from \"../../utils/base58-id.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { loadErrorDetailDecoders } from \"../../shared/error-detail.js\";\nimport { PolyesterError } from \"../../shared/errors.js\";\nimport { createMutationRequestId } from \"../../shared/request-id.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { formatConnectError, isResourceNotFoundError } from \"../../utils/errors.js\";\nimport {\n OpenOrdersInputSchema,\n OrderHistoryInputSchema,\n type NewOrderInput,\n createNewOrderInputSchema,\n CancelOrderInputSchema,\n CancelOrderResultSchema,\n type CancelOrderResult,\n CancelAllOrdersInputSchema,\n CancelAllOrdersResponseSchema,\n type CancelAllOrdersResponse,\n type Order,\n GetOrderDetailsInputSchema,\n createCreateOrderResultSchema,\n createPreviewOrderResultSchema,\n type PreviewOrderResult,\n type ModifyOrderInput,\n assertKnownModifyOrderInputKeys,\n createModifyOrderInputSchema,\n ModifyOrderResultSchema,\n type CreateOrderResult,\n type ModifyOrderResult,\n type OrderDetails,\n formatOrder,\n createOrderDetailsSchema,\n CancelAllAfterInputSchema,\n CancelAllAfterResultSchema,\n type CancelAllAfterInput,\n type CancelAllAfterResult,\n BatchCancelOrdersInputSchema,\n BatchCancelOrdersResultSchema,\n type BatchCancelOrdersInput,\n type BatchCancelOrdersResult,\n createBatchCreateOrdersResultSchema,\n type BatchCreateOrdersInput,\n type BatchCreateOrdersResult,\n BatchReplaceOrdersResultSchema,\n type BatchReplaceOrdersInput,\n type BatchReplaceOrdersResult,\n GetBatchReplaceStatusInputSchema,\n GetBatchReplaceStatusResultSchema,\n type GetBatchReplaceStatusInput,\n type GetBatchReplaceStatusResult,\n assertKnownBatchReplaceOrderItemInputKeys,\n createBatchCreateOrdersInputSchema,\n createBatchReplaceOrdersInputSchema,\n} from \"./orders.schemas.js\";\n\nfunction hasKnownOrderSymbol(scales: SdkScales, order: { symbolId: number }): boolean {\n try {\n scales.baseQty(order.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\nconst MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE = \"order not found\";\n\nfunction isOrderNotFoundError(error: unknown): boolean {\n const mapped = toPolyesterError(error);\n return (\n isResourceNotFoundError(error) ||\n (mapped instanceof PolyesterError &&\n mapped.detail?.service === \"orders\" &&\n mapped.detail.code === \"NOT_FOUND\") ||\n formatConnectError(error, \"\").toLowerCase() === MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE\n );\n}\n\nexport interface SubscribeOrdersInput extends BaseSubscribeInput<Order> {\n /** The account's base58 public ID, the root account's or a sub-account's. */\n accountId: string;\n /**\n * The account's full live view: open orders, orders not yet on the book, and\n * recently ended orders. Sent when the subscription starts and whenever the\n * server replaces its state; replace local order state with it. When omitted,\n * each snapshot order goes to `onEvent` instead.\n */\n onSnapshot?: (orders: Order[]) => void;\n /**\n * Orders that left the live view and remain only in history. Not cancellations.\n * Without `onSnapshot`, also the orders a resync snapshot no longer contains.\n */\n onRemoved?: (orderIds: string[]) => void;\n /**\n * `true` while the account's live view is behind; `false` once it caught up.\n * `orderIds`, when set, names the only orders whose rows show an earlier state;\n * the rest of the view is current. A later call replaces the earlier one.\n */\n onStale?: (stale: boolean, orderIds?: string[]) => void;\n}\n\nfunction assertBatchResultCount(operation: string, requested: number, returned: number): void {\n if (requested !== returned) {\n throw new Error(\n `${operation} returned ${returned} results for ${requested} requested items.`,\n );\n }\n}\n\n/**\n * Manages account-scoped spot orders across read, write, and realtime order update surfaces.\n */\nexport class OrdersService {\n #readClient: Client<typeof ProtoRead.OrdersReadService>;\n #writeClient: Client<typeof ProtoWrite.OrdersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #orderDetailsSchema: ReturnType<typeof createOrderDetailsSchema>;\n #newOrderInputSchema: ReturnType<typeof createNewOrderInputSchema>;\n #modifyOrderInputSchema: ReturnType<typeof createModifyOrderInputSchema>;\n #batchCreateOrdersInputSchema: ReturnType<typeof createBatchCreateOrdersInputSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#readClient = createClient(ProtoRead.OrdersReadService, transports.authApi);\n this.#writeClient = createClient(ProtoWrite.OrdersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#orderDetailsSchema = createOrderDetailsSchema(scales);\n this.#newOrderInputSchema = createNewOrderInputSchema(scales);\n this.#modifyOrderInputSchema = createModifyOrderInputSchema(scales);\n this.#batchCreateOrdersInputSchema = createBatchCreateOrdersInputSchema(scales);\n }\n\n /**\n * Returns open orders for the resolved root account or subaccount, with optional symbol IDs, trigger ID, side, pagination, and attached-risk inclusion filters. Results are paginated with a server-determined page size: a single call is not the full set of open orders — keep calling with the returned nextPageToken until it is empty.\n */\n async listOpen(\n input: v.InferInput<typeof OpenOrdersInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OpenOrdersInputSchema, resolved);\n const res = await this.#readClient.getOpenOrders(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns historical orders for the resolved account scope, supporting symbol IDs, trigger ID, side, status, time range, pagination, and attached-risk filters. A page may hold fewer orders than requested, or none: keep calling with the returned nextPageToken until it is empty.\n */\n async listHistory(\n input: v.InferInput<typeof OrderHistoryInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OrderHistoryInputSchema, resolved);\n const res = await this.#readClient.getOrderHistory(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Evaluates one complete order intent against current market, policy, risk, and balance state without creating an order, reserving funds, or claiming its client order ID.\n */\n async preview(\n input: NewOrderInput,\n options?: PolyesterRequestOptions,\n ): Promise<PreviewOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(this.#newOrderInputSchema, resolved);\n const response = await this.#writeClient.previewOrder(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(\n createPreviewOrderResultSchema(this.#scales, request.order.symbolId),\n response,\n );\n }\n\n /**\n * Places a spot order with an explicit market-IOC, limit-GTC, limit-GTD, limit-IOC, or limit-FOK execution policy and optional attached risk controls. Size it by `qty`, a BUY IOC by `maxQuoteDebit`, or a SELL IOC by `quoteProceeds`, the quote it stops at before fees. A GTC or GTD limit can show only `execution.displayQty` at a time (iceberg), and `peg` takes a limit price from the best bid or ask at entry, capped or floored by `execution.price`. clientOrderId is an account-scoped correlation, lookup, and cancellation identifier. Reuse while retained returns CONFLICT_DUPLICATE_CLIENT_ORDER_ID, including after rejection or completion; it does not replay the earlier result. After an ambiguous timeout, reconcile through get using clientOrderId; an immediate lookup miss does not prove admission failed. Without clientOrderId, the outcome may remain unknown.\n */\n async create(\n input: NewOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#newOrderInputSchema, resolved);\n const requestPayload = removeUndefined(validatedInput);\n const res = await this.#writeClient.createOrder(\n requestPayload,\n toConnectCallOptions(options),\n );\n return parse(\n createCreateOrderResultSchema(this.#scales, validatedInput.order.symbolId),\n res,\n );\n }\n\n /**\n * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. Reusing the account-scoped requestId with the same payload within 15 minutes returns each decided item's original result and result time and retries items still unresolved, never admitting an item twice; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. After 15 minutes the ID is free and a repeat can place its orders again, so read the items back instead of repeating an older batch. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.\n */\n async batchCreate(\n input: BatchCreateOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCreateOrdersResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(this.#batchCreateOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCreateOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(\n createBatchCreateOrdersResultSchema(\n this.#scales,\n request.items.map((item) => item.symbolId),\n ),\n response,\n );\n assertBatchResultCount(\"batchCreate\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Requests cancellation of one order in the resolved account scope by order id or client order id, with optional symbol routing. The response acknowledges the cancellation request, not the order's final lifecycle state; reconcile through order reads or realtime before releasing local state. A missing target remains a {@link ResourceNotFoundError}; callers performing desired-state cleanup may treat that error as success when the order could already have filled or left the book.\n */\n async cancel(\n input: v.InferInput<typeof CancelOrderInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOrderResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n\n const validated = parse(CancelOrderInputSchema, resolved);\n\n const res = await this.#writeClient.cancelOrder(\n {\n key: validated.key,\n symbolId: validated.symbolId,\n subaccountId: validated.subaccountId,\n },\n toConnectCallOptions(options),\n );\n return parse(CancelOrderResultSchema, res);\n }\n\n /**\n * Cancels 1–50 explicit orders in one best-effort request. Results preserve item order and acknowledge cancellation admission rather than final order state. Supply a stable requestId when an ambiguous batch may be retried.\n */\n async batchCancel(\n input: BatchCancelOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelOrdersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(BatchCancelOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCancelOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelOrdersResultSchema, response);\n assertBatchResultCount(\"batchCancel\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Applies a price, quantity, client id, or attached-risk patch to one open order. The symbol ID routes policy checks and quantity scaling. A requestId is generated when omitted; provide a stable value when retrying the same logical modification.\n */\n async modify(\n input: ModifyOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyOrderResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n assertKnownModifyOrderInputKeys(resolved);\n const validated = parse(this.#modifyOrderInputSchema, resolved);\n const res = await this.#writeClient.modifyOrder(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ModifyOrderResultSchema, res);\n }\n\n /**\n * Replaces 1–50 same-symbol orders and returns an index-stable durable admission receipt. Reuse requestId only when retrying the same logical batch; use the returned batchRequestId for later status reads. An AMENDED actionTaken is cancel-only with no successor; keep tracking oldOrderId until its terminal state is confirmed.\n *\n * An item refused for its value (a price off the pair's tick size, or an invalid attached-risk price, distance or slippage) is rejected alone in `results`, with its `code` and an `error` whose violations name `items[i]`; the other items are processed. Resend only the corrected rejected items under a fresh `requestId`. A malformed batch still throws as a whole.\n *\n * The receipt answers admission, before each admitted item's change completes. Until then, the next change of the same order is rejected with the retryable item `code` `ORDER_MODIFY_IN_PROGRESS`, or `ORDER_PLACEMENT_PENDING` when it names the returned `replacementOrderId`. Resend only those items, in a new batch under a fresh `requestId`, after a short jittered backoff (for example 50 ms doubling to 1 s). The rejected batch's `requestId` replays its rejection, admitted items must never be resent, and a batch whose outcome you did not receive is reconciled under its own `requestId`, never resent under a new one.\n */\n async batchReplace(\n input: BatchReplaceOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchReplaceOrdersResult> {\n await this.#scales.ready();\n for (const item of input.items) {\n assertKnownBatchReplaceOrderItemInputKeys(item);\n }\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(createBatchReplaceOrdersInputSchema(this.#scales), resolved);\n const response = await this.#writeClient.batchReplaceOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchReplaceOrdersResultSchema, response);\n assertBatchResultCount(\"batchReplace\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Reads the admission and each item's current execution phase for an accepted batch\n * replacement. Status is retained for 60 seconds from acceptance and is readable as soon as\n * `batchReplace` returns. A `ServiceUnavailableError` means the status is not established\n * yet: retry the same request within the window. A `ResourceNotFoundError` means no batch is\n * retained under this ID (none was accepted, or the window ended), never that the replacement\n * was rejected: reconcile the individual orders and never resubmit an accepted batch. An\n * item's `updatedTsNs` can be a later recovery time, so do not use it to identify a refusal.\n * For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is\n * undefined.\n */\n async getBatchReplaceStatus(\n input: GetBatchReplaceStatusInput,\n options?: PolyesterRequestOptions,\n ): Promise<GetBatchReplaceStatusResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(GetBatchReplaceStatusInputSchema, resolved);\n const response = await this.#readClient.getBatchReplaceStatus(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetBatchReplaceStatusResultSchema, response);\n }\n\n /**\n * Cancels all matching open orders for the resolved account scope, optionally narrowed by up to 100 symbol IDs and side, with dry-run preview. A requestId is generated when omitted; reuse it with the same criteria for retries. Completed results are retained for at least two minutes; use a fresh key for each new cancellation.\n * `canceledOrders` lists up to 200 of the orders whose cancellation was requested, oldest first; `truncated` is true when `totalCanceled` counts more. Read each order's final state from `orders.subscribe` or the order reads.\n * A retry with the same requestId and criteria returns the original counts with `listingStatus: \"not_retained_read_open_orders\"` and an empty `canceledOrders`, which does not mean nothing was canceled; read open orders instead.\n */\n async cancelAll(\n input: v.InferInput<typeof CancelAllOrdersInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllOrdersResponse> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(CancelAllOrdersInputSchema, resolved);\n const res = await this.#writeClient.cancelAllOrders(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelAllOrdersResponseSchema, res);\n }\n\n /**\n * Arms, refreshes, or disables the account dead-man switch, optionally scoped by symbol ID and side. timeoutSec 0 disables it; 10–120 arms it. An armed switch returns its recorded `effectiveScope`. Generate a new requestId for each deliberate heartbeat, but reuse the same ID when retrying one ambiguous heartbeat.\n */\n async cancelAllAfter(\n input: CancelAllAfterInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllAfterResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(CancelAllAfterInputSchema, resolved);\n const response = await this.#writeClient.cancelAllAfter(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(CancelAllAfterResultSchema, response);\n }\n\n /**\n * Fetches one physical order and a bounded page of lineage executions through its generation.\n * Pass nextPageToken as pageToken with the same orderId to continue; deduplicate transfers by txId.\n * Set includeExecutionHistory to false for state-only polling, omitting limit and pageToken.\n * Execution pages are eventually consistent and need not reconcile with cumulative order quantities.\n * `executionsComplete` is true once the trades across every page add up to the filled quantity; while false, read again for the rest.\n * Returns null when the requested order is not found.\n */\n async getDetails(\n input: v.InferInput<typeof GetOrderDetailsInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderDetails | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetOrderDetailsInputSchema, resolved);\n let res: ProtoRead.GetOrderResponse;\n try {\n res = await this.#readClient.getOrder(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n } catch (error) {\n // Injected transports skip SDK error mapping, so load the detail decoder here.\n await loadErrorDetailDecoders(error);\n if (isOrderNotFoundError(error)) return null;\n throw error;\n }\n if (!res.order) return null;\n return parse(this.#orderDetailsSchema, res);\n }\n\n /**\n * Streams an account's orders over the private WebSocket until the returned unsubscribe\n * function is called. Each changed order arrives complete through `onEvent`; keep the\n * copy with the higher `version`, since equal versions are identical. Gaps, expired\n * tokens, and reconnects resume from the last applied position automatically.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n subscribe(input: SubscribeOrdersInput): () => void {\n idToBigInt(input.accountId, \"accountId\");\n const channel = `private:spot:orders:${input.accountId}`;\n const onError = input.onError;\n const known = (orders: ProtoRead.Order[]) =>\n orders.filter((o) => hasKnownOrderSymbol(this.#scales, o));\n // Order IDs in the live view, so a snapshot can report orders that left it while\n // their removal was not delivered (a resync after an expired cursor).\n const live = new Set<bigint>();\n return connectReadyGated<PrivateOrdersEvent>(\n {\n channel,\n ready: () => this.#scales.ready(),\n onPublication: (event) => {\n if (event.type === \"stale\") {\n input.onStale?.(\n event.stale,\n event.orderIds?.map((id) => formatId(id)),\n );\n return;\n }\n if (event.type === \"snapshot\") {\n const ids = new Set(event.orders.map((o) => o.orderId));\n const removed = [...live].filter((id) => !ids.has(id));\n live.clear();\n for (const id of ids) live.add(id);\n if (input.onSnapshot) {\n input.onSnapshot(\n known(event.orders).map((o) => formatOrder(this.#scales, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (removed.length > 0)\n input.onRemoved?.(removed.map((id) => formatId(id)));\n return;\n }\n const { unit } = event;\n for (const o of unit.orders) live.add(o.orderId);\n for (const id of unit.removedOrderIds) live.delete(id);\n deliverBatch(\n channel,\n known(unit.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (unit.removedOrderIds.length > 0) {\n input.onRemoved?.(unit.removedOrderIds.map((id) => formatId(id)));\n }\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError,\n },\n (handlers) =>\n this.#realtime.connectPrivateOrders({\n accountId: input.accountId,\n onEvent: handlers.onPublication,\n onConnected: handlers.onConnected,\n onDisconnected: handlers.onDisconnected,\n onError: handlers.onError,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyEA,SAAS,oBAAoB,QAAmB,OAAsC;CAClF,IAAI;EACA,OAAO,QAAQ,MAAM,QAAQ;EAC7B,OAAO;CACX,QAAQ;EACJ,OAAO;CACX;AACJ;AAEA,MAAM,wCAAwC;AAE9C,SAAS,qBAAqB,OAAyB;CACnD,MAAM,SAAS,iBAAiB,KAAK;CACrC,OACI,wBAAwB,KAAK,KAC5B,kBAAkB,kBACf,OAAO,QAAQ,YAAY,YAC3B,OAAO,OAAO,SAAS,eAC3B,mBAAmB,OAAO,EAAE,CAAC,CAAC,YAAY,MAAM;AAExD;AAyBA,SAAS,uBAAuB,WAAmB,WAAmB,UAAwB;CAC1F,IAAI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B,MAAM,YAAY,QAAQ,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;KACvD;IACJ;IACA,MAAM,EAAE,SAAS;IACjB,KAAK,MAAM,KAAK,KAAK,QAAQ,KAAK,IAAI,EAAE,OAAO;IAC/C,KAAK,MAAM,MAAM,KAAK,iBAAiB,KAAK,OAAO,EAAE;IACrD,aACI,SACA,MAAM,KAAK,MAAM,IAChB,MAAM,MAAM,QAAQ,YAAY,KAAKA,SAAS,CAAC,CAAC,GACjD,OACJ;IACA,IAAI,KAAK,gBAAgB,SAAS,GAC9B,MAAM,YAAY,KAAK,gBAAgB,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;GAExE;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC;EACJ,IACC,aACG,KAAKF,UAAU,qBAAqB;GAChC,WAAW,MAAM;GACjB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,gBAAgB,SAAS;GACzB,SAAS,SAAS;EACtB,CAAC,CACT;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"orders.js","names":["#readClient","ProtoRead.OrdersReadService","#writeClient","ProtoWrite.OrdersService","#realtime","#resolver","#scales","#orderDetailsSchema","#newOrderInputSchema","#modifyOrderInputSchema","#batchCreateOrdersInputSchema"],"sources":["../../../src/services/orders/orders.ts"],"sourcesContent":["import * as ProtoRead from \"../../gen/orders/v1/orders_read_pb.js\";\nimport * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type * 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 { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { connectReadyGated } from \"../../realtime/ready-gated-subscription.js\";\nimport type { PrivateOrdersEvent } from \"../../realtime/private-orders.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { formatId, idToBigInt } from \"../../utils/base58-id.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { loadErrorDetailDecoders } from \"../../shared/error-detail.js\";\nimport { PolyesterError } from \"../../shared/errors.js\";\nimport { createMutationRequestId } from \"../../shared/request-id.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport { formatConnectError, isResourceNotFoundError } from \"../../utils/errors.js\";\nimport {\n OpenOrdersInputSchema,\n OrderHistoryInputSchema,\n type NewOrderInput,\n createNewOrderInputSchema,\n CancelOrderInputSchema,\n CancelOrderResultSchema,\n type CancelOrderResult,\n CancelAllOrdersInputSchema,\n CancelAllOrdersResponseSchema,\n type CancelAllOrdersResponse,\n type Order,\n GetOrderDetailsInputSchema,\n createCreateOrderResultSchema,\n createPreviewOrderResultSchema,\n type PreviewOrderResult,\n type ModifyOrderInput,\n assertKnownModifyOrderInputKeys,\n createModifyOrderInputSchema,\n ModifyOrderResultSchema,\n type CreateOrderResult,\n type ModifyOrderResult,\n type OrderDetails,\n formatOrder,\n createOrderDetailsSchema,\n CancelAllAfterInputSchema,\n CancelAllAfterResultSchema,\n type CancelAllAfterInput,\n type CancelAllAfterResult,\n BatchCancelOrdersInputSchema,\n BatchCancelOrdersResultSchema,\n type BatchCancelOrdersInput,\n type BatchCancelOrdersResult,\n createBatchCreateOrdersResultSchema,\n type BatchCreateOrdersInput,\n type BatchCreateOrdersResult,\n BatchReplaceOrdersResultSchema,\n type BatchReplaceOrdersInput,\n type BatchReplaceOrdersResult,\n GetBatchReplaceStatusInputSchema,\n GetBatchReplaceStatusResultSchema,\n type GetBatchReplaceStatusInput,\n type GetBatchReplaceStatusResult,\n assertKnownBatchReplaceOrderItemInputKeys,\n createBatchCreateOrdersInputSchema,\n createBatchReplaceOrdersInputSchema,\n} from \"./orders.schemas.js\";\n\nfunction hasKnownOrderSymbol(scales: SdkScales, order: { symbolId: number }): boolean {\n try {\n scales.baseQty(order.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\nconst MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE = \"order not found\";\n\nfunction isOrderNotFoundError(error: unknown): boolean {\n const mapped = toPolyesterError(error);\n return (\n isResourceNotFoundError(error) ||\n (mapped instanceof PolyesterError &&\n mapped.detail?.service === \"orders\" &&\n mapped.detail.code === \"NOT_FOUND\") ||\n formatConnectError(error, \"\").toLowerCase() === MISCLASSIFIED_ORDER_NOT_FOUND_MESSAGE\n );\n}\n\nexport interface SubscribeOrdersInput extends BaseSubscribeInput<Order> {\n /** The account's base58 public ID, the root account's or a sub-account's. */\n accountId: string;\n /**\n * The account's full live view: open orders, orders not yet on the book, and\n * recently ended orders. Sent when the subscription starts and whenever the\n * server replaces its state; replace local order state with it. When omitted,\n * each snapshot order goes to `onEvent` instead.\n */\n onSnapshot?: (orders: Order[]) => void;\n /**\n * Orders that left the live view and remain only in history. Not cancellations.\n * Without `onSnapshot`, also the orders a resync snapshot no longer contains.\n */\n onRemoved?: (orderIds: string[]) => void;\n /**\n * `true` while the account's live view is behind; `false` once it caught up.\n * `orderIds`, when set, names the only orders whose rows show an earlier state;\n * the rest of the view is current. A later call replaces the earlier one.\n */\n onStale?: (stale: boolean, orderIds?: string[]) => void;\n /**\n * The stream reflects every order change acknowledged before it subscribed, including\n * every order read made before then. Wait for it before relying on the stream. Called\n * again after each resubscribe or reconnect.\n */\n onReady?: () => void;\n}\n\nfunction assertBatchResultCount(operation: string, requested: number, returned: number): void {\n if (requested !== returned) {\n throw new Error(\n `${operation} returned ${returned} results for ${requested} requested items.`,\n );\n }\n}\n\n/**\n * Manages account-scoped spot orders across read, write, and realtime order update surfaces.\n */\nexport class OrdersService {\n #readClient: Client<typeof ProtoRead.OrdersReadService>;\n #writeClient: Client<typeof ProtoWrite.OrdersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #orderDetailsSchema: ReturnType<typeof createOrderDetailsSchema>;\n #newOrderInputSchema: ReturnType<typeof createNewOrderInputSchema>;\n #modifyOrderInputSchema: ReturnType<typeof createModifyOrderInputSchema>;\n #batchCreateOrdersInputSchema: ReturnType<typeof createBatchCreateOrdersInputSchema>;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#readClient = createClient(ProtoRead.OrdersReadService, transports.authApi);\n this.#writeClient = createClient(ProtoWrite.OrdersService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#orderDetailsSchema = createOrderDetailsSchema(scales);\n this.#newOrderInputSchema = createNewOrderInputSchema(scales);\n this.#modifyOrderInputSchema = createModifyOrderInputSchema(scales);\n this.#batchCreateOrdersInputSchema = createBatchCreateOrdersInputSchema(scales);\n }\n\n /**\n * Returns open orders for the resolved root account or subaccount, with optional symbol IDs, trigger ID, side, pagination, and attached-risk inclusion filters. Results are paginated with a server-determined page size: a single call is not the full set of open orders — keep calling with the returned nextPageToken until it is empty.\n */\n async listOpen(\n input: v.InferInput<typeof OpenOrdersInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OpenOrdersInputSchema, resolved);\n const res = await this.#readClient.getOpenOrders(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Returns historical orders for the resolved account scope, supporting symbol IDs, trigger ID, side, status, time range, pagination, and attached-risk filters. A page may hold fewer orders than requested, or none: keep calling with the returned nextPageToken until it is empty.\n */\n async listHistory(\n input: v.InferInput<typeof OrderHistoryInputSchema> = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ orders: Order[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(OrderHistoryInputSchema, resolved);\n const res = await this.#readClient.getOrderHistory(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n orders: res.orders\n .filter((order) => hasKnownOrderSymbol(this.#scales, order))\n .map((order) => formatOrder(this.#scales, order)),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Evaluates one complete order intent against current market, policy, risk, and balance state without creating an order, reserving funds, or claiming its client order ID.\n */\n async preview(\n input: NewOrderInput,\n options?: PolyesterRequestOptions,\n ): Promise<PreviewOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(this.#newOrderInputSchema, resolved);\n const response = await this.#writeClient.previewOrder(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(\n createPreviewOrderResultSchema(this.#scales, request.order.symbolId),\n response,\n );\n }\n\n /**\n * Places a spot order with an explicit market-IOC, limit-GTC, limit-GTD, limit-IOC, or limit-FOK execution policy and optional attached risk controls. Size it by `qty`, a BUY IOC by `maxQuoteDebit`, or a SELL IOC by `quoteProceeds`, the quote it stops at before fees. A GTC or GTD limit can show only `execution.displayQty` at a time (iceberg), and `peg` takes a limit price from the best bid or ask at entry, capped or floored by `execution.price`. clientOrderId is an account-scoped correlation, lookup, and cancellation identifier. Reuse while retained returns CONFLICT_DUPLICATE_CLIENT_ORDER_ID, including after rejection or completion; it does not replay the earlier result. After an ambiguous timeout, reconcile through get using clientOrderId; an immediate lookup miss does not prove admission failed. Without clientOrderId, the outcome may remain unknown.\n */\n async create(\n input: NewOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateOrderResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#newOrderInputSchema, resolved);\n const requestPayload = removeUndefined(validatedInput);\n const res = await this.#writeClient.createOrder(\n requestPayload,\n toConnectCallOptions(options),\n );\n return parse(\n createCreateOrderResultSchema(this.#scales, validatedInput.order.symbolId),\n res,\n );\n }\n\n /**\n * Places 1–20 spot orders in one best-effort request. Results preserve item order and report admission as accepted or rejected; accepted orders still require lifecycle reconciliation. requestId is the idempotency boundary for the ordered batch and is generated when omitted; supply and reuse it when an ambiguous batch may be retried. Reusing the account-scoped requestId with the same payload within 15 minutes returns each decided item's original result and result time and retries items still unresolved, never admitting an item twice; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. After 15 minutes the ID is free and a repeat can place its orders again, so read the items back instead of repeating an older batch. Per-item clientOrderId values are optional correlation identifiers and must be unique when supplied.\n */\n async batchCreate(\n input: BatchCreateOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCreateOrdersResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(this.#batchCreateOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCreateOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(\n createBatchCreateOrdersResultSchema(\n this.#scales,\n request.items.map((item) => item.symbolId),\n ),\n response,\n );\n assertBatchResultCount(\"batchCreate\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Requests cancellation of one order in the resolved account scope by order id or client order id, with optional symbol routing. The response acknowledges the cancellation request, not the order's final lifecycle state; reconcile through order reads or realtime before releasing local state. A missing target remains a {@link ResourceNotFoundError}; callers performing desired-state cleanup may treat that error as success when the order could already have filled or left the book.\n */\n async cancel(\n input: v.InferInput<typeof CancelOrderInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelOrderResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n\n const validated = parse(CancelOrderInputSchema, resolved);\n\n const res = await this.#writeClient.cancelOrder(\n {\n key: validated.key,\n symbolId: validated.symbolId,\n subaccountId: validated.subaccountId,\n },\n toConnectCallOptions(options),\n );\n return parse(CancelOrderResultSchema, res);\n }\n\n /**\n * Cancels 1–50 explicit orders in one best-effort request. Results preserve item order and acknowledge cancellation admission rather than final order state. Supply a stable requestId when an ambiguous batch may be retried.\n */\n async batchCancel(\n input: BatchCancelOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchCancelOrdersResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(BatchCancelOrdersInputSchema, resolved);\n const response = await this.#writeClient.batchCancelOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchCancelOrdersResultSchema, response);\n assertBatchResultCount(\"batchCancel\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Applies a price, quantity, client id, or attached-risk patch to one open order. The symbol ID routes policy checks and quantity scaling. A requestId is generated when omitted; provide a stable value when retrying the same logical modification.\n */\n async modify(\n input: ModifyOrderInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyOrderResult> {\n await this.#scales.ready();\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n assertKnownModifyOrderInputKeys(resolved);\n const validated = parse(this.#modifyOrderInputSchema, resolved);\n const res = await this.#writeClient.modifyOrder(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ModifyOrderResultSchema, res);\n }\n\n /**\n * Replaces 1–50 same-symbol orders and returns an index-stable durable admission receipt. Reuse requestId only when retrying the same logical batch; use the returned batchRequestId for later status reads. An AMENDED actionTaken is cancel-only with no successor; keep tracking oldOrderId until its terminal state is confirmed.\n *\n * An item refused for its value (a price off the pair's tick size, or an invalid attached-risk price, distance or slippage) is rejected alone in `results`, with its `code` and an `error` whose violations name `items[i]`; the other items are processed. Resend only the corrected rejected items under a fresh `requestId`. A malformed batch still throws as a whole.\n *\n * The receipt answers admission, before each admitted item's change completes. Until then, the next change of the same order is rejected with the retryable item `code` `ORDER_MODIFY_IN_PROGRESS`, or `ORDER_PLACEMENT_PENDING` when it names the returned `replacementOrderId`. Resend only those items, in a new batch under a fresh `requestId`, after a short jittered backoff (for example 50 ms doubling to 1 s). The rejected batch's `requestId` replays its rejection, admitted items must never be resent, and a batch whose outcome you did not receive is reconciled under its own `requestId`, never resent under a new one.\n */\n async batchReplace(\n input: BatchReplaceOrdersInput,\n options?: PolyesterMutationOptions,\n ): Promise<BatchReplaceOrdersResult> {\n await this.#scales.ready();\n for (const item of input.items) {\n assertKnownBatchReplaceOrderItemInputKeys(item);\n }\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(createBatchReplaceOrdersInputSchema(this.#scales), resolved);\n const response = await this.#writeClient.batchReplaceOrders(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n const result = parse(BatchReplaceOrdersResultSchema, response);\n assertBatchResultCount(\"batchReplace\", input.items.length, result.results.length);\n return result;\n }\n\n /**\n * Reads the admission and each item's current execution phase for an accepted batch\n * replacement. Status is retained for 60 seconds from acceptance and is readable as soon as\n * `batchReplace` returns. A `ServiceUnavailableError` means the status is not established\n * yet: retry the same request within the window. A `ResourceNotFoundError` means no batch is\n * retained under this ID (none was accepted, or the window ended), never that the replacement\n * was rejected: reconcile the individual orders and never resubmit an accepted batch. An\n * item's `updatedTsNs` can be a later recovery time, so do not use it to identify a refusal.\n * For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is\n * undefined.\n */\n async getBatchReplaceStatus(\n input: GetBatchReplaceStatusInput,\n options?: PolyesterRequestOptions,\n ): Promise<GetBatchReplaceStatusResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const request = parse(GetBatchReplaceStatusInputSchema, resolved);\n const response = await this.#readClient.getBatchReplaceStatus(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetBatchReplaceStatusResultSchema, response);\n }\n\n /**\n * Cancels all matching open orders for the resolved account scope, optionally narrowed by up to 100 symbol IDs and side, with dry-run preview. A requestId is generated when omitted; reuse it with the same criteria for retries. Completed results are retained for at least two minutes; use a fresh key for each new cancellation.\n * `canceledOrders` lists up to 200 of the orders whose cancellation was requested, oldest first; `truncated` is true when `totalCanceled` counts more. Read each order's final state from `orders.subscribe` or the order reads.\n * A retry with the same requestId and criteria returns the original counts with `listingStatus: \"not_retained_read_open_orders\"` and an empty `canceledOrders`, which does not mean nothing was canceled; read open orders instead.\n */\n async cancelAll(\n input: v.InferInput<typeof CancelAllOrdersInputSchema>,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllOrdersResponse> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const validated = parse(CancelAllOrdersInputSchema, resolved);\n const res = await this.#writeClient.cancelAllOrders(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelAllOrdersResponseSchema, res);\n }\n\n /**\n * Arms, refreshes, or disables the account dead-man switch, optionally scoped by symbol ID and side. timeoutSec 0 disables it; 10–120 arms it. An armed switch returns its recorded `effectiveScope`. Generate a new requestId for each deliberate heartbeat, but reuse the same ID when retrying one ambiguous heartbeat.\n */\n async cancelAllAfter(\n input: CancelAllAfterInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelAllAfterResult> {\n const resolved = {\n ...resolveAccountScopedInput(input, this.#resolver),\n requestId: input.requestId ?? createMutationRequestId(),\n };\n const request = parse(CancelAllAfterInputSchema, resolved);\n const response = await this.#writeClient.cancelAllAfter(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(CancelAllAfterResultSchema, response);\n }\n\n /**\n * Fetches one physical order and a bounded page of lineage executions through its generation.\n * Pass nextPageToken as pageToken with the same orderId to continue; deduplicate transfers by txId.\n * Set includeExecutionHistory to false for state-only polling, omitting limit and pageToken.\n * Execution pages are eventually consistent and need not reconcile with cumulative order quantities.\n * `executionsComplete` is true once the trades across every page add up to the filled quantity; while false, read again for the rest.\n * Returns null when the requested order is not found.\n */\n async getDetails(\n input: v.InferInput<typeof GetOrderDetailsInputSchema>,\n options?: PolyesterRequestOptions,\n ): Promise<OrderDetails | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetOrderDetailsInputSchema, resolved);\n let res: ProtoRead.GetOrderResponse;\n try {\n res = await this.#readClient.getOrder(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n } catch (error) {\n // Injected transports skip SDK error mapping, so load the detail decoder here.\n await loadErrorDetailDecoders(error);\n if (isOrderNotFoundError(error)) return null;\n throw error;\n }\n if (!res.order) return null;\n return parse(this.#orderDetailsSchema, res);\n }\n\n /**\n * Streams an account's orders over the private WebSocket until the returned unsubscribe\n * function is called. Each changed order arrives complete through `onEvent`; keep the\n * copy with the higher `version`, since equal versions are identical. Gaps, expired\n * tokens, and reconnects resume from the last applied position automatically.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n subscribe(input: SubscribeOrdersInput): () => void {\n idToBigInt(input.accountId, \"accountId\");\n const channel = `private:spot:orders:${input.accountId}`;\n const onError = input.onError;\n const known = (orders: ProtoRead.Order[]) =>\n orders.filter((o) => hasKnownOrderSymbol(this.#scales, o));\n // Order IDs in the live view, so a snapshot can report orders that left it while\n // their removal was not delivered (a resync after an expired cursor).\n const live = new Set<bigint>();\n return connectReadyGated<PrivateOrdersEvent>(\n {\n channel,\n ready: () => this.#scales.ready(),\n onPublication: (event) => {\n if (event.type === \"ready\") {\n input.onReady?.();\n return;\n }\n if (event.type === \"stale\") {\n input.onStale?.(\n event.stale,\n event.orderIds?.map((id) => formatId(id)),\n );\n return;\n }\n if (event.type === \"snapshot\") {\n const ids = new Set(event.orders.map((o) => o.orderId));\n const removed = [...live].filter((id) => !ids.has(id));\n live.clear();\n for (const id of ids) live.add(id);\n if (input.onSnapshot) {\n input.onSnapshot(\n known(event.orders).map((o) => formatOrder(this.#scales, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (removed.length > 0)\n input.onRemoved?.(removed.map((id) => formatId(id)));\n return;\n }\n const { unit } = event;\n for (const o of unit.orders) live.add(o.orderId);\n for (const id of unit.removedOrderIds) live.delete(id);\n deliverBatch(\n channel,\n known(unit.orders),\n (o) => input.onEvent(formatOrder(this.#scales, o)),\n onError,\n );\n if (unit.removedOrderIds.length > 0) {\n input.onRemoved?.(unit.removedOrderIds.map((id) => formatId(id)));\n }\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError,\n },\n (handlers) =>\n this.#realtime.connectPrivateOrders({\n accountId: input.accountId,\n onEvent: handlers.onPublication,\n onConnected: handlers.onConnected,\n onDisconnected: handlers.onDisconnected,\n onError: handlers.onError,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyEA,SAAS,oBAAoB,QAAmB,OAAsC;CAClF,IAAI;EACA,OAAO,QAAQ,MAAM,QAAQ;EAC7B,OAAO;CACX,QAAQ;EACJ,OAAO;CACX;AACJ;AAEA,MAAM,wCAAwC;AAE9C,SAAS,qBAAqB,OAAyB;CACnD,MAAM,SAAS,iBAAiB,KAAK;CACrC,OACI,wBAAwB,KAAK,KAC5B,kBAAkB,kBACf,OAAO,QAAQ,YAAY,YAC3B,OAAO,OAAO,SAAS,eAC3B,mBAAmB,OAAO,EAAE,CAAC,CAAC,YAAY,MAAM;AAExD;AA+BA,SAAS,uBAAuB,WAAmB,WAAmB,UAAwB;CAC1F,IAAI,cAAc,UACd,MAAM,IAAI,MACN,GAAG,UAAU,YAAY,SAAS,eAAe,UAAU,kBAC/D;AAER;;;;AAKA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CACA;CAC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AM,EAAE,SAAS;IACjB,KAAK,MAAM,KAAK,KAAK,QAAQ,KAAK,IAAI,EAAE,OAAO;IAC/C,KAAK,MAAM,MAAM,KAAK,iBAAiB,KAAK,OAAO,EAAE;IACrD,aACI,SACA,MAAM,KAAK,MAAM,IAChB,MAAM,MAAM,QAAQ,YAAY,KAAKA,SAAS,CAAC,CAAC,GACjD,OACJ;IACA,IAAI,KAAK,gBAAgB,SAAS,GAC9B,MAAM,YAAY,KAAK,gBAAgB,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC;GAExE;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC;EACJ,IACC,aACG,KAAKF,UAAU,qBAAqB;GAChC,WAAW,MAAM;GACjB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,gBAAgB,SAAS;GACzB,SAAS,SAAS;EACtB,CAAC,CACT;CACJ;AACJ"}
|
|
@@ -37,7 +37,7 @@ declare const ListPriceAlertsInputSchema: v.SchemaWithPipe<readonly [v.StrictObj
|
|
|
37
37
|
/** Previous `nextPageToken`; reuse only with the same filters. */
|
|
38
38
|
readonly pageToken: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction]>, undefined>;
|
|
39
39
|
}, undefined>, v.TransformAction<{
|
|
40
|
-
statuses?: ("active" | "
|
|
40
|
+
statuses?: ("active" | "triggered" | "canceled")[] | undefined;
|
|
41
41
|
symbolId?: number | undefined;
|
|
42
42
|
limit?: number | undefined;
|
|
43
43
|
pageToken?: string | undefined;
|
|
@@ -92,7 +92,7 @@ declare const PriceAlertSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
|
92
92
|
readonly priceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
93
93
|
readonly referencePriceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
94
94
|
readonly armed: v.BooleanSchema<undefined>;
|
|
95
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "
|
|
95
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "triggered" | "canceled">]>;
|
|
96
96
|
readonly channels: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "in_app" | "telegram">]>, undefined>;
|
|
97
97
|
readonly revision: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
98
98
|
readonly createdAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -125,7 +125,7 @@ declare const PriceAlertSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
|
125
125
|
priceTicks: string;
|
|
126
126
|
referencePriceTicks: string;
|
|
127
127
|
armed: boolean;
|
|
128
|
-
status: "unspecified" | "active" | "
|
|
128
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
129
129
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
130
130
|
revision: string;
|
|
131
131
|
createdAt?: number | undefined;
|
|
@@ -143,7 +143,7 @@ declare const PriceAlertSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
|
143
143
|
referencePrice: string;
|
|
144
144
|
/** False while an alert created past its price waits for the price to move back first. */
|
|
145
145
|
armed: boolean;
|
|
146
|
-
status: "unspecified" | "active" | "
|
|
146
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
147
147
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
148
148
|
/** Pass as `expectedRevision` to `update`. */
|
|
149
149
|
revision: string;
|
|
@@ -164,7 +164,7 @@ declare const ListPriceAlertsResultSchema: v.ObjectSchema<{
|
|
|
164
164
|
readonly priceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
165
165
|
readonly referencePriceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
166
166
|
readonly armed: v.BooleanSchema<undefined>;
|
|
167
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "
|
|
167
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "triggered" | "canceled">]>;
|
|
168
168
|
readonly channels: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "in_app" | "telegram">]>, undefined>;
|
|
169
169
|
readonly revision: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
170
170
|
readonly createdAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -197,7 +197,7 @@ declare const ListPriceAlertsResultSchema: v.ObjectSchema<{
|
|
|
197
197
|
priceTicks: string;
|
|
198
198
|
referencePriceTicks: string;
|
|
199
199
|
armed: boolean;
|
|
200
|
-
status: "unspecified" | "active" | "
|
|
200
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
201
201
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
202
202
|
revision: string;
|
|
203
203
|
createdAt?: number | undefined;
|
|
@@ -215,7 +215,7 @@ declare const ListPriceAlertsResultSchema: v.ObjectSchema<{
|
|
|
215
215
|
referencePrice: string;
|
|
216
216
|
/** False while an alert created past its price waits for the price to move back first. */
|
|
217
217
|
armed: boolean;
|
|
218
|
-
status: "unspecified" | "active" | "
|
|
218
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
219
219
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
220
220
|
/** Pass as `expectedRevision` to `update`. */
|
|
221
221
|
revision: string;
|
|
@@ -239,7 +239,7 @@ declare const UpdatePriceAlertResultSchema: v.ObjectSchema<{
|
|
|
239
239
|
readonly priceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
240
240
|
readonly referencePriceTicks: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
241
241
|
readonly armed: v.BooleanSchema<undefined>;
|
|
242
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "
|
|
242
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "active" | "triggered" | "canceled">]>;
|
|
243
243
|
readonly channels: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "in_app" | "telegram">]>, undefined>;
|
|
244
244
|
readonly revision: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
245
245
|
readonly createdAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -272,7 +272,7 @@ declare const UpdatePriceAlertResultSchema: v.ObjectSchema<{
|
|
|
272
272
|
priceTicks: string;
|
|
273
273
|
referencePriceTicks: string;
|
|
274
274
|
armed: boolean;
|
|
275
|
-
status: "unspecified" | "active" | "
|
|
275
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
276
276
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
277
277
|
revision: string;
|
|
278
278
|
createdAt?: number | undefined;
|
|
@@ -290,7 +290,7 @@ declare const UpdatePriceAlertResultSchema: v.ObjectSchema<{
|
|
|
290
290
|
referencePrice: string;
|
|
291
291
|
/** False while an alert created past its price waits for the price to move back first. */
|
|
292
292
|
armed: boolean;
|
|
293
|
-
status: "unspecified" | "active" | "
|
|
293
|
+
status: "unspecified" | "active" | "triggered" | "canceled";
|
|
294
294
|
channels: ("unspecified" | "in_app" | "telegram")[];
|
|
295
295
|
/** Pass as `expectedRevision` to `update`. */
|
|
296
296
|
revision: string;
|
|
@@ -29,7 +29,7 @@ declare const RewardAwardSchema: v.ObjectSchema<{
|
|
|
29
29
|
readonly assetId: v.NumberSchema<undefined>;
|
|
30
30
|
readonly amountBaseUnits: v.StringSchema<undefined>;
|
|
31
31
|
readonly fulfillmentMethod: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "external_testnet" | "internal_trading">]>;
|
|
32
|
-
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
32
|
+
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "awaiting_destination" | "ready_for_payout" | "paid">]>;
|
|
33
33
|
readonly publishedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
34
34
|
readonly seconds: v.BigintSchema<undefined>;
|
|
35
35
|
readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
|
|
@@ -67,7 +67,7 @@ declare const ListRewardAwardsResultSchema: v.ObjectSchema<{
|
|
|
67
67
|
readonly assetId: v.NumberSchema<undefined>;
|
|
68
68
|
readonly amountBaseUnits: v.StringSchema<undefined>;
|
|
69
69
|
readonly fulfillmentMethod: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "external_testnet" | "internal_trading">]>;
|
|
70
|
-
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
70
|
+
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "awaiting_destination" | "ready_for_payout" | "paid">]>;
|
|
71
71
|
readonly publishedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
72
72
|
readonly seconds: v.BigintSchema<undefined>;
|
|
73
73
|
readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
|
|
@@ -114,7 +114,7 @@ declare const SetRewardDestinationResultSchema: v.ObjectSchema<{
|
|
|
114
114
|
readonly assetId: v.NumberSchema<undefined>;
|
|
115
115
|
readonly amountBaseUnits: v.StringSchema<undefined>;
|
|
116
116
|
readonly fulfillmentMethod: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "external_testnet" | "internal_trading">]>;
|
|
117
|
-
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
117
|
+
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "awaiting_destination" | "ready_for_payout" | "paid">]>;
|
|
118
118
|
readonly publishedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
119
119
|
readonly seconds: v.BigintSchema<undefined>;
|
|
120
120
|
readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
|
|
@@ -153,7 +153,7 @@ declare const AcknowledgeRewardAwardResultSchema: v.ObjectSchema<{
|
|
|
153
153
|
readonly assetId: v.NumberSchema<undefined>;
|
|
154
154
|
readonly amountBaseUnits: v.StringSchema<undefined>;
|
|
155
155
|
readonly fulfillmentMethod: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "external_testnet" | "internal_trading">]>;
|
|
156
|
-
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
156
|
+
readonly fulfillmentState: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "awaiting_destination" | "ready_for_payout" | "paid">]>;
|
|
157
157
|
readonly publishedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
|
|
158
158
|
readonly seconds: v.BigintSchema<undefined>;
|
|
159
159
|
readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
|