@polyester/sdk 0.33.0 → 0.34.0-devnet-20261105175240
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 +10 -0
- package/dist/services/changelog/changelog.schemas.d.ts +17 -17
- package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
- package/dist/services/orders/orders-input.schemas.d.ts +2 -2
- package/dist/services/orders/orders-input.schemas.js +2 -2
- package/dist/services/orders/orders-input.schemas.js.map +1 -1
- package/dist/services/orders/orders.d.ts +2 -2
- package/dist/services/orders/orders.js +2 -2
- package/dist/services/orders/orders.js.map +1 -1
- package/dist/services/social-verification/social-verification.codecs.js +2 -2
- package/dist/services/social-verification/social-verification.codecs.js.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.d.ts +2 -2
- package/dist/services/subaccounts/subaccounts.codecs.js +1 -1
- package/dist/services/subaccounts/subaccounts.codecs.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
- package/dist/services/subaccounts/subaccounts.schemas.js +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +15 -15
- package/dist/services/triggers/triggers.codecs.js +3 -3
- package/dist/services/triggers/triggers.codecs.js.map +1 -1
- package/dist/shared/connect-error-mapping.d.ts +1 -1
- package/dist/shared/connect-error-mapping.js +1 -1
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/request-options.d.ts +1 -1
- package/dist/shared/request-options.js.map +1 -1
- package/dist/shared/validation.js +22 -1
- package/dist/shared/validation.js.map +1 -1
- package/dist/smart-account/smart-account.js.map +1 -1
- package/package.json +1 -1
|
@@ -10,7 +10,7 @@ declare const GetOrderbookInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema
|
|
|
10
10
|
depth: number;
|
|
11
11
|
}, {
|
|
12
12
|
symbolId: number;
|
|
13
|
-
depth: 1 | 5 | 10 | 20 | 100 | 500 | 1000 |
|
|
13
|
+
depth: 1 | 5 | 10 | 20 | 100 | 500 | 1000 | 50 | 200;
|
|
14
14
|
protoDepth: Depth;
|
|
15
15
|
}>]>;
|
|
16
16
|
type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
|
|
@@ -3754,7 +3754,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3754
3754
|
readonly admissionStatus: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "rejected" | "admitted" | "partially_admitted">]>;
|
|
3755
3755
|
readonly items: v.ArraySchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
3756
3756
|
readonly itemIndex: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
|
|
3757
|
-
readonly phase: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
3757
|
+
readonly phase: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "terminal" | "working" | "rejected" | "admitted">]>;
|
|
3758
3758
|
readonly oldOrderId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.BigintSchema<undefined>, undefined>, v.TransformAction<bigint | undefined, string | undefined>]>;
|
|
3759
3759
|
readonly replacementOrderId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.BigintSchema<undefined>, undefined>, v.TransformAction<bigint | undefined, string | undefined>]>;
|
|
3760
3760
|
readonly actionTaken: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "AMENDED" | "REPLACED">]>;
|
|
@@ -3763,7 +3763,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3763
3763
|
readonly updatedTsNs: v.BigintSchema<undefined>;
|
|
3764
3764
|
}, undefined>, v.TransformAction<{
|
|
3765
3765
|
itemIndex: number;
|
|
3766
|
-
phase: "unspecified" | "
|
|
3766
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3767
3767
|
oldOrderId?: string | undefined;
|
|
3768
3768
|
replacementOrderId?: string | undefined;
|
|
3769
3769
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -3775,7 +3775,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3775
3775
|
updatedTs: number;
|
|
3776
3776
|
updatedTsNs: string;
|
|
3777
3777
|
itemIndex: number;
|
|
3778
|
-
phase: "unspecified" | "
|
|
3778
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3779
3779
|
oldOrderId?: string | undefined;
|
|
3780
3780
|
replacementOrderId?: string | undefined;
|
|
3781
3781
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -3793,7 +3793,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3793
3793
|
updatedTs: number;
|
|
3794
3794
|
updatedTsNs: string;
|
|
3795
3795
|
itemIndex: number;
|
|
3796
|
-
phase: "unspecified" | "
|
|
3796
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3797
3797
|
oldOrderId?: string | undefined;
|
|
3798
3798
|
replacementOrderId?: string | undefined;
|
|
3799
3799
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -3811,7 +3811,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3811
3811
|
updatedTs: number;
|
|
3812
3812
|
updatedTsNs: string;
|
|
3813
3813
|
itemIndex: number;
|
|
3814
|
-
phase: "unspecified" | "
|
|
3814
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3815
3815
|
oldOrderId?: string | undefined;
|
|
3816
3816
|
replacementOrderId?: string | undefined;
|
|
3817
3817
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -3829,7 +3829,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3829
3829
|
updatedTs: number;
|
|
3830
3830
|
updatedTsNs: string;
|
|
3831
3831
|
itemIndex: number;
|
|
3832
|
-
phase: "unspecified" | "
|
|
3832
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3833
3833
|
oldOrderId?: string | undefined;
|
|
3834
3834
|
replacementOrderId?: string | undefined;
|
|
3835
3835
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -3851,7 +3851,7 @@ declare const GetBatchReplaceStatusResultSchema: v.SchemaWithPipe<readonly [v.Ob
|
|
|
3851
3851
|
updatedTs: number;
|
|
3852
3852
|
updatedTsNs: string;
|
|
3853
3853
|
itemIndex: number;
|
|
3854
|
-
phase: "unspecified" | "
|
|
3854
|
+
phase: "unspecified" | "terminal" | "working" | "rejected" | "admitted";
|
|
3855
3855
|
oldOrderId?: string | undefined;
|
|
3856
3856
|
replacementOrderId?: string | undefined;
|
|
3857
3857
|
actionTaken: "unspecified" | "AMENDED" | "REPLACED";
|
|
@@ -4634,11 +4634,11 @@ declare const CancelAllOrdersResponseSchema: v.SchemaWithPipe<readonly [v.Object
|
|
|
4634
4634
|
submittedCancels: number;
|
|
4635
4635
|
failedCancels: number;
|
|
4636
4636
|
ts: number;
|
|
4637
|
-
|
|
4637
|
+
canceledOrders: {
|
|
4638
4638
|
orderId: string;
|
|
4639
4639
|
clientOrderId: string;
|
|
4640
4640
|
}[];
|
|
4641
|
-
|
|
4641
|
+
totalCanceled: number;
|
|
4642
4642
|
truncated: boolean;
|
|
4643
4643
|
listingStatus: "unspecified" | "included" | "not_retained_read_open_orders";
|
|
4644
4644
|
}>]>;
|
|
@@ -241,8 +241,8 @@ const CancelAllOrdersResponseSchema = v.pipe(v.object({
|
|
|
241
241
|
submittedCancels: o.submittedCancels,
|
|
242
242
|
failedCancels: o.failedCancels,
|
|
243
243
|
ts: tsNsToMs(o.tsNs),
|
|
244
|
-
|
|
245
|
-
|
|
244
|
+
canceledOrders: o.cancelledOrders,
|
|
245
|
+
totalCanceled: o.totalCancelled,
|
|
246
246
|
truncated: o.truncated,
|
|
247
247
|
listingStatus: o.listingStatus
|
|
248
248
|
})));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders-input.schemas.js","names":["ProtoWrite.MarketIocSchema","ProtoWrite.LimitGtcSchema","ProtoWrite.LimitGtdSchema","ProtoWrite.LimitIocSchema","ProtoWrite.LimitFokSchema"],"sources":["../../../src/services/orders/orders-input.schemas.ts"],"sourcesContent":["import * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { create } from \"@bufbuild/protobuf\";\nimport * as v from \"valibot\";\nimport { SideSchema, SymbolIdInputSchema } from \"../shared.js\";\nimport { tsNsToMs } from \"../../utils/time.js\";\nimport { msToTimestamp } from \"../../utils/timestamp.js\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n OptionalPublicIdSchema,\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampMsSchema,\n optionalIdInputSchema,\n optionalUint64DecimalFilterSchema,\n} from \"../../shared/schemas.js\";\nimport {\n positiveDecimalInputToScaled,\n scaledToDecimalOutput,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport {\n FEE_ASSET_VALUES,\n ORDER_STATUS_FILTER_VALUES,\n OrderSideCodec,\n OrderStatusFilterCodec,\n SELF_TRADE_PREVENTION_MODE_VALUES,\n FeeAssetCodec,\n SelfTradePreventionModeCodec,\n CancelAllOrdersStatusCodec,\n CancelAllListingStatusCodec,\n CancelOrderStatusCodec,\n} from \"./orders.codecs.js\";\nimport {\n MarketMaxSlippageSchema,\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n attachedTrailingLimitMatchesSide,\n createRiskPolicyInputSchema,\n parseMarketMaxSlippage,\n} from \"./orders-risk.schemas.js\";\nimport {\n ClientOrderIdInputSchema,\n OptionalClientOrderIdInputSchema,\n OrderIdInputSchema,\n OrderRequestIdInputSchema,\n} from \"./orders-identifiers.schemas.js\";\nimport { OrderErrorDetailSchema } from \"./order-errors.schemas.js\";\nimport { MAX_SELLING_SLIPPAGE_BPS } from \"../trailing-oneof-inputs.js\";\n\nconst OrderStatusSchema = v.picklist(ORDER_STATUS_FILTER_VALUES);\nconst FeeAssetSchema = v.picklist(FEE_ASSET_VALUES);\nconst SelfTradePreventionModeSchema = v.picklist(SELF_TRADE_PREVENTION_MODE_VALUES);\n\nconst BaseOrdersFilterInputEntries = {\n ...AccountScopeInputEntries,\n symbolId: v.optional(v.array(SymbolIdInputSchema)),\n triggerId: optionalIdInputSchema(\"triggerId\"),\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? OrderSideCodec.inputToProto[v] : undefined)),\n ),\n limit: v.optional(v.number()),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n};\n\nexport const BaseOrdersFilterInputSchema = v.pipe(\n v.strictObject(BaseOrdersFilterInputEntries),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport const OpenOrdersInputSchema = v.pipe(\n v.strictObject({\n ...BaseOrdersFilterInputEntries,\n\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), false),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type OpenOrdersInput = v.InferInput<typeof OpenOrdersInputSchema>;\n\nexport const OrderHistoryInputSchema = v.pipe(\n v.strictObject({\n ...BaseOrdersFilterInputEntries,\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), false),\n status: v.pipe(\n v.optional(OrderStatusSchema),\n v.transform((v) => (v ? OrderStatusFilterCodec.inputToProto[v] : undefined)),\n ),\n startTsNs: optionalUint64DecimalFilterSchema(\"startTsNs\"),\n endTsNs: optionalUint64DecimalFilterSchema(\"endTsNs\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type OrderHistoryInput = v.InferInput<typeof OrderHistoryInputSchema>;\n\nconst DecimalInputStringSchema = v.pipe(v.string(), v.trim(), v.minLength(1));\n\n/**\n * The wire contract stores GTD expiries as signed Unix nanoseconds. The public\n * `execution.expireAt` surface is integer epoch milliseconds, so these are the\n * inclusive millisecond values that remain representable by that contract.\n * The 1s..30d lead-time window is enforced server-side; checking it here\n * against the client clock would only add skew-dependent false rejections.\n */\nconst GTD_EXPIRE_AT_MIN_MS = -9_223_372_036_854;\nconst GTD_EXPIRE_AT_MAX_MS = 9_223_372_036_854;\n\nconst GtdExpireAtSchema = v.pipe(\n v.number(),\n v.integer(),\n v.minValue(GTD_EXPIRE_AT_MIN_MS),\n v.maxValue(GTD_EXPIRE_AT_MAX_MS),\n);\n\nfunction createOrderIntentBaseEntries(scales: SdkScales) {\n return {\n symbolId: SymbolIdInputSchema,\n side: v.pipe(\n SideSchema,\n v.transform((v) => OrderSideCodec.inputToProto[v]),\n ),\n execution: createOrderExecutionInputSchema(scales),\n clientOrderId: OptionalClientOrderIdInputSchema,\n feeAsset: v.pipe(\n v.optional(FeeAssetSchema),\n v.transform((v) => (v ? FeeAssetCodec.inputToProto[v] : undefined)),\n ),\n selfTradePreventionMode: v.pipe(\n v.optional(SelfTradePreventionModeSchema),\n v.transform((v) => (v ? SelfTradePreventionModeCodec.inputToProto[v] : undefined)),\n ),\n risk: createRiskPolicyInputSchema(scales),\n };\n}\n\ntype ParsedOrderIntentInput = v.InferOutput<ReturnType<typeof createOrderIntentInputObjectSchema>>;\n\ntype SellingSlippageInput = {\n side: ProtoWrite.Side;\n execution: v.InferOutput<ReturnType<typeof createOrderExecutionInputSchema>>;\n};\n\nconst SELLING_SLIPPAGE_MESSAGE = `maxSlippageBps must be between 1 and ${MAX_SELLING_SLIPPAGE_BPS} for a market order that sells`;\n\n/** Checks the bps cap of a market sell; attached trailing stops are capped when parsed. */\nfunction sellingSlippageWithinCap(input: SellingSlippageInput): boolean {\n const slippage =\n input.side === ProtoWrite.Side.SELL && input.execution.case === \"marketIoc\"\n ? input.execution.value.maxSlippage\n : undefined;\n return slippage?.case !== \"maxSlippageBps\" || slippage.value <= MAX_SELLING_SLIPPAGE_BPS;\n}\n\nfunction createOrderIntentInputObjectSchema(scales: SdkScales) {\n const baseEntries = createOrderIntentBaseEntries(scales);\n return v.pipe(\n v.union([\n v.strictObject({\n ...baseEntries,\n qty: DecimalInputStringSchema,\n maxQuoteDebit: v.optional(v.never()),\n }),\n v.strictObject({\n ...baseEntries,\n qty: v.optional(v.never()),\n maxQuoteDebit: DecimalInputStringSchema,\n }),\n ]),\n v.check(\n (input) =>\n input.maxQuoteDebit === undefined ||\n (input.side === ProtoWrite.Side.BUY &&\n (input.execution.case === \"marketIoc\" || input.execution.case === \"limitIoc\")),\n \"maxQuoteDebit is supported only for BUY market IOC and BUY limit IOC orders\",\n ),\n v.check(\n (input) =>\n input.side !== ProtoWrite.Side.SELL ||\n input.feeAsset === undefined ||\n input.feeAsset === ProtoWrite.FeeAsset.QUOTE,\n \"SELL orders must use the quote fee asset\",\n ),\n v.check((input) => sellingSlippageWithinCap(input), SELLING_SLIPPAGE_MESSAGE),\n v.check(\n (input) => attachedTrailingLimitMatchesSide(input),\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n ),\n );\n}\n\nfunction createScopedOrderIntentInputObjectSchema(scales: SdkScales) {\n const baseEntries = {\n ...AccountScopeInputEntries,\n ...createOrderIntentBaseEntries(scales),\n };\n return v.pipe(\n v.union([\n v.strictObject({\n ...baseEntries,\n qty: DecimalInputStringSchema,\n maxQuoteDebit: v.optional(v.never()),\n }),\n v.strictObject({\n ...baseEntries,\n qty: v.optional(v.never()),\n maxQuoteDebit: DecimalInputStringSchema,\n }),\n ]),\n v.check(\n (input) =>\n input.maxQuoteDebit === undefined ||\n (input.side === ProtoWrite.Side.BUY &&\n (input.execution.case === \"marketIoc\" || input.execution.case === \"limitIoc\")),\n \"maxQuoteDebit is supported only for BUY market IOC and BUY limit IOC orders\",\n ),\n v.check(\n (input) =>\n input.side !== ProtoWrite.Side.SELL ||\n input.feeAsset === undefined ||\n input.feeAsset === ProtoWrite.FeeAsset.QUOTE,\n \"SELL orders must use the quote fee asset\",\n ),\n v.check((input) => sellingSlippageWithinCap(input), SELLING_SLIPPAGE_MESSAGE),\n v.check(\n (input) => attachedTrailingLimitMatchesSide(input),\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n ),\n );\n}\n\nfunction toOrderIntent(input: ParsedOrderIntentInput, scales: SdkScales) {\n const { risk, qty, maxQuoteDebit, ...intent } = input;\n const sizing =\n qty !== undefined\n ? ({\n case: \"baseQtyScaled\",\n value: positiveDecimalInputToScaled(\"qty\", qty, scales.baseQty(intent.symbolId)),\n } as const)\n : ({\n case: \"maxQuoteDebitScaled\",\n value: positiveDecimalInputToScaled(\n \"maxQuoteDebit\",\n maxQuoteDebit,\n scales.quoteAmount(intent.symbolId),\n ),\n } as const);\n return {\n ...intent,\n sizing,\n feeAsset: intent.feeAsset ?? ProtoWrite.FeeAsset.QUOTE,\n attachedRisk: risk,\n };\n}\n\nexport function createOrderIntentInputSchema(scales: SdkScales) {\n return v.pipe(\n createOrderIntentInputObjectSchema(scales),\n v.transform((input) => toOrderIntent(input, scales)),\n );\n}\n\nexport type OrderIntentInput = v.InferInput<ReturnType<typeof createOrderIntentInputSchema>>;\n\nfunction createOrderExecutionInputSchema(scales: SdkScales) {\n const priceToTicks = (fieldName: string, price: string) =>\n positiveDecimalInputToScaled(fieldName, price, scales.price());\n\n return v.variant(\"type\", [\n v.pipe(\n v.strictObject({\n type: v.literal(\"market_ioc\"),\n maxSlippage: v.optional(MarketMaxSlippageSchema),\n clientRefPrice: v.optional(DecimalInputStringSchema),\n }),\n v.transform(({ maxSlippage, clientRefPrice }) => ({\n case: \"marketIoc\" as const,\n value: create(ProtoWrite.MarketIocSchema, {\n maxSlippage: parseMarketMaxSlippage(scales, maxSlippage),\n clientRefPriceTicks:\n clientRefPrice === undefined\n ? 0n\n : priceToTicks(\"execution.clientRefPrice\", clientRefPrice),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_gtc\"),\n price: DecimalInputStringSchema,\n postOnly: v.optional(v.boolean(), false),\n }),\n v.transform(({ price, postOnly }) => ({\n case: \"limitGtc\" as const,\n value: create(ProtoWrite.LimitGtcSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n postOnly,\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_gtd\"),\n price: DecimalInputStringSchema,\n /** Exact UTC expiry as integer epoch milliseconds. */\n expireAt: GtdExpireAtSchema,\n postOnly: v.optional(v.boolean(), false),\n }),\n v.transform(({ price, expireAt, postOnly }) => ({\n case: \"limitGtd\" as const,\n value: create(ProtoWrite.LimitGtdSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n postOnly,\n expireAt: msToTimestamp(expireAt),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_ioc\"),\n price: DecimalInputStringSchema,\n }),\n v.transform(({ price }) => ({\n case: \"limitIoc\" as const,\n value: create(ProtoWrite.LimitIocSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_fok\"),\n price: DecimalInputStringSchema,\n }),\n v.transform(({ price }) => ({\n case: \"limitFok\" as const,\n value: create(ProtoWrite.LimitFokSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n }),\n })),\n ),\n ]);\n}\n\nexport function createNewOrderInputSchema(scales: SdkScales) {\n return v.pipe(\n createScopedOrderIntentInputObjectSchema(scales),\n v.transform(({ account, ...input }) => {\n return {\n subaccountId: accountScopeToSubaccountId(account),\n order: toOrderIntent(input, scales),\n };\n }),\n );\n}\n\nexport type NewOrderInput = v.InferInput<ReturnType<typeof createNewOrderInputSchema>>;\n\nconst CancelOrderScopeInputEntries = {\n symbolId: v.optional(SymbolIdInputSchema),\n ...AccountScopeInputEntries,\n};\n\nexport const CancelOrderInputSchema = v.pipe(\n v.union([\n v.strictObject({\n ...CancelOrderScopeInputEntries,\n orderId: OrderIdInputSchema,\n clientOrderId: v.optional(v.never()),\n }),\n v.strictObject({\n ...CancelOrderScopeInputEntries,\n orderId: v.optional(v.never()),\n clientOrderId: ClientOrderIdInputSchema,\n }),\n ]),\n v.transform(({ orderId, clientOrderId, account, ...rest }) => {\n const key =\n orderId !== undefined\n ? ({ case: \"orderId\", value: orderId } as const)\n : ({ case: \"clientOrderId\", value: clientOrderId } as const);\n return {\n ...rest,\n subaccountId: accountScopeToSubaccountId(account),\n key,\n };\n }),\n);\n\nexport type CancelOrderInput = v.InferInput<typeof CancelOrderInputSchema>;\n\nexport const CancelOrderResultSchema = v.pipe(\n v.object({\n status: enumLabelSchema(CancelOrderStatusCodec.protoToOutput),\n orderId: PublicIdSchema,\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 CancelOrderResult = v.InferOutput<typeof CancelOrderResultSchema>;\n\nexport const CancelAllOrdersInputSchema = v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n symbolIds: v.optional(v.pipe(v.array(SymbolIdInputSchema), v.maxLength(100)), []),\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? OrderSideCodec.inputToProto[v] : undefined)),\n ),\n dryRun: v.optional(v.boolean(), false),\n requestId: v.optional(OrderRequestIdInputSchema),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type CancelAllOrdersInput = v.InferInput<typeof CancelAllOrdersInputSchema>;\n\nexport const CancelAllOrdersResponseSchema = v.pipe(\n v.object({\n status: enumLabelSchema(CancelAllOrdersStatusCodec.protoToOutput),\n matchedOrders: v.number(),\n submittedCancels: v.number(),\n failedCancels: v.number(),\n tsNs: v.bigint(),\n cancelledOrders: v.optional(\n v.array(v.object({ orderId: PublicIdSchema, clientOrderId: v.string() })),\n [],\n ),\n totalCancelled: v.optional(v.number(), 0),\n truncated: v.optional(v.boolean(), false),\n listingStatus: v.optional(enumLabelSchema(CancelAllListingStatusCodec.protoToOutput), 0),\n }),\n v.transform((o) => ({\n status: o.status,\n matchedOrders: o.matchedOrders,\n submittedCancels: o.submittedCancels,\n failedCancels: o.failedCancels,\n ts: tsNsToMs(o.tsNs),\n cancelledOrders: o.cancelledOrders,\n totalCancelled: o.totalCancelled,\n truncated: o.truncated,\n listingStatus: o.listingStatus,\n })),\n);\n\nexport type CancelAllOrdersResponse = v.InferOutput<typeof CancelAllOrdersResponseSchema>;\n\nexport const GetOrderDetailsInputSchema = v.pipe(\n v.strictObject({\n orderId: v.optional(OrderIdInputSchema),\n clientOrderId: v.optional(ClientOrderIdInputSchema),\n ...AccountScopeInputEntries,\n includeExecutionHistory: v.optional(v.boolean()),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000))),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), true),\n }),\n v.check(\n (input) =>\n input.includeExecutionHistory !== false ||\n (input.limit === undefined && input.pageToken === undefined),\n \"limit and pageToken must be omitted when includeExecutionHistory is false\",\n ),\n v.check((input) => {\n const hasOrderId = input.orderId !== undefined;\n const hasClientOrderId = input.clientOrderId !== undefined;\n return hasOrderId !== hasClientOrderId;\n }, \"Provide exactly one of orderId or clientOrderId\"),\n v.transform(({ account, orderId, clientOrderId, ...rest }) => {\n const key =\n orderId !== undefined\n ? ({ case: \"orderId\", value: orderId } as const)\n : ({ case: \"clientOrderId\", value: clientOrderId ?? \"\" } as const);\n return {\n ...rest,\n subaccountId: accountScopeToSubaccountId(account),\n key,\n };\n }),\n);\n\nexport type GetOrderDetailsInput = v.InferInput<typeof GetOrderDetailsInputSchema>;\n\nexport function createCreateOrderResultSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n orderId: PublicIdSchema,\n clientOrderId: v.string(),\n acceptedAt: OptionalTimestampMsSchema,\n acceptedAtTsNs: v.bigint(),\n resolvedBaseQtyScaled: v.bigint(),\n submittedMaxQuoteDebitScaled: v.optional(v.bigint()),\n takeProfitTriggerId: OptionalPublicIdSchema,\n stopLossTriggerId: OptionalPublicIdSchema,\n trailingStopTriggerId: OptionalPublicIdSchema,\n }),\n v.transform(\n ({\n acceptedAt,\n acceptedAtTsNs,\n resolvedBaseQtyScaled,\n submittedMaxQuoteDebitScaled,\n ...result\n }) => ({\n ...result,\n acceptedAt: acceptedAt ?? tsNsToMs(acceptedAtTsNs),\n acceptedAtNs: acceptedAtTsNs.toString(),\n resolvedBaseQty: scaledToDecimalOutput(\n resolvedBaseQtyScaled,\n scales.baseQty(symbolId),\n ),\n ...(submittedMaxQuoteDebitScaled === undefined\n ? {}\n : {\n submittedMaxQuoteDebit: scaledToDecimalOutput(\n submittedMaxQuoteDebitScaled,\n scales.quoteAmount(symbolId),\n ),\n }),\n }),\n ),\n );\n}\n\nexport type CreateOrderResult = v.InferOutput<ReturnType<typeof createCreateOrderResultSchema>>;\n\nexport function createPreviewOrderResultSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n admissible: v.optional(v.boolean()),\n rejection: v.optional(OrderErrorDetailSchema),\n resolvedBaseQtyScaled: v.optional(v.bigint()),\n protectedPriceBoundTicks: v.optional(v.bigint()),\n evaluatedAt: TimestampMsSchema,\n }),\n v.transform(({ resolvedBaseQtyScaled, protectedPriceBoundTicks, ...result }) => ({\n ...result,\n ...(resolvedBaseQtyScaled === undefined\n ? {}\n : {\n resolvedBaseQty: scaledToDecimalOutput(\n resolvedBaseQtyScaled,\n scales.baseQty(symbolId),\n ),\n }),\n ...(protectedPriceBoundTicks === undefined\n ? {}\n : {\n protectedPriceBound: scaledToDecimalOutput(\n protectedPriceBoundTicks,\n scales.price(),\n ),\n }),\n })),\n );\n}\n\nexport type PreviewOrderResult = v.InferOutput<ReturnType<typeof createPreviewOrderResultSchema>>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,MAAM,oBAAoB,EAAE,SAAS,0BAA0B;AAC/D,MAAM,iBAAiB,EAAE,SAAS,gBAAgB;AAClD,MAAM,gCAAgC,EAAE,SAAS,iCAAiC;AAElF,MAAM,+BAA+B;CACjC,GAAG;CACH,UAAU,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;CACjD,WAAW,sBAAsB,WAAW;CAC5C,MAAM,EAAE,KACJ,EAAE,SAAS,UAAU,GACrB,EAAE,WAAW,MAAO,IAAI,eAAe,aAAa,KAAK,KAAA,CAAU,CACvE;CACA,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;CAC5B,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC;AACtD;AAE2C,EAAE,KACzC,EAAE,aAAa,4BAA4B,GAC3C,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;AACpD,EAAE,CACN;AAEA,MAAa,wBAAwB,EAAE,KACnC,EAAE,aAAa;CACX,GAAG;CAEH,qBAAqB,EAAE,SAAS,EAAE,QAAQ,GAAG,IAAI;CACjD,0BAA0B,EAAE,SAAS,EAAE,QAAQ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AC,IACD,EACI,iBAAiB,sBACb,uBACA,OAAO,QAAQ,QAAQ,CAC3B,EACJ;EACN,GAAI,6BAA6B,KAAA,IAC3B,CAAC,IACD,EACI,qBAAqB,sBACjB,0BACA,OAAO,MAAM,CACjB,EACJ;CACV,EAAE,CACN;AACJ"}
|
|
1
|
+
{"version":3,"file":"orders-input.schemas.js","names":["ProtoWrite.MarketIocSchema","ProtoWrite.LimitGtcSchema","ProtoWrite.LimitGtdSchema","ProtoWrite.LimitIocSchema","ProtoWrite.LimitFokSchema"],"sources":["../../../src/services/orders/orders-input.schemas.ts"],"sourcesContent":["import * as ProtoWrite from \"../../gen/orders/v1/orders_pb.js\";\nimport { create } from \"@bufbuild/protobuf\";\nimport * as v from \"valibot\";\nimport { SideSchema, SymbolIdInputSchema } from \"../shared.js\";\nimport { tsNsToMs } from \"../../utils/time.js\";\nimport { msToTimestamp } from \"../../utils/timestamp.js\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n OptionalPublicIdSchema,\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampMsSchema,\n optionalIdInputSchema,\n optionalUint64DecimalFilterSchema,\n} from \"../../shared/schemas.js\";\nimport {\n positiveDecimalInputToScaled,\n scaledToDecimalOutput,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport {\n FEE_ASSET_VALUES,\n ORDER_STATUS_FILTER_VALUES,\n OrderSideCodec,\n OrderStatusFilterCodec,\n SELF_TRADE_PREVENTION_MODE_VALUES,\n FeeAssetCodec,\n SelfTradePreventionModeCodec,\n CancelAllOrdersStatusCodec,\n CancelAllListingStatusCodec,\n CancelOrderStatusCodec,\n} from \"./orders.codecs.js\";\nimport {\n MarketMaxSlippageSchema,\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n attachedTrailingLimitMatchesSide,\n createRiskPolicyInputSchema,\n parseMarketMaxSlippage,\n} from \"./orders-risk.schemas.js\";\nimport {\n ClientOrderIdInputSchema,\n OptionalClientOrderIdInputSchema,\n OrderIdInputSchema,\n OrderRequestIdInputSchema,\n} from \"./orders-identifiers.schemas.js\";\nimport { OrderErrorDetailSchema } from \"./order-errors.schemas.js\";\nimport { MAX_SELLING_SLIPPAGE_BPS } from \"../trailing-oneof-inputs.js\";\n\nconst OrderStatusSchema = v.picklist(ORDER_STATUS_FILTER_VALUES);\nconst FeeAssetSchema = v.picklist(FEE_ASSET_VALUES);\nconst SelfTradePreventionModeSchema = v.picklist(SELF_TRADE_PREVENTION_MODE_VALUES);\n\nconst BaseOrdersFilterInputEntries = {\n ...AccountScopeInputEntries,\n symbolId: v.optional(v.array(SymbolIdInputSchema)),\n triggerId: optionalIdInputSchema(\"triggerId\"),\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? OrderSideCodec.inputToProto[v] : undefined)),\n ),\n limit: v.optional(v.number()),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n};\n\nexport const BaseOrdersFilterInputSchema = v.pipe(\n v.strictObject(BaseOrdersFilterInputEntries),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport const OpenOrdersInputSchema = v.pipe(\n v.strictObject({\n ...BaseOrdersFilterInputEntries,\n\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), false),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type OpenOrdersInput = v.InferInput<typeof OpenOrdersInputSchema>;\n\nexport const OrderHistoryInputSchema = v.pipe(\n v.strictObject({\n ...BaseOrdersFilterInputEntries,\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), false),\n status: v.pipe(\n v.optional(OrderStatusSchema),\n v.transform((v) => (v ? OrderStatusFilterCodec.inputToProto[v] : undefined)),\n ),\n startTsNs: optionalUint64DecimalFilterSchema(\"startTsNs\"),\n endTsNs: optionalUint64DecimalFilterSchema(\"endTsNs\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type OrderHistoryInput = v.InferInput<typeof OrderHistoryInputSchema>;\n\nconst DecimalInputStringSchema = v.pipe(v.string(), v.trim(), v.minLength(1));\n\n/**\n * The wire contract stores GTD expiries as signed Unix nanoseconds. The public\n * `execution.expireAt` surface is integer epoch milliseconds, so these are the\n * inclusive millisecond values that remain representable by that contract.\n * The 1s..30d lead-time window is enforced server-side; checking it here\n * against the client clock would only add skew-dependent false rejections.\n */\nconst GTD_EXPIRE_AT_MIN_MS = -9_223_372_036_854;\nconst GTD_EXPIRE_AT_MAX_MS = 9_223_372_036_854;\n\nconst GtdExpireAtSchema = v.pipe(\n v.number(),\n v.integer(),\n v.minValue(GTD_EXPIRE_AT_MIN_MS),\n v.maxValue(GTD_EXPIRE_AT_MAX_MS),\n);\n\nfunction createOrderIntentBaseEntries(scales: SdkScales) {\n return {\n symbolId: SymbolIdInputSchema,\n side: v.pipe(\n SideSchema,\n v.transform((v) => OrderSideCodec.inputToProto[v]),\n ),\n execution: createOrderExecutionInputSchema(scales),\n clientOrderId: OptionalClientOrderIdInputSchema,\n feeAsset: v.pipe(\n v.optional(FeeAssetSchema),\n v.transform((v) => (v ? FeeAssetCodec.inputToProto[v] : undefined)),\n ),\n selfTradePreventionMode: v.pipe(\n v.optional(SelfTradePreventionModeSchema),\n v.transform((v) => (v ? SelfTradePreventionModeCodec.inputToProto[v] : undefined)),\n ),\n risk: createRiskPolicyInputSchema(scales),\n };\n}\n\ntype ParsedOrderIntentInput = v.InferOutput<ReturnType<typeof createOrderIntentInputObjectSchema>>;\n\ntype SellingSlippageInput = {\n side: ProtoWrite.Side;\n execution: v.InferOutput<ReturnType<typeof createOrderExecutionInputSchema>>;\n};\n\nconst SELLING_SLIPPAGE_MESSAGE = `maxSlippageBps must be between 1 and ${MAX_SELLING_SLIPPAGE_BPS} for a market order that sells`;\n\n/** Checks the bps cap of a market sell; attached trailing stops are capped when parsed. */\nfunction sellingSlippageWithinCap(input: SellingSlippageInput): boolean {\n const slippage =\n input.side === ProtoWrite.Side.SELL && input.execution.case === \"marketIoc\"\n ? input.execution.value.maxSlippage\n : undefined;\n return slippage?.case !== \"maxSlippageBps\" || slippage.value <= MAX_SELLING_SLIPPAGE_BPS;\n}\n\nfunction createOrderIntentInputObjectSchema(scales: SdkScales) {\n const baseEntries = createOrderIntentBaseEntries(scales);\n return v.pipe(\n v.union([\n v.strictObject({\n ...baseEntries,\n qty: DecimalInputStringSchema,\n maxQuoteDebit: v.optional(v.never()),\n }),\n v.strictObject({\n ...baseEntries,\n qty: v.optional(v.never()),\n maxQuoteDebit: DecimalInputStringSchema,\n }),\n ]),\n v.check(\n (input) =>\n input.maxQuoteDebit === undefined ||\n (input.side === ProtoWrite.Side.BUY &&\n (input.execution.case === \"marketIoc\" || input.execution.case === \"limitIoc\")),\n \"maxQuoteDebit is supported only for BUY market IOC and BUY limit IOC orders\",\n ),\n v.check(\n (input) =>\n input.side !== ProtoWrite.Side.SELL ||\n input.feeAsset === undefined ||\n input.feeAsset === ProtoWrite.FeeAsset.QUOTE,\n \"SELL orders must use the quote fee asset\",\n ),\n v.check((input) => sellingSlippageWithinCap(input), SELLING_SLIPPAGE_MESSAGE),\n v.check(\n (input) => attachedTrailingLimitMatchesSide(input),\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n ),\n );\n}\n\nfunction createScopedOrderIntentInputObjectSchema(scales: SdkScales) {\n const baseEntries = {\n ...AccountScopeInputEntries,\n ...createOrderIntentBaseEntries(scales),\n };\n return v.pipe(\n v.union([\n v.strictObject({\n ...baseEntries,\n qty: DecimalInputStringSchema,\n maxQuoteDebit: v.optional(v.never()),\n }),\n v.strictObject({\n ...baseEntries,\n qty: v.optional(v.never()),\n maxQuoteDebit: DecimalInputStringSchema,\n }),\n ]),\n v.check(\n (input) =>\n input.maxQuoteDebit === undefined ||\n (input.side === ProtoWrite.Side.BUY &&\n (input.execution.case === \"marketIoc\" || input.execution.case === \"limitIoc\")),\n \"maxQuoteDebit is supported only for BUY market IOC and BUY limit IOC orders\",\n ),\n v.check(\n (input) =>\n input.side !== ProtoWrite.Side.SELL ||\n input.feeAsset === undefined ||\n input.feeAsset === ProtoWrite.FeeAsset.QUOTE,\n \"SELL orders must use the quote fee asset\",\n ),\n v.check((input) => sellingSlippageWithinCap(input), SELLING_SLIPPAGE_MESSAGE),\n v.check(\n (input) => attachedTrailingLimitMatchesSide(input),\n ATTACHED_TRAILING_LIMIT_SIDE_MESSAGE,\n ),\n );\n}\n\nfunction toOrderIntent(input: ParsedOrderIntentInput, scales: SdkScales) {\n const { risk, qty, maxQuoteDebit, ...intent } = input;\n const sizing =\n qty !== undefined\n ? ({\n case: \"baseQtyScaled\",\n value: positiveDecimalInputToScaled(\"qty\", qty, scales.baseQty(intent.symbolId)),\n } as const)\n : ({\n case: \"maxQuoteDebitScaled\",\n value: positiveDecimalInputToScaled(\n \"maxQuoteDebit\",\n maxQuoteDebit,\n scales.quoteAmount(intent.symbolId),\n ),\n } as const);\n return {\n ...intent,\n sizing,\n feeAsset: intent.feeAsset ?? ProtoWrite.FeeAsset.QUOTE,\n attachedRisk: risk,\n };\n}\n\nexport function createOrderIntentInputSchema(scales: SdkScales) {\n return v.pipe(\n createOrderIntentInputObjectSchema(scales),\n v.transform((input) => toOrderIntent(input, scales)),\n );\n}\n\nexport type OrderIntentInput = v.InferInput<ReturnType<typeof createOrderIntentInputSchema>>;\n\nfunction createOrderExecutionInputSchema(scales: SdkScales) {\n const priceToTicks = (fieldName: string, price: string) =>\n positiveDecimalInputToScaled(fieldName, price, scales.price());\n\n return v.variant(\"type\", [\n v.pipe(\n v.strictObject({\n type: v.literal(\"market_ioc\"),\n maxSlippage: v.optional(MarketMaxSlippageSchema),\n clientRefPrice: v.optional(DecimalInputStringSchema),\n }),\n v.transform(({ maxSlippage, clientRefPrice }) => ({\n case: \"marketIoc\" as const,\n value: create(ProtoWrite.MarketIocSchema, {\n maxSlippage: parseMarketMaxSlippage(scales, maxSlippage),\n clientRefPriceTicks:\n clientRefPrice === undefined\n ? 0n\n : priceToTicks(\"execution.clientRefPrice\", clientRefPrice),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_gtc\"),\n price: DecimalInputStringSchema,\n postOnly: v.optional(v.boolean(), false),\n }),\n v.transform(({ price, postOnly }) => ({\n case: \"limitGtc\" as const,\n value: create(ProtoWrite.LimitGtcSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n postOnly,\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_gtd\"),\n price: DecimalInputStringSchema,\n /** Exact UTC expiry as integer epoch milliseconds. */\n expireAt: GtdExpireAtSchema,\n postOnly: v.optional(v.boolean(), false),\n }),\n v.transform(({ price, expireAt, postOnly }) => ({\n case: \"limitGtd\" as const,\n value: create(ProtoWrite.LimitGtdSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n postOnly,\n expireAt: msToTimestamp(expireAt),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_ioc\"),\n price: DecimalInputStringSchema,\n }),\n v.transform(({ price }) => ({\n case: \"limitIoc\" as const,\n value: create(ProtoWrite.LimitIocSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n }),\n })),\n ),\n v.pipe(\n v.strictObject({\n type: v.literal(\"limit_fok\"),\n price: DecimalInputStringSchema,\n }),\n v.transform(({ price }) => ({\n case: \"limitFok\" as const,\n value: create(ProtoWrite.LimitFokSchema, {\n priceTicks: priceToTicks(\"execution.price\", price),\n }),\n })),\n ),\n ]);\n}\n\nexport function createNewOrderInputSchema(scales: SdkScales) {\n return v.pipe(\n createScopedOrderIntentInputObjectSchema(scales),\n v.transform(({ account, ...input }) => {\n return {\n subaccountId: accountScopeToSubaccountId(account),\n order: toOrderIntent(input, scales),\n };\n }),\n );\n}\n\nexport type NewOrderInput = v.InferInput<ReturnType<typeof createNewOrderInputSchema>>;\n\nconst CancelOrderScopeInputEntries = {\n symbolId: v.optional(SymbolIdInputSchema),\n ...AccountScopeInputEntries,\n};\n\nexport const CancelOrderInputSchema = v.pipe(\n v.union([\n v.strictObject({\n ...CancelOrderScopeInputEntries,\n orderId: OrderIdInputSchema,\n clientOrderId: v.optional(v.never()),\n }),\n v.strictObject({\n ...CancelOrderScopeInputEntries,\n orderId: v.optional(v.never()),\n clientOrderId: ClientOrderIdInputSchema,\n }),\n ]),\n v.transform(({ orderId, clientOrderId, account, ...rest }) => {\n const key =\n orderId !== undefined\n ? ({ case: \"orderId\", value: orderId } as const)\n : ({ case: \"clientOrderId\", value: clientOrderId } as const);\n return {\n ...rest,\n subaccountId: accountScopeToSubaccountId(account),\n key,\n };\n }),\n);\n\nexport type CancelOrderInput = v.InferInput<typeof CancelOrderInputSchema>;\n\nexport const CancelOrderResultSchema = v.pipe(\n v.object({\n status: enumLabelSchema(CancelOrderStatusCodec.protoToOutput),\n orderId: PublicIdSchema,\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 CancelOrderResult = v.InferOutput<typeof CancelOrderResultSchema>;\n\nexport const CancelAllOrdersInputSchema = v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n symbolIds: v.optional(v.pipe(v.array(SymbolIdInputSchema), v.maxLength(100)), []),\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? OrderSideCodec.inputToProto[v] : undefined)),\n ),\n dryRun: v.optional(v.boolean(), false),\n requestId: v.optional(OrderRequestIdInputSchema),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\nexport type CancelAllOrdersInput = v.InferInput<typeof CancelAllOrdersInputSchema>;\n\nexport const CancelAllOrdersResponseSchema = v.pipe(\n v.object({\n status: enumLabelSchema(CancelAllOrdersStatusCodec.protoToOutput),\n matchedOrders: v.number(),\n submittedCancels: v.number(),\n failedCancels: v.number(),\n tsNs: v.bigint(),\n cancelledOrders: v.optional(\n v.array(v.object({ orderId: PublicIdSchema, clientOrderId: v.string() })),\n [],\n ),\n totalCancelled: v.optional(v.number(), 0),\n truncated: v.optional(v.boolean(), false),\n listingStatus: v.optional(enumLabelSchema(CancelAllListingStatusCodec.protoToOutput), 0),\n }),\n v.transform((o) => ({\n status: o.status,\n matchedOrders: o.matchedOrders,\n submittedCancels: o.submittedCancels,\n failedCancels: o.failedCancels,\n ts: tsNsToMs(o.tsNs),\n canceledOrders: o.cancelledOrders,\n totalCanceled: o.totalCancelled,\n truncated: o.truncated,\n listingStatus: o.listingStatus,\n })),\n);\n\nexport type CancelAllOrdersResponse = v.InferOutput<typeof CancelAllOrdersResponseSchema>;\n\nexport const GetOrderDetailsInputSchema = v.pipe(\n v.strictObject({\n orderId: v.optional(OrderIdInputSchema),\n clientOrderId: v.optional(ClientOrderIdInputSchema),\n ...AccountScopeInputEntries,\n includeExecutionHistory: v.optional(v.boolean()),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000))),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n includeAttachedRisk: v.optional(v.boolean(), true),\n includeAttachedRiskState: v.optional(v.boolean(), true),\n }),\n v.check(\n (input) =>\n input.includeExecutionHistory !== false ||\n (input.limit === undefined && input.pageToken === undefined),\n \"limit and pageToken must be omitted when includeExecutionHistory is false\",\n ),\n v.check((input) => {\n const hasOrderId = input.orderId !== undefined;\n const hasClientOrderId = input.clientOrderId !== undefined;\n return hasOrderId !== hasClientOrderId;\n }, \"Provide exactly one of orderId or clientOrderId\"),\n v.transform(({ account, orderId, clientOrderId, ...rest }) => {\n const key =\n orderId !== undefined\n ? ({ case: \"orderId\", value: orderId } as const)\n : ({ case: \"clientOrderId\", value: clientOrderId ?? \"\" } as const);\n return {\n ...rest,\n subaccountId: accountScopeToSubaccountId(account),\n key,\n };\n }),\n);\n\nexport type GetOrderDetailsInput = v.InferInput<typeof GetOrderDetailsInputSchema>;\n\nexport function createCreateOrderResultSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n orderId: PublicIdSchema,\n clientOrderId: v.string(),\n acceptedAt: OptionalTimestampMsSchema,\n acceptedAtTsNs: v.bigint(),\n resolvedBaseQtyScaled: v.bigint(),\n submittedMaxQuoteDebitScaled: v.optional(v.bigint()),\n takeProfitTriggerId: OptionalPublicIdSchema,\n stopLossTriggerId: OptionalPublicIdSchema,\n trailingStopTriggerId: OptionalPublicIdSchema,\n }),\n v.transform(\n ({\n acceptedAt,\n acceptedAtTsNs,\n resolvedBaseQtyScaled,\n submittedMaxQuoteDebitScaled,\n ...result\n }) => ({\n ...result,\n acceptedAt: acceptedAt ?? tsNsToMs(acceptedAtTsNs),\n acceptedAtNs: acceptedAtTsNs.toString(),\n resolvedBaseQty: scaledToDecimalOutput(\n resolvedBaseQtyScaled,\n scales.baseQty(symbolId),\n ),\n ...(submittedMaxQuoteDebitScaled === undefined\n ? {}\n : {\n submittedMaxQuoteDebit: scaledToDecimalOutput(\n submittedMaxQuoteDebitScaled,\n scales.quoteAmount(symbolId),\n ),\n }),\n }),\n ),\n );\n}\n\nexport type CreateOrderResult = v.InferOutput<ReturnType<typeof createCreateOrderResultSchema>>;\n\nexport function createPreviewOrderResultSchema(scales: SdkScales, symbolId: number) {\n return v.pipe(\n v.object({\n admissible: v.optional(v.boolean()),\n rejection: v.optional(OrderErrorDetailSchema),\n resolvedBaseQtyScaled: v.optional(v.bigint()),\n protectedPriceBoundTicks: v.optional(v.bigint()),\n evaluatedAt: TimestampMsSchema,\n }),\n v.transform(({ resolvedBaseQtyScaled, protectedPriceBoundTicks, ...result }) => ({\n ...result,\n ...(resolvedBaseQtyScaled === undefined\n ? {}\n : {\n resolvedBaseQty: scaledToDecimalOutput(\n resolvedBaseQtyScaled,\n scales.baseQty(symbolId),\n ),\n }),\n ...(protectedPriceBoundTicks === undefined\n ? {}\n : {\n protectedPriceBound: scaledToDecimalOutput(\n protectedPriceBoundTicks,\n scales.price(),\n ),\n }),\n })),\n );\n}\n\nexport type PreviewOrderResult = v.InferOutput<ReturnType<typeof createPreviewOrderResultSchema>>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,MAAM,oBAAoB,EAAE,SAAS,0BAA0B;AAC/D,MAAM,iBAAiB,EAAE,SAAS,gBAAgB;AAClD,MAAM,gCAAgC,EAAE,SAAS,iCAAiC;AAElF,MAAM,+BAA+B;CACjC,GAAG;CACH,UAAU,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;CACjD,WAAW,sBAAsB,WAAW;CAC5C,MAAM,EAAE,KACJ,EAAE,SAAS,UAAU,GACrB,EAAE,WAAW,MAAO,IAAI,eAAe,aAAa,KAAK,KAAA,CAAU,CACvE;CACA,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;CAC5B,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC;AACtD;AAE2C,EAAE,KACzC,EAAE,aAAa,4BAA4B,GAC3C,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;AACpD,EAAE,CACN;AAEA,MAAa,wBAAwB,EAAE,KACnC,EAAE,aAAa;CACX,GAAG;CAEH,qBAAqB,EAAE,SAAS,EAAE,QAAQ,GAAG,IAAI;CACjD,0BAA0B,EAAE,SAAS,EAAE,QAAQ,GAAG,KAAK;AAC3D,CAAC,GACD,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;AACpD,EAAE,CACN;AAIA,MAAa,0BAA0B,EAAE,KACrC,EAAE,aAAa;CACX,GAAG;CACH,qBAAqB,EAAE,SAAS,EAAE,Q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class OrdersService {
|
|
|
87
87
|
getBatchReplaceStatus(input: GetBatchReplaceStatusInput, options?: PolyesterRequestOptions): Promise<GetBatchReplaceStatusResult>;
|
|
88
88
|
/**
|
|
89
89
|
* 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.
|
|
90
|
-
* `
|
|
91
|
-
* A retry with the same requestId and criteria returns the original counts with `listingStatus: "not_retained_read_open_orders"` and an empty `
|
|
90
|
+
* `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.
|
|
91
|
+
* 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.
|
|
92
92
|
*/
|
|
93
93
|
cancelAll(input: v.InferInput<typeof CancelAllOrdersInputSchema>, options?: PolyesterMutationOptions): Promise<CancelAllOrdersResponse>;
|
|
94
94
|
/**
|
|
@@ -200,8 +200,8 @@ var OrdersService = class {
|
|
|
200
200
|
}
|
|
201
201
|
/**
|
|
202
202
|
* 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.
|
|
203
|
-
* `
|
|
204
|
-
* A retry with the same requestId and criteria returns the original counts with `listingStatus: "not_retained_read_open_orders"` and an empty `
|
|
203
|
+
* `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.
|
|
204
|
+
* 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.
|
|
205
205
|
*/
|
|
206
206
|
async cancelAll(input, options) {
|
|
207
207
|
const resolved = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders.js","names":["#readClient","ProtoRead.OrdersReadService","#writeClient","ProtoWrite.OrdersService","#realtime","#resolver","#scales","#orderSchema","#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 * 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 { ConfigurationError, PolyesterError } from \"../../shared/errors.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 createOrderSchema,\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 createMutationRequestId(): string {\n const crypto = globalThis.crypto;\n if (crypto?.randomUUID) return crypto.randomUUID();\n\n if (crypto?.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n throw new ConfigurationError(\n \"Secure request ID generation requires crypto.randomUUID or crypto.getRandomValues.\",\n );\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 #orderSchema: ReturnType<typeof createOrderSchema>;\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.#orderSchema = createOrderSchema(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: parse(\n v.array(this.#orderSchema),\n res.orders.filter((order) => hasKnownOrderSymbol(this.#scales, order)),\n ),\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: parse(\n v.array(this.#orderSchema),\n res.orders.filter((order) => hasKnownOrderSymbol(this.#scales, order)),\n ),\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-IOC, or limit-FOK execution policy and optional attached risk controls. 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. The same payload and account-scoped requestId replay the original results and timestamp for 60 seconds from acceptance; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. 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 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 durable per-item execution status for a batch replacement receipt. For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is 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 * `cancelledOrders` lists up to 200 of the orders whose cancellation was requested, oldest first; `truncated` is true when `totalCancelled` 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 `cancelledOrders`, 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) => parse(this.#orderSchema, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(parse(this.#orderSchema, 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(parse(this.#orderSchema, 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":";;;;;;;;;;;;;;;;;;;;AAwEA,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,0BAAkC;CACvC,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,YAAY,OAAO,OAAO,WAAW;CAEjD,IAAI,QAAQ,iBAAiB;EACzB,MAAM,wBAAQ,IAAI,WAAW,EAAE;EAC/B,OAAO,gBAAgB,KAAK;EAC5B,OAAO,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,C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,SACA,MAAM,MAAM,MAAM,IACjB,MAAM,MAAM,QAAQ,MAAM,KAAKA,cAAc,CAAC,CAAC,GAChD,OACJ;KACA,IAAI,QAAQ,SAAS,GACjB,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,MAAM,KAAKA,cAAc,CAAC,CAAC,GAChD,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,KAAKH,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","#orderSchema","#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 * 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 { ConfigurationError, PolyesterError } from \"../../shared/errors.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 createOrderSchema,\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 createMutationRequestId(): string {\n const crypto = globalThis.crypto;\n if (crypto?.randomUUID) return crypto.randomUUID();\n\n if (crypto?.getRandomValues) {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n throw new ConfigurationError(\n \"Secure request ID generation requires crypto.randomUUID or crypto.getRandomValues.\",\n );\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 #orderSchema: ReturnType<typeof createOrderSchema>;\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.#orderSchema = createOrderSchema(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: parse(\n v.array(this.#orderSchema),\n res.orders.filter((order) => hasKnownOrderSymbol(this.#scales, order)),\n ),\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: parse(\n v.array(this.#orderSchema),\n res.orders.filter((order) => hasKnownOrderSymbol(this.#scales, order)),\n ),\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-IOC, or limit-FOK execution policy and optional attached risk controls. 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. The same payload and account-scoped requestId replay the original results and timestamp for 60 seconds from acceptance; a different payload during that window returns CONFLICT_IDEMPOTENCY_KEY_REUSE. 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 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 durable per-item execution status for a batch replacement receipt. For cancel-only AMENDED items, orderStatus describes oldOrderId and replacementOrderId is 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) => parse(this.#orderSchema, o)),\n );\n return;\n }\n deliverBatch(\n channel,\n known(event.orders),\n (o) => input.onEvent(parse(this.#orderSchema, 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(parse(this.#orderSchema, 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 onD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,SAAS,EAAE,CAAC,CAAC;GAExE;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC;EACJ,IACC,aACG,KAAKH,UAAU,qBAAqB;GAChC,WAAW,MAAM;GACjB,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,gBAAgB,SAAS;GACzB,SAAS,SAAS;EACtB,CAAC,CACT;CACJ;AACJ"}
|
|
@@ -14,7 +14,7 @@ const SOCIAL_VERIFICATION_STATUS_VALUES = [
|
|
|
14
14
|
"verified",
|
|
15
15
|
"failed",
|
|
16
16
|
"expired",
|
|
17
|
-
"
|
|
17
|
+
"canceled"
|
|
18
18
|
];
|
|
19
19
|
const SocialProviderCodec = {
|
|
20
20
|
inputToProto: {
|
|
@@ -48,7 +48,7 @@ const SocialVerificationStatusCodec = { protoToOutput: {
|
|
|
48
48
|
[4]: "verified",
|
|
49
49
|
[5]: "failed",
|
|
50
50
|
[6]: "expired",
|
|
51
|
-
[7]: "
|
|
51
|
+
[7]: "canceled"
|
|
52
52
|
} };
|
|
53
53
|
const SOCIAL_VERIFICATION_ERROR_CODE_VALUES = [
|
|
54
54
|
"username_invalid",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"social-verification.codecs.js","names":[],"sources":["../../../src/services/social-verification/social-verification.codecs.ts"],"sourcesContent":["import { AuthErrorCode } from \"../../gen/auth/v1/auth_pb.js\";\nimport * as Proto from \"../../gen/auth/v1/social_verification_pb.js\";\nimport type { InputToProto, ProtoToOutput } from \"../../utils/types.js\";\n\nexport const SOCIAL_PROVIDER_VALUES = [\"twitter\", \"discord\"] as const;\nexport type SocialProviderValue = (typeof SOCIAL_PROVIDER_VALUES)[number];\n\nexport const SOCIAL_VERIFICATION_METHOD_VALUES = [\"profile\", \"channel\", \"dm\"] as const;\nexport type SocialVerificationMethodValue = (typeof SOCIAL_VERIFICATION_METHOD_VALUES)[number];\n\nexport const SOCIAL_VERIFICATION_STATUS_VALUES = [\n \"pending_user_action\",\n \"queued\",\n \"in_progress\",\n \"verified\",\n \"failed\",\n \"expired\",\n \"
|
|
1
|
+
{"version":3,"file":"social-verification.codecs.js","names":[],"sources":["../../../src/services/social-verification/social-verification.codecs.ts"],"sourcesContent":["import { AuthErrorCode } from \"../../gen/auth/v1/auth_pb.js\";\nimport * as Proto from \"../../gen/auth/v1/social_verification_pb.js\";\nimport type { InputToProto, ProtoToOutput } from \"../../utils/types.js\";\n\nexport const SOCIAL_PROVIDER_VALUES = [\"twitter\", \"discord\"] as const;\nexport type SocialProviderValue = (typeof SOCIAL_PROVIDER_VALUES)[number];\n\nexport const SOCIAL_VERIFICATION_METHOD_VALUES = [\"profile\", \"channel\", \"dm\"] as const;\nexport type SocialVerificationMethodValue = (typeof SOCIAL_VERIFICATION_METHOD_VALUES)[number];\n\nexport const SOCIAL_VERIFICATION_STATUS_VALUES = [\n \"pending_user_action\",\n \"queued\",\n \"in_progress\",\n \"verified\",\n \"failed\",\n \"expired\",\n \"canceled\",\n] as const;\nexport type SocialVerificationStatusValue = (typeof SOCIAL_VERIFICATION_STATUS_VALUES)[number];\n\nexport const SocialProviderCodec = {\n inputToProto: {\n twitter: Proto.SocialProvider.TWITTER,\n discord: Proto.SocialProvider.DISCORD,\n } satisfies InputToProto<SocialProviderValue, Proto.SocialProvider>,\n protoToOutput: {\n [Proto.SocialProvider.PROVIDER_UNSPECIFIED]: \"unspecified\",\n [Proto.SocialProvider.TWITTER]: \"twitter\",\n [Proto.SocialProvider.DISCORD]: \"discord\",\n } satisfies ProtoToOutput<Proto.SocialProvider, SocialProviderValue>,\n} as const;\n\nexport const SocialVerificationMethodCodec = {\n inputToProto: {\n profile: Proto.SocialVerificationMethod.METHOD_PROFILE,\n channel: Proto.SocialVerificationMethod.METHOD_CHANNEL,\n dm: Proto.SocialVerificationMethod.METHOD_DM,\n } satisfies InputToProto<SocialVerificationMethodValue, Proto.SocialVerificationMethod>,\n protoToOutput: {\n [Proto.SocialVerificationMethod.METHOD_UNSPECIFIED]: \"unspecified\",\n [Proto.SocialVerificationMethod.METHOD_PROFILE]: \"profile\",\n [Proto.SocialVerificationMethod.METHOD_CHANNEL]: \"channel\",\n [Proto.SocialVerificationMethod.METHOD_DM]: \"dm\",\n } satisfies ProtoToOutput<Proto.SocialVerificationMethod, SocialVerificationMethodValue>,\n} as const;\n\nexport const SocialVerificationStatusCodec = {\n protoToOutput: {\n [Proto.SocialVerificationStatus.STATUS_UNSPECIFIED]: \"unspecified\",\n [Proto.SocialVerificationStatus.STATUS_PENDING_USER_ACTION]: \"pending_user_action\",\n [Proto.SocialVerificationStatus.STATUS_QUEUED]: \"queued\",\n [Proto.SocialVerificationStatus.STATUS_IN_PROGRESS]: \"in_progress\",\n [Proto.SocialVerificationStatus.STATUS_VERIFIED]: \"verified\",\n [Proto.SocialVerificationStatus.STATUS_FAILED]: \"failed\",\n [Proto.SocialVerificationStatus.STATUS_EXPIRED]: \"expired\",\n [Proto.SocialVerificationStatus.STATUS_CANCELLED]: \"canceled\",\n } satisfies ProtoToOutput<Proto.SocialVerificationStatus, SocialVerificationStatusValue>,\n} as const;\n\nexport const SOCIAL_VERIFICATION_ERROR_CODE_VALUES = [\n \"username_invalid\",\n \"username_taken\",\n \"username_cooldown\",\n \"username_feature_locked\",\n \"username_reserved\",\n \"invalid_request\",\n \"authentication_required\",\n \"session_kind_not_allowed\",\n \"wallet_login_failed\",\n \"resource_not_found\",\n \"subaccount_access_denied\",\n \"api_key_access_denied\",\n \"api_key_invalid_status_transition\",\n \"policy_invalid\",\n \"smart_account_already_linked\",\n \"invite_access_denied\",\n \"invite_invalid_state\",\n \"mfa_disabled\",\n \"mfa_not_enrolled\",\n \"mfa_session_invalid\",\n \"mfa_challenge_not_found\",\n \"mfa_challenge_invalid\",\n \"mfa_challenge_locked\",\n \"mfa_otp_invalid\",\n \"mfa_recovery_invalid\",\n \"mfa_passkey_not_available\",\n \"mfa_passkey_credential_invalid\",\n \"mfa_passkey_verify_failed\",\n \"mfa_enrollment_binding_invalid\",\n \"step_up_required\",\n \"step_up_proof_unavailable\",\n \"step_up_already_claimed\",\n \"policy_in_use\",\n \"policy_locked\",\n \"policy_scope_mismatch\",\n \"revision_conflict\",\n \"mfa_elevation_required\",\n \"mfa_last_factor_required\",\n \"internal_error\",\n \"terms_not_accepted\",\n \"social_verification_expired\",\n \"social_verification_invalid_state\",\n \"subaccount_challenge_invalid\",\n \"social_account_already_linked\",\n] as const;\nexport type SocialVerificationErrorCodeValue =\n (typeof SOCIAL_VERIFICATION_ERROR_CODE_VALUES)[number];\n\n// Partial: auth codes added upstream decode to \"unspecified\" until mapped here.\nexport const SocialVerificationErrorCodeCodec = {\n protoToOutput: {\n [AuthErrorCode.AUTH_UNSPECIFIED]: \"unspecified\",\n [AuthErrorCode.AUTH_USERNAME_INVALID]: \"username_invalid\",\n [AuthErrorCode.AUTH_USERNAME_TAKEN]: \"username_taken\",\n [AuthErrorCode.AUTH_USERNAME_COOLDOWN]: \"username_cooldown\",\n [AuthErrorCode.AUTH_USERNAME_FEATURE_LOCKED]: \"username_feature_locked\",\n [AuthErrorCode.AUTH_USERNAME_RESERVED]: \"username_reserved\",\n [AuthErrorCode.AUTH_INVALID_REQUEST]: \"invalid_request\",\n [AuthErrorCode.AUTH_AUTHENTICATION_REQUIRED]: \"authentication_required\",\n [AuthErrorCode.AUTH_SESSION_KIND_NOT_ALLOWED]: \"session_kind_not_allowed\",\n [AuthErrorCode.AUTH_WALLET_LOGIN_FAILED]: \"wallet_login_failed\",\n [AuthErrorCode.AUTH_RESOURCE_NOT_FOUND]: \"resource_not_found\",\n [AuthErrorCode.AUTH_SUBACCOUNT_ACCESS_DENIED]: \"subaccount_access_denied\",\n [AuthErrorCode.AUTH_API_KEY_ACCESS_DENIED]: \"api_key_access_denied\",\n [AuthErrorCode.AUTH_API_KEY_INVALID_STATUS_TRANSITION]: \"api_key_invalid_status_transition\",\n [AuthErrorCode.AUTH_POLICY_INVALID]: \"policy_invalid\",\n [AuthErrorCode.AUTH_SMART_ACCOUNT_ALREADY_LINKED]: \"smart_account_already_linked\",\n [AuthErrorCode.AUTH_INVITE_ACCESS_DENIED]: \"invite_access_denied\",\n [AuthErrorCode.AUTH_INVITE_INVALID_STATE]: \"invite_invalid_state\",\n [AuthErrorCode.AUTH_MFA_DISABLED]: \"mfa_disabled\",\n [AuthErrorCode.AUTH_MFA_NOT_ENROLLED]: \"mfa_not_enrolled\",\n [AuthErrorCode.AUTH_MFA_SESSION_INVALID]: \"mfa_session_invalid\",\n [AuthErrorCode.AUTH_MFA_CHALLENGE_NOT_FOUND]: \"mfa_challenge_not_found\",\n [AuthErrorCode.AUTH_MFA_CHALLENGE_INVALID]: \"mfa_challenge_invalid\",\n [AuthErrorCode.AUTH_MFA_CHALLENGE_LOCKED]: \"mfa_challenge_locked\",\n [AuthErrorCode.AUTH_MFA_OTP_INVALID]: \"mfa_otp_invalid\",\n [AuthErrorCode.AUTH_MFA_RECOVERY_INVALID]: \"mfa_recovery_invalid\",\n [AuthErrorCode.AUTH_MFA_PASSKEY_NOT_AVAILABLE]: \"mfa_passkey_not_available\",\n [AuthErrorCode.AUTH_MFA_PASSKEY_CREDENTIAL_INVALID]: \"mfa_passkey_credential_invalid\",\n [AuthErrorCode.AUTH_MFA_PASSKEY_VERIFY_FAILED]: \"mfa_passkey_verify_failed\",\n [AuthErrorCode.AUTH_MFA_ENROLLMENT_BINDING_INVALID]: \"mfa_enrollment_binding_invalid\",\n [AuthErrorCode.AUTH_STEP_UP_REQUIRED]: \"step_up_required\",\n [AuthErrorCode.AUTH_STEP_UP_PROOF_UNAVAILABLE]: \"step_up_proof_unavailable\",\n [AuthErrorCode.AUTH_STEP_UP_ALREADY_CLAIMED]: \"step_up_already_claimed\",\n [AuthErrorCode.AUTH_POLICY_IN_USE]: \"policy_in_use\",\n [AuthErrorCode.AUTH_POLICY_LOCKED]: \"policy_locked\",\n [AuthErrorCode.AUTH_POLICY_SCOPE_MISMATCH]: \"policy_scope_mismatch\",\n [AuthErrorCode.AUTH_REVISION_CONFLICT]: \"revision_conflict\",\n [AuthErrorCode.AUTH_MFA_ELEVATION_REQUIRED]: \"mfa_elevation_required\",\n [AuthErrorCode.AUTH_MFA_LAST_FACTOR_REQUIRED]: \"mfa_last_factor_required\",\n [AuthErrorCode.AUTH_INTERNAL_ERROR]: \"internal_error\",\n [AuthErrorCode.AUTH_TERMS_NOT_ACCEPTED]: \"terms_not_accepted\",\n [AuthErrorCode.AUTH_SOCIAL_VERIFICATION_EXPIRED]: \"social_verification_expired\",\n [AuthErrorCode.AUTH_SOCIAL_VERIFICATION_INVALID_STATE]: \"social_verification_invalid_state\",\n [AuthErrorCode.AUTH_SUBACCOUNT_CHALLENGE_INVALID]: \"subaccount_challenge_invalid\",\n [AuthErrorCode.AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED]: \"social_account_already_linked\",\n } satisfies Partial<ProtoToOutput<AuthErrorCode, SocialVerificationErrorCodeValue>>,\n} as const;\n"],"mappings":";;;AAIA,MAAa,yBAAyB,CAAC,WAAW,SAAS;AAG3D,MAAa,oCAAoC;CAAC;CAAW;CAAW;AAAI;AAG5E,MAAa,oCAAoC;CAC7C;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;AAGA,MAAa,sBAAsB;CAC/B,cAAc;EACV,SAAA;EACA,SAAA;CACJ;CACA,eAAe;GACkC,IAAA;GACb,IAAA;GACA,IAAA;CACpC;AACJ;AAEA,MAAa,gCAAgC;CACzC,cAAc;EACV,SAAA;EACA,SAAA;EACA,IAAA;CACJ;CACA,eAAe;GAC0C,IAAA;GACJ,IAAA;GACA,IAAA;GACL,IAAA;CAChD;AACJ;AAEA,MAAa,gCAAgC,EACzC,eAAe;EAC0C,IAAA;EACQ,IAAA;EACb,IAAA;EACK,IAAA;EACH,IAAA;EACF,IAAA;EACC,IAAA;EACE,IAAA;AACvD,EACJ;AAEA,MAAa,wCAAwC;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;AAKA,MAAa,mCAAmC,EAC5C,eAAe;EACuB,IAAA;EACK,IAAA;EACF,IAAA;EACG,IAAA;EACM,IAAA;EACN,IAAA;EACF,IAAA;EACQ,IAAA;EACC,IAAA;EACL,IAAA;EACD,KAAA;EACM,KAAA;EACH,KAAA;EACY,KAAA;EACnB,KAAA;EACc,KAAA;EACR,KAAA;EACA,KAAA;EACR,KAAA;EACI,KAAA;EACG,KAAA;EACI,KAAA;EACF,KAAA;EACD,KAAA;EACL,KAAA;EACK,KAAA;EACK,KAAA;EACK,KAAA;EACL,KAAA;EACK,KAAA;EACd,KAAA;EACS,KAAA;EACF,KAAA;EACV,KAAA;EACA,KAAA;EACQ,KAAA;EACJ,KAAA;EACK,KAAA;EACE,KAAA;EACV,KAAA;EACI,KAAA;EACS,KAAA;EACM,KAAA;EACL,KAAA;EACC,KAAA;AACxD,EACJ"}
|
|
@@ -9,7 +9,7 @@ declare const SocialVerificationMethodSchema: v.PicklistSchema<readonly ["profil
|
|
|
9
9
|
type SocialVerificationMethod = v.InferInput<typeof SocialVerificationMethodSchema>;
|
|
10
10
|
declare const SocialVerificationErrorCodeSchema: v.PicklistSchema<readonly ["username_invalid", "username_taken", "username_cooldown", "username_feature_locked", "username_reserved", "invalid_request", "authentication_required", "session_kind_not_allowed", "wallet_login_failed", "resource_not_found", "subaccount_access_denied", "api_key_access_denied", "api_key_invalid_status_transition", "policy_invalid", "smart_account_already_linked", "invite_access_denied", "invite_invalid_state", "mfa_disabled", "mfa_not_enrolled", "mfa_session_invalid", "mfa_challenge_not_found", "mfa_challenge_invalid", "mfa_challenge_locked", "mfa_otp_invalid", "mfa_recovery_invalid", "mfa_passkey_not_available", "mfa_passkey_credential_invalid", "mfa_passkey_verify_failed", "mfa_enrollment_binding_invalid", "step_up_required", "step_up_proof_unavailable", "step_up_already_claimed", "policy_in_use", "policy_locked", "policy_scope_mismatch", "revision_conflict", "mfa_elevation_required", "mfa_last_factor_required", "internal_error", "terms_not_accepted", "social_verification_expired", "social_verification_invalid_state", "subaccount_challenge_invalid", "social_account_already_linked"], undefined>;
|
|
11
11
|
type SocialVerificationErrorCode = v.InferOutput<typeof SocialVerificationErrorCodeSchema>;
|
|
12
|
-
declare const SocialVerificationStatusSchema: v.PicklistSchema<readonly ["pending_user_action", "queued", "in_progress", "verified", "failed", "expired", "
|
|
12
|
+
declare const SocialVerificationStatusSchema: v.PicklistSchema<readonly ["pending_user_action", "queued", "in_progress", "verified", "failed", "expired", "canceled"], undefined>;
|
|
13
13
|
type SocialVerificationStatus = v.InferOutput<typeof SocialVerificationStatusSchema>;
|
|
14
14
|
declare const SocialVerificationSchema: v.ObjectSchema<{
|
|
15
15
|
readonly id: v.BigintSchema<undefined>;
|
|
@@ -18,7 +18,7 @@ declare const SocialVerificationSchema: v.ObjectSchema<{
|
|
|
18
18
|
readonly handle: v.StringSchema<undefined>;
|
|
19
19
|
readonly providerUserId: v.StringSchema<undefined>;
|
|
20
20
|
readonly challengeCode: v.StringSchema<undefined>;
|
|
21
|
-
readonly status: v.PicklistSchema<readonly ["pending_user_action", "queued", "in_progress", "verified", "failed", "expired", "
|
|
21
|
+
readonly status: v.PicklistSchema<readonly ["pending_user_action", "queued", "in_progress", "verified", "failed", "expired", "canceled"], undefined>;
|
|
22
22
|
readonly requestedAt: v.OptionalSchema<v.ObjectSchema<{
|
|
23
23
|
readonly seconds: v.BigintSchema<undefined>;
|
|
24
24
|
readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
|