@polyester/sdk 0.5.0 → 0.7.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 +18 -0
- package/dist/catalogs/readers.d.ts.map +1 -1
- package/dist/catalogs/readers.js +11 -3
- package/dist/catalogs/readers.js.map +1 -1
- package/dist/catalogs/types.d.ts +8 -0
- package/dist/catalogs/types.d.ts.map +1 -1
- package/dist/catalogs/types.js.map +1 -1
- package/dist/gen/auth/v1/address_book_pb.d.ts +8 -0
- package/dist/gen/auth/v1/address_book_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/address_book_pb.js +1 -1
- package/dist/gen/auth/v1/address_book_pb.js.map +1 -1
- package/dist/gen/auth/v1/auth_pb.d.ts +7 -1
- package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/auth_pb.js +7 -1
- package/dist/gen/auth/v1/auth_pb.js.map +1 -1
- package/dist/services/address-book/address-book.d.ts +1 -1
- package/dist/services/address-book/address-book.js +1 -1
- package/dist/services/address-book/address-book.js.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +27 -4
- package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.js +11 -5
- package/dist/services/address-book/address-book.schemas.js.map +1 -1
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
- package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/social-verification/social-verification.schemas.d.ts +10 -2
- package/dist/services/social-verification/social-verification.schemas.d.ts.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.js +4 -2
- package/dist/services/social-verification/social-verification.schemas.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +1 -1
- package/dist/services/trailing-oneof-inputs.js +2 -3
- 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 +2 -2
- package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +1 -0
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/decimal-surface.d.ts.map +1 -1
- package/dist/shared/decimal-surface.js +12 -3
- package/dist/shared/decimal-surface.js.map +1 -1
- package/dist/shared/wire-bounds.js +9 -0
- package/dist/shared/wire-bounds.js.map +1 -0
- package/package.json +1 -1
|
@@ -13,8 +13,8 @@ type TimestampInit = {
|
|
|
13
13
|
};
|
|
14
14
|
declare const GetOrderbookHeatmapInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
15
15
|
readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>]>;
|
|
16
|
-
readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"
|
|
17
|
-
readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<5 | 10 | 20 | 1 | 200 | 1000 | 500 |
|
|
16
|
+
readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"1s" | "1m" | "5m" | "1h", HeatmapInterval>]>;
|
|
17
|
+
readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<5 | 10 | 20 | 1 | 200 | 1000 | 500 | 100 | 50, HeatmapDepth>]>;
|
|
18
18
|
readonly quantityMode: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["close", "peak"], undefined>, "close">, v.TransformAction<"close" | "peak", HeatmapQuantityMode>]>;
|
|
19
19
|
readonly limit: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 20000, undefined>]>;
|
|
20
20
|
readonly startTsSec: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>, v.TransformAction<number, bigint>]>, undefined>;
|
|
@@ -122,7 +122,7 @@ declare function convertHeatmapDeltaBucket(bucket: OrderbookHeatmapDeltaBucketRa
|
|
|
122
122
|
type OrderbookHeatmapDeltaBucket = ReturnType<typeof convertHeatmapDeltaBucket>;
|
|
123
123
|
declare const OrderbookHeatmapLiveBucketRawSchema: v.ObjectSchema<{
|
|
124
124
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
125
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
125
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1s" | "1m" | "5m" | "1h">>]>;
|
|
126
126
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
127
127
|
readonly isFinal: v.BooleanSchema<undefined>;
|
|
128
128
|
readonly bids: v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -142,7 +142,7 @@ declare const OrderbookHeatmapLiveBucketRawSchema: v.ObjectSchema<{
|
|
|
142
142
|
type OrderbookHeatmapLiveBucketRaw = v.InferOutput<typeof OrderbookHeatmapLiveBucketRawSchema>;
|
|
143
143
|
declare function convertHeatmapLiveBucket(bucket: OrderbookHeatmapLiveBucketRaw, scales: SdkScales): {
|
|
144
144
|
symbolId: number;
|
|
145
|
-
interval: DecodedEnum<"
|
|
145
|
+
interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
|
|
146
146
|
tsSec: number;
|
|
147
147
|
isFinal: boolean;
|
|
148
148
|
bids: {
|
|
@@ -226,8 +226,8 @@ declare function convertHeatmapDeltaChain(chain: OrderbookHeatmapDeltaChainRaw,
|
|
|
226
226
|
type OrderbookHeatmapDeltaChain = ReturnType<typeof convertHeatmapDeltaChain>;
|
|
227
227
|
declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
228
228
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
229
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
230
|
-
readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
229
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1s" | "1m" | "5m" | "1h">>]>;
|
|
230
|
+
readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 100 | 50>]>;
|
|
231
231
|
readonly chain: v.OptionalSchema<v.ObjectSchema<{
|
|
232
232
|
readonly baseKeyframe: v.OptionalSchema<v.ObjectSchema<{
|
|
233
233
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
@@ -267,7 +267,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
267
267
|
readonly quantityMode: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"close" | "peak">>]>;
|
|
268
268
|
readonly liveBucket: v.OptionalSchema<v.ObjectSchema<{
|
|
269
269
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
270
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
270
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1s" | "1m" | "5m" | "1h">>]>;
|
|
271
271
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
272
272
|
readonly isFinal: v.BooleanSchema<undefined>;
|
|
273
273
|
readonly bids: v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -286,8 +286,8 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
286
286
|
}, undefined>, undefined>;
|
|
287
287
|
}, undefined>, v.TransformAction<{
|
|
288
288
|
symbolId: number;
|
|
289
|
-
interval: DecodedEnum<"
|
|
290
|
-
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
289
|
+
interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
|
|
290
|
+
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 100 | 50;
|
|
291
291
|
chain?: {
|
|
292
292
|
baseKeyframe?: {
|
|
293
293
|
tsSec: number;
|
|
@@ -327,7 +327,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
327
327
|
quantityMode: DecodedEnum<"close" | "peak">;
|
|
328
328
|
liveBucket?: {
|
|
329
329
|
symbolId: number;
|
|
330
|
-
interval: DecodedEnum<"
|
|
330
|
+
interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
|
|
331
331
|
tsSec: number;
|
|
332
332
|
isFinal: boolean;
|
|
333
333
|
bids?: {
|
|
@@ -346,8 +346,8 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
346
346
|
} | undefined;
|
|
347
347
|
}, {
|
|
348
348
|
symbolId: number;
|
|
349
|
-
interval: DecodedEnum<"
|
|
350
|
-
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
349
|
+
interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
|
|
350
|
+
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 100 | 50;
|
|
351
351
|
chain: {
|
|
352
352
|
baseKeyframe: {
|
|
353
353
|
tsSec: number;
|
|
@@ -387,7 +387,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
387
387
|
quantityMode: DecodedEnum<"close" | "peak">;
|
|
388
388
|
liveBucket: {
|
|
389
389
|
symbolId: number;
|
|
390
|
-
interval: DecodedEnum<"
|
|
390
|
+
interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
|
|
391
391
|
tsSec: number;
|
|
392
392
|
isFinal: boolean;
|
|
393
393
|
bids: {
|
|
@@ -30,7 +30,7 @@ declare function createMarketOverviewSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
30
30
|
readonly bestAskTicks: v.BigintSchema<undefined>;
|
|
31
31
|
readonly bestAskQtyScaled: v.BigintSchema<undefined>;
|
|
32
32
|
readonly sparklines: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
|
|
33
|
-
readonly interval: v.SchemaWithPipe<readonly [v.EnumSchema<typeof SparklineInterval, undefined>, v.TransformAction<SparklineInterval, "unspecified" | "
|
|
33
|
+
readonly interval: v.SchemaWithPipe<readonly [v.EnumSchema<typeof SparklineInterval, undefined>, v.TransformAction<SparklineInterval, "unspecified" | "1m" | "1h" | "1w" | "24h">]>;
|
|
34
34
|
readonly closeTicks: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
35
35
|
}, undefined>, undefined>, readonly []>;
|
|
36
36
|
readonly indexPriceTicks: v.BigintSchema<undefined>;
|
|
@@ -50,7 +50,7 @@ declare function createMarketOverviewSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
50
50
|
bestAskTicks: bigint;
|
|
51
51
|
bestAskQtyScaled: bigint;
|
|
52
52
|
sparklines: {
|
|
53
|
-
interval: "unspecified" | "
|
|
53
|
+
interval: "unspecified" | "1m" | "1h" | "1w" | "24h";
|
|
54
54
|
closeTicks: bigint[];
|
|
55
55
|
}[];
|
|
56
56
|
indexPriceTicks: bigint;
|
|
@@ -80,7 +80,7 @@ declare const ListMarketOverviewInputSchema: v.ObjectSchema<{
|
|
|
80
80
|
readonly orderBy: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["change_24h_bps", "volume_24h_quote", "last_price", "date_added"], undefined>, "volume_24h_quote">, v.TransformAction<"change_24h_bps" | "volume_24h_quote" | "last_price" | "date_added", MarketOrderBy.ORDER_BY_CHANGE_24H_BPS | MarketOrderBy.ORDER_BY_VOLUME_24H_QUOTE | MarketOrderBy.ORDER_BY_LAST_PRICE | MarketOrderBy.ORDER_BY_DATE_ADDED>]>;
|
|
81
81
|
readonly sort: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["asc", "desc"], undefined>, "desc">, v.TransformAction<"asc" | "desc", SortDirection.SORT_ASC | SortDirection.SORT_DESC>]>;
|
|
82
82
|
readonly includeSparklines: v.OptionalSchema<v.BooleanSchema<undefined>, true>;
|
|
83
|
-
readonly sparklineIntervals: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["1h", "24h", "1w", "1m"], undefined>, undefined>, readonly ["24h"]>, v.TransformAction<("
|
|
83
|
+
readonly sparklineIntervals: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["1h", "24h", "1w", "1m"], undefined>, undefined>, readonly ["24h"]>, v.TransformAction<("1m" | "1h" | "1w" | "24h")[], (SparklineInterval.SPARKLINE_1H | SparklineInterval.SPARKLINE_24H | SparklineInterval.SPARKLINE_1W | SparklineInterval.SPARKLINE_1M)[]>]>;
|
|
84
84
|
}, undefined>;
|
|
85
85
|
type ListMarketOverviewInput = v.InferInput<typeof ListMarketOverviewInputSchema>;
|
|
86
86
|
//#endregion
|
|
@@ -11,7 +11,7 @@ declare const GetOrderbookInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema
|
|
|
11
11
|
depth: number;
|
|
12
12
|
}, {
|
|
13
13
|
symbol: string;
|
|
14
|
-
depth: 5 | 10 | 20 | 1 | 200 | 1000 | 500 |
|
|
14
|
+
depth: 5 | 10 | 20 | 1 | 200 | 1000 | 500 | 100 | 50;
|
|
15
15
|
protoDepth: Depth;
|
|
16
16
|
}>]>;
|
|
17
17
|
type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
|
|
@@ -42,11 +42,19 @@ type SocialVerification = Omit<SocialVerificationBase, "provider" | "method" | "
|
|
|
42
42
|
method: DecodedEnum<SocialVerificationMethod>;
|
|
43
43
|
status: DecodedEnum<SocialVerificationStatus>;
|
|
44
44
|
};
|
|
45
|
-
declare const StartVerificationInputSchema: v.StrictObjectSchema<{
|
|
45
|
+
declare const StartVerificationInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
|
|
46
46
|
readonly provider: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["twitter", "discord"], undefined>, v.TransformAction<"twitter" | "discord", SocialProvider$1.TWITTER | SocialProvider$1.DISCORD>]>;
|
|
47
47
|
readonly handle: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TransformAction<string, string>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 64, undefined>]>;
|
|
48
48
|
readonly method: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["profile", "channel", "dm"], undefined>, "profile">, v.TransformAction<"profile" | "channel" | "dm", SocialVerificationMethod$1.METHOD_PROFILE | SocialVerificationMethod$1.METHOD_CHANNEL | SocialVerificationMethod$1.METHOD_DM>]>;
|
|
49
|
-
}, undefined
|
|
49
|
+
}, undefined>, v.CheckAction<{
|
|
50
|
+
provider: SocialProvider$1.TWITTER | SocialProvider$1.DISCORD;
|
|
51
|
+
handle: string;
|
|
52
|
+
method: SocialVerificationMethod$1.METHOD_PROFILE | SocialVerificationMethod$1.METHOD_CHANNEL | SocialVerificationMethod$1.METHOD_DM;
|
|
53
|
+
}, "Handle must not contain '<' or '>'">, v.CheckAction<{
|
|
54
|
+
provider: SocialProvider$1.TWITTER | SocialProvider$1.DISCORD;
|
|
55
|
+
handle: string;
|
|
56
|
+
method: SocialVerificationMethod$1.METHOD_PROFILE | SocialVerificationMethod$1.METHOD_CHANNEL | SocialVerificationMethod$1.METHOD_DM;
|
|
57
|
+
}, "Twitter handle must be 1-15 letters, digits, or underscores">]>;
|
|
50
58
|
type StartVerificationInput = v.InferInput<typeof StartVerificationInputSchema>;
|
|
51
59
|
declare const SocialProviderInputSchema: v.StrictObjectSchema<{
|
|
52
60
|
readonly provider: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["twitter", "discord"], undefined>, v.TransformAction<"twitter" | "discord", SocialProvider$1.TWITTER | SocialProvider$1.DISCORD>]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"social-verification.schemas.d.ts","names":[],"sources":["../../../src/services/social-verification/social-verification.schemas.ts"],"mappings":";;;;;cAoBa,sBAAoB,EAAA;KACrB,iBAAiB,EAAE,kBAAkB;cAEpC,gCAA8B,EAAA;KAC/B,2BAA2B,EAAE,kBAAkB;cAE9C,gCAA8B,EAAA;KAC/B,2BAA2B,EAAE,mBAAmB;
|
|
1
|
+
{"version":3,"file":"social-verification.schemas.d.ts","names":[],"sources":["../../../src/services/social-verification/social-verification.schemas.ts"],"mappings":";;;;;cAoBa,sBAAoB,EAAA;KACrB,iBAAiB,EAAE,kBAAkB;cAEpC,gCAA8B,EAAA;KAC/B,2BAA2B,EAAE,kBAAkB;cAE9C,gCAA8B,EAAA;KAC/B,2BAA2B,EAAE,mBAAmB;cA+C/C,0BAAwB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgBhC,yBAAyB,EAAE,mBAAmB;KACvC,qBAAqB,KAAK;EAClC,UAAU,YAAY;EACtB,QAAQ,YAAY;EACpB,QAAQ,YAAY;;cAGX,8BAA4B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;KAoB7B,yBAAyB,EAAE,kBAAkB;cAO5C,2BAAyB,EAAA;;;KAI1B,sBAAsB,EAAE,kBAAkB;cAEzC,iCAA+B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;KAahC,4BAA4B,EAAE,mBAAmB;cAEhD,iCAA+B,EAAA,yBAAA,EAAA;;;;;;;KAShC,4BAA4B,EAAE,mBAAmB;cAEhD,+BAA6B,EAAA,yBAAA,EAAA;;;;;;;KAS9B,0BAA0B,EAAE,mBAAmB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { requiredEnumLabel } from "../../shared/proto-enum-codec.js";
|
|
2
2
|
import { TimestampSchema } from "../../shared/schemas.js";
|
|
3
|
+
import "../../gen/auth/v1/social_verification_pb.js";
|
|
3
4
|
import { SOCIAL_PROVIDER_VALUES, SOCIAL_VERIFICATION_METHOD_VALUES, SOCIAL_VERIFICATION_STATUS_VALUES, SocialProviderCodec, SocialVerificationMethodCodec, SocialVerificationStatusCodec } from "./social-verification.codecs.js";
|
|
4
5
|
import * as v from "valibot";
|
|
5
6
|
//#region src/services/social-verification/social-verification.schemas.ts
|
|
@@ -9,6 +10,7 @@ const SocialVerificationStatusSchema = v.picklist(SOCIAL_VERIFICATION_STATUS_VAL
|
|
|
9
10
|
function normalizeHandle(input) {
|
|
10
11
|
return (input ?? "").trim().replace(/^@+/, "");
|
|
11
12
|
}
|
|
13
|
+
const TWITTER_HANDLE_PATTERN = /^[A-Za-z0-9_]{1,15}$/;
|
|
12
14
|
/**
|
|
13
15
|
* Normalizes a social verification response into the SDK verification shape.
|
|
14
16
|
*/
|
|
@@ -45,11 +47,11 @@ v.object({
|
|
|
45
47
|
lastError: v.string(),
|
|
46
48
|
updatedAt: v.optional(TimestampSchema)
|
|
47
49
|
});
|
|
48
|
-
const StartVerificationInputSchema = v.strictObject({
|
|
50
|
+
const StartVerificationInputSchema = v.pipe(v.strictObject({
|
|
49
51
|
provider: v.pipe(SocialProviderSchema, v.transform((v) => SocialProviderCodec.inputToProto[v])),
|
|
50
52
|
handle: v.pipe(v.string(), v.transform(normalizeHandle), v.minLength(1), v.maxLength(64)),
|
|
51
53
|
method: v.pipe(v.optional(SocialVerificationMethodSchema, "profile"), v.transform((v) => SocialVerificationMethodCodec.inputToProto[v ?? "profile"]))
|
|
52
|
-
});
|
|
54
|
+
}), v.check(({ handle }) => !/[<>]/.test(handle), "Handle must not contain '<' or '>'"), v.check(({ provider, handle }) => provider !== 1 || TWITTER_HANDLE_PATTERN.test(handle), "Twitter handle must be 1-15 letters, digits, or underscores"));
|
|
53
55
|
const ProviderInputSchema = v.pipe(SocialProviderSchema, v.transform((v) => SocialProviderCodec.inputToProto[v]));
|
|
54
56
|
const SocialProviderInputSchema = v.strictObject({ provider: ProviderInputSchema });
|
|
55
57
|
const StartVerificationResponseSchema = v.pipe(v.object({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"social-verification.schemas.js","names":[],"sources":["../../../src/services/social-verification/social-verification.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { TimestampSchema } from \"../../shared/schemas.js\";\nimport { requiredEnumLabel } from \"../../shared/proto-enum-codec.js\";\nimport type { DecodedEnum } from \"../../utils/types.js\";\nimport
|
|
1
|
+
{"version":3,"file":"social-verification.schemas.js","names":[],"sources":["../../../src/services/social-verification/social-verification.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { TimestampSchema } from \"../../shared/schemas.js\";\nimport { requiredEnumLabel } from \"../../shared/proto-enum-codec.js\";\nimport type { DecodedEnum } from \"../../utils/types.js\";\nimport * as Proto from \"../../gen/auth/v1/social_verification_pb.js\";\nimport {\n SOCIAL_PROVIDER_VALUES,\n SOCIAL_VERIFICATION_METHOD_VALUES,\n SOCIAL_VERIFICATION_STATUS_VALUES,\n SocialProviderCodec,\n SocialVerificationMethodCodec,\n SocialVerificationStatusCodec,\n} from \"./social-verification.codecs.js\";\n\nexport {\n SOCIAL_PROVIDER_VALUES,\n SOCIAL_VERIFICATION_METHOD_VALUES,\n SOCIAL_VERIFICATION_STATUS_VALUES,\n} from \"./social-verification.codecs.js\";\n\nexport const SocialProviderSchema = v.picklist(SOCIAL_PROVIDER_VALUES);\nexport type SocialProvider = v.InferInput<typeof SocialProviderSchema>;\n\nexport const SocialVerificationMethodSchema = v.picklist(SOCIAL_VERIFICATION_METHOD_VALUES);\nexport type SocialVerificationMethod = v.InferInput<typeof SocialVerificationMethodSchema>;\n\nexport const SocialVerificationStatusSchema = v.picklist(SOCIAL_VERIFICATION_STATUS_VALUES);\nexport type SocialVerificationStatus = v.InferOutput<typeof SocialVerificationStatusSchema>;\n\nfunction normalizeHandle(input: string): string {\n return (input ?? \"\").trim().replace(/^@+/, \"\");\n}\n\nconst TWITTER_HANDLE_PATTERN = /^[A-Za-z0-9_]{1,15}$/;\n\n/**\n * Normalizes a social verification response into the SDK verification shape.\n */\nexport function transformVerification(\n v: Proto.SocialVerification | undefined,\n): SocialVerification | undefined {\n if (!v) return undefined;\n return {\n id: v.id,\n provider: requiredEnumLabel(\n SocialProviderCodec.protoToOutput,\n v.provider,\n \"SocialVerificationSchema\",\n \"provider\",\n ),\n method: requiredEnumLabel(\n SocialVerificationMethodCodec.protoToOutput,\n v.method,\n \"SocialVerificationSchema\",\n \"method\",\n ),\n handle: v.handle,\n providerUserId: v.providerUserId,\n challengeCode: v.challengeCode,\n status: requiredEnumLabel(\n SocialVerificationStatusCodec.protoToOutput,\n v.status,\n \"SocialVerificationSchema\",\n \"status\",\n ),\n requestedAt: v.requestedAt,\n expiresAt: v.expiresAt,\n verifiedAt: v.verifiedAt,\n attempts: v.attempts,\n lastError: v.lastError,\n updatedAt: v.updatedAt,\n };\n}\n\nexport const SocialVerificationSchema = v.object({\n id: v.bigint(),\n provider: SocialProviderSchema,\n method: SocialVerificationMethodSchema,\n handle: v.string(),\n providerUserId: v.string(),\n challengeCode: v.string(),\n status: SocialVerificationStatusSchema,\n requestedAt: v.optional(TimestampSchema),\n expiresAt: v.optional(TimestampSchema),\n verifiedAt: v.optional(TimestampSchema),\n attempts: v.number(),\n lastError: v.string(),\n updatedAt: v.optional(TimestampSchema),\n});\n\ntype SocialVerificationBase = v.InferOutput<typeof SocialVerificationSchema>;\nexport type SocialVerification = Omit<SocialVerificationBase, \"provider\" | \"method\" | \"status\"> & {\n provider: DecodedEnum<SocialProvider>;\n method: DecodedEnum<SocialVerificationMethod>;\n status: DecodedEnum<SocialVerificationStatus>;\n};\n\nexport const StartVerificationInputSchema = v.pipe(\n v.strictObject({\n provider: v.pipe(\n SocialProviderSchema,\n v.transform((v) => SocialProviderCodec.inputToProto[v]),\n ),\n handle: v.pipe(v.string(), v.transform(normalizeHandle), v.minLength(1), v.maxLength(64)),\n method: v.pipe(\n v.optional(SocialVerificationMethodSchema, \"profile\"),\n v.transform((v) => SocialVerificationMethodCodec.inputToProto[v ?? \"profile\"]),\n ),\n }),\n v.check(({ handle }) => !/[<>]/.test(handle), \"Handle must not contain '<' or '>'\"),\n v.check(\n ({ provider, handle }) =>\n provider !== Proto.SocialProvider.TWITTER || TWITTER_HANDLE_PATTERN.test(handle),\n \"Twitter handle must be 1-15 letters, digits, or underscores\",\n ),\n);\n\nexport type StartVerificationInput = v.InferInput<typeof StartVerificationInputSchema>;\n\nexport const ProviderInputSchema = v.pipe(\n SocialProviderSchema,\n v.transform((v) => SocialProviderCodec.inputToProto[v]),\n);\n\nexport const SocialProviderInputSchema = v.strictObject({\n provider: ProviderInputSchema,\n});\n\nexport type SocialProviderInput = v.InferInput<typeof SocialProviderInputSchema>;\n\nexport const StartVerificationResponseSchema = v.pipe(\n v.object({\n challengeCode: v.string(),\n expiresAt: v.optional(TimestampSchema),\n verification: v.optional(v.custom<Proto.SocialVerification>(() => true)),\n }),\n v.transform((res) => ({\n challengeCode: res.challengeCode,\n expiresAt: res.expiresAt,\n verification: transformVerification(res.verification),\n })),\n);\n\nexport type StartVerificationResponse = v.InferOutput<typeof StartVerificationResponseSchema>;\n\nexport const VerificationReadyResponseSchema = v.pipe(\n v.object({\n verification: v.optional(v.custom<Proto.SocialVerification>(() => true)),\n }),\n v.transform((res) => ({\n verification: transformVerification(res.verification),\n })),\n);\n\nexport type VerificationReadyResponse = v.InferOutput<typeof VerificationReadyResponseSchema>;\n\nexport const GetVerificationResponseSchema = v.pipe(\n v.object({\n verification: v.optional(v.custom<Proto.SocialVerification>(() => true)),\n }),\n v.transform((res) => ({\n verification: transformVerification(res.verification),\n })),\n);\n\nexport type GetVerificationResponse = v.InferOutput<typeof GetVerificationResponseSchema>;\n"],"mappings":";;;;;;AAoBA,MAAa,uBAAuB,EAAE,SAAS,sBAAsB;AAGrE,MAAa,iCAAiC,EAAE,SAAS,iCAAiC;AAG1F,MAAa,iCAAiC,EAAE,SAAS,iCAAiC;AAG1F,SAAS,gBAAgB,OAAuB;CAC5C,QAAQ,SAAS,GAAA,CAAI,KAAK,CAAC,CAAC,QAAQ,OAAO,EAAE;AACjD;AAEA,MAAM,yBAAyB;;;;AAK/B,SAAgB,sBACZ,GAC8B;CAC9B,IAAI,CAAC,GAAG,OAAO,KAAA;CACf,OAAO;EACH,IAAI,EAAE;EACN,UAAU,kBACN,oBAAoB,eACpB,EAAE,UACF,4BACA,UACJ;EACA,QAAQ,kBACJ,8BAA8B,eAC9B,EAAE,QACF,4BACA,QACJ;EACA,QAAQ,EAAE;EACV,gBAAgB,EAAE;EAClB,eAAe,EAAE;EACjB,QAAQ,kBACJ,8BAA8B,eAC9B,EAAE,QACF,4BACA,QACJ;EACA,aAAa,EAAE;EACf,WAAW,EAAE;EACb,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,WAAW,EAAE;EACb,WAAW,EAAE;CACjB;AACJ;AAEwC,EAAE,OAAO;CAC7C,IAAI,EAAE,OAA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KAC7C,EAAE,OAAO,EACL,cAAc,EAAE,SAAS,EAAE,aAAuC,IAAI,CAAC,EAC3E,CAAC,GACD,EAAE,WAAW,SAAS,EAClB,cAAc,sBAAsB,IAAI,YAAY,EACxD,EAAE,CACN;AAIA,MAAa,gCAAgC,EAAE,KAC3C,EAAE,OAAO,EACL,cAAc,EAAE,SAAS,EAAE,aAAuC,IAAI,CAAC,EAC3E,CAAC,GACD,EAAE,WAAW,SAAS,EAClB,cAAc,sBAAsB,IAAI,YAAY,EACxD,EAAE,CACN"}
|
|
@@ -243,7 +243,7 @@ declare const SubaccountActivityEventSchema: v.ObjectSchema<{
|
|
|
243
243
|
seconds: bigint;
|
|
244
244
|
nanos: number;
|
|
245
245
|
} | undefined, number | undefined>]>;
|
|
246
|
-
readonly entityKind: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEntityKind, undefined>, v.TransformAction<ActivityEntityKind, "unspecified" | "api_key" | "account" | "subaccount" | "destination" | "session" | "
|
|
246
|
+
readonly entityKind: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEntityKind, undefined>, v.TransformAction<ActivityEntityKind, "unspecified" | "api_key" | "account" | "subaccount" | "destination" | "session" | "member" | "policy" | "invite" | "security">]>;
|
|
247
247
|
readonly eventAction: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEventAction, undefined>, v.TransformAction<ActivityEventAction, "unspecified" | "enabled" | "disabled" | "deleted" | "created" | "updated" | "removed" | "role_set" | "received" | "replied" | "failed" | "revoked" | "blocked" | "hold_placed" | "hold_released">]>;
|
|
248
248
|
readonly source: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ActivityEventSource, undefined>, v.TransformAction<ActivityEventSource, "unspecified" | "web" | "mobile" | "api">]>;
|
|
249
249
|
readonly ip: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { parseOptionalPositiveIntLike } from "../utils/numbers.js";
|
|
2
2
|
import { CatalogConversionError } from "../catalogs/types.js";
|
|
3
|
+
import "../shared/wire-bounds.js";
|
|
3
4
|
import { positiveDecimalInputToScaled } from "../shared/decimal-surface.js";
|
|
4
5
|
//#region src/services/trailing-oneof-inputs.ts
|
|
5
|
-
/** Slippage ticks travel as int32 on the wire. */
|
|
6
|
-
const MAX_INT32_TICKS = 2147483647n;
|
|
7
6
|
function parseTrailingDistanceInput(scales, distance, fieldName) {
|
|
8
7
|
if (distance.kind === "none") return {
|
|
9
8
|
case: void 0,
|
|
@@ -27,7 +26,7 @@ function parseSlippageInput(scales, slippage, options) {
|
|
|
27
26
|
};
|
|
28
27
|
if (slippage.kind === "slippage") {
|
|
29
28
|
const ticks = positiveDecimalInputToScaled(`${options.fieldName}.slippage`, slippage.slippage, scales.price());
|
|
30
|
-
if (ticks >
|
|
29
|
+
if (ticks > 2147483647n) throw new CatalogConversionError(`${options.fieldName}.slippage`, `${options.fieldName}.slippage exceeds the maximum supported price distance: ${slippage.slippage}`);
|
|
31
30
|
return {
|
|
32
31
|
case: options.ticksCase,
|
|
33
32
|
value: Number(ticks)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trailing-oneof-inputs.js","names":[],"sources":["../../src/services/trailing-oneof-inputs.ts"],"sourcesContent":["import { positiveDecimalInputToScaled, type SdkScales } from \"../shared/decimal-surface.js\";\nimport { CatalogConversionError } from \"../catalogs/types.js\";\nimport { parseOptionalPositiveIntLike } from \"../utils/numbers.js\";\n\ntype PositiveIntLikeInput = string | number;\n\n/**\n * Trailing distance and slippage inputs: absolute price distances and\n * slippages are decimal price strings (e.g. \"0.50\"), converted to wire ticks\n * via the price scale; basis points are integers.\n */\nexport type TrailingDistanceInput =\n | { kind: \"distance\"; distance: string }\n | { kind: \"bps\"; bps: PositiveIntLikeInput }\n | { kind: \"none\" };\n\nexport type SlippageInput =\n | { kind: \"slippage\"; slippage: string }\n | { kind: \"bps\"; bps: PositiveIntLikeInput }\n | { kind: \"none\" };\n\ntype UnsetOneof = { case: undefined; value: undefined };\n\ntype TrailingDistanceOneof =\n | { case: \"trailingDistanceTicks\"; value: bigint }\n | { case: \"trailingDistanceBps\"; value: number }\n | UnsetOneof;\n\ntype SlippageOneof<TicksCase extends string, BpsCase extends string> =\n | { case: TicksCase; value: number }\n | { case: BpsCase; value: number }\n | UnsetOneof;\n\ntype SlippageOptions<TicksCase extends string, BpsCase extends string> = {\n fieldName: string;\n ticksCase: TicksCase;\n bpsCase: BpsCase;\n maxBps?: number;\n};\n\
|
|
1
|
+
{"version":3,"file":"trailing-oneof-inputs.js","names":[],"sources":["../../src/services/trailing-oneof-inputs.ts"],"sourcesContent":["import { positiveDecimalInputToScaled, type SdkScales } from \"../shared/decimal-surface.js\";\nimport { CatalogConversionError } from \"../catalogs/types.js\";\nimport { parseOptionalPositiveIntLike } from \"../utils/numbers.js\";\nimport { PROTOBUF_INT32_MAX } from \"../shared/wire-bounds.js\";\n\ntype PositiveIntLikeInput = string | number;\n\n/**\n * Trailing distance and slippage inputs: absolute price distances and\n * slippages are decimal price strings (e.g. \"0.50\"), converted to wire ticks\n * via the price scale; basis points are integers.\n */\nexport type TrailingDistanceInput =\n | { kind: \"distance\"; distance: string }\n | { kind: \"bps\"; bps: PositiveIntLikeInput }\n | { kind: \"none\" };\n\nexport type SlippageInput =\n | { kind: \"slippage\"; slippage: string }\n | { kind: \"bps\"; bps: PositiveIntLikeInput }\n | { kind: \"none\" };\n\ntype UnsetOneof = { case: undefined; value: undefined };\n\ntype TrailingDistanceOneof =\n | { case: \"trailingDistanceTicks\"; value: bigint }\n | { case: \"trailingDistanceBps\"; value: number }\n | UnsetOneof;\n\ntype SlippageOneof<TicksCase extends string, BpsCase extends string> =\n | { case: TicksCase; value: number }\n | { case: BpsCase; value: number }\n | UnsetOneof;\n\ntype SlippageOptions<TicksCase extends string, BpsCase extends string> = {\n fieldName: string;\n ticksCase: TicksCase;\n bpsCase: BpsCase;\n maxBps?: number;\n};\n\nexport function parseTrailingDistanceInput(\n scales: SdkScales,\n distance: TrailingDistanceInput,\n fieldName: string,\n): TrailingDistanceOneof {\n if (distance.kind === \"none\") {\n return { case: undefined, value: undefined };\n }\n if (distance.kind === \"distance\") {\n return {\n case: \"trailingDistanceTicks\",\n value: positiveDecimalInputToScaled(\n `${fieldName}.distance`,\n distance.distance,\n scales.price(),\n ),\n };\n }\n\n const bps = parseOptionalPositiveIntLike(distance.bps);\n if (bps === undefined || bps <= 0) {\n throw new Error(`${fieldName}Bps must be a positive integer`);\n }\n return { case: \"trailingDistanceBps\", value: bps };\n}\n\nexport function parseSlippageInput<const TicksCase extends string, const BpsCase extends string>(\n scales: SdkScales,\n slippage: SlippageInput | undefined,\n options: SlippageOptions<TicksCase, BpsCase>,\n): SlippageOneof<TicksCase, BpsCase> {\n if (!slippage || slippage.kind === \"none\") {\n return { case: undefined, value: undefined };\n }\n if (slippage.kind === \"slippage\") {\n const ticks = positiveDecimalInputToScaled(\n `${options.fieldName}.slippage`,\n slippage.slippage,\n scales.price(),\n );\n if (ticks > PROTOBUF_INT32_MAX) {\n throw new CatalogConversionError(\n `${options.fieldName}.slippage`,\n `${options.fieldName}.slippage exceeds the maximum supported price distance: ${slippage.slippage}`,\n );\n }\n return { case: options.ticksCase, value: Number(ticks) };\n }\n\n const bps = parseOptionalPositiveIntLike(slippage.bps);\n if (bps === undefined || bps <= 0 || exceedsMax(bps, options.maxBps)) {\n throw new Error(\n `${options.fieldName}Bps must be ${\n options.maxBps === undefined\n ? \"a positive integer\"\n : `between 1 and ${options.maxBps}`\n }`,\n );\n }\n return { case: options.bpsCase, value: bps };\n}\n\nfunction exceedsMax(value: number, max: number | undefined): boolean {\n return max !== undefined && value > max;\n}\n"],"mappings":";;;;;AAyCA,SAAgB,2BACZ,QACA,UACA,WACqB;CACrB,IAAI,SAAS,SAAS,QAClB,OAAO;EAAE,MAAM,KAAA;EAAW,OAAO,KAAA;CAAU;CAE/C,IAAI,SAAS,SAAS,YAClB,OAAO;EACH,MAAM;EACN,OAAO,6BACH,GAAG,UAAU,YACb,SAAS,UACT,OAAO,MAAM,CACjB;CACJ;CAGJ,MAAM,MAAM,6BAA6B,SAAS,GAAG;CACrD,IAAI,QAAQ,KAAA,KAAa,OAAO,GAC5B,MAAM,IAAI,MAAM,GAAG,UAAU,+BAA+B;CAEhE,OAAO;EAAE,MAAM;EAAuB,OAAO;CAAI;AACrD;AAEA,SAAgB,mBACZ,QACA,UACA,SACiC;CACjC,IAAI,CAAC,YAAY,SAAS,SAAS,QAC/B,OAAO;EAAE,MAAM,KAAA;EAAW,OAAO,KAAA;CAAU;CAE/C,IAAI,SAAS,SAAS,YAAY;EAC9B,MAAM,QAAQ,6BACV,GAAG,QAAQ,UAAU,YACrB,SAAS,UACT,OAAO,MAAM,CACjB;EACA,IAAI,QAAA,aACA,MAAM,IAAI,uBACN,GAAG,QAAQ,UAAU,YACrB,GAAG,QAAQ,UAAU,0DAA0D,SAAS,UAC5F;EAEJ,OAAO;GAAE,MAAM,QAAQ;GAAW,OAAO,OAAO,KAAK;EAAE;CAC3D;CAEA,MAAM,MAAM,6BAA6B,SAAS,GAAG;CACrD,IAAI,QAAQ,KAAA,KAAa,OAAO,KAAK,WAAW,KAAK,QAAQ,MAAM,GAC/D,MAAM,IAAI,MACN,GAAG,QAAQ,UAAU,cACjB,QAAQ,WAAW,KAAA,IACb,uBACA,iBAAiB,QAAQ,UAEvC;CAEJ,OAAO;EAAE,MAAM,QAAQ;EAAS,OAAO;CAAI;AAC/C;AAEA,SAAS,WAAW,OAAe,KAAkC;CACjE,OAAO,QAAQ,KAAA,KAAa,QAAQ;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trigger-input.schemas.d.ts","names":[],"sources":["../../../src/services/triggers/trigger-input.schemas.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"trigger-input.schemas.d.ts","names":[],"sources":["../../../src/services/triggers/trigger-input.schemas.ts"],"mappings":";;;;;iBAyVgB,+BAA+B,QAAQ,Y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;;;;;KACtB,kBAAkB,EAAE,kBAAkB;cAErC,yBAAuB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;KACxB,oBAAoB,EAAE,kBAAkB;cAEvC,0BAAwB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;KACzB,qBAAqB,EAAE,kBAAkB;iBAErC,+BAA+B,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAsDpD,qBAAqB,EAAE,WAAW,kBAAkB;cAEnD,8BAA4B,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;KAiB7B,yBAAyB,EAAE,kBAAkB"}
|
|
@@ -4,6 +4,7 @@ import { parseOptionalPositiveIntLike } from "../../utils/numbers.js";
|
|
|
4
4
|
import { idInputSchema } from "../../shared/schemas.js";
|
|
5
5
|
import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
|
|
6
6
|
import { CatalogConversionError } from "../../catalogs/types.js";
|
|
7
|
+
import "../../shared/wire-bounds.js";
|
|
7
8
|
import { positiveDecimalInputToScaled } from "../../shared/decimal-surface.js";
|
|
8
9
|
import { BpsStringOrNumberInputSchema, NoneInputSchema } from "../shared.js";
|
|
9
10
|
import { OrderSideCodec } from "../orders/order-enums.codecs.js";
|
|
@@ -39,7 +40,6 @@ const MaxSlippageInputSchema = v.union([
|
|
|
39
40
|
BpsStringOrNumberInputSchema,
|
|
40
41
|
NoneInputSchema
|
|
41
42
|
]);
|
|
42
|
-
const MAX_INT32 = 2147483647n;
|
|
43
43
|
function parseTrailingDistance(scales, distance) {
|
|
44
44
|
if (distance.kind === "distance") return {
|
|
45
45
|
case: "trailingDistanceTicks",
|
|
@@ -59,7 +59,7 @@ function parseMaxSlippage(scales, slippage) {
|
|
|
59
59
|
};
|
|
60
60
|
if (slippage.kind === "slippage") {
|
|
61
61
|
const ticks = positiveDecimalInputToScaled("maxSlippage.slippage", slippage.slippage, scales.price());
|
|
62
|
-
if (ticks >
|
|
62
|
+
if (ticks > 2147483647n) throw new CatalogConversionError("maxSlippage.slippage", `maxSlippage.slippage exceeds the maximum supported price distance: ${slippage.slippage}`);
|
|
63
63
|
return {
|
|
64
64
|
case: "maxSlippageTicks",
|
|
65
65
|
value: Number(ticks)
|
|
@@ -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 { CatalogConversionError } from \"../../catalogs/types.js\";\nimport { parseOptionalPositiveIntLike } 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 } 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\";\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 MAX_INT32 = 2_147_483_647n;\n\nfunction parseTrailingDistance(\n scales: SdkScales,\n distance: v.InferOutput<typeof TrailingDistanceInputSchema>,\n): TrailingDistanceOneof {\n if (distance.kind === \"distance\") {\n return {\n case: \"trailingDistanceTicks\",\n value: positiveDecimalInputToScaled(\n \"trailingDistance.distance\",\n distance.distance,\n scales.price(),\n ),\n };\n }\n const bps = parseOptionalPositiveIntLike(distance.bps);\n if (bps === undefined || bps <= 0) {\n throw new Error(\"trailingDistanceBps must be a positive integer\");\n }\n return { case: \"trailingDistanceBps\", value: bps };\n}\n\nfunction parseMaxSlippage(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippageInputSchema> | undefined,\n): MaxSlippageOneof {\n if (!slippage || slippage.kind === \"none\") {\n return { case: undefined, value: undefined };\n }\n if (slippage.kind === \"slippage\") {\n const ticks = positiveDecimalInputToScaled(\n \"maxSlippage.slippage\",\n slippage.slippage,\n scales.price(),\n );\n if (ticks > MAX_INT32) {\n throw new CatalogConversionError(\n \"maxSlippage.slippage\",\n `maxSlippage.slippage exceeds the maximum supported price distance: ${slippage.slippage}`,\n );\n }\n return { case: \"maxSlippageTicks\", value: Number(ticks) };\n }\n const bps = parseOptionalPositiveIntLike(slippage.bps);\n if (bps === undefined || bps <= 0) {\n throw new Error(\"maxSlippageBps must be a positive integer\");\n }\n return { case: \"maxSlippageBps\", value: bps };\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) => {\n const durationMs = parseOptionalPositiveIntLike(value);\n if (!durationMs || durationMs < 1000) {\n throw new Error(\"durationMs must be at least 1000ms\");\n }\n return BigInt(durationMs);\n }),\n ),\n sliceIntervalMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => {\n const sliceIntervalMs = parseOptionalPositiveIntLike(value);\n if (!sliceIntervalMs || sliceIntervalMs < 100) {\n throw new Error(\"sliceIntervalMs must be at least 100ms\");\n }\n return BigInt(sliceIntervalMs);\n }),\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 );\n}\n\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\nexport type CreateTriggerInput = v.InferInput<ReturnType<typeof createCreateTriggerInputSchema>>;\n\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 symbol: v.optional(v.pipe(v.string(), v.trim())),\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\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 = TriggerScopedInputSchema;\nexport type ResumeTriggerInput = v.InferInput<typeof ResumeTriggerInputSchema>;\n\nexport function createModifyTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n triggerPrice: v.optional(DecimalInputStringSchema),\n limitPrice: v.optional(DecimalInputStringSchema),\n trailingDistance: v.optional(TrailingDistanceInputSchema),\n activationPrice: v.optional(DecimalInputStringSchema),\n maxSlippage: v.optional(MaxSlippageInputSchema),\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 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 : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage:\n input.maxSlippage === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseMaxSlippage(scales, input.maxSlippage),\n })),\n );\n}\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":";;;;;;;;;;;;;;AAoCA,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,0BACA,4BACJ,CAAC;AAED,MAAM,yBAAyB,EAAE,MAAM;CACnC;CACA;CACA;AACJ,CAAC;AAED,MAAM,YAAY;AAElB,SAAS,sBACL,QACA,UACqB;CACrB,IAAI,SAAS,SAAS,YAClB,OAAO;EACH,MAAM;EACN,OAAO,6BACH,6BACA,SAAS,UACT,OAAO,MAAM,CACjB;CACJ;CAEJ,MAAM,MAAM,6BAA6B,SAAS,GAAG;CACrD,IAAI,QAAQ,KAAA,KAAa,OAAO,GAC5B,MAAM,IAAI,MAAM,gDAAgD;CAEpE,OAAO;EAAE,MAAM;EAAuB,OAAO;CAAI;AACrD;AAEA,SAAS,iBACL,QACA,UACgB;CAChB,IAAI,CAAC,YAAY,SAAS,SAAS,QA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W;CACxD,EAAE,CACN;AACJ;AAIA,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
|
+
{"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 { CatalogConversionError } from \"../../catalogs/types.js\";\nimport { PROTOBUF_INT32_MAX } from \"../../shared/wire-bounds.js\";\nimport { parseOptionalPositiveIntLike } 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 } 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\";\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\nfunction parseTrailingDistance(\n scales: SdkScales,\n distance: v.InferOutput<typeof TrailingDistanceInputSchema>,\n): TrailingDistanceOneof {\n if (distance.kind === \"distance\") {\n return {\n case: \"trailingDistanceTicks\",\n value: positiveDecimalInputToScaled(\n \"trailingDistance.distance\",\n distance.distance,\n scales.price(),\n ),\n };\n }\n const bps = parseOptionalPositiveIntLike(distance.bps);\n if (bps === undefined || bps <= 0) {\n throw new Error(\"trailingDistanceBps must be a positive integer\");\n }\n return { case: \"trailingDistanceBps\", value: bps };\n}\n\nfunction parseMaxSlippage(\n scales: SdkScales,\n slippage: v.InferOutput<typeof MaxSlippageInputSchema> | undefined,\n): MaxSlippageOneof {\n if (!slippage || slippage.kind === \"none\") {\n return { case: undefined, value: undefined };\n }\n if (slippage.kind === \"slippage\") {\n const ticks = positiveDecimalInputToScaled(\n \"maxSlippage.slippage\",\n slippage.slippage,\n scales.price(),\n );\n if (ticks > PROTOBUF_INT32_MAX) {\n throw new CatalogConversionError(\n \"maxSlippage.slippage\",\n `maxSlippage.slippage exceeds the maximum supported price distance: ${slippage.slippage}`,\n );\n }\n return { case: \"maxSlippageTicks\", value: Number(ticks) };\n }\n const bps = parseOptionalPositiveIntLike(slippage.bps);\n if (bps === undefined || bps <= 0) {\n throw new Error(\"maxSlippageBps must be a positive integer\");\n }\n return { case: \"maxSlippageBps\", value: bps };\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) => {\n const durationMs = parseOptionalPositiveIntLike(value);\n if (!durationMs || durationMs < 1000) {\n throw new Error(\"durationMs must be at least 1000ms\");\n }\n return BigInt(durationMs);\n }),\n ),\n sliceIntervalMs: v.pipe(\n v.union([v.pipe(v.string(), v.trim()), v.number()]),\n v.transform((value) => {\n const sliceIntervalMs = parseOptionalPositiveIntLike(value);\n if (!sliceIntervalMs || sliceIntervalMs < 100) {\n throw new Error(\"sliceIntervalMs must be at least 100ms\");\n }\n return BigInt(sliceIntervalMs);\n }),\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 );\n}\n\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\nexport type CreateTriggerInput = v.InferInput<ReturnType<typeof createCreateTriggerInputSchema>>;\n\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 symbol: v.optional(v.pipe(v.string(), v.trim())),\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\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 = TriggerScopedInputSchema;\nexport type ResumeTriggerInput = v.InferInput<typeof ResumeTriggerInputSchema>;\n\nexport function createModifyTriggerInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...TriggerScopedInputEntries,\n triggerPrice: v.optional(DecimalInputStringSchema),\n limitPrice: v.optional(DecimalInputStringSchema),\n trailingDistance: v.optional(TrailingDistanceInputSchema),\n activationPrice: v.optional(DecimalInputStringSchema),\n maxSlippage: v.optional(MaxSlippageInputSchema),\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 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 : positiveDecimalInputToScaled(\n \"activationPrice\",\n input.activationPrice,\n scales.price(),\n ),\n maxSlippage:\n input.maxSlippage === undefined\n ? ({ case: undefined, value: undefined } as const)\n : parseMaxSlippage(scales, input.maxSlippage),\n })),\n );\n}\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":";;;;;;;;;;;;;;;AAqCA,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,0BACA,4BACJ,CAAC;AAED,MAAM,yBAAyB,EAAE,MAAM;CACnC;CACA;CACA;AACJ,CAAC;AAED,SAAS,sBACL,QACA,UACqB;CACrB,IAAI,SAAS,SAAS,YAClB,OAAO;EACH,MAAM;EACN,OAAO,6BACH,6BACA,SAAS,UACT,OAAO,MAAM,CACjB;CACJ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AAsB,QAAQ,MAAM,gBAAgB;EAC9D,sBACI,MAAM,oBAAoB,KAAA,IACpB,KAAA,IACA,6BACI,mBACA,MAAM,iBACN,OAAO,MAAM,CACjB;EACV,aACI,MAAM,gBAAgB,KAAA,IACf;GAAE,MAAM,KAAA;GAAW,OAAO,KAAA;EAAU,IACrC,iBAAiB,QAAQ,MAAM,WAAW;CACxD,EAAE,CACN;AACJ;AAIA,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":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAkHgB,6BAA6B,IAAI,eAAe;;;;;;
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAkHgB,6BAA6B,IAAI,eAAe;;;;;;iBAyIhD,iBAAiB;;;;;;iBAyBjB,iCAAiC"}
|
|
@@ -75,6 +75,7 @@ function connectErrorToPolyesterError(ce) {
|
|
|
75
75
|
if (hasAuthErrorCode(ce, 35)) return new PolicyLockedError(withFallback("Policy is locked."), options);
|
|
76
76
|
if (hasAuthErrorCode(ce, 36)) return new PolicyScopeMismatchError(withFallback("Policy does not belong to the target account scope."), options);
|
|
77
77
|
if (hasAuthErrorCode(ce, 39)) return new MfaLastFactorRequiredError(withFallback("At least one active MFA factor must remain enrolled."), options);
|
|
78
|
+
if (hasAuthErrorCode(ce, 40)) return new InternalServerError(withFallback("Internal server error."), options);
|
|
78
79
|
const mfaVerificationReason = getMfaVerificationFailureReason(ce);
|
|
79
80
|
if (mfaVerificationReason) return new MfaVerificationError(withFallback("MFA verification failed."), mfaVerificationReason, options);
|
|
80
81
|
const mfaKind = detectMfaErrorKind(ce);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.js","names":["OrderErrorDetailSchema"],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { AuthErrorCode, AuthErrorDetailSchema } from \"../gen/auth/v1/auth_pb.js\";\nimport {\n ErrorCode as OrderErrorCode,\n ErrorDetailSchema as OrderErrorDetailSchema,\n} from \"../gen/orders/v1/orders_pb.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n InternalServerError,\n isAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n StepUpRequiredError,\n TimeoutError,\n TransientError,\n ValidationError,\n} from \"./errors.js\";\nimport { RateLimitDetailSchema, type RateLimitDetail } from \"./rate-limit.schemas.js\";\n\nfunction getAuthErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(AuthErrorDetailSchema);\n}\n\nfunction hasAuthErrorCode(err: unknown, code: AuthErrorCode): boolean {\n return getAuthErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction hasOrderErrorCode(err: unknown, code: OrderErrorCode): boolean {\n return getOrderErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction getOrderErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(OrderErrorDetailSchema);\n}\n\nfunction getRateLimitDetail(err: unknown): RateLimitDetail | undefined {\n for (const orderDetail of getOrderErrorDetails(err)) {\n if (!orderDetail.rateLimit) continue;\n const result = v.safeParse(RateLimitDetailSchema, orderDetail.rateLimit);\n if (result.success) return result.output;\n }\n return undefined;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_ELEVATION_REQUIRED)) {\n return \"session-elevation\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_STEP_UP_REQUIRED)) return \"step-up\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_NOT_ENROLLED)) return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const options: PolyesterErrorOptions = { cause: ce };\n const withFallback = (fallback: string) => message || fallback;\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_RESOURCE_NOT_FOUND)) {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_REVISION_CONFLICT)) {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_IN_USE)) {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_LOCKED)) {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_SCOPE_MISMATCH)) {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_MFA_LAST_FACTOR_REQUIRED)) {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(ce);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = detectMfaErrorKind(ce);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n if (hasOrderErrorCode(ce, OrderErrorCode.STALE_QUOTE)) {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = getRateLimitDetail(ce);\n if (rateLimit || hasOrderErrorCode(ce, OrderErrorCode.RATE_LIMIT_EXCEEDED)) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(err: unknown): MfaVerificationFailureReason | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_INVALID)) {\n return \"challenge-invalid\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_LOCKED)) {\n return \"challenge-locked\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_OTP_INVALID)) return \"otp-invalid\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_RECOVERY_INVALID)) {\n return \"recovery-code-invalid\";\n }\n if (\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_CREDENTIAL_INVALID) ||\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_VERIFY_FAILED)\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-cancelled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) return err;\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nasync function* mapStreamErrors<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw toPolyesterError(err);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message) };\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAqCA,SAAS,oBAAoB,KAAc;CACvC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAY,qBAAqB;AACnE;AAEA,SAAS,iBAAiB,KAAc,MAA8B;CAClE,OAAO,oBAAoB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AACzE;AAEA,SAAS,kBAAkB,KAAc,MAA+B;CACpE,OAAO,qBAAqB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AAC1E;AAEA,SAAS,qBAAqB,KAAc;CACxC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAYA,iBAAsB;AACpE;AAEA,SAAS,mBAAmB,KAA2C;CACnE,KAAK,MAAM,eAAe,qBAAqB,GAAG,GAAG;EACjD,IAAI,CAAC,YAAY,WAAW;EAC5B,MAAM,SAAS,EAAE,UAAU,uBAAuB,YAAY,SAAS;EACvE,IAAI,OAAO,SAAS,OAAO,OAAO;CACtC;AAEJ;AAEA,SAAS,iBAAiB,WAA4D;CAClF,IAAI,WAAW,iBAAiB,KAAA,GAAW,OAAO,KAAA;CAClD,MAAM,QAAQ,OAAO,UAAU,YAAY;CAC3C,OAAO,SAAS,OAAO,OAAO,gBAAgB,IAAI,OAAO,KAAK,IAAI,KAAA;AACtE;;;;;;AAOA,SAAgB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;;;;;AAOA,SAAgB,gCAA6C;CACzD,QAAQ,SAAS,OAAO,QAAQ;EAC5B,IAAI;GACA,MAAM,MAAM,MAAM,KAAK,GAAG;GAC1B,IAAI,IAAI,QACJ,OAAO;IAAE,GAAG;IAAK,SAAS,gBAAgB,IAAI,OAAO;GAAE;GAE3D,OAAO;EACX,SAAS,KAAK;GACV,MAAM,iBAAiB,GAAG;EAC9B;CACJ;AACJ;;;;;AAMA,SAAgB,4BAA4B,WAAiC;CACzE,OAAO;EACH,MAAM,MAAM,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GACjE,IAAI;IACA,OAAO,MAAM,UAAU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,OAAO;IAAE;GACrE,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.js","names":["OrderErrorDetailSchema"],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { AuthErrorCode, AuthErrorDetailSchema } from \"../gen/auth/v1/auth_pb.js\";\nimport {\n ErrorCode as OrderErrorCode,\n ErrorDetailSchema as OrderErrorDetailSchema,\n} from \"../gen/orders/v1/orders_pb.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n InternalServerError,\n isAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n StepUpRequiredError,\n TimeoutError,\n TransientError,\n ValidationError,\n} from \"./errors.js\";\nimport { RateLimitDetailSchema, type RateLimitDetail } from \"./rate-limit.schemas.js\";\n\nfunction getAuthErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(AuthErrorDetailSchema);\n}\n\nfunction hasAuthErrorCode(err: unknown, code: AuthErrorCode): boolean {\n return getAuthErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction hasOrderErrorCode(err: unknown, code: OrderErrorCode): boolean {\n return getOrderErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction getOrderErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(OrderErrorDetailSchema);\n}\n\nfunction getRateLimitDetail(err: unknown): RateLimitDetail | undefined {\n for (const orderDetail of getOrderErrorDetails(err)) {\n if (!orderDetail.rateLimit) continue;\n const result = v.safeParse(RateLimitDetailSchema, orderDetail.rateLimit);\n if (result.success) return result.output;\n }\n return undefined;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_ELEVATION_REQUIRED)) {\n return \"session-elevation\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_STEP_UP_REQUIRED)) return \"step-up\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_NOT_ENROLLED)) return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const options: PolyesterErrorOptions = { cause: ce };\n const withFallback = (fallback: string) => message || fallback;\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_RESOURCE_NOT_FOUND)) {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_REVISION_CONFLICT)) {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_IN_USE)) {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_LOCKED)) {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_SCOPE_MISMATCH)) {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_MFA_LAST_FACTOR_REQUIRED)) {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_INTERNAL_ERROR)) {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(ce);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = detectMfaErrorKind(ce);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n if (hasOrderErrorCode(ce, OrderErrorCode.STALE_QUOTE)) {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = getRateLimitDetail(ce);\n if (rateLimit || hasOrderErrorCode(ce, OrderErrorCode.RATE_LIMIT_EXCEEDED)) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(err: unknown): MfaVerificationFailureReason | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_INVALID)) {\n return \"challenge-invalid\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_LOCKED)) {\n return \"challenge-locked\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_OTP_INVALID)) return \"otp-invalid\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_RECOVERY_INVALID)) {\n return \"recovery-code-invalid\";\n }\n if (\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_CREDENTIAL_INVALID) ||\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_VERIFY_FAILED)\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-cancelled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) return err;\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nasync function* mapStreamErrors<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw toPolyesterError(err);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message) };\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAqCA,SAAS,oBAAoB,KAAc;CACvC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAY,qBAAqB;AACnE;AAEA,SAAS,iBAAiB,KAAc,MAA8B;CAClE,OAAO,oBAAoB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AACzE;AAEA,SAAS,kBAAkB,KAAc,MAA+B;CACpE,OAAO,qBAAqB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AAC1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;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,OAAO;IAAE;GACrE,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;CACJ;AACJ"}
|
|
@@ -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":";;;;;;;UA8BiB;EACb,SAAS;EACT;EACA,QAAQ,MAAM;EACd,YAAY,MAAM;EAClB,aAAa;EACb,kBAAkB"}
|