@polyester/sdk 0.14.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/core-client.js +1 -1
- package/dist/gen/fees/v1/fees_pb.d.ts +4 -2
- package/dist/gen/fees/v1/fees_pb.d.ts.map +1 -1
- package/dist/gen/fees/v1/fees_pb.js +9 -1
- package/dist/gen/fees/v1/fees_pb.js.map +1 -1
- package/dist/gen/index.d.ts +4 -1
- package/dist/gen/index.js +4 -1
- package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts +4 -2
- package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts.map +1 -1
- package/dist/gen/ratelimit/v1/ratelimit_pb.js +13 -1
- package/dist/gen/ratelimit/v1/ratelimit_pb.js.map +1 -1
- package/dist/gen/vip/v1/vip_pb.d.ts +4 -2
- package/dist/gen/vip/v1/vip_pb.d.ts.map +1 -1
- package/dist/gen/vip/v1/vip_pb.js +12 -1
- package/dist/gen/vip/v1/vip_pb.js.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.js +2 -1
- package/dist/services/address-book/address-book.schemas.js.map +1 -1
- package/dist/services/candles/candles.d.ts.map +1 -1
- package/dist/services/candles/candles.js +2 -1
- package/dist/services/candles/candles.js.map +1 -1
- package/dist/services/candles/candles.schemas.d.ts +1 -1
- package/dist/services/candles/candles.schemas.d.ts.map +1 -1
- package/dist/services/candles/candles.schemas.js +3 -2
- package/dist/services/candles/candles.schemas.js.map +1 -1
- package/dist/services/chain-analytics/chain-analytics.schemas.d.ts.map +1 -1
- package/dist/services/chain-analytics/chain-analytics.schemas.js +5 -5
- package/dist/services/chain-analytics/chain-analytics.schemas.js.map +1 -1
- package/dist/services/deposit/deposit.schemas.d.ts +3 -3
- package/dist/services/deposit/deposit.schemas.d.ts.map +1 -1
- package/dist/services/deposit/deposit.schemas.js +4 -4
- package/dist/services/deposit/deposit.schemas.js.map +1 -1
- package/dist/services/guard-signer/guard-signer.schemas.d.ts +2 -2
- package/dist/services/guard-signer/guard-signer.schemas.d.ts.map +1 -1
- package/dist/services/guard-signer/guard-signer.schemas.js +2 -1
- package/dist/services/guard-signer/guard-signer.schemas.js.map +1 -1
- package/dist/services/heatmap/heatmap.d.ts.map +1 -1
- package/dist/services/heatmap/heatmap.js +2 -1
- package/dist/services/heatmap/heatmap.js.map +1 -1
- package/dist/services/heatmap/heatmap.schemas.d.ts +1 -1
- package/dist/services/heatmap/heatmap.schemas.d.ts.map +1 -1
- package/dist/services/heatmap/heatmap.schemas.js +2 -1
- package/dist/services/heatmap/heatmap.schemas.js.map +1 -1
- package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +2 -2
- package/dist/services/internal-transfers/internal-transfers.schemas.d.ts.map +1 -1
- package/dist/services/internal-transfers/internal-transfers.schemas.js +3 -2
- package/dist/services/internal-transfers/internal-transfers.schemas.js.map +1 -1
- package/dist/services/market-data/market-data.d.ts.map +1 -1
- package/dist/services/market-data/market-data.js +2 -1
- package/dist/services/market-data/market-data.js.map +1 -1
- package/dist/services/market-data/market-data.schemas.d.ts +1 -1
- package/dist/services/market-data/market-data.schemas.js +2 -2
- package/dist/services/market-data/market-data.schemas.js.map +1 -1
- package/dist/services/market-overview/market-overview.schemas.d.ts +1 -1
- package/dist/services/market-overview/market-overview.schemas.js +2 -2
- package/dist/services/market-overview/market-overview.schemas.js.map +1 -1
- package/dist/services/orders/orders-modify.schemas.js +1 -1
- package/dist/services/orders/orders-risk.schemas.d.ts.map +1 -1
- package/dist/services/orders/orders-risk.schemas.js +3 -4
- package/dist/services/orders/orders-risk.schemas.js.map +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +9 -9
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts.map +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +17 -8
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js.map +1 -1
- package/dist/services/shared.js +4 -2
- package/dist/services/shared.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +4 -4
- package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts +2 -2
- package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts.map +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js +3 -2
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js.map +1 -1
- package/dist/services/trailing-oneof-inputs.js +3 -1
- package/dist/services/trailing-oneof-inputs.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.js +3 -3
- package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
- package/dist/shared/decimal-surface.d.ts.map +1 -1
- package/dist/shared/decimal-surface.js.map +1 -1
- package/dist/shared/schemas.js +4 -4
- package/dist/shared/schemas.js.map +1 -1
- package/dist/utils/numbers.js +1 -10
- package/dist/utils/numbers.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import "../../gen/orders/v1/orders_pb.js";
|
|
2
2
|
import { idToBigInt } from "../../utils/base58-id.js";
|
|
3
3
|
import { parseOptionalPositiveBigIntLike, parseOptionalPositiveIntLike } from "../../utils/numbers.js";
|
|
4
|
+
import { PROTOBUF_INT64_MAX } from "../../shared/wire-bounds.js";
|
|
4
5
|
import { idInputSchema } from "../../shared/schemas.js";
|
|
5
|
-
import { PROTOBUF_INT32_MAX, PROTOBUF_INT64_MAX } from "../../shared/wire-bounds.js";
|
|
6
6
|
import { BpsStringOrNumberInputSchema, NoneInputSchema, SymbolIdInputSchema } from "../shared.js";
|
|
7
7
|
import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
|
|
8
8
|
import { positiveDecimalInputToScaled } from "../../shared/decimal-surface.js";
|
|
9
9
|
import { OrderSideCodec } from "../orders/order-enums.codecs.js";
|
|
10
|
-
import { parseSlippageInput, parseTrailingDistanceInput } from "../trailing-oneof-inputs.js";
|
|
10
|
+
import { MAX_SLIPPAGE_BPS, parseSlippageInput, parseTrailingDistanceInput } from "../trailing-oneof-inputs.js";
|
|
11
11
|
import "../../gen/triggers/v1/triggers_pb.js";
|
|
12
12
|
import { TRIGGER_EVENT_TYPE_VALUES, TRIGGER_STATUS_FILTER_VALUES, TRIGGER_TYPE_VALUES, TriggerEventTypeCodec, TriggerStatusCodec, TriggerTypeCodec } from "./triggers.codecs.js";
|
|
13
13
|
import { BaseTriggerFieldsSchema, ConditionalExecutionInputSchema, DecimalInputStringSchema, LimitConditionalExecutionInputSchema, TriggerSideInputSchema, TwapExecutionInputSchema, buildConditionalExecution, buildTriggerIntentBase, buildTwapExecution } from "./trigger-child-order.schemas.js";
|
|
@@ -59,7 +59,7 @@ function parseMaxSlippage(scales, slippage) {
|
|
|
59
59
|
fieldName: "maxSlippage",
|
|
60
60
|
ticksCase: "maxSlippageTicks",
|
|
61
61
|
bpsCase: "maxSlippageBps",
|
|
62
|
-
maxBps:
|
|
62
|
+
maxBps: MAX_SLIPPAGE_BPS
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
65
|
function parseMaxSlippagePatch(scales, slippage) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trigger-input.schemas.js","names":["TriggerSideCodec"],"sources":["../../../src/services/triggers/trigger-input.schemas.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport * as ProtoOrders from \"../../gen/orders/v1/orders_pb.js\";\nimport * as v from \"valibot\";\nimport { idInputSchema } from \"../../shared/schemas.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { positiveDecimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { PROTOBUF_INT32_MAX, PROTOBUF_INT64_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n parseOptionalPositiveBigIntLike,\n parseOptionalPositiveIntLike,\n} from \"../../utils/numbers.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport {\n TRIGGER_EVENT_TYPE_VALUES,\n TRIGGER_STATUS_FILTER_VALUES,\n TRIGGER_TYPE_VALUES,\n TriggerEventTypeCodec,\n TriggerSideCodec,\n TriggerTypeCodec,\n TriggerStatusCodec,\n} from \"./triggers.codecs.js\";\nimport { BpsStringOrNumberInputSchema, NoneInputSchema, SymbolIdInputSchema } from \"../shared.js\";\nimport {\n BaseTriggerFieldsSchema,\n ConditionalExecutionInputSchema,\n DecimalInputStringSchema,\n LimitConditionalExecutionInputSchema,\n TriggerSideInputSchema,\n TwapExecutionInputSchema,\n buildConditionalExecution,\n buildTriggerIntentBase,\n buildTwapExecution,\n type MaxSlippageOneof,\n type TrailingDistanceOneof,\n} from \"./trigger-child-order.schemas.js\";\nimport { parseSlippageInput, parseTrailingDistanceInput } from \"../trailing-oneof-inputs.js\";\n\nconst TriggerTypeSchema = v.picklist(TRIGGER_TYPE_VALUES);\nconst TriggerStatusFilterSchema = v.picklist(TRIGGER_STATUS_FILTER_VALUES);\nconst TriggerEventTypeSchema = v.picklist(TRIGGER_EVENT_TYPE_VALUES);\nconst TriggerIdInputSchema = idInputSchema(\"triggerId\");\n\nconst TriggerScopedInputEntries = {\n triggerId: TriggerIdInputSchema,\n ...AccountScopeInputEntries,\n};\n\nconst TriggerScopedInputSchema = v.pipe(\n v.strictObject(TriggerScopedInputEntries),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\n/** Absolute price distance, as a decimal price string (e.g. \"0.50\"). */\nconst PriceDistanceInputSchema = v.strictObject({\n kind: v.literal(\"distance\"),\n distance: DecimalInputStringSchema,\n});\n\n/** Absolute price slippage, as a decimal price string (e.g. \"0.25\"). */\nconst PriceSlippageInputSchema = v.strictObject({\n kind: v.literal(\"slippage\"),\n slippage: DecimalInputStringSchema,\n});\n\nconst TrailingDistanceInputSchema = v.union([\n PriceDistanceInputSchema,\n BpsStringOrNumberInputSchema,\n]);\n\nconst MaxSlippageInputSchema = v.union([\n PriceSlippageInputSchema,\n BpsStringOrNumberInputSchema,\n NoneInputSchema,\n]);\n\nconst MaxSlippagePatchInputSchema = v.union([\n PriceSlippageInputSchema,\n BpsStringOrNumberInputSchema,\n NoneInputSchema,\n]);\n\nconst ActivationPricePatchInputSchema = v.union([DecimalInputStringSchema, NoneInputSchema]);\n\nfunction parseTrailingDistance(\n scales: SdkScales,\n distance: v.InferOutput<typeof TrailingDistanceInputSchema>,\n): TrailingDistanceOneof {\n return parseTrailingDistanceInput(scales, distance, \"trailingDistance\");\n}\n\nfunction parseTwapMilliseconds(\n value: string | number,\n fieldName: \"durationMs\" | \"sliceIntervalMs\",\n minimum: bigint,\n): bigint {\n const parsed = parseOptionalPositiveBigIntLike(value);\n if (parsed === undefined || parsed < minimum || parsed > PROTOBUF_INT64_MAX) {\n throw new Error(\n `${fieldName} must be between ${minimum} and ${PROTOBUF_INT64_MAX} milliseconds`,\n );\n }\n return parsed;\n}\n\nfunction parseMaxSlippage(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippageInputSchema> | undefined,\n): MaxSlippageOneof {\n return parseSlippageInput(scales, slippage, {\n fieldName: \"maxSlippage\",\n ticksCase: \"maxSlippageTicks\",\n bpsCase: \"maxSlippageBps\",\n maxBps: Number(PROTOBUF_INT32_MAX),\n });\n}\n\nfunction parseMaxSlippagePatch(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippagePatchInputSchema>,\n): MaxSlippageOneof {\n if (slippage.kind === \"none\") {\n return { case: \"maxSlippageTicks\", value: 0 };\n }\n return parseMaxSlippage(scales, slippage);\n}\n\nfunction createConditionalTriggerInputSchema<const TriggerType extends \"stop_loss\" | \"take_profit\">(\n scales: SdkScales,\n triggerType: TriggerType,\n) {\n const sharedEntries = {\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(triggerType),\n triggerPrice: DecimalInputStringSchema,\n };\n\n const sellInputSchema = v.strictObject({\n ...sharedEntries,\n side: v.literal(\"sell\"),\n execution: ConditionalExecutionInputSchema,\n });\n const buyInputSchema = v.strictObject({\n ...sharedEntries,\n side: v.literal(\"buy\"),\n execution: LimitConditionalExecutionInputSchema,\n });\n\n function transformInput(\n input: v.InferOutput<typeof sellInputSchema> | v.InferOutput<typeof buyInputSchema>,\n ) {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n const strategy = {\n triggerPriceTicks: positiveDecimalInputToScaled(\n \"triggerPrice\",\n input.triggerPrice,\n scales.price(),\n ),\n side: TriggerSideCodec.inputToProto[input.side],\n child: buildConditionalExecution(input.execution, scales),\n };\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy:\n triggerType === \"stop_loss\"\n ? ({ case: \"stopLoss\", value: strategy } as const)\n : ({ case: \"takeProfit\", value: strategy } as const),\n },\n };\n }\n\n return [\n v.pipe(\n sellInputSchema,\n v.check(\n (input) => input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.transform((input: v.InferOutput<typeof sellInputSchema>) => transformInput(input)),\n ),\n v.pipe(\n buyInputSchema,\n v.transform((input: v.InferOutput<typeof buyInputSchema>) => transformInput(input)),\n ),\n ] as const;\n}\n\nfunction createTrailingStopTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"trailing_stop\"),\n trailingDistance: TrailingDistanceInputSchema,\n activationPrice: v.optional(DecimalInputStringSchema),\n maxSlippage: v.optional(MaxSlippageInputSchema),\n }),\n v.check(\n (input) => input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"Trailing-stop triggers must use the quote fee asset\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"trailingStop\",\n value: {\n trailingDistance: parseTrailingDistance(scales, input.trailingDistance),\n activationPriceTicks:\n input.activationPrice === undefined\n ? 0n\n : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage: parseMaxSlippage(scales, input.maxSlippage),\n side: ProtoOrders.Side.SELL,\n },\n } as const,\n },\n };\n }),\n );\n}\n\nfunction createTwapTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"twap\"),\n side: TriggerSideInputSchema,\n durationMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => parseTwapMilliseconds(value, \"durationMs\", 1_000n)),\n ),\n sliceIntervalMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => parseTwapMilliseconds(value, \"sliceIntervalMs\", 100n)),\n ),\n execution: TwapExecutionInputSchema,\n }),\n v.check(\n (input) =>\n input.side !== ProtoOrders.Side.SELL ||\n input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.check(\n (input) => input.sliceIntervalMs <= input.durationMs,\n \"sliceIntervalMs cannot exceed durationMs\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"twap\",\n value: {\n side: input.side,\n durationMs: input.durationMs,\n sliceIntervalMs: input.sliceIntervalMs,\n execution: buildTwapExecution(input.execution, scales),\n },\n } as const,\n },\n };\n }),\n );\n}\n\nfunction createLadderTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"ladder\"),\n side: TriggerSideInputSchema,\n priceMin: DecimalInputStringSchema,\n priceMax: DecimalInputStringSchema,\n levels: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.pipe(v.number(), v.integer())]),\n v.transform((value) => {\n const levels = parseOptionalPositiveIntLike(value);\n if (!levels || levels < 2 || levels > 100) {\n throw new Error(\"levels must be between 2 and 100\");\n }\n return levels;\n }),\n ),\n postOnly: v.optional(v.boolean(), false),\n }),\n v.check(\n (input) =>\n input.side !== ProtoOrders.Side.SELL ||\n input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"ladder\",\n value: {\n side: input.side,\n priceMinTicks: positiveDecimalInputToScaled(\n \"priceMin\",\n input.priceMin,\n scales.price(),\n ),\n priceMaxTicks: positiveDecimalInputToScaled(\n \"priceMax\",\n input.priceMax,\n scales.price(),\n ),\n levels: input.levels,\n postOnly: input.postOnly,\n },\n } as const,\n },\n };\n }),\n v.check(\n (output) =>\n output.trigger.strategy.value.priceMinTicks <\n output.trigger.strategy.value.priceMaxTicks,\n \"priceMin must be less than priceMax\",\n ),\n );\n}\n\n/** Builds the create-trigger boundary schema using catalog scales keyed by symbol ID. */\nexport function createCreateTriggerInputSchema(scales: SdkScales) {\n return v.union([\n ...createConditionalTriggerInputSchema(scales, \"stop_loss\"),\n ...createConditionalTriggerInputSchema(scales, \"take_profit\"),\n createTrailingStopTriggerInputSchema(scales),\n createTwapTriggerInputSchema(scales),\n createLadderTriggerInputSchema(scales),\n ]);\n}\n\n/** Public input for creating a standalone trigger. */\nexport type CreateTriggerInput = v.InferInput<ReturnType<typeof createCreateTriggerInputSchema>>;\n\n/** Public filters for listing triggers in an account scope. */\nexport const ListTriggersInputSchema = v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n parentOrderId: v.pipe(\n v.optional(v.pipe(v.string(), v.trim())),\n v.transform((value) => (value ? idToBigInt(value, \"parentOrderId\") : undefined)),\n ),\n symbolId: v.optional(SymbolIdInputSchema),\n status: v.pipe(\n v.optional(v.array(TriggerStatusFilterSchema)),\n v.transform(\n (values) => values?.map((value) => TriggerStatusCodec.inputToProto[value]) ?? [],\n ),\n ),\n triggerType: v.pipe(\n v.optional(TriggerTypeSchema),\n v.transform((value) =>\n value\n ? TriggerTypeCodec.inputToProto[value]\n : Proto.TriggerType.TRIGGER_TYPE_UNSPECIFIED,\n ),\n ),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(1000)), 50),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\n/** Public filters for listing triggers. */\nexport type ListTriggersInput = v.InferInput<typeof ListTriggersInputSchema>;\n\nexport const CancelTriggerInputSchema = TriggerScopedInputSchema;\nexport type CancelTriggerInput = v.InferInput<typeof CancelTriggerInputSchema>;\n\nexport const GetTriggerInputSchema = CancelTriggerInputSchema;\nexport type GetTriggerInput = v.InferInput<typeof GetTriggerInputSchema>;\n\nexport const PauseTriggerInputSchema = TriggerScopedInputSchema;\nexport type PauseTriggerInput = v.InferInput<typeof PauseTriggerInputSchema>;\n\nexport const ResumeTriggerInputSchema = v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n symbolId: SymbolIdInputSchema,\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\nexport type ResumeTriggerInput = v.InferInput<typeof ResumeTriggerInputSchema>;\n\nexport function createModifyTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n symbolId: SymbolIdInputSchema,\n triggerPrice: v.optional(DecimalInputStringSchema),\n limitPrice: v.optional(DecimalInputStringSchema),\n trailingDistance: v.optional(TrailingDistanceInputSchema),\n activationPrice: v.optional(ActivationPricePatchInputSchema),\n maxSlippage: v.optional(MaxSlippagePatchInputSchema),\n }),\n v.check(\n (input) =>\n input.triggerPrice !== undefined ||\n input.limitPrice !== undefined ||\n input.trailingDistance !== undefined ||\n input.activationPrice !== undefined ||\n input.maxSlippage !== undefined,\n \"At least one patch field is required\",\n ),\n v.transform(({ account, ...input }) => ({\n triggerId: input.triggerId,\n subaccountId: accountScopeToSubaccountId(account),\n symbolId: input.symbolId,\n triggerPriceTicks:\n input.triggerPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\n \"triggerPrice\",\n input.triggerPrice,\n scales.price(),\n ),\n limitPriceTicks:\n input.limitPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\"limitPrice\", input.limitPrice, scales.price()),\n trailingDistance:\n input.trailingDistance === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseTrailingDistance(scales, input.trailingDistance),\n activationPriceTicks:\n input.activationPrice === undefined\n ? undefined\n : typeof input.activationPrice !== \"string\"\n ? 0n\n : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage:\n input.maxSlippage === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseMaxSlippagePatch(scales, input.maxSlippage),\n })),\n );\n}\n\n/**\n * A trigger patch. Omitted fields remain unchanged; `{ kind: \"none\" }` clears\n * `activationPrice` or `maxSlippage`.\n */\nexport type ModifyTriggerInput = v.InferInput<ReturnType<typeof createModifyTriggerInputSchema>>;\n\nexport const ListTriggerEventsInputSchema = v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n limit: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(1000))),\n eventType: v.optional(TriggerEventTypeSchema),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n eventType:\n input.eventType === undefined\n ? undefined\n : TriggerEventTypeCodec.inputToProto[input.eventType],\n })),\n);\n\nexport type ListTriggerEventsInput = v.InferInput<typeof ListTriggerEventsInputSchema>;\n"],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AAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE;AAC1D,CAAC,GACD,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;CAChD,WACI,MAAM,cAAc,KAAA,IACd,KAAA,IACA,sBAAsB,aAAa,MAAM;AACvD,EAAE,CACN"}
|
|
1
|
+
{"version":3,"file":"trigger-input.schemas.js","names":["TriggerSideCodec"],"sources":["../../../src/services/triggers/trigger-input.schemas.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport * as ProtoOrders from \"../../gen/orders/v1/orders_pb.js\";\nimport * as v from \"valibot\";\nimport { idInputSchema } from \"../../shared/schemas.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { positiveDecimalInputToScaled, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { PROTOBUF_INT64_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n parseOptionalPositiveBigIntLike,\n parseOptionalPositiveIntLike,\n} from \"../../utils/numbers.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport {\n TRIGGER_EVENT_TYPE_VALUES,\n TRIGGER_STATUS_FILTER_VALUES,\n TRIGGER_TYPE_VALUES,\n TriggerEventTypeCodec,\n TriggerSideCodec,\n TriggerTypeCodec,\n TriggerStatusCodec,\n} from \"./triggers.codecs.js\";\nimport { BpsStringOrNumberInputSchema, NoneInputSchema, SymbolIdInputSchema } from \"../shared.js\";\nimport {\n BaseTriggerFieldsSchema,\n ConditionalExecutionInputSchema,\n DecimalInputStringSchema,\n LimitConditionalExecutionInputSchema,\n TriggerSideInputSchema,\n TwapExecutionInputSchema,\n buildConditionalExecution,\n buildTriggerIntentBase,\n buildTwapExecution,\n type MaxSlippageOneof,\n type TrailingDistanceOneof,\n} from \"./trigger-child-order.schemas.js\";\nimport {\n MAX_SLIPPAGE_BPS,\n parseSlippageInput,\n parseTrailingDistanceInput,\n} from \"../trailing-oneof-inputs.js\";\n\nconst TriggerTypeSchema = v.picklist(TRIGGER_TYPE_VALUES);\nconst TriggerStatusFilterSchema = v.picklist(TRIGGER_STATUS_FILTER_VALUES);\nconst TriggerEventTypeSchema = v.picklist(TRIGGER_EVENT_TYPE_VALUES);\nconst TriggerIdInputSchema = idInputSchema(\"triggerId\");\n\nconst TriggerScopedInputEntries = {\n triggerId: TriggerIdInputSchema,\n ...AccountScopeInputEntries,\n};\n\nconst TriggerScopedInputSchema = v.pipe(\n v.strictObject(TriggerScopedInputEntries),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\n/** Absolute price distance, as a decimal price string (e.g. \"0.50\"). */\nconst PriceDistanceInputSchema = v.strictObject({\n kind: v.literal(\"distance\"),\n distance: DecimalInputStringSchema,\n});\n\n/** Absolute price slippage, as a decimal price string (e.g. \"0.25\"). */\nconst PriceSlippageInputSchema = v.strictObject({\n kind: v.literal(\"slippage\"),\n slippage: DecimalInputStringSchema,\n});\n\nconst TrailingDistanceInputSchema = v.union([\n PriceDistanceInputSchema,\n BpsStringOrNumberInputSchema,\n]);\n\nconst MaxSlippageInputSchema = v.union([\n PriceSlippageInputSchema,\n BpsStringOrNumberInputSchema,\n NoneInputSchema,\n]);\n\nconst MaxSlippagePatchInputSchema = v.union([\n PriceSlippageInputSchema,\n BpsStringOrNumberInputSchema,\n NoneInputSchema,\n]);\n\nconst ActivationPricePatchInputSchema = v.union([DecimalInputStringSchema, NoneInputSchema]);\n\nfunction parseTrailingDistance(\n scales: SdkScales,\n distance: v.InferOutput<typeof TrailingDistanceInputSchema>,\n): TrailingDistanceOneof {\n return parseTrailingDistanceInput(scales, distance, \"trailingDistance\");\n}\n\nfunction parseTwapMilliseconds(\n value: string | number,\n fieldName: \"durationMs\" | \"sliceIntervalMs\",\n minimum: bigint,\n): bigint {\n const parsed = parseOptionalPositiveBigIntLike(value);\n if (parsed === undefined || parsed < minimum || parsed > PROTOBUF_INT64_MAX) {\n throw new Error(\n `${fieldName} must be between ${minimum} and ${PROTOBUF_INT64_MAX} milliseconds`,\n );\n }\n return parsed;\n}\n\nfunction parseMaxSlippage(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippageInputSchema> | undefined,\n): MaxSlippageOneof {\n return parseSlippageInput(scales, slippage, {\n fieldName: \"maxSlippage\",\n ticksCase: \"maxSlippageTicks\",\n bpsCase: \"maxSlippageBps\",\n maxBps: MAX_SLIPPAGE_BPS,\n });\n}\n\nfunction parseMaxSlippagePatch(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippagePatchInputSchema>,\n): MaxSlippageOneof {\n if (slippage.kind === \"none\") {\n return { case: \"maxSlippageTicks\", value: 0 };\n }\n return parseMaxSlippage(scales, slippage);\n}\n\nfunction createConditionalTriggerInputSchema<const TriggerType extends \"stop_loss\" | \"take_profit\">(\n scales: SdkScales,\n triggerType: TriggerType,\n) {\n const sharedEntries = {\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(triggerType),\n triggerPrice: DecimalInputStringSchema,\n };\n\n const sellInputSchema = v.strictObject({\n ...sharedEntries,\n side: v.literal(\"sell\"),\n execution: ConditionalExecutionInputSchema,\n });\n const buyInputSchema = v.strictObject({\n ...sharedEntries,\n side: v.literal(\"buy\"),\n execution: LimitConditionalExecutionInputSchema,\n });\n\n function transformInput(\n input: v.InferOutput<typeof sellInputSchema> | v.InferOutput<typeof buyInputSchema>,\n ) {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n const strategy = {\n triggerPriceTicks: positiveDecimalInputToScaled(\n \"triggerPrice\",\n input.triggerPrice,\n scales.price(),\n ),\n side: TriggerSideCodec.inputToProto[input.side],\n child: buildConditionalExecution(input.execution, scales),\n };\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy:\n triggerType === \"stop_loss\"\n ? ({ case: \"stopLoss\", value: strategy } as const)\n : ({ case: \"takeProfit\", value: strategy } as const),\n },\n };\n }\n\n return [\n v.pipe(\n sellInputSchema,\n v.check(\n (input) => input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.transform((input: v.InferOutput<typeof sellInputSchema>) => transformInput(input)),\n ),\n v.pipe(\n buyInputSchema,\n v.transform((input: v.InferOutput<typeof buyInputSchema>) => transformInput(input)),\n ),\n ] as const;\n}\n\nfunction createTrailingStopTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"trailing_stop\"),\n trailingDistance: TrailingDistanceInputSchema,\n activationPrice: v.optional(DecimalInputStringSchema),\n maxSlippage: v.optional(MaxSlippageInputSchema),\n }),\n v.check(\n (input) => input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"Trailing-stop triggers must use the quote fee asset\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"trailingStop\",\n value: {\n trailingDistance: parseTrailingDistance(scales, input.trailingDistance),\n activationPriceTicks:\n input.activationPrice === undefined\n ? 0n\n : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage: parseMaxSlippage(scales, input.maxSlippage),\n side: ProtoOrders.Side.SELL,\n },\n } as const,\n },\n };\n }),\n );\n}\n\nfunction createTwapTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"twap\"),\n side: TriggerSideInputSchema,\n durationMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => parseTwapMilliseconds(value, \"durationMs\", 1_000n)),\n ),\n sliceIntervalMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => parseTwapMilliseconds(value, \"sliceIntervalMs\", 100n)),\n ),\n execution: TwapExecutionInputSchema,\n }),\n v.check(\n (input) =>\n input.side !== ProtoOrders.Side.SELL ||\n input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.check(\n (input) => input.sliceIntervalMs <= input.durationMs,\n \"sliceIntervalMs cannot exceed durationMs\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"twap\",\n value: {\n side: input.side,\n durationMs: input.durationMs,\n sliceIntervalMs: input.sliceIntervalMs,\n execution: buildTwapExecution(input.execution, scales),\n },\n } as const,\n },\n };\n }),\n );\n}\n\nfunction createLadderTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...BaseTriggerFieldsSchema.entries,\n triggerType: v.literal(\"ladder\"),\n side: TriggerSideInputSchema,\n priceMin: DecimalInputStringSchema,\n priceMax: DecimalInputStringSchema,\n levels: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.pipe(v.number(), v.integer())]),\n v.transform((value) => {\n const levels = parseOptionalPositiveIntLike(value);\n if (!levels || levels < 2 || levels > 100) {\n throw new Error(\"levels must be between 2 and 100\");\n }\n return levels;\n }),\n ),\n postOnly: v.optional(v.boolean(), false),\n }),\n v.check(\n (input) =>\n input.side !== ProtoOrders.Side.SELL ||\n input.feeAsset === ProtoOrders.FeeAsset.QUOTE,\n \"SELL triggers must use the quote fee asset\",\n ),\n v.transform((input) => {\n const { subaccountId, intent } = buildTriggerIntentBase(input, scales);\n return {\n subaccountId,\n trigger: {\n ...intent,\n strategy: {\n case: \"ladder\",\n value: {\n side: input.side,\n priceMinTicks: positiveDecimalInputToScaled(\n \"priceMin\",\n input.priceMin,\n scales.price(),\n ),\n priceMaxTicks: positiveDecimalInputToScaled(\n \"priceMax\",\n input.priceMax,\n scales.price(),\n ),\n levels: input.levels,\n postOnly: input.postOnly,\n },\n } as const,\n },\n };\n }),\n v.check(\n (output) =>\n output.trigger.strategy.value.priceMinTicks <\n output.trigger.strategy.value.priceMaxTicks,\n \"priceMin must be less than priceMax\",\n ),\n );\n}\n\n/** Builds the create-trigger boundary schema using catalog scales keyed by symbol ID. */\nexport function createCreateTriggerInputSchema(scales: SdkScales) {\n return v.union([\n ...createConditionalTriggerInputSchema(scales, \"stop_loss\"),\n ...createConditionalTriggerInputSchema(scales, \"take_profit\"),\n createTrailingStopTriggerInputSchema(scales),\n createTwapTriggerInputSchema(scales),\n createLadderTriggerInputSchema(scales),\n ]);\n}\n\n/** Public input for creating a standalone trigger. */\nexport type CreateTriggerInput = v.InferInput<ReturnType<typeof createCreateTriggerInputSchema>>;\n\n/** Public filters for listing triggers in an account scope. */\nexport const ListTriggersInputSchema = v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n parentOrderId: v.pipe(\n v.optional(v.pipe(v.string(), v.trim())),\n v.transform((value) => (value ? idToBigInt(value, \"parentOrderId\") : undefined)),\n ),\n symbolId: v.optional(SymbolIdInputSchema),\n status: v.pipe(\n v.optional(v.array(TriggerStatusFilterSchema)),\n v.transform(\n (values) => values?.map((value) => TriggerStatusCodec.inputToProto[value]) ?? [],\n ),\n ),\n triggerType: v.pipe(\n v.optional(TriggerTypeSchema),\n v.transform((value) =>\n value\n ? TriggerTypeCodec.inputToProto[value]\n : Proto.TriggerType.TRIGGER_TYPE_UNSPECIFIED,\n ),\n ),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(1000)), 50),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\n\n/** Public filters for listing triggers. */\nexport type ListTriggersInput = v.InferInput<typeof ListTriggersInputSchema>;\n\nexport const CancelTriggerInputSchema = TriggerScopedInputSchema;\nexport type CancelTriggerInput = v.InferInput<typeof CancelTriggerInputSchema>;\n\nexport const GetTriggerInputSchema = CancelTriggerInputSchema;\nexport type GetTriggerInput = v.InferInput<typeof GetTriggerInputSchema>;\n\nexport const PauseTriggerInputSchema = TriggerScopedInputSchema;\nexport type PauseTriggerInput = v.InferInput<typeof PauseTriggerInputSchema>;\n\nexport const ResumeTriggerInputSchema = v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n symbolId: SymbolIdInputSchema,\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n })),\n);\nexport type ResumeTriggerInput = v.InferInput<typeof ResumeTriggerInputSchema>;\n\nexport function createModifyTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n symbolId: SymbolIdInputSchema,\n triggerPrice: v.optional(DecimalInputStringSchema),\n limitPrice: v.optional(DecimalInputStringSchema),\n trailingDistance: v.optional(TrailingDistanceInputSchema),\n activationPrice: v.optional(ActivationPricePatchInputSchema),\n maxSlippage: v.optional(MaxSlippagePatchInputSchema),\n }),\n v.check(\n (input) =>\n input.triggerPrice !== undefined ||\n input.limitPrice !== undefined ||\n input.trailingDistance !== undefined ||\n input.activationPrice !== undefined ||\n input.maxSlippage !== undefined,\n \"At least one patch field is required\",\n ),\n v.transform(({ account, ...input }) => ({\n triggerId: input.triggerId,\n subaccountId: accountScopeToSubaccountId(account),\n symbolId: input.symbolId,\n triggerPriceTicks:\n input.triggerPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\n \"triggerPrice\",\n input.triggerPrice,\n scales.price(),\n ),\n limitPriceTicks:\n input.limitPrice === undefined\n ? undefined\n : positiveDecimalInputToScaled(\"limitPrice\", input.limitPrice, scales.price()),\n trailingDistance:\n input.trailingDistance === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseTrailingDistance(scales, input.trailingDistance),\n activationPriceTicks:\n input.activationPrice === undefined\n ? undefined\n : typeof input.activationPrice !== \"string\"\n ? 0n\n : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage:\n input.maxSlippage === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseMaxSlippagePatch(scales, input.maxSlippage),\n })),\n );\n}\n\n/**\n * A trigger patch. Omitted fields remain unchanged; `{ kind: \"none\" }` clears\n * `activationPrice` or `maxSlippage`.\n */\nexport type ModifyTriggerInput = v.InferInput<ReturnType<typeof createModifyTriggerInputSchema>>;\n\nexport const ListTriggerEventsInputSchema = v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n limit: v.optional(v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(1000))),\n eventType: v.optional(TriggerEventTypeSchema),\n pageToken: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n }),\n v.transform(({ account, ...input }) => ({\n ...input,\n subaccountId: accountScopeToSubaccountId(account),\n eventType:\n input.eventType === undefined\n ? undefined\n : TriggerEventTypeCodec.inputToProto[input.eventType],\n })),\n);\n\nexport type ListTriggerEventsInput = v.InferInput<typeof ListTriggerEventsInputSchema>;\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,MAAM,oBAAoB,EAAE,SAAS,mBAAmB;AACxD,MAAM,4BAA4B,EAAE,SAAS,4BAA4B;AACzE,MAAM,yBAAyB,EAAE,SAAS,yBAAyB;AAGnE,MAAM,4BAA4B;CAC9B,WAHyB,cAAc,WAGT;CAC9B,GAAG;AACP;AAEA,MAAM,2BAA2B,EAAE,KAC/B,EAAE,aAAa,yBAAyB,GACxC,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;AACpD,EAAE,CACN;;AAGA,MAAM,2BAA2B,EAAE,aAAa;CAC5C,MAAM,EAAE,QAAQ,UAAU;CAC1B,UAAU;AACd,CAAC;;AAGD,MAAM,2BAA2B,EAAE,aAAa;CAC5C,MAAM,EAAE,QAAQ,UAAU;CAC1B,UAAU;AACd,CAAC;AAED,MAAM,8BAA8B,EAAE,MAAM,CACxC,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O,MAAM,CAAC;EACrF,kBACI,MAAM,qBAAqB,KAAA,IACpB;GAAE,MAAM,KAAA;GAAW,OAAO,KAAA;EAAU,IACrC,sBAAsB,QAAQ,MAAM,gBAAgB;EAC9D,sBACI,MAAM,oBAAoB,KAAA,IACpB,KAAA,IACA,OAAO,MAAM,oBAAoB,WAC/B,KACA,6BACI,mBACA,MAAM,iBACN,OAAO,MAAM,CACjB;EACZ,aACI,MAAM,gBAAgB,KAAA,IACf;GAAE,MAAM,KAAA;GAAW,OAAO,KAAA;EAAU,IACrC,sBAAsB,QAAQ,MAAM,WAAW;CAC7D,EAAE,CACN;AACJ;AAQA,MAAa,+BAA+B,EAAE,KAC1C,EAAE,aAAa;CACX,GAAG;CACH,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,QAAQ,CAAC,GAAG,EAAE,SAAS,GAAI,CAAC,CAAC;CACjF,WAAW,EAAE,SAAS,sBAAsB;CAC5C,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE;AAC1D,CAAC,GACD,EAAE,WAAW,EAAE,SAAS,GAAG,aAAa;CACpC,GAAG;CACH,cAAc,2BAA2B,OAAO;CAChD,WACI,MAAM,cAAc,KAAA,IACd,KAAA,IACA,sBAAsB,aAAa,MAAM;AACvD,EAAE,CACN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decimal-surface.d.ts","names":[],"sources":["../../src/shared/decimal-surface.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"decimal-surface.d.ts","names":[],"sources":["../../src/shared/decimal-surface.ts"],"mappings":";;;;;;;UAwCiB;EACb,SAAS;EACT;EACA,QAAQ,MAAM;EACd,YAAY,MAAM;EAClB,aAAa;EACb,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decimal-surface.js","names":[],"sources":["../../src/shared/decimal-surface.ts"],"sourcesContent":["/**\n * Internal scaled⇄decimal bridge for the SDK's public decimal-string surface.\n *\n * The wire protocol carries scaled integers (price ticks, per-asset scaled\n * quantities); the public SDK surface carries plain decimal strings. Output\n * schemas convert exactly (no rounding, trailing zeros trimmed); input schemas\n * accept zero padding but reject fractional precision that remains above the\n * scale after trailing zeros are removed. Scaled integers must not escape\n * through any service input or output.\n */\nimport {\n scaledToDecimal,\n tryDecimalToScaled,\n type DecimalToScaledFailure,\n} from \"../catalogs/decimal.js\";\nimport {\n CatalogConversionError,\n CatalogLookupError,\n CatalogNotReadyError,\n type ClientCatalog,\n type PairCatalogKey,\n} from \"../catalogs/types.js\";\nimport { PRICE_SCALE } from \"../catalogs/readers.js\";\nimport { PROTOBUF_INT64_MAX } from \"./wire-bounds.js\";\n\n/** On-chain unified-asset amounts (`amountE18`) are always 18-decimal scaled. */\nexport const E18_SCALE = 18;\n\n/**\n * Resolves wire scales for the SDK's internal decimal conversion. Backed by\n * the client catalog; `ready()` must be awaited before the synchronous lookups\n * are used so the catalog can answer them.\n */\nexport interface SdkScales {\n ready(): Promise<void>;\n price(): number;\n baseQty(pair: PairCatalogKey): number;\n quoteAmount(pair: PairCatalogKey): number;\n ledgerAmount(ledgerAssetId: number): number;\n zippedAssetAmount(zippedAssetId: number): number;\n}\n\n/**\n * Catalog-backed scale resolver. Takes a getter so it can be constructed\n * before the owning client has assigned its catalog.\n */\nexport function createCatalogSdkScales(getCatalog: () => ClientCatalog): SdkScales {\n return {\n ready: async () => {\n await getCatalog().ensureReady();\n },\n price: () => PRICE_SCALE,\n baseQty: (pair) => requirePair(getCatalog(), pair).baseAsset.quantityScale,\n quoteAmount: (pair) => requirePair(getCatalog(), pair).quoteAsset.quantityScale,\n ledgerAmount: (ledgerAssetId) => {\n const ledger = getCatalog().ledger;\n if (!ledger.isKnownAssetId(ledgerAssetId)) {\n throw new CatalogLookupError(\"ledger\", \"ledgerId\", ledgerAssetId);\n }\n return ledger.requireAssetByLedgerId(ledgerAssetId).quantityScale;\n },\n zippedAssetAmount: (zippedAssetId) =>\n getCatalog().zipper.requireAssetChainByZippedAssetId(zippedAssetId).asset.quantityScale,\n };\n}\n\nfunction requirePair(catalog: ClientCatalog, pair: PairCatalogKey) {\n return typeof pair === \"string\" || (typeof pair === \"object\" && \"symbol\" in pair)\n ? catalog.market.requirePairBySymbol(typeof pair === \"string\" ? pair : pair.symbol)\n : catalog.market.requirePairBySymbolId(typeof pair === \"number\" ? pair : pair.symbolId);\n}\n\n/** Output direction: exact scaled→decimal conversion (`1500000n`@6 → `\"1.5\"`). */\nexport function scaledToDecimalOutput(value: bigint, scale: number): string {\n return scaledToDecimal(value, scale);\n}\n\nfunction conversionFailureMessage(\n field: string,\n value: string,\n failure: DecimalToScaledFailure,\n): string {\n return failure.reason === \"precision\"\n ? `${field} supports at most ${failure.maxDecimals} decimal places: ${value}`\n : `${field} must be a non-negative decimal number: ${value}`;\n}\n\n/**\n * Input direction: strict decimal→scaled conversion. Throws\n * CatalogConversionError for non-decimal input or inexact excess precision.\n */\nexport function decimalInputToScaled(field: string, value: string, scale: number): bigint {\n const result = tryDecimalToScaled(value.trim(), scale);\n if (!result.ok) {\n throw new CatalogConversionError(\n field,\n conversionFailureMessage(field, value, result.failure),\n );\n }\n return result.scaled;\n}\n\nfunction unboundedPositiveDecimalInputToScaled(\n field: string,\n value: string,\n scale: number,\n): bigint {\n const scaled = decimalInputToScaled(field, value, scale);\n if (scaled <= 0n) {\n throw new CatalogConversionError(field, `${field} must be greater than 0: ${value}`);\n }\n return scaled;\n}\n\n/**\n * Converts a positive decimal input to a scaled protobuf `int64` value.\n * Rejects values above the wire-format ceiling before serialization.\n */\nexport function positiveDecimalInputToScaled(field: string, value: string, scale: number): bigint {\n const scaled = unboundedPositiveDecimalInputToScaled(field, value, scale);\n if (scaled > PROTOBUF_INT64_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${value}`,\n );\n }\n return scaled;\n}\n\n/**\n * Decimal quantity → PolyesterChain E18 ledger units.\n * Input precision is capped at the asset's quantityScale; the wire value is\n * always upscaled to E18 (trading balances / amount_e18 convention).\n */\nexport function quantityInputToE18(params: {\n scales: SdkScales;\n assetId: number;\n quantity: string;\n field?: string;\n}): bigint {\n const field = params.field ?? \"quantity\";\n const assetScale = params.scales.ledgerAmount(params.assetId);\n if (assetScale > E18_SCALE) {\n throw new CatalogConversionError(\n field,\n `${field} asset quantityScale ${assetScale} exceeds E18 ledger scale`,\n );\n }\n return (\n unboundedPositiveDecimalInputToScaled(field, params.quantity, assetScale) *\n 10n ** BigInt(E18_SCALE - assetScale)\n );\n}\n\nexport interface ReadyGate {\n /** Queues or delivers one transition while the gate remains active. */\n run(deliver: () => void): void;\n /** Drops pending transitions and permanently prevents future delivery. */\n close(): void;\n}\n\ninterface ReadyGateHandlers {\n onDeliveryError?: (error: unknown) => void;\n onTerminalError: (error: unknown) => void;\n}\n\nconst READY_GATE_MAX_PENDING_DELIVERIES = 1_024;\n\n/**\n * Transition event delivery behind catalog readiness. Events arriving before the\n * catalog can resolve scales are queued and flushed in arrival order once it\n * is ready. Delivery errors are isolated from the transport. Readiness failure\n * or queue overflow is terminal because dropping an event would break stream\n * continuity; the owning subscription must visibly terminate when notified.\n */\nexport function createReadyGate(\n ready: () => Promise<void>,\n handlers: ReadyGateHandlers,\n): ReadyGate {\n let state: \"pending\" | \"open\" | \"closed\" = \"pending\";\n const queue: Array<() => void> = [];\n\n const deliverIsolated = (deliver: () => void) => {\n try {\n deliver();\n } catch (error) {\n handlers.onDeliveryError?.(error);\n }\n };\n\n const closeWithError = (error: unknown) => {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n handlers.onTerminalError(error);\n };\n\n Promise.resolve()\n .then(ready)\n .then(\n () => {\n if (state !== \"pending\") return;\n state = \"open\";\n for (const deliver of queue.splice(0)) deliverIsolated(deliver);\n },\n (error) => {\n if (state !== \"pending\") return;\n closeWithError(error);\n },\n );\n\n return {\n run(deliver) {\n if (state === \"open\") deliverIsolated(deliver);\n else if (state === \"pending\") {\n if (queue.length === READY_GATE_MAX_PENDING_DELIVERIES) {\n closeWithError(new CatalogNotReadyError());\n return;\n }\n queue.push(deliver);\n }\n },\n close() {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;AA8CA,SAAgB,uBAAuB,YAA4C;CAC/E,OAAO;EACH,OAAO,YAAY;GACf,MAAM,WAAW,CAAC,CAAC,YAAY;EACnC;EACA,aAAA;EACA,UAAU,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,UAAU;EAC7D,cAAc,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,WAAW;EAClE,eAAe,kBAAkB;GAC7B,MAAM,SAAS,WAAW,CAAC,CAAC;GAC5B,IAAI,CAAC,OAAO,eAAe,aAAa,GACpC,MAAM,IAAI,mBAAmB,UAAU,YAAY,aAAa;GAEpE,OAAO,OAAO,uBAAuB,aAAa,CAAC,CAAC;EACxD;EACA,oBAAoB,kBAChB,WAAW,CAAC,CAAC,OAAO,iCAAiC,aAAa,CAAC,CAAC,MAAM;CAClF;AACJ;AAEA,SAAS,YAAY,SAAwB,MAAsB;CAC/D,OAAO,OAAO,SAAS,YAAa,OAAO,SAAS,YAAY,YAAY,OACtE,QAAQ,OAAO,oBAAoB,OAAO,SAAS,WAAW,OAAO,KAAK,MAAM,IAChF,QAAQ,OAAO,sBAAsB,OAAO,SAAS,WAAW,OAAO,KAAK,QAAQ;AAC9F;;AAGA,SAAgB,sBAAsB,OAAe,OAAuB;CACxE,OAAO,gBAAgB,OAAO,KAAK;AACvC;AAEA,SAAS,yBACL,OACA,OACA,SACM;CACN,OAAO,QAAQ,WAAW,cACpB,GAAG,MAAM,oBAAoB,QAAQ,YAAY,mBAAmB,UACpE,GAAG,MAAM,0CAA0C;AAC7D;;;;;AAMA,SAAgB,qBAAqB,OAAe,OAAe,OAAuB;CACtF,MAAM,SAAS,mB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AO,CAAC,GAAG,gBAAgB,OAAO;CAClE,IACC,UAAU;EACP,IAAI,UAAU,WAAW;EACzB,eAAe,KAAK;CACxB,CACJ;CAEJ,OAAO;EACH,IAAI,SAAS;GACT,IAAI,UAAU,QAAQ,gBAAgB,OAAO;QACxC,IAAI,UAAU,WAAW;IAC1B,IAAI,MAAM,WAAW,mCAAmC;KACpD,eAAe,IAAI,qBAAqB,CAAC;KACzC;IACJ;IACA,MAAM,KAAK,OAAO;GACtB;EACJ;EACA,QAAQ;GACJ,IAAI,UAAU,UAAU;GACxB,QAAQ;GACR,MAAM,SAAS;EACnB;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"decimal-surface.js","names":[],"sources":["../../src/shared/decimal-surface.ts"],"sourcesContent":["/**\n * Internal scaled⇄decimal bridge for the SDK's public decimal-string surface.\n *\n * The wire protocol carries scaled integers (price ticks, per-asset scaled\n * quantities); the public SDK surface carries plain decimal strings. Output\n * schemas convert exactly (no rounding, trailing zeros trimmed); input schemas\n * accept zero padding but reject fractional precision that remains above the\n * scale after trailing zeros are removed. Scaled integers must not escape\n * through any service input or output.\n */\nimport {\n scaledToDecimal,\n tryDecimalToScaled,\n type DecimalToScaledFailure,\n} from \"../catalogs/decimal.js\";\nimport {\n CatalogConversionError,\n CatalogLookupError,\n CatalogNotReadyError,\n type ClientCatalog,\n type PairCatalogKey,\n} from \"../catalogs/types.js\";\nimport { PRICE_SCALE } from \"../catalogs/readers.js\";\nimport { PROTOBUF_INT64_MAX } from \"./wire-bounds.js\";\n\n/** On-chain unified-asset amounts (`amountE18`) are always 18-decimal scaled. */\nexport const E18_SCALE = 18;\n\n/**\n * Policy notional caps (`max_order_notional`) are canonical quote microunits:\n * one unit is 0.000001 USDT, per the `auth.v1` policy contract. Fixed by the\n * protocol rather than per-pair, so it needs no catalog lookup.\n */\nexport const QUOTE_NOTIONAL_SCALE = 6;\n\n/**\n * Resolves wire scales for the SDK's internal decimal conversion. Backed by\n * the client catalog; `ready()` must be awaited before the synchronous lookups\n * are used so the catalog can answer them.\n */\nexport interface SdkScales {\n ready(): Promise<void>;\n price(): number;\n baseQty(pair: PairCatalogKey): number;\n quoteAmount(pair: PairCatalogKey): number;\n ledgerAmount(ledgerAssetId: number): number;\n zippedAssetAmount(zippedAssetId: number): number;\n}\n\n/**\n * Catalog-backed scale resolver. Takes a getter so it can be constructed\n * before the owning client has assigned its catalog.\n */\nexport function createCatalogSdkScales(getCatalog: () => ClientCatalog): SdkScales {\n return {\n ready: async () => {\n await getCatalog().ensureReady();\n },\n price: () => PRICE_SCALE,\n baseQty: (pair) => requirePair(getCatalog(), pair).baseAsset.quantityScale,\n quoteAmount: (pair) => requirePair(getCatalog(), pair).quoteAsset.quantityScale,\n ledgerAmount: (ledgerAssetId) => {\n const ledger = getCatalog().ledger;\n if (!ledger.isKnownAssetId(ledgerAssetId)) {\n throw new CatalogLookupError(\"ledger\", \"ledgerId\", ledgerAssetId);\n }\n return ledger.requireAssetByLedgerId(ledgerAssetId).quantityScale;\n },\n zippedAssetAmount: (zippedAssetId) =>\n getCatalog().zipper.requireAssetChainByZippedAssetId(zippedAssetId).asset.quantityScale,\n };\n}\n\nfunction requirePair(catalog: ClientCatalog, pair: PairCatalogKey) {\n return typeof pair === \"string\" || (typeof pair === \"object\" && \"symbol\" in pair)\n ? catalog.market.requirePairBySymbol(typeof pair === \"string\" ? pair : pair.symbol)\n : catalog.market.requirePairBySymbolId(typeof pair === \"number\" ? pair : pair.symbolId);\n}\n\n/** Output direction: exact scaled→decimal conversion (`1500000n`@6 → `\"1.5\"`). */\nexport function scaledToDecimalOutput(value: bigint, scale: number): string {\n return scaledToDecimal(value, scale);\n}\n\nfunction conversionFailureMessage(\n field: string,\n value: string,\n failure: DecimalToScaledFailure,\n): string {\n return failure.reason === \"precision\"\n ? `${field} supports at most ${failure.maxDecimals} decimal places: ${value}`\n : `${field} must be a non-negative decimal number: ${value}`;\n}\n\n/**\n * Input direction: strict decimal→scaled conversion. Throws\n * CatalogConversionError for non-decimal input or inexact excess precision.\n */\nexport function decimalInputToScaled(field: string, value: string, scale: number): bigint {\n const result = tryDecimalToScaled(value.trim(), scale);\n if (!result.ok) {\n throw new CatalogConversionError(\n field,\n conversionFailureMessage(field, value, result.failure),\n );\n }\n return result.scaled;\n}\n\nfunction unboundedPositiveDecimalInputToScaled(\n field: string,\n value: string,\n scale: number,\n): bigint {\n const scaled = decimalInputToScaled(field, value, scale);\n if (scaled <= 0n) {\n throw new CatalogConversionError(field, `${field} must be greater than 0: ${value}`);\n }\n return scaled;\n}\n\n/**\n * Converts a positive decimal input to a scaled protobuf `int64` value.\n * Rejects values above the wire-format ceiling before serialization.\n */\nexport function positiveDecimalInputToScaled(field: string, value: string, scale: number): bigint {\n const scaled = unboundedPositiveDecimalInputToScaled(field, value, scale);\n if (scaled > PROTOBUF_INT64_MAX) {\n throw new CatalogConversionError(\n field,\n `${field} exceeds the maximum supported value: ${value}`,\n );\n }\n return scaled;\n}\n\n/**\n * Decimal quantity → PolyesterChain E18 ledger units.\n * Input precision is capped at the asset's quantityScale; the wire value is\n * always upscaled to E18 (trading balances / amount_e18 convention).\n */\nexport function quantityInputToE18(params: {\n scales: SdkScales;\n assetId: number;\n quantity: string;\n field?: string;\n}): bigint {\n const field = params.field ?? \"quantity\";\n const assetScale = params.scales.ledgerAmount(params.assetId);\n if (assetScale > E18_SCALE) {\n throw new CatalogConversionError(\n field,\n `${field} asset quantityScale ${assetScale} exceeds E18 ledger scale`,\n );\n }\n return (\n unboundedPositiveDecimalInputToScaled(field, params.quantity, assetScale) *\n 10n ** BigInt(E18_SCALE - assetScale)\n );\n}\n\nexport interface ReadyGate {\n /** Queues or delivers one transition while the gate remains active. */\n run(deliver: () => void): void;\n /** Drops pending transitions and permanently prevents future delivery. */\n close(): void;\n}\n\ninterface ReadyGateHandlers {\n onDeliveryError?: (error: unknown) => void;\n onTerminalError: (error: unknown) => void;\n}\n\nconst READY_GATE_MAX_PENDING_DELIVERIES = 1_024;\n\n/**\n * Transition event delivery behind catalog readiness. Events arriving before the\n * catalog can resolve scales are queued and flushed in arrival order once it\n * is ready. Delivery errors are isolated from the transport. Readiness failure\n * or queue overflow is terminal because dropping an event would break stream\n * continuity; the owning subscription must visibly terminate when notified.\n */\nexport function createReadyGate(\n ready: () => Promise<void>,\n handlers: ReadyGateHandlers,\n): ReadyGate {\n let state: \"pending\" | \"open\" | \"closed\" = \"pending\";\n const queue: Array<() => void> = [];\n\n const deliverIsolated = (deliver: () => void) => {\n try {\n deliver();\n } catch (error) {\n handlers.onDeliveryError?.(error);\n }\n };\n\n const closeWithError = (error: unknown) => {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n handlers.onTerminalError(error);\n };\n\n Promise.resolve()\n .then(ready)\n .then(\n () => {\n if (state !== \"pending\") return;\n state = \"open\";\n for (const deliver of queue.splice(0)) deliverIsolated(deliver);\n },\n (error) => {\n if (state !== \"pending\") return;\n closeWithError(error);\n },\n );\n\n return {\n run(deliver) {\n if (state === \"open\") deliverIsolated(deliver);\n else if (state === \"pending\") {\n if (queue.length === READY_GATE_MAX_PENDING_DELIVERIES) {\n closeWithError(new CatalogNotReadyError());\n return;\n }\n queue.push(deliver);\n }\n },\n close() {\n if (state === \"closed\") return;\n state = \"closed\";\n queue.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;AAqDA,SAAgB,uBAAuB,YAA4C;CAC/E,OAAO;EACH,OAAO,YAAY;GACf,MAAM,WAAW,CAAC,CAAC,YAAY;EACnC;EACA,aAAA;EACA,UAAU,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,UAAU;EAC7D,cAAc,SAAS,YAAY,WAAW,GAAG,IAAI,CAAC,CAAC,WAAW;EAClE,eAAe,kBAAkB;GAC7B,MAAM,SAAS,WAAW,CAAC,CAAC;GAC5B,IAAI,CAAC,OAAO,eAAe,aAAa,GACpC,MAAM,IAAI,mBAAmB,UAAU,YAAY,aAAa;GAEpE,OAAO,OAAO,uBAAuB,aAAa,CA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,aAAA,IACA,MAAM,IAAI,uBACN,OACA,GAAG,MAAM,uBAAuB,WAAW,0BAC/C;CAEJ,OACI,sCAAsC,OAAO,OAAO,UAAU,UAAU,IACxE,OAAO,OAAA,KAAmB,UAAU;AAE5C;AAcA,MAAM,oCAAoC;;;;;;;;AAS1C,SAAgB,gBACZ,OACA,UACS;CACT,IAAI,QAAuC;CAC3C,MAAM,QAA2B,CAAC;CAElC,MAAM,mBAAmB,YAAwB;EAC7C,IAAI;GACA,QAAQ;EACZ,SAAS,OAAO;GACZ,SAAS,kBAAkB,KAAK;EACpC;CACJ;CAEA,MAAM,kBAAkB,UAAmB;EACvC,IAAI,UAAU,UAAU;EACxB,QAAQ;EACR,MAAM,SAAS;EACf,SAAS,gBAAgB,KAAK;CAClC;CAEA,QAAQ,QAAQ,CAAC,CACZ,KAAK,KAAK,CAAC,CACX,WACS;EACF,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,KAAK,MAAM,WAAW,MAAM,OAAO,CAAC,GAAG,gBAAgB,OAAO;CAClE,IACC,UAAU;EACP,IAAI,UAAU,WAAW;EACzB,eAAe,KAAK;CACxB,CACJ;CAEJ,OAAO;EACH,IAAI,SAAS;GACT,IAAI,UAAU,QAAQ,gBAAgB,OAAO;QACxC,IAAI,UAAU,WAAW;IAC1B,IAAI,MAAM,WAAW,mCAAmC;KACpD,eAAe,IAAI,qBAAqB,CAAC;KACzC;IACJ;IACA,MAAM,KAAK,OAAO;GACtB;EACJ;EACA,QAAQ;GACJ,IAAI,UAAU,UAAU;GACxB,QAAQ;GACR,MAAM,SAAS;EACnB;CACJ;AACJ"}
|
package/dist/shared/schemas.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { formatId, idToBigInt } from "../utils/base58-id.js";
|
|
2
|
-
import { parseOptionalUint64DecimalStrict,
|
|
2
|
+
import { parseOptionalUint64DecimalStrict, toBpsOrZero, toIntOrZero } from "../utils/numbers.js";
|
|
3
3
|
import { tsNsToMs, tsObjToMs } from "../utils/time.js";
|
|
4
|
+
import { PROTOBUF_UINT32_MAX } from "./wire-bounds.js";
|
|
4
5
|
import * as v from "valibot";
|
|
5
6
|
//#region src/shared/schemas.ts
|
|
6
7
|
const UINT64_MAX = (1n << 64n) - 1n;
|
|
@@ -15,8 +16,7 @@ const TimestampSchema = v.object({
|
|
|
15
16
|
const TimestampMsSchema = v.pipe(TimestampSchema, v.transform((value) => tsObjToMs(value)));
|
|
16
17
|
const OptionalTimestampMsSchema = v.pipe(v.optional(TimestampSchema), v.transform((value) => tsObjToMs(value)));
|
|
17
18
|
const OptionalNumberDefaultNullSchema = v.optional(v.nullable(v.number()), null);
|
|
18
|
-
const
|
|
19
|
-
const OptionalNumberToIntOrZeroSchema = v.pipe(OptionalNumberDefaultNullSchema, v.transform((value) => toIntOrZero(value)));
|
|
19
|
+
const OptionalNumberToIntOrZeroSchema = v.pipe(v.optional(v.nullable(v.pipe(v.number(), v.maxValue(PROTOBUF_UINT32_MAX))), null), v.transform((value) => toIntOrZero(value)));
|
|
20
20
|
v.pipe(OptionalNumberDefaultNullSchema, v.transform((value) => toBpsOrZero(value)));
|
|
21
21
|
v.pipe(v.bigint(), v.transform((value) => tsNsToMs(value)));
|
|
22
22
|
const BigIntStringSchema = v.pipe(v.bigint(), v.transform((value) => value.toString()));
|
|
@@ -60,6 +60,6 @@ function positiveBigintStringInputSchema(fieldName) {
|
|
|
60
60
|
}
|
|
61
61
|
const JsonObjectSchema = v.custom((input) => typeof input === "object" && input !== null && !Array.isArray(input));
|
|
62
62
|
//#endregion
|
|
63
|
-
export { BigIntStringSchema, JsonObjectSchema, OptionalBigIntStringSchema, OptionalNumberDefaultNullSchema,
|
|
63
|
+
export { BigIntStringSchema, JsonObjectSchema, OptionalBigIntStringSchema, OptionalNumberDefaultNullSchema, OptionalNumberToIntOrZeroSchema, OptionalPublicIdSchema, OptionalTimestampMsSchema, OptionalTimestampMsToUsInputSchema, OptionalTimestampSecondsInputSchema, PublicIdSchema, TimestampMsSchema, TimestampSchema, bigintStringInputSchema, idInputSchema, optionalIdInputSchema, optionalSubaccountIdInputSchema, optionalUint64DecimalFilterSchema, positiveBigintStringInputSchema };
|
|
64
64
|
|
|
65
65
|
//# sourceMappingURL=schemas.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.js","names":[],"sources":["../../src/shared/schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { formatId, idToBigInt } from \"../utils/base58-id.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"schemas.js","names":[],"sources":["../../src/shared/schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { formatId, idToBigInt } from \"../utils/base58-id.js\";\nimport { parseOptionalUint64DecimalStrict, toBpsOrZero, toIntOrZero } from \"../utils/numbers.js\";\nimport { tsNsToMs, tsObjToMs } from \"../utils/time.js\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { PROTOBUF_UINT32_MAX } from \"./wire-bounds.js\";\n\nconst UINT64_MAX = (1n << 64n) - 1n;\nconst MS_TO_US = 1_000n;\nconst MS_TO_NS = 1_000_000n;\nconst MAX_UINT64_TIMESTAMP_MS_US = Number(UINT64_MAX / MS_TO_US);\nconst MAX_UINT64_TIMESTAMP_MS = Number(UINT64_MAX / MS_TO_NS);\n\nexport const TimestampSchema = v.object({\n seconds: v.bigint(),\n nanos: v.optional(v.number(), 0),\n});\n\nexport const TimestampMsSchema = v.pipe(\n TimestampSchema,\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalTimestampMsSchema = v.pipe(\n v.optional(TimestampSchema),\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalNumberDefaultNullSchema = v.optional(v.nullable(v.number()), null);\n\nexport const OptionalNumberToIntOrZeroSchema = v.pipe(\n v.optional(v.nullable(v.pipe(v.number(), v.maxValue(PROTOBUF_UINT32_MAX))), null),\n v.transform((value) => toIntOrZero(value)),\n);\n\nexport const OptionalNumberToBpsOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toBpsOrZero(value)),\n);\n\nexport const TimestampNsMsSchema = v.pipe(\n v.bigint(),\n v.transform((value) => tsNsToMs(value)),\n);\n\nexport const BigIntStringSchema = v.pipe(\n v.bigint(),\n v.transform((value) => value.toString()),\n);\n\nexport const OptionalBigIntStringSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value === undefined ? undefined : value.toString())),\n);\n\nexport const OptionalTimestampMsToNsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS),\n v.transform((value) => BigInt(value) * MS_TO_NS),\n ),\n);\n\nexport const OptionalTimestampMsToUsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS_US),\n v.transform((value) => BigInt(value) * MS_TO_US),\n ),\n);\n\nexport const OptionalTimestampSecondsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n v.transform((value) => BigInt(value)),\n ),\n);\n\nexport const PublicIdSchema = v.pipe(\n v.bigint(),\n v.transform((value) => formatId(value)),\n);\n\nexport const OptionalPublicIdSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value ? formatId(value) : undefined)),\n);\n\nconst TrimmedStringSchema = v.pipe(v.string(), v.trim());\n\nconst OptionalTrimmedStringSchema = v.optional(TrimmedStringSchema);\n\n/**\n * Creates a schema for required public id input.\n */\nexport function idInputSchema(fieldName: string) {\n return v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.transform((value) => idToBigInt(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for optional public id input.\n */\nexport function optionalIdInputSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => (value ? idToBigInt(value, fieldName) : undefined)),\n );\n}\n\n/**\n * Creates a schema for optional subaccount id input.\n */\nexport function optionalSubaccountIdInputSchema() {\n return optionalIdInputSchema(\"subaccountId\");\n}\n\n/**\n * Creates a schema for optional uint64 decimal filter input.\n */\nexport function optionalUint64DecimalFilterSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => parseOptionalUint64DecimalStrict(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for positive bigint-like input.\n */\nexport function positiveBigintLikeSchema(message: string) {\n return v.pipe(\n v.union([\n v.bigint(),\n v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/),\n v.transform((value) => BigInt(value)),\n ),\n ]),\n v.check((value) => value > 0n, message),\n );\n}\n\nexport function bigintStringInputSchema(fieldName: string) {\n return v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/, `${fieldName} must be a decimal integer`),\n v.transform((value) => BigInt(value)),\n );\n}\n\nexport function positiveBigintStringInputSchema(fieldName: string) {\n return v.pipe(\n bigintStringInputSchema(fieldName),\n v.check((value) => value > 0n, `${fieldName} must be greater than 0`),\n );\n}\n\nexport const JsonObjectSchema = v.custom<JsonObject>(\n (input): input is JsonObject =>\n typeof input === \"object\" && input !== null && !Array.isArray(input),\n);\n"],"mappings":";;;;;;AAOA,MAAM,cAAc,MAAM,OAAO;AACjC,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,6BAA6B,OAAO,aAAa,QAAQ;AAC/D,MAAM,0BAA0B,OAAO,aAAa,QAAQ;AAE5D,MAAa,kBAAkB,EAAE,OAAO;CACpC,SAAS,EAAE,OAAO;CAClB,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,CAAC;AACnC,CAAC;AAED,MAAa,oBAAoB,EAAE,KAC/B,iBACA,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa,4BAA4B,EAAE,KACvC,EAAE,SAAS,eAAe,GAC1B,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa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|
return parsed > 0n ? parsed : void 0;
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
-
* Coerce optional UI number into non-negative bigint (e.g. caps, limits).
|
|
40
|
-
* @param value - The value to coerce.
|
|
41
|
-
* @returns The coerced bigint.
|
|
42
|
-
*/
|
|
43
|
-
function toBigIntOrZero(value) {
|
|
44
|
-
if (value == null || Number.isNaN(value)) return 0n;
|
|
45
|
-
return BigInt(Math.max(0, Math.trunc(value)));
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
39
|
* Coerce optional UI number into non-negative integer.
|
|
49
40
|
* @param value - The value to coerce.
|
|
50
41
|
* @returns The coerced integer.
|
|
@@ -63,6 +54,6 @@ function toBpsOrZero(value) {
|
|
|
63
54
|
return Math.max(0, Math.trunc(value * 100));
|
|
64
55
|
}
|
|
65
56
|
//#endregion
|
|
66
|
-
export { parseOptionalPositiveBigIntLike, parseOptionalPositiveIntLike, parseOptionalUint64DecimalStrict,
|
|
57
|
+
export { parseOptionalPositiveBigIntLike, parseOptionalPositiveIntLike, parseOptionalUint64DecimalStrict, toBpsOrZero, toIntOrZero };
|
|
67
58
|
|
|
68
59
|
//# sourceMappingURL=numbers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numbers.js","names":[],"sources":["../../src/utils/numbers.ts"],"sourcesContent":["// Shared numeric helpers for gRPC/Connect clients.\n\n/**\n * Parse a required uint64 encoded as a base-10 string into bigint.\n * @param raw - The raw string to parse.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive integer.\n */\nexport function parseRequiredUint64Decimal(raw: string, fieldName: string): bigint {\n const s = (raw ?? \"\").trim();\n if (!s) throw new Error(`${fieldName} is required`);\n if (!/^[0-9]+$/.test(s)) throw new Error(`${fieldName} must be a positive integer`);\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64 encoded as a base-10 string into bigint, or undefined on invalid/empty.\n * @param raw - The raw string to parse.\n * @returns The parsed bigint, or undefined if the field is invalid or empty.\n */\nexport function parseOptionalUint64Decimal(raw: string | undefined): bigint | undefined {\n const s = (raw ?? \"\").trim();\n if (!s) return;\n // For optional filters, treat invalid input as \"unset\" rather than surfacing an error.\n if (!/^[0-9]+$/.test(s)) return;\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64 encoded as a base-10 string into bigint.\n * Empty values are omitted, but supplied invalid values are rejected.\n */\nexport function parseOptionalUint64DecimalStrict(\n raw: string | undefined,\n fieldName: string,\n): bigint | undefined {\n const s = (raw ?? \"\").trim();\n if (!s) return;\n if (!/^[0-9]+$/.test(s)) throw new Error(`${fieldName} must be a positive integer`);\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64-ish value (string/number/bigint) into bigint, or undefined on invalid/empty.\n * Accepts base-10 strings, numeric inputs (truncated), and bigint inputs.\n */\nexport function parseOptionalUint64Like(\n value: string | number | bigint | undefined | null,\n): bigint | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"bigint\") return value >= 0n ? value : undefined;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return undefined;\n const n = Math.trunc(value);\n return n >= 0 ? BigInt(n) : undefined;\n }\n return parseOptionalUint64Decimal(value);\n}\n\n/**\n * Parse an optional positive integer-ish value (string/number) into a number, or undefined on invalid/empty.\n * Useful for common \"limit\" fields coming from UI inputs.\n */\nexport function parseOptionalPositiveIntLike(\n value: string | number | undefined | null,\n): number | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\") {\n const decimal = value.trim();\n if (!/^\\d+$/.test(decimal)) return undefined;\n const parsed = Number(decimal);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;\n }\n return Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Parse a positive integer-like value without losing precision.\n * Decimal strings may exceed JavaScript's safe-integer range; number inputs may not.\n */\nexport function parseOptionalPositiveBigIntLike(\n value: string | number | undefined | null,\n): bigint | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) && value > 0 ? BigInt(value) : undefined;\n }\n const decimal = value.trim();\n if (!/^\\d+$/.test(decimal)) return undefined;\n const parsed = BigInt(decimal);\n return parsed > 0n ? parsed : undefined;\n}\n\n/**\n * Convert a decimal string into a scaled bigint (e.g. 18dp quantity, 6dp price).\n * @param raw - The raw string to parse.\n * @param scale - The scale of the number.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function decimalToScaledInt(raw: string, scale: number, fieldName: string): bigint {\n const s = (raw ?? \"\").trim();\n if (!s) throw new Error(`${fieldName} is required`);\n if (!/^[0-9]+(\\.[0-9]+)?$/.test(s)) throw new Error(`${fieldName} must be a positive number`);\n const [intPartRaw, fracRaw = \"\"] = s.split(\".\");\n if (fracRaw.length > scale) {\n throw new Error(`${fieldName} supports at most ${scale} decimal places`);\n }\n const intPart = intPartRaw?.replace(/^0+/, \"\") ?? \"0\";\n const fracPart = fracRaw.padEnd(scale, \"0\");\n const combined = `${intPart}${fracPart}`;\n return BigInt(combined ?? \"0\");\n}\n\n/**\n * Parse a quantity scaled to the given number of decimal places.\n * @param raw - The raw string to parse.\n * @param scale - The number of decimal places to scale to.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function parseQtyScaled(raw: string, scale: number, fieldName: string): bigint {\n return decimalToScaledInt(raw, scale, fieldName);\n}\n\n/**\n * Parse a price scaled to 6 decimal places.\n * @param raw - The raw string to parse.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function parsePriceTicks(raw: string, fieldName: string): bigint {\n return decimalToScaledInt(raw, 6, fieldName);\n}\n\n/**\n * Coerce optional UI number into non-negative
|
|
1
|
+
{"version":3,"file":"numbers.js","names":[],"sources":["../../src/utils/numbers.ts"],"sourcesContent":["// Shared numeric helpers for gRPC/Connect clients.\n\n/**\n * Parse a required uint64 encoded as a base-10 string into bigint.\n * @param raw - The raw string to parse.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive integer.\n */\nexport function parseRequiredUint64Decimal(raw: string, fieldName: string): bigint {\n const s = (raw ?? \"\").trim();\n if (!s) throw new Error(`${fieldName} is required`);\n if (!/^[0-9]+$/.test(s)) throw new Error(`${fieldName} must be a positive integer`);\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64 encoded as a base-10 string into bigint, or undefined on invalid/empty.\n * @param raw - The raw string to parse.\n * @returns The parsed bigint, or undefined if the field is invalid or empty.\n */\nexport function parseOptionalUint64Decimal(raw: string | undefined): bigint | undefined {\n const s = (raw ?? \"\").trim();\n if (!s) return;\n // For optional filters, treat invalid input as \"unset\" rather than surfacing an error.\n if (!/^[0-9]+$/.test(s)) return;\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64 encoded as a base-10 string into bigint.\n * Empty values are omitted, but supplied invalid values are rejected.\n */\nexport function parseOptionalUint64DecimalStrict(\n raw: string | undefined,\n fieldName: string,\n): bigint | undefined {\n const s = (raw ?? \"\").trim();\n if (!s) return;\n if (!/^[0-9]+$/.test(s)) throw new Error(`${fieldName} must be a positive integer`);\n return BigInt(s);\n}\n\n/**\n * Parse an optional uint64-ish value (string/number/bigint) into bigint, or undefined on invalid/empty.\n * Accepts base-10 strings, numeric inputs (truncated), and bigint inputs.\n */\nexport function parseOptionalUint64Like(\n value: string | number | bigint | undefined | null,\n): bigint | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"bigint\") return value >= 0n ? value : undefined;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) return undefined;\n const n = Math.trunc(value);\n return n >= 0 ? BigInt(n) : undefined;\n }\n return parseOptionalUint64Decimal(value);\n}\n\n/**\n * Parse an optional positive integer-ish value (string/number) into a number, or undefined on invalid/empty.\n * Useful for common \"limit\" fields coming from UI inputs.\n */\nexport function parseOptionalPositiveIntLike(\n value: string | number | undefined | null,\n): number | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\") {\n const decimal = value.trim();\n if (!/^\\d+$/.test(decimal)) return undefined;\n const parsed = Number(decimal);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;\n }\n return Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Parse a positive integer-like value without losing precision.\n * Decimal strings may exceed JavaScript's safe-integer range; number inputs may not.\n */\nexport function parseOptionalPositiveBigIntLike(\n value: string | number | undefined | null,\n): bigint | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) && value > 0 ? BigInt(value) : undefined;\n }\n const decimal = value.trim();\n if (!/^\\d+$/.test(decimal)) return undefined;\n const parsed = BigInt(decimal);\n return parsed > 0n ? parsed : undefined;\n}\n\n/**\n * Convert a decimal string into a scaled bigint (e.g. 18dp quantity, 6dp price).\n * @param raw - The raw string to parse.\n * @param scale - The scale of the number.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function decimalToScaledInt(raw: string, scale: number, fieldName: string): bigint {\n const s = (raw ?? \"\").trim();\n if (!s) throw new Error(`${fieldName} is required`);\n if (!/^[0-9]+(\\.[0-9]+)?$/.test(s)) throw new Error(`${fieldName} must be a positive number`);\n const [intPartRaw, fracRaw = \"\"] = s.split(\".\");\n if (fracRaw.length > scale) {\n throw new Error(`${fieldName} supports at most ${scale} decimal places`);\n }\n const intPart = intPartRaw?.replace(/^0+/, \"\") ?? \"0\";\n const fracPart = fracRaw.padEnd(scale, \"0\");\n const combined = `${intPart}${fracPart}`;\n return BigInt(combined ?? \"0\");\n}\n\n/**\n * Parse a quantity scaled to the given number of decimal places.\n * @param raw - The raw string to parse.\n * @param scale - The number of decimal places to scale to.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function parseQtyScaled(raw: string, scale: number, fieldName: string): bigint {\n return decimalToScaledInt(raw, scale, fieldName);\n}\n\n/**\n * Parse a price scaled to 6 decimal places.\n * @param raw - The raw string to parse.\n * @param fieldName - The name of the field to parse.\n * @returns The parsed bigint.\n * @throws An error if the field is required and not provided.\n * @throws An error if the field is not a positive number.\n */\nexport function parsePriceTicks(raw: string, fieldName: string): bigint {\n return decimalToScaledInt(raw, 6, fieldName);\n}\n\n/**\n * Coerce optional UI number into non-negative integer.\n * @param value - The value to coerce.\n * @returns The coerced integer.\n */\nexport function toIntOrZero(value?: number | null): number {\n if (value == null || Number.isNaN(value)) return 0;\n return Math.max(0, Math.trunc(value));\n}\n\n/**\n * Coerce optional UI percentage into non-negative basis points integer.\n * @param value - The value to coerce.\n * @returns The coerced integer.\n */\nexport function toBpsOrZero(value?: number | null): number {\n if (value == null || Number.isNaN(value)) return 0;\n return Math.max(0, Math.trunc(value * 100));\n}\n\n/**\n * Convert basis points to percentage.\n * @param value - The value to convert.\n * @returns The converted percentage.\n */\nexport function bpsToPct(value?: number | null): number {\n if (value == null || Number.isNaN(value)) return 0;\n return value / 100;\n}\n"],"mappings":";;;;;AAkCA,SAAgB,iCACZ,KACA,WACkB;CAClB,MAAM,KAAK,OAAO,GAAA,CAAI,KAAK;CAC3B,IAAI,CAAC,GAAG;CACR,IAAI,CAAC,WAAW,KAAK,CAAC,GAAG,MAAM,IAAI,MAAM,GAAG,UAAU,4BAA4B;CAClF,OAAO,OAAO,CAAC;AACnB;;;;;AAuBA,SAAgB,6BACZ,OACkB;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;CAClD,IAAI,OAAO,UAAU,UAAU;EAC3B,MAAM,UAAU,MAAM,KAAK;EAC3B,IAAI,CAAC,Q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