@domfi/sdk 0.1.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.
Files changed (93) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +786 -0
  3. package/dist/actions.cjs +1 -0
  4. package/dist/actions.d.cts +17 -0
  5. package/dist/actions.d.ts +17 -0
  6. package/dist/actions.js +1 -0
  7. package/dist/api.cjs +1 -0
  8. package/dist/api.d.cts +664 -0
  9. package/dist/api.d.ts +664 -0
  10. package/dist/api.js +0 -0
  11. package/dist/chunk-2VSPOLVO.js +1 -0
  12. package/dist/chunk-5YZVCHRU.js +0 -0
  13. package/dist/chunk-77XMXAXE.js +1 -0
  14. package/dist/chunk-7OVWNPZQ.js +1 -0
  15. package/dist/chunk-BMYMNNJK.js +1 -0
  16. package/dist/chunk-C5Y2WM7C.js +1 -0
  17. package/dist/chunk-C64LJM7D.js +2 -0
  18. package/dist/chunk-CLOFJTBP.js +1 -0
  19. package/dist/chunk-CMREWGOI.js +1 -0
  20. package/dist/chunk-D5VE2O4F.js +1 -0
  21. package/dist/chunk-LDE3JHVE.js +1 -0
  22. package/dist/chunk-N4Q67DTE.js +1 -0
  23. package/dist/chunk-SZE5DE54.js +1 -0
  24. package/dist/chunk-XHQVWI2J.js +1 -0
  25. package/dist/chunk-YU5DN3PI.js +1 -0
  26. package/dist/config.cjs +2 -0
  27. package/dist/config.d.cts +132 -0
  28. package/dist/config.d.ts +132 -0
  29. package/dist/config.js +1 -0
  30. package/dist/contracts.cjs +1 -0
  31. package/dist/contracts.d.cts +13073 -0
  32. package/dist/contracts.d.ts +13073 -0
  33. package/dist/contracts.js +1 -0
  34. package/dist/delegation.cjs +1 -0
  35. package/dist/delegation.d.cts +7 -0
  36. package/dist/delegation.d.ts +7 -0
  37. package/dist/delegation.js +0 -0
  38. package/dist/errors.cjs +3 -0
  39. package/dist/errors.d.cts +155 -0
  40. package/dist/errors.d.ts +155 -0
  41. package/dist/errors.js +3 -0
  42. package/dist/index.cjs +2 -0
  43. package/dist/index.d.cts +216 -0
  44. package/dist/index.d.ts +216 -0
  45. package/dist/index.js +1 -0
  46. package/dist/math.cjs +1 -0
  47. package/dist/math.d.cts +273 -0
  48. package/dist/math.d.ts +273 -0
  49. package/dist/math.js +1 -0
  50. package/dist/position-BnhSFyGe.d.cts +56 -0
  51. package/dist/position-BnhSFyGe.d.ts +56 -0
  52. package/dist/rawSchemas-MAT7EZCV.js +1 -0
  53. package/dist/referrals.cjs +1 -0
  54. package/dist/referrals.d.cts +66 -0
  55. package/dist/referrals.d.ts +66 -0
  56. package/dist/referrals.js +1 -0
  57. package/dist/serde.cjs +1 -0
  58. package/dist/serde.d.cts +24 -0
  59. package/dist/serde.d.ts +24 -0
  60. package/dist/serde.js +1 -0
  61. package/dist/token.cjs +1 -0
  62. package/dist/token.d.cts +32 -0
  63. package/dist/token.d.ts +32 -0
  64. package/dist/token.js +0 -0
  65. package/dist/trading.cjs +1 -0
  66. package/dist/trading.d.cts +20 -0
  67. package/dist/trading.d.ts +20 -0
  68. package/dist/trading.js +1 -0
  69. package/dist/types-7s13ZSql.d.ts +533 -0
  70. package/dist/types-BK6dYOXr.d.cts +118 -0
  71. package/dist/types-CMtixBIP.d.cts +464 -0
  72. package/dist/types-DB1r_Ppi.d.ts +464 -0
  73. package/dist/types-DDgJiEFg.d.ts +780 -0
  74. package/dist/types-DJBX-p4X.d.cts +780 -0
  75. package/dist/types-DQft82W7.d.cts +533 -0
  76. package/dist/types-DhCzEwnS.d.ts +118 -0
  77. package/dist/types-veTDfbhq.d.ts +436 -0
  78. package/dist/types-x1MvxSdy.d.cts +436 -0
  79. package/dist/units-BYd75H7U.d.cts +22 -0
  80. package/dist/units-BYd75H7U.d.ts +22 -0
  81. package/dist/units.cjs +1 -0
  82. package/dist/units.d.cts +248 -0
  83. package/dist/units.d.ts +248 -0
  84. package/dist/units.js +1 -0
  85. package/dist/valuation.cjs +1 -0
  86. package/dist/valuation.d.cts +5 -0
  87. package/dist/valuation.d.ts +5 -0
  88. package/dist/valuation.js +1 -0
  89. package/dist/vault.cjs +1 -0
  90. package/dist/vault.d.cts +34 -0
  91. package/dist/vault.d.ts +34 -0
  92. package/dist/vault.js +1 -0
  93. package/package.json +181 -0
@@ -0,0 +1,248 @@
1
+ /** Nominal marker used to keep protocol units from being mixed accidentally. */
2
+ type Brand<T, Name extends string> = T & {
3
+ readonly __brand: Name;
4
+ };
5
+ /** EVM address string. The SDK validates address shape at runtime where needed. */
6
+ type Address = `0x${string}`;
7
+ /** Hex string prefixed with `0x`. */
8
+ type Hex = `0x${string}`;
9
+ /** ISO-8601 timestamp returned by REST read models. */
10
+ type IsoTimestamp = string & {
11
+ readonly __brand: "IsoTimestamp";
12
+ };
13
+ /** Validated display decimal string that avoids JS number precision loss. */
14
+ type DecimalString = string & {
15
+ readonly __brand: "DecimalString";
16
+ };
17
+ /** Human-readable decimal string accepted by selected high-level trading APIs. */
18
+ type DecimalInput = string;
19
+ /** Timestamp input accepted by REST query helpers. */
20
+ type TimeInput = IsoTimestamp | UnixMs;
21
+ type FormatOptions = {
22
+ /** Decimal places to render. Defaults to the codec's native precision. */
23
+ decimals?: number;
24
+ /** Whether to remove trailing fractional zeroes. Defaults to true. */
25
+ trimTrailingZeros?: boolean;
26
+ /** Optional locale for grouping and decimal separator formatting. */
27
+ locale?: string;
28
+ /** Optional prefix, such as `$`, inserted after the sign. */
29
+ symbol?: string;
30
+ };
31
+ /**
32
+ * Codec for a fixed-point branded bigint unit.
33
+ *
34
+ * Methods are safe to destructure, for example `const { fromDecimal } = Collateral`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const amount = Collateral.fromDecimal("1.25");
39
+ * Collateral.toRaw(amount); // 1250000n
40
+ * Collateral.format(amount); // "1.25"
41
+ * ```
42
+ */
43
+ type UnitCodec<T> = {
44
+ /**
45
+ * Parses a human-readable decimal string into the branded raw integer.
46
+ *
47
+ * @throws Error when the string has invalid syntax, too many decimal places,
48
+ * or falls outside this unit's raw bounds.
49
+ */
50
+ fromDecimal(value: string): T;
51
+ /**
52
+ * Wraps an already-scaled raw integer.
53
+ *
54
+ * @throws Error when a string raw value is not an integer or the raw value is
55
+ * outside this unit's bounds.
56
+ */
57
+ fromRaw(value: bigint | string): T;
58
+ /** Returns the raw integer without its brand. */
59
+ toRaw(value: T): bigint;
60
+ /** Returns the raw integer as a decimal string. */
61
+ toRawString(value: T): string;
62
+ /**
63
+ * Formats the branded value as a human-readable decimal string.
64
+ *
65
+ * @throws Error when `opts.decimals` is not a non-negative integer.
66
+ */
67
+ format(value: T, opts?: FormatOptions): string;
68
+ };
69
+ /** Codec for bounded numeric brand values such as pair and trade indexes. */
70
+ type NumberBrandCodec<T> = {
71
+ /**
72
+ * Brands an integer after checking the codec-specific range.
73
+ *
74
+ * @throws Error when the value is not an integer or is out of range.
75
+ */
76
+ from(value: number): T;
77
+ /** Returns the unbranded numeric value. */
78
+ toNumber(value: T): number;
79
+ };
80
+ /** Codec for non-empty string brand values such as trade and order IDs. */
81
+ type StringBrandCodec<T> = {
82
+ /**
83
+ * Brands a non-empty string.
84
+ *
85
+ * @throws Error when the value is empty.
86
+ */
87
+ parse(value: string): T;
88
+ /** Returns the unbranded string value. */
89
+ toString(value: T): string;
90
+ };
91
+ type TriggerOrderIndexCodec = NumberBrandCodec<TriggerOrderIndex> & {
92
+ /** Parses the decimal-string index form returned by the REST API. */
93
+ parseApi(value: string): TriggerOrderIndex;
94
+ };
95
+ /** Codec for signed decimal ratio strings that should not be coerced through JS numbers. */
96
+ type RatioCodec = {
97
+ /** Validates and brands a signed display decimal string. */
98
+ fromDecimal(value: string): Ratio;
99
+ /** Validates and brands the raw signed decimal string form. */
100
+ fromRaw(value: string): Ratio;
101
+ /** Returns the raw ratio string. */
102
+ toRawString(value: Ratio): string;
103
+ /** Returns the display ratio string. */
104
+ format(value: Ratio, opts?: FormatOptions): string;
105
+ };
106
+ /**
107
+ * Validates a display decimal string and returns it with a decimal-string brand.
108
+ *
109
+ * @throws Error for empty strings, scientific notation, plus signs, or leading zeroes.
110
+ */
111
+ declare function parseDecimalString(value: string): DecimalString;
112
+ /** Protocol market identifier, valid from 0 to 65535. */
113
+ type PairIndex = Brand<number, "PairIndex">;
114
+ /** Pair index codec for protocol market IDs, valid from 0 to 65535. */
115
+ declare const PairIndex: NumberBrandCodec<PairIndex>;
116
+ /** Open-trade slot index, valid from 0 to 255. */
117
+ type TradeIndex = Brand<number, "TradeIndex">;
118
+ /** Open-trade slot index codec, valid from 0 to 255. */
119
+ declare const TradeIndex: NumberBrandCodec<TradeIndex>;
120
+ /** Trigger-order slot index, valid from 0 to 255. */
121
+ type TriggerOrderIndex = Brand<number, "TriggerOrderIndex">;
122
+ /** Trigger-order slot index codec, valid from 0 to 255. */
123
+ declare const TriggerOrderIndex: NumberBrandCodec<TriggerOrderIndex> & {
124
+ parseApi(value: string): TriggerOrderIndex;
125
+ };
126
+ /** REST/indexer trade identifier. */
127
+ type TradeId = Brand<string, "TradeId">;
128
+ /** Trade ID codec for non-empty string IDs returned by the REST API. */
129
+ declare const TradeId: StringBrandCodec<TradeId>;
130
+ /** REST/indexer order lifecycle identifier. */
131
+ type OrderId = Brand<string, "OrderId">;
132
+ /** Order ID codec for non-empty string IDs returned by the REST API. */
133
+ declare const OrderId: StringBrandCodec<OrderId>;
134
+ /** 6-decimal fixed-point collateral amount, typically USDC. */
135
+ type Collateral = Brand<bigint, "Collateral">;
136
+ /**
137
+ * 6-decimal fixed-point collateral amount, typically USDC.
138
+ *
139
+ * @example `Collateral.fromDecimal("1.25")` stores `1250000n`.
140
+ */
141
+ declare const Collateral: UnitCodec<Collateral>;
142
+ /** Signed 6-decimal fixed-point collateral delta. */
143
+ type SignedCollateral = Brand<bigint, "SignedCollateral">;
144
+ /** Signed 6-decimal fixed-point collateral delta. */
145
+ declare const SignedCollateral: UnitCodec<SignedCollateral>;
146
+ /** 18-decimal fixed-point price. */
147
+ type Price = Brand<bigint, "Price">;
148
+ /**
149
+ * 18-decimal fixed-point asset price.
150
+ *
151
+ * @example `Price.fromDecimal("42000.50")` stores a protocol-scaled mark price.
152
+ */
153
+ declare const Price: UnitCodec<Price>;
154
+ /** 18-decimal fixed-point notional value. */
155
+ type Notional = Brand<bigint, "Notional">;
156
+ /** 18-decimal fixed-point notional value. */
157
+ declare const Notional: UnitCodec<Notional>;
158
+ /** 2-decimal fixed-point leverage value, where `200n` means 2x. */
159
+ type Leverage = Brand<bigint, "Leverage">;
160
+ /**
161
+ * 2-decimal leverage value.
162
+ *
163
+ * @example `Leverage.fromDecimal("2")` is 2x leverage.
164
+ */
165
+ declare const Leverage: UnitCodec<Leverage>;
166
+ /** Signed 18-decimal fixed-point protocol value. */
167
+ type SignedP18 = Brand<bigint, "SignedP18">;
168
+ /** Signed 18-decimal fixed-point protocol value. */
169
+ declare const SignedP18: UnitCodec<SignedP18>;
170
+ /** Unsigned 18-decimal fixed-point protocol value. */
171
+ type UnsignedP18 = Brand<bigint, "UnsignedP18">;
172
+ /** Unsigned 18-decimal fixed-point protocol value. */
173
+ declare const UnsignedP18: UnitCodec<UnsignedP18>;
174
+ /** Signed 6-decimal fixed-point protocol value. */
175
+ type SignedP6 = Brand<bigint, "SignedP6">;
176
+ /** Signed 6-decimal fixed-point protocol value. */
177
+ declare const SignedP6: UnitCodec<SignedP6>;
178
+ /** 2-decimal fixed-point scale value. */
179
+ type ScaleP2 = Brand<bigint, "ScaleP2">;
180
+ /** 2-decimal fixed-point scale value. */
181
+ declare const ScaleP2: UnitCodec<ScaleP2>;
182
+ /** 6-decimal fixed-point USD amount. */
183
+ type UsdP6 = Brand<bigint, "UsdP6">;
184
+ /**
185
+ * 6-decimal USD amount codec that accepts optional dollar-prefixed input.
186
+ *
187
+ * @example `UsdP6.fromDollar("$10.50")` stores `10500000n`.
188
+ */
189
+ declare const UsdP6: UnitCodec<UsdP6> & {
190
+ /** Parses either `"10.50"` or `"$10.50"` as a 6-decimal USD amount. */
191
+ fromDollar(value: `$${string}` | string): UsdP6;
192
+ };
193
+ /** 2-decimal slippage percent, where `25n` means 0.25%. */
194
+ type SlippagePercent = Brand<bigint, "SlippagePercent">;
195
+ /**
196
+ * Slippage percentage with two decimal places.
197
+ *
198
+ * @example `SlippagePercent.fromBps(25n)` is 0.25%.
199
+ */
200
+ declare const SlippagePercent: UnitCodec<SlippagePercent> & {
201
+ /** Brands a basis-point value, where `25n` means 0.25%. */
202
+ fromBps(value: bigint | string): SlippagePercent;
203
+ };
204
+ /** 2-decimal close percent, where `10000n` means 100%. */
205
+ type ClosePercent = Brand<bigint, "ClosePercent">;
206
+ /**
207
+ * Close percentage with two decimal places.
208
+ *
209
+ * @example `ClosePercent.full()` is 100%.
210
+ */
211
+ declare const ClosePercent: UnitCodec<ClosePercent> & {
212
+ /** Returns 100% as a close percentage. */
213
+ full(): ClosePercent;
214
+ };
215
+ /** 6-decimal fixed-point fee percentage. */
216
+ type FeePercent = Brand<bigint, "FeePercent">;
217
+ /** 6-decimal fixed-point fee percentage. */
218
+ declare const FeePercent: UnitCodec<FeePercent>;
219
+ /** Whole-number percentage from 0 to 100. */
220
+ type WholePercent = Brand<bigint, "WholePercent">;
221
+ /** Whole-number percentage from 0 to 100. */
222
+ declare const WholePercent: UnitCodec<WholePercent>;
223
+ /** 2-decimal percentage value. */
224
+ type Precision2Percent = Brand<bigint, "Precision2Percent">;
225
+ /** 2-decimal fixed-point percentage. */
226
+ declare const Precision2Percent: UnitCodec<Precision2Percent>;
227
+ /** Unix timestamp in milliseconds. */
228
+ type UnixMs = Brand<bigint, "UnixMs">;
229
+ /** Unix timestamp in milliseconds. */
230
+ declare const UnixMs: UnitCodec<UnixMs>;
231
+ /** 6-decimal fixed-point vault asset amount. */
232
+ type VaultAsset = Brand<bigint, "VaultAsset">;
233
+ /** 6-decimal fixed-point vault asset amount. */
234
+ declare const VaultAsset: UnitCodec<VaultAsset>;
235
+ /** 6-decimal fixed-point vault share amount. */
236
+ type VaultShare = Brand<bigint, "VaultShare">;
237
+ /** 6-decimal fixed-point vault share amount. */
238
+ declare const VaultShare: UnitCodec<VaultShare>;
239
+ /** 18-decimal fixed-point vault share price. */
240
+ type VaultSharePrice = Brand<bigint, "VaultSharePrice">;
241
+ /** 18-decimal fixed-point vault share price. */
242
+ declare const VaultSharePrice: UnitCodec<VaultSharePrice>;
243
+ /** Signed decimal ratio string kept exact instead of converted through JS numbers. */
244
+ type Ratio = Brand<string, "Ratio">;
245
+ /** Signed decimal ratio codec that preserves exact string precision. */
246
+ declare const Ratio: RatioCodec;
247
+
248
+ export { type Address, type Brand, ClosePercent, Collateral, type DecimalInput, type DecimalString, FeePercent, type FormatOptions, type Hex, type IsoTimestamp, Leverage, Notional, type NumberBrandCodec, OrderId, PairIndex, Precision2Percent, Price, Ratio, type RatioCodec, ScaleP2, SignedCollateral, SignedP18, SignedP6, SlippagePercent, type StringBrandCodec, type TimeInput, TradeId, TradeIndex, TriggerOrderIndex, type TriggerOrderIndexCodec, type UnitCodec, UnixMs, UnsignedP18, UsdP6, VaultAsset, VaultShare, VaultSharePrice, WholePercent, parseDecimalString };
@@ -0,0 +1,248 @@
1
+ /** Nominal marker used to keep protocol units from being mixed accidentally. */
2
+ type Brand<T, Name extends string> = T & {
3
+ readonly __brand: Name;
4
+ };
5
+ /** EVM address string. The SDK validates address shape at runtime where needed. */
6
+ type Address = `0x${string}`;
7
+ /** Hex string prefixed with `0x`. */
8
+ type Hex = `0x${string}`;
9
+ /** ISO-8601 timestamp returned by REST read models. */
10
+ type IsoTimestamp = string & {
11
+ readonly __brand: "IsoTimestamp";
12
+ };
13
+ /** Validated display decimal string that avoids JS number precision loss. */
14
+ type DecimalString = string & {
15
+ readonly __brand: "DecimalString";
16
+ };
17
+ /** Human-readable decimal string accepted by selected high-level trading APIs. */
18
+ type DecimalInput = string;
19
+ /** Timestamp input accepted by REST query helpers. */
20
+ type TimeInput = IsoTimestamp | UnixMs;
21
+ type FormatOptions = {
22
+ /** Decimal places to render. Defaults to the codec's native precision. */
23
+ decimals?: number;
24
+ /** Whether to remove trailing fractional zeroes. Defaults to true. */
25
+ trimTrailingZeros?: boolean;
26
+ /** Optional locale for grouping and decimal separator formatting. */
27
+ locale?: string;
28
+ /** Optional prefix, such as `$`, inserted after the sign. */
29
+ symbol?: string;
30
+ };
31
+ /**
32
+ * Codec for a fixed-point branded bigint unit.
33
+ *
34
+ * Methods are safe to destructure, for example `const { fromDecimal } = Collateral`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const amount = Collateral.fromDecimal("1.25");
39
+ * Collateral.toRaw(amount); // 1250000n
40
+ * Collateral.format(amount); // "1.25"
41
+ * ```
42
+ */
43
+ type UnitCodec<T> = {
44
+ /**
45
+ * Parses a human-readable decimal string into the branded raw integer.
46
+ *
47
+ * @throws Error when the string has invalid syntax, too many decimal places,
48
+ * or falls outside this unit's raw bounds.
49
+ */
50
+ fromDecimal(value: string): T;
51
+ /**
52
+ * Wraps an already-scaled raw integer.
53
+ *
54
+ * @throws Error when a string raw value is not an integer or the raw value is
55
+ * outside this unit's bounds.
56
+ */
57
+ fromRaw(value: bigint | string): T;
58
+ /** Returns the raw integer without its brand. */
59
+ toRaw(value: T): bigint;
60
+ /** Returns the raw integer as a decimal string. */
61
+ toRawString(value: T): string;
62
+ /**
63
+ * Formats the branded value as a human-readable decimal string.
64
+ *
65
+ * @throws Error when `opts.decimals` is not a non-negative integer.
66
+ */
67
+ format(value: T, opts?: FormatOptions): string;
68
+ };
69
+ /** Codec for bounded numeric brand values such as pair and trade indexes. */
70
+ type NumberBrandCodec<T> = {
71
+ /**
72
+ * Brands an integer after checking the codec-specific range.
73
+ *
74
+ * @throws Error when the value is not an integer or is out of range.
75
+ */
76
+ from(value: number): T;
77
+ /** Returns the unbranded numeric value. */
78
+ toNumber(value: T): number;
79
+ };
80
+ /** Codec for non-empty string brand values such as trade and order IDs. */
81
+ type StringBrandCodec<T> = {
82
+ /**
83
+ * Brands a non-empty string.
84
+ *
85
+ * @throws Error when the value is empty.
86
+ */
87
+ parse(value: string): T;
88
+ /** Returns the unbranded string value. */
89
+ toString(value: T): string;
90
+ };
91
+ type TriggerOrderIndexCodec = NumberBrandCodec<TriggerOrderIndex> & {
92
+ /** Parses the decimal-string index form returned by the REST API. */
93
+ parseApi(value: string): TriggerOrderIndex;
94
+ };
95
+ /** Codec for signed decimal ratio strings that should not be coerced through JS numbers. */
96
+ type RatioCodec = {
97
+ /** Validates and brands a signed display decimal string. */
98
+ fromDecimal(value: string): Ratio;
99
+ /** Validates and brands the raw signed decimal string form. */
100
+ fromRaw(value: string): Ratio;
101
+ /** Returns the raw ratio string. */
102
+ toRawString(value: Ratio): string;
103
+ /** Returns the display ratio string. */
104
+ format(value: Ratio, opts?: FormatOptions): string;
105
+ };
106
+ /**
107
+ * Validates a display decimal string and returns it with a decimal-string brand.
108
+ *
109
+ * @throws Error for empty strings, scientific notation, plus signs, or leading zeroes.
110
+ */
111
+ declare function parseDecimalString(value: string): DecimalString;
112
+ /** Protocol market identifier, valid from 0 to 65535. */
113
+ type PairIndex = Brand<number, "PairIndex">;
114
+ /** Pair index codec for protocol market IDs, valid from 0 to 65535. */
115
+ declare const PairIndex: NumberBrandCodec<PairIndex>;
116
+ /** Open-trade slot index, valid from 0 to 255. */
117
+ type TradeIndex = Brand<number, "TradeIndex">;
118
+ /** Open-trade slot index codec, valid from 0 to 255. */
119
+ declare const TradeIndex: NumberBrandCodec<TradeIndex>;
120
+ /** Trigger-order slot index, valid from 0 to 255. */
121
+ type TriggerOrderIndex = Brand<number, "TriggerOrderIndex">;
122
+ /** Trigger-order slot index codec, valid from 0 to 255. */
123
+ declare const TriggerOrderIndex: NumberBrandCodec<TriggerOrderIndex> & {
124
+ parseApi(value: string): TriggerOrderIndex;
125
+ };
126
+ /** REST/indexer trade identifier. */
127
+ type TradeId = Brand<string, "TradeId">;
128
+ /** Trade ID codec for non-empty string IDs returned by the REST API. */
129
+ declare const TradeId: StringBrandCodec<TradeId>;
130
+ /** REST/indexer order lifecycle identifier. */
131
+ type OrderId = Brand<string, "OrderId">;
132
+ /** Order ID codec for non-empty string IDs returned by the REST API. */
133
+ declare const OrderId: StringBrandCodec<OrderId>;
134
+ /** 6-decimal fixed-point collateral amount, typically USDC. */
135
+ type Collateral = Brand<bigint, "Collateral">;
136
+ /**
137
+ * 6-decimal fixed-point collateral amount, typically USDC.
138
+ *
139
+ * @example `Collateral.fromDecimal("1.25")` stores `1250000n`.
140
+ */
141
+ declare const Collateral: UnitCodec<Collateral>;
142
+ /** Signed 6-decimal fixed-point collateral delta. */
143
+ type SignedCollateral = Brand<bigint, "SignedCollateral">;
144
+ /** Signed 6-decimal fixed-point collateral delta. */
145
+ declare const SignedCollateral: UnitCodec<SignedCollateral>;
146
+ /** 18-decimal fixed-point price. */
147
+ type Price = Brand<bigint, "Price">;
148
+ /**
149
+ * 18-decimal fixed-point asset price.
150
+ *
151
+ * @example `Price.fromDecimal("42000.50")` stores a protocol-scaled mark price.
152
+ */
153
+ declare const Price: UnitCodec<Price>;
154
+ /** 18-decimal fixed-point notional value. */
155
+ type Notional = Brand<bigint, "Notional">;
156
+ /** 18-decimal fixed-point notional value. */
157
+ declare const Notional: UnitCodec<Notional>;
158
+ /** 2-decimal fixed-point leverage value, where `200n` means 2x. */
159
+ type Leverage = Brand<bigint, "Leverage">;
160
+ /**
161
+ * 2-decimal leverage value.
162
+ *
163
+ * @example `Leverage.fromDecimal("2")` is 2x leverage.
164
+ */
165
+ declare const Leverage: UnitCodec<Leverage>;
166
+ /** Signed 18-decimal fixed-point protocol value. */
167
+ type SignedP18 = Brand<bigint, "SignedP18">;
168
+ /** Signed 18-decimal fixed-point protocol value. */
169
+ declare const SignedP18: UnitCodec<SignedP18>;
170
+ /** Unsigned 18-decimal fixed-point protocol value. */
171
+ type UnsignedP18 = Brand<bigint, "UnsignedP18">;
172
+ /** Unsigned 18-decimal fixed-point protocol value. */
173
+ declare const UnsignedP18: UnitCodec<UnsignedP18>;
174
+ /** Signed 6-decimal fixed-point protocol value. */
175
+ type SignedP6 = Brand<bigint, "SignedP6">;
176
+ /** Signed 6-decimal fixed-point protocol value. */
177
+ declare const SignedP6: UnitCodec<SignedP6>;
178
+ /** 2-decimal fixed-point scale value. */
179
+ type ScaleP2 = Brand<bigint, "ScaleP2">;
180
+ /** 2-decimal fixed-point scale value. */
181
+ declare const ScaleP2: UnitCodec<ScaleP2>;
182
+ /** 6-decimal fixed-point USD amount. */
183
+ type UsdP6 = Brand<bigint, "UsdP6">;
184
+ /**
185
+ * 6-decimal USD amount codec that accepts optional dollar-prefixed input.
186
+ *
187
+ * @example `UsdP6.fromDollar("$10.50")` stores `10500000n`.
188
+ */
189
+ declare const UsdP6: UnitCodec<UsdP6> & {
190
+ /** Parses either `"10.50"` or `"$10.50"` as a 6-decimal USD amount. */
191
+ fromDollar(value: `$${string}` | string): UsdP6;
192
+ };
193
+ /** 2-decimal slippage percent, where `25n` means 0.25%. */
194
+ type SlippagePercent = Brand<bigint, "SlippagePercent">;
195
+ /**
196
+ * Slippage percentage with two decimal places.
197
+ *
198
+ * @example `SlippagePercent.fromBps(25n)` is 0.25%.
199
+ */
200
+ declare const SlippagePercent: UnitCodec<SlippagePercent> & {
201
+ /** Brands a basis-point value, where `25n` means 0.25%. */
202
+ fromBps(value: bigint | string): SlippagePercent;
203
+ };
204
+ /** 2-decimal close percent, where `10000n` means 100%. */
205
+ type ClosePercent = Brand<bigint, "ClosePercent">;
206
+ /**
207
+ * Close percentage with two decimal places.
208
+ *
209
+ * @example `ClosePercent.full()` is 100%.
210
+ */
211
+ declare const ClosePercent: UnitCodec<ClosePercent> & {
212
+ /** Returns 100% as a close percentage. */
213
+ full(): ClosePercent;
214
+ };
215
+ /** 6-decimal fixed-point fee percentage. */
216
+ type FeePercent = Brand<bigint, "FeePercent">;
217
+ /** 6-decimal fixed-point fee percentage. */
218
+ declare const FeePercent: UnitCodec<FeePercent>;
219
+ /** Whole-number percentage from 0 to 100. */
220
+ type WholePercent = Brand<bigint, "WholePercent">;
221
+ /** Whole-number percentage from 0 to 100. */
222
+ declare const WholePercent: UnitCodec<WholePercent>;
223
+ /** 2-decimal percentage value. */
224
+ type Precision2Percent = Brand<bigint, "Precision2Percent">;
225
+ /** 2-decimal fixed-point percentage. */
226
+ declare const Precision2Percent: UnitCodec<Precision2Percent>;
227
+ /** Unix timestamp in milliseconds. */
228
+ type UnixMs = Brand<bigint, "UnixMs">;
229
+ /** Unix timestamp in milliseconds. */
230
+ declare const UnixMs: UnitCodec<UnixMs>;
231
+ /** 6-decimal fixed-point vault asset amount. */
232
+ type VaultAsset = Brand<bigint, "VaultAsset">;
233
+ /** 6-decimal fixed-point vault asset amount. */
234
+ declare const VaultAsset: UnitCodec<VaultAsset>;
235
+ /** 6-decimal fixed-point vault share amount. */
236
+ type VaultShare = Brand<bigint, "VaultShare">;
237
+ /** 6-decimal fixed-point vault share amount. */
238
+ declare const VaultShare: UnitCodec<VaultShare>;
239
+ /** 18-decimal fixed-point vault share price. */
240
+ type VaultSharePrice = Brand<bigint, "VaultSharePrice">;
241
+ /** 18-decimal fixed-point vault share price. */
242
+ declare const VaultSharePrice: UnitCodec<VaultSharePrice>;
243
+ /** Signed decimal ratio string kept exact instead of converted through JS numbers. */
244
+ type Ratio = Brand<string, "Ratio">;
245
+ /** Signed decimal ratio codec that preserves exact string precision. */
246
+ declare const Ratio: RatioCodec;
247
+
248
+ export { type Address, type Brand, ClosePercent, Collateral, type DecimalInput, type DecimalString, FeePercent, type FormatOptions, type Hex, type IsoTimestamp, Leverage, Notional, type NumberBrandCodec, OrderId, PairIndex, Precision2Percent, Price, Ratio, type RatioCodec, ScaleP2, SignedCollateral, SignedP18, SignedP6, SlippagePercent, type StringBrandCodec, type TimeInput, TradeId, TradeIndex, TriggerOrderIndex, type TriggerOrderIndexCodec, type UnitCodec, UnixMs, UnsignedP18, UsdP6, VaultAsset, VaultShare, VaultSharePrice, WholePercent, parseDecimalString };
package/dist/units.js ADDED
@@ -0,0 +1 @@
1
+ export{r as ClosePercent,g as Collateral,s as FeePercent,k as Leverage,j as Notional,f as OrderId,b as PairIndex,u as Precision2Percent,i as Price,z as Ratio,o as ScaleP2,h as SignedCollateral,l as SignedP18,n as SignedP6,q as SlippagePercent,e as TradeId,c as TradeIndex,d as TriggerOrderIndex,v as UnixMs,m as UnsignedP18,p as UsdP6,w as VaultAsset,x as VaultShare,y as VaultSharePrice,t as WholePercent,a as parseDecimalString}from'./chunk-C5Y2WM7C.js';
@@ -0,0 +1 @@
1
+ 'use strict';var w=100n,l=1000000n;function g(e,r,n){if(n<=0n)throw new Error("denominator must be positive");let t=e*r,i=t/n,a=t%n;return t>0n&&a!==0n?i+1n:i}function u(e,r){if(typeof e=="bigint")return e;if(!Number.isSafeInteger(e))throw new Error(`${r} must be a safe integer`);return BigInt(e)}function o(e,r){let n=u(e,r);if(n<0n)throw new Error(`${r} must be non-negative`);return n}function c(e){if(e.collateralRaw<0n)throw new Error("collateralRaw must be non-negative");let r=o(e.leverageRaw,"leverageRaw"),n=o(e.maxLeverageRaw,"maxLeverageRaw"),t=o(e.liqMarginThresholdP,"liqMarginThresholdP");if(n===0n)throw new Error("maxLeverageRaw must be positive");let i=t*r*l/n;return e.collateralRaw*i/(100n*l)}function s(e){let r=o(e.leverageRaw,"leverageRaw");if(e.openPriceRaw<0n)throw new Error("openPriceRaw must be non-negative");if(e.collateralRaw<=0n)throw new Error("collateralRaw must be positive");if(r===0n)throw new Error("leverageRaw must be positive");let n=c(e),t=e.collateralRaw-n-e.fundingFeeRaw;if(t<0n)throw new Error("targetCollateralAfterFees must be non-negative");let i=g(e.openPriceRaw,t*w,e.collateralRaw*r),a=e.buy?e.openPriceRaw-i:e.openPriceRaw+i;return a>0n?a:0n}exports.liquidationMarginRaw=c;exports.liquidationPriceRaw=s;
@@ -0,0 +1,5 @@
1
+ export { L as LiquidationMarginInput, a as LiquidationPriceInput, l as liquidationMarginRaw, b as liquidationPriceRaw } from './position-BnhSFyGe.cjs';
2
+ export { B as BulkSnapshotOptions, M as MarkSource, a as MarkSourcePreference, P as PositionSnapshot, S as SnapshotFreshness, b as SnapshotOptions, U as UnverifiedPositionSlot, c as UnverifiedSlotSnapshot, V as ValuationClient, d as ValuationClientNoApi, e as VerifiedPositionSnapshot, W as WatchCallback, f as WatchEvent, g as WatchHandle, h as WatchSnapshotOptions } from './types-BK6dYOXr.cjs';
3
+ import './types-DQft82W7.cjs';
4
+ import './errors.cjs';
5
+ import './units.cjs';
@@ -0,0 +1,5 @@
1
+ export { L as LiquidationMarginInput, a as LiquidationPriceInput, l as liquidationMarginRaw, b as liquidationPriceRaw } from './position-BnhSFyGe.js';
2
+ export { B as BulkSnapshotOptions, M as MarkSource, a as MarkSourcePreference, P as PositionSnapshot, S as SnapshotFreshness, b as SnapshotOptions, U as UnverifiedPositionSlot, c as UnverifiedSlotSnapshot, V as ValuationClient, d as ValuationClientNoApi, e as VerifiedPositionSnapshot, W as WatchCallback, f as WatchEvent, g as WatchHandle, h as WatchSnapshotOptions } from './types-DhCzEwnS.js';
3
+ import './types-7s13ZSql.js';
4
+ import './errors.js';
5
+ import './units.js';
@@ -0,0 +1 @@
1
+ import'./chunk-5YZVCHRU.js';export{m as liquidationMarginRaw,n as liquidationPriceRaw}from'./chunk-SZE5DE54.js';
package/dist/vault.cjs ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var units=require('@domfi/sdk/units'),errors=require('@domfi/sdk/errors');var g="0.1.0";var je=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;function l(e,n){let t=e.charCodeAt(n);return t>=48&&t<=57}function y(e,n,t){return Number(e.slice(n,t))}function We(e){return e%4===0&&(e%100!==0||e%400===0)}function X(e,n){return n===2?We(e)?29:28:n===4||n===6||n===9||n===11?30:31}function ze(e){return e.length===24&&e[4]==="-"&&e[7]==="-"&&e[10]==="T"&&e[13]===":"&&e[16]===":"&&e[19]==="."&&e[23]==="Z"&&l(e,0)&&l(e,1)&&l(e,2)&&l(e,3)&&l(e,5)&&l(e,6)&&l(e,8)&&l(e,9)&&l(e,11)&&l(e,12)&&l(e,14)&&l(e,15)&&l(e,17)&&l(e,18)&&l(e,20)&&l(e,21)&&l(e,22)}function Ge(e){if(!ze(e))return false;let n=y(e,0,4),t=y(e,5,7),r=y(e,8,10),a=y(e,11,13),i=y(e,14,16),o=y(e,17,19);return t>=1&&t<=12&&r>=1&&r<=X(n,t)&&a<=23&&i<=59&&o<=59}function Ye(e,n){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${n} invalid timestamp`);let t=new Date(e);if(!Number.isFinite(t.getTime()))throw new Error(`${n} invalid timestamp`);return e}function Ze(e,n){let t=je.exec(e);if(!t)throw new Error(`${n} must be an ISO timestamp`);let r=Date.parse(e);if(!Number.isFinite(r))throw new Error(`${n} must be an ISO timestamp`);let a=new Date(r).toISOString(),[,i="",o="",s="",u="",c="",m="",p="",A="Z",,Z="",q=""]=t,Fe=Number(i),D=Number(o),K=Number(s),Me=Number(u),Ce=Number(c),He=Number(m),Le=Z===""?0:Number(Z),$e=q===""?0:Number(q);if(!(D>=1&&D<=12&&K>=1&&K<=X(Fe,D)&&Me<=23&&Ce<=59&&He<=59&&Le<=23&&$e<=59))throw new Error(`${n} must be an ISO timestamp`);let Ue=`${i}-${o}-${s}T${u}:${c}:${m}.${p.slice(0,3).padEnd(3,"0")}Z`;if(A==="Z"&&a!==Ue)throw new Error(`${n} must be an ISO timestamp`);return {isoTimestamp:a,millis:r}}function J(e,n){if(typeof e=="string")return Ge(e)?e:Ze(e,n).isoTimestamp;if(typeof e=="number")return new Date(Ye(e,n)).toISOString();throw new Error(`${n} invalid timestamp`)}var qe=/^-?(?:0|[1-9]\d*)$/,Ke="serde";function v(e,n){throw new errors.ValidationError({message:e,diagnostics:{sdkVersion:g,sourceTag:Ke,chainId:0},...n!==void 0?{cause:n}:{}})}function Xe(e,n){if(typeof e=="bigint")return e;if(typeof e=="number")return Number.isSafeInteger(e)||v(`${n} must be a safe integer; unsafe integer values are rejected`),BigInt(e);if(typeof e=="string")return qe.test(e)||v(`${n} must be an integer string`),BigInt(e);v(`${n} must be an integer`);}function ee(e,n){try{return J(e,n)}catch(t){if(t instanceof errors.ValidationError)throw t;let r=t instanceof Error?t.message:`${n} invalid timestamp`;v(r,t);}}function _(e,n){if(e!=null)return Xe(e,n)}var Qe="read-plane";function ne(e){let n=e.policy??"strict";if(n==="ignore")return;let t=e.unsafeReasons??[],r=e.degradedReasons??[],a=t.length>0?t:r;if(a.length===0)return;let i=en(e);if(n==="warn"){e.onEvent?.({type:"warning",code:"READ_MODEL_NOT_READY",message:"Read model is degraded for this route",diagnostics:i,degradedReasons:a});return}if(t.length!==0)throw new errors.ReadModelNotReadyError({message:"Read model is not ready for this route",diagnostics:i})}function en(e){return {sdkVersion:g,sourceTag:Qe,...e.diagnostics,chainId:e.chainId}}function O(e){let n={hasNext:e.has_next,limit:e.limit};return e.cursor!==void 0&&e.cursor!==null&&(n.cursor=e.cursor),e.next_cursor!==void 0&&e.next_cursor!==null&&(n.nextCursor=e.next_cursor),n}var nn=/^0x(?:[0-9a-fA-F]{2})*$/;function tn(e,n){return typeof e!="string"||!nn.test(e)||e==="0x"?false:n?.bytes===void 0||e.length===2+n.bytes*2}function rn(e,n,t,r){if(tn(e,r))return e;let a=r?.bytes===void 0?"hex string":`${r.bytes}-byte hex string`;return t(`${n} must be a ${a}`)}function te(e,n,t){return rn(e,n,t,{bytes:32})}function re(e){if(e!==void 0)return n=>{try{let t=e(n);an(t)&&Promise.resolve(t).catch(()=>{});}catch{}}}function an(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&"then"in e&&typeof e.then=="function"}var on=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,ie=/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/,ae=/^(?:0|[1-9]\d*)$/,sn=/^-?(?:0|[1-9]\d*)$/;function oe(e){return N(e,true),e}function N(e,n){if(!(n?ie:on).test(e))throw new Error(`invalid decimal string: ${e}`);let r=e.startsWith("-"),a=r?e.slice(1):e,[i="0",o=""]=a.split(".");return {negative:r,whole:i,fraction:o}}function cn(e,n){if(!(n?sn:ae).test(e))throw new Error(`invalid raw integer: ${e}`);return BigInt(e)}function un(e,n){return n===void 0?e.toString():new Intl.NumberFormat(n).format(e)}function dn(e){return e===void 0?".":new Intl.NumberFormat(e).formatToParts(1.1).find(n=>n.type==="decimal")?.value??"."}function ln(e,n,t,r){let a=r?.decimals??t;if(!Number.isInteger(a)||a<0)throw new Error("decimals must be a non-negative integer");let i=e<0n,o=i?-e:e,s=o/n,u=t===0?"":(o%n).toString().padStart(t,"0"),c=a<=t?u.slice(0,a):u.padEnd(a,"0");r?.trimTrailingZeros!==false&&(c=c.replace(/0+$/,""));let m=un(s,r?.locale),p=c.length===0?m:`${m}${dn(r?.locale)}${c}`;return `${i?"-":""}${r?.symbol??""}${p}`}function B(e,n,t){return {from(r){if(!Number.isInteger(r)||r<n||r>t)throw new Error(`${e} out of range`);return r},toNumber(r){return r}}}function d(e,n,t=0n,r){let a=i=>{let o=typeof i=="bigint"?i:cn(i,t<0n);if(o<t)throw new Error("value below minimum");if(r!==void 0&&o>r)throw new Error("value above maximum");return o};return {fromDecimal(i){let{negative:o,whole:s,fraction:u}=N(i,t<0n);if(u.length>n)throw new Error(`too many fractional digits: expected ${n}`);let c=BigInt(s)*e+BigInt(u.padEnd(n,"0")||"0");return a(o?-c:c)},fromRaw:a,toRaw(i){return i},toRawString(i){return i.toString()},format(i,o){return ln(i,e,n,o)}}}var k=2n**256n-1n,gn=Object.assign(B("TriggerOrderIndex",0,255),{parseApi(e){if(!ae.test(e))throw new Error("TriggerOrderIndex out of range");return gn.from(Number(e))}}),fn=Object.assign(d(1000000n,6,0n,k),{fromDollar(e){return fn.fromDecimal(e.startsWith("$")?e.slice(1):e)}}),pn=Object.assign(d(100n,2,1n,9999n),{fromBps(e){return pn.fromRaw(e)}}),hn=Object.assign(d(100n,2,1n,10000n),{full(){return hn.fromRaw(10000n)}}),ue=d(1000000n,6,0n,k),de=d(1000000n,6,0n,k),le=d(1000000000000000000n,18),me={fromDecimal(e){return N(e,true),e},fromRaw(e){if(!ie.test(e))throw new Error("invalid ratio");return e},toRawString(e){return e},format(e){return e}};var bn=new Set(["Deposit","DepositLocked","DepositUnlocked","WithdrawRequested","Withdraw","WithdrawCanceled","LockedDepositTransferIn","LockedDepositTransferOut"]),yn=6,xn=6,_n=18,kn=30n,fe="vault-read";function b(e,n){throw new errors.ValidationError({message:e,diagnostics:{sdkVersion:g,sourceTag:fe,chainId:0},...n!==void 0?{cause:n}:{}})}function f(e,n){try{return n()}catch(t){if(t instanceof errors.ValidationError&&t.diagnostics.sourceTag===fe)throw t;return b(e,t)}}function pe(e){return {accPnlPerToken:Tn(e.acc_pnl_per_token,"acc_pnl_per_token"),currentEpoch:e.current_epoch,currentValueLocked:$(e.current_value_locked,"current_value_locked"),epochStart:e.epoch_start,totalShares:S(e.total_shares,"total_shares"),apr:C(e.apr,"apr"),sharePrice:Vn(e.share_price,"share_price"),collateralizationRatio:C(e.collateralization_ratio,"collateralization_ratio"),overCollateralization:C(e.over_collateralization,"over_collateralization")}}function h(e){let n={time:E(e,"time"),blockNumber:E(e,"block_number"),txIndex:E(e,"tx_index"),logIndex:E(e,"log_index"),opType:"unknown"},t=In(e.tx_hash,"tx_hash");t!==void 0&&(n.txHash=t);let r=vn(R(e,"op_type"));n.opType=r.opType,r.rawOpType!==void 0&&(n.rawOpType=r.rawOpType);let a=R(e,"id");a!==void 0&&(n.id=a);let i=R(e,"assets");i!==void 0&&(n.assets=$(i,"assets"));let o=R(e,"shares");o!==void 0&&(n.shares=S(o,"shares"));let s=H(e,"current_epoch");s!==void 0&&(n.currentEpoch=s);let u=H(e,"unlock_epoch");u!==void 0&&(n.unlockEpoch=u);let c=H(e,"lock_duration_seconds");return c!==void 0&&(n.lockDurationSeconds=c),n}function he(e){return {totalAssets:$(e.total_assets,"total_assets"),totalShares:S(e.total_shares,"total_shares"),totalLockedShares:S(e.total_locked_shares,"total_locked_shares"),lockedDeposits:e.locked_deposits.map(h),unlockedDeposits:e.unlocked_deposits.map(h),pendingWithdraws:e.pending_withdraws.map(h),history:e.history.map(h),historyPagination:O(e.history_pagination)}}function be(e){return {history:e.history.map(h),pagination:O(e.pagination)}}function ye(e){let n=_e(e.tx_hash,"tx_hash");return {txHash:n,events:e.events.map(t=>h({...t,tx_hash:t.tx_hash??n}))}}function L(e,n){let t=e.indexOf(".");if(t===-1)return e;let r=e.slice(t+1);return r.length<=n?e:`${e.slice(0,t)}.${r.slice(0,n)}`}function V(e,n){return typeof e!="string"&&b(`${n} must be a string`),e}function C(e,n){return f(`${n} must be a decimal string`,()=>oe(V(e,n)))}function Tn(e,n){return f(`${n} must be a ratio string`,()=>me.fromRaw(V(e,n)))}function $(e,n){return f(`${n} must be a vault asset decimal`,()=>ue.fromDecimal(L(V(e,n),yn)))}function S(e,n){return f(`${n} must be a vault share decimal`,()=>de.fromDecimal(L(V(e,n),xn)))}function Vn(e,n){return f(`${n} must be a vault share price decimal`,()=>le.fromDecimal(L(V(e,n),_n)))}function wn(e){function n(t,r,a){xe(e,t,r,a);}return {stats:async t=>{let r=await e.raw.vault.stats(t),a=T(r.freshness);return n(r,a,t),I(r,{data:pe(r.data),freshness:a})},account:async(t,r)=>{let a=await e.raw.vault.account(t,r),i=T(a.freshness);return n(a,i,r),I(a,{data:he(a.data),freshness:i})},accountHistory:async(t,r)=>{let a=await e.raw.vault.accountHistory(t,r),i=T(a.freshness);return n(a,i,r),I(a,{data:be(a.data),freshness:i})},transactionEvents:async(t,r)=>{let a=await e.raw.vault.transactionEvents(t,r),i=T(a.freshness);return n(a,i,r),I(a,{data:ye(a.data),freshness:i})},accountHistoryIterator:(t,r)=>Pn(e,t,r)}}async function*Pn(e,n,t={}){let r=t;for(;;){let a=await e.raw.vault.accountHistory(n,r);xe(e,a,T(a.freshness),r);for(let o of a.data.history)yield h(o);let i=a.data.pagination.next_cursor;if(i==null)return;r={...t,cursor:i};}}function xe(e,n,t,r){let a=re(e.onEvent),i=n.readiness;if(i===void 0||i.status==="ready")return;let o=i.unsafe_reasons??[],s=i.degraded_reasons??[],u=i.status==="unsafe"?o.length>0?o:s.length>0?s:[i.status]:o,c=s.length>0?s:i.status==="degraded"?[i.status]:[];ne({policy:r?.readinessPolicy??"strict",chainId:e.chainId??0,degradedReasons:c,unsafeReasons:u,diagnostics:{apiFreshness:t},...a!==void 0?{onEvent:a}:{}});}function vn(e){return e===void 0?{opType:"unknown"}:bn.has(e)?{opType:e}:{opType:"unknown",rawOpType:e}}function _e(e,n){return typeof e!="string"&&b(`vault event ${n} is required for domain mapping`),te(e,n,b)}function In(e,n){if(e!=null)return _e(e,n)}function I(e,n){let t=e.diagnostics;return t===void 0?n:{...n,diagnostics:t}}function T(e){let n=f("indexed_block must be an integer",()=>_(e.indexed_block,"indexed_block")),t=f("chain_head_block must be an integer",()=>_(e.chain_head_block,"chain_head_block")),r=f("lag_blocks must be an integer",()=>_(e.lag_blocks,"lag_blocks")),a=f("cache_age_seconds must be an integer",()=>_(e.cache_age_seconds,"cache_age_seconds")),i={source:e.source,generatedAt:f("generated_at must be an ISO timestamp",()=>ee(e.generated_at,"generated_at")),isStale:r!==void 0&&r>kn};return n!==void 0&&(i.indexedBlock=n),t!==void 0&&(i.chainHeadBlock=t),r!==void 0&&(i.lagBlocks=r),e.cache_status!==void 0&&e.cache_status!==null&&(i.cacheStatus=e.cache_status),a!==void 0&&(i.cacheAgeSeconds=a),i}function E(e,n){let t=e[n];return (typeof t!="number"||!Number.isInteger(t))&&b(`${n} must be an integer`),t}function H(e,n){let t=e[n];if(t!=null)return (typeof t!="number"||!Number.isInteger(t))&&b(`${n} must be an integer`),t}function R(e,n){let t=e[n];if(t!=null)return typeof t!="string"&&b(`${n} must be a string`),t}var En=1e3,Te={sdkVersion:g,sourceTag:"internal-polling",chainId:0};function Ve(e,n,t,r){return new errors.ValidationError({message:`${e} must be ${n}`,diagnostics:r??Te,cause:t})}function U(e,n,t){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw Ve(n,"a finite positive number",e,t)}function we(e,n,t){if(e!==void 0&&!(Number.isInteger(e)&&e>=0))throw Ve(n,"a finite non-negative integer",e,t)}function Rn(e,n){return new errors.ValidationError({message:"intervalMs must be a finite positive number",diagnostics:n??Te,hint:"Omit intervalMs to use the default polling interval, or pass a value greater than 0.",cause:e})}function Pe(e,n){return j(e,n),e===void 0?En:Math.max(1,Math.floor(e))}function j(e,n){if(e!==void 0&&(!Number.isFinite(e)||e<=0))throw Rn(e,n)}var Sn="vault-track",An=25;function G(e){let n={sdkVersion:g,sourceTag:Sn,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(n.registryAddress=e.chain.registryAddress),n}function Y(e,n,t){return {message:n,diagnostics:G(e),...t!==void 0?{cause:t}:{}}}function Ee(e,n){throw new errors.AbortError(Y(e,"vault tracking was aborted",n))}function x(e){throw new errors.TimeoutError(Y(e,"vault tracking timed out"))}function Re(e){return e instanceof errors.AbortError||e instanceof Error&&e.name==="AbortError"?true:typeof e=="object"&&e!==null&&"code"in e&&e.code==="ABORTED"}function Dn(e){if(e instanceof errors.TimeoutError||Re(e)||typeof e!="object"||e===null)return false;let n=e.status??e.httpStatus;if(n===404||n===405||n===501)return true;let t=e.code;if(typeof t!="string")return false;let r=t.toUpperCase();return r.includes("NOT_FOUND")||r.includes("UNSUPPORTED")||r.includes("NOT_IMPLEMENTED")||r.includes("METHOD_NOT_ALLOWED")}function w(e,n){n?.aborted===true&&Ee(e,n.reason);}function Se(e){return [e?.timeoutMs,e?.maxDurationMs].filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0)}function On(e){let n=Se(e);if(n.length!==0)return Date.now()+Math.min(...n)}function P(e){if(e!==void 0)return e-Date.now()}function Nn(e){return e?.maxAttempts!==void 0?Math.max(0,e.maxAttempts):Se(e).length>0?Number.POSITIVE_INFINITY:1}function Ae(e,n){let t=G(e);j(n?.intervalMs,t),U(n?.timeoutMs,"timeoutMs",t),U(n?.maxDurationMs,"maxDurationMs",t),we(n?.maxAttempts,"maxAttempts",t);}function Bn(e,n){return Pe(n?.intervalMs,G(e))}function De(e,n){let t=[];e?.timeoutMs!==void 0&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&t.push(e.timeoutMs);let r=P(n);if(r!==void 0&&r>0&&t.push(r),t.length!==0)return Math.max(1,Math.floor(Math.min(...t)))}function Fn(e,n,t){let r={limit:e?.limit??An};return e?.signal!==void 0&&(r.signal=e.signal),t!==void 0&&(r.timeoutMs=t),e?.readinessPolicy!==void 0&&(r.readinessPolicy=e.readinessPolicy),n!==void 0&&(r.cursor=n),r}function Mn(e,n){let t={};return e?.signal!==void 0&&(t.signal=e.signal),n!==void 0&&(t.timeoutMs=n),e?.readinessPolicy!==void 0&&(t.readinessPolicy=e.readinessPolicy),t}async function Cn(e,n,t){if(w(e,t),n<=0)return;let r;await new Promise((a,i)=>{let o=setTimeout(a,n);r=()=>{clearTimeout(o),i(new errors.AbortError(Y(e,"vault tracking was aborted",t?.reason)));},t?.addEventListener("abort",r,{once:true});}).finally(()=>{r!==void 0&&t?.removeEventListener("abort",r);});}function Oe(e){switch(e){case "deposit":case "mint":return "Deposit";case "depositWithDiscountAndLock":case "mintWithDiscountAndLock":return "DepositLocked";case "makeWithdrawRequest":return "WithdrawRequested";case "cancelWithdrawRequest":return "WithdrawCanceled";case "withdraw":case "redeem":return "Withdraw";case "unlockDeposit":return "DepositUnlocked"}}function Hn(e,n){let t=n;return t.blockNumber===void 0||t.txIndex===void 0||t.logIndex===void 0?true:BigInt(e.blockNumber)===t.blockNumber&&e.txIndex===t.txIndex&&e.logIndex===t.logIndex}function Ln(e,n){return e!==void 0&&e.toLowerCase()===n.toLowerCase()}function Ne(e,n){return Ln(e.txHash,n.txHash)&&e.opType===Oe(n.verb)&&Hn(e,n)}async function $n(e,n,t,r,a){try{let i=Fn(t,r,De(t,a));if(e.vault.accountHistory!==void 0)return await e.vault.accountHistory(n.owner,i);let o=await e.vault.account(n.owner,i);return {...o,data:{history:o.data.history,pagination:o.data.historyPagination}}}catch(i){throw i instanceof errors.TimeoutError||(Re(i)||t?.signal?.aborted===true)&&Ee(e,i),i}}function Un(e){return `${String(e.freshness?.generatedAt)}:${String(e.freshness?.indexedBlock)}`}function jn(e,n){return e.some(t=>BigInt(t.blockNumber)<n.blockNumber)}function ve(e,n,t){n===void 0||t===void 0||(e.exhaustedFirstPage={freshnessKey:n,nextCursor:t});}async function Ie(e,n,t,r,a){let i,o,s;for(;;){w(e,t?.signal);let u=P(r);u!==void 0&&u<=0&&x(e);let c=await $n(e,n,t,i,r),m=c.data.history.find(A=>Ne(A,n));if(m!==void 0)return m;let p=c.data.pagination.nextCursor;if(i===void 0&&(o=Un(c),s=p,p!==void 0&&a.exhaustedFirstPage?.nextCursor===p&&a.exhaustedFirstPage.freshnessKey===o))return;if(jn(c.data.history,n)){ve(a,o,s);return}if(p===void 0){ve(a,o,s);return}i=p;}}async function Wn(e,n,t,r,a){if(e.vault.transactionEvents!==void 0&&!a.transactionEventsUnavailable){w(e,t?.signal);let i=P(r);i!==void 0&&i<=0&&x(e);let o;try{o=await e.vault.transactionEvents(n.txHash,Mn(t,De(t,r)));}catch(s){if(!Dn(s))throw s;return a.transactionEventsUnavailable=true,Ie(e,n,t,r,a.accountHistory)}return o.data.events.find(s=>Ne(s,n))}return Ie(e,n,t,r,a.accountHistory)}async function Be(e,n,t){Ae(e,t);let r=On(t),a=Nn(t),i=Bn(e,t),o={transactionEventsUnavailable:false,accountHistory:{}},s=0;for(w(e,t?.signal),a<=0&&x(e);;){w(e,t?.signal);let u=P(r);u!==void 0&&u<=0&&x(e),s+=1;let c=await Wn(e,n,t,r,o);if(c!==void 0)return {outcome:n,event:c};s>=a&&x(e);let m=P(r);m!==void 0&&m<=0&&x(e),await Cn(e,Math.min(i,m??i),t?.signal);}}async function zn(e,n,t){Ae(e,t);let r=await n.waitReceipt(t),a=await n.outcome(t),i=await Be(e,a,t);return {receipt:r,outcome:a,indexed:i}}Object.defineProperty(exports,"VaultAsset",{enumerable:true,get:function(){return units.VaultAsset}});Object.defineProperty(exports,"VaultShare",{enumerable:true,get:function(){return units.VaultShare}});Object.defineProperty(exports,"VaultSharePrice",{enumerable:true,get:function(){return units.VaultSharePrice}});exports.createVaultReadClient=wn;exports.expectedVaultOpType=Oe;exports.mapVaultAccount=he;exports.mapVaultAccountHistory=be;exports.mapVaultEvent=h;exports.mapVaultStats=pe;exports.mapVaultTransactionEvents=ye;exports.trackVaultOutcome=zn;exports.waitVaultIndexed=Be;
@@ -0,0 +1,34 @@
1
+ export { Address, Hex, VaultAsset, VaultShare, VaultSharePrice } from '@domfi/sdk/units';
2
+ import { DomfiRawClient, ReadinessWarningEvent, RawVaultAccountData, RawVaultAccountHistoryData, RawVaultEvent, RawVaultStatsData, RawVaultTransactionEventsData } from './api.cjs';
3
+ import { l as VaultReadClient, m as VaultAccount, n as VaultAccountHistory, o as VaultEvent, p as VaultStats, q as VaultTransactionEvents, V as VaultVerb, r as VaultTxHandle, s as VaultTrackOptions, t as VaultTrackedOutcome, a as VaultOutcomeForVerb, u as VaultIndexedOutcome } from './types-x1MvxSdy.cjs';
4
+ export { P as PreparedVaultTx, v as VaultAccountHistoryOptions, w as VaultAccountOptions, x as VaultApprovalAction, y as VaultApprovalNeed, e as VaultCancelWithdrawRequestParams, k as VaultClient, z as VaultDepositOutcome, b as VaultDepositParams, h as VaultDepositWithDiscountAndLockParams, A as VaultDirectSendOptions, B as VaultIndexedOutcomeForVerb, C as VaultLockedDeposit, D as VaultLockedDepositOutcome, d as VaultMakeWithdrawRequestParams, c as VaultMintParams, i as VaultMintWithDiscountAndLockParams, E as VaultNormalizedParams, F as VaultOperationType, G as VaultOutcomeBase, H as VaultPreflightReport, I as VaultPreflightWarning, J as VaultPrepareOptions, K as VaultPreparedSendOptions, L as VaultReceiptOutcome, g as VaultRedeemParams, M as VaultSendOptions, N as VaultSimResult, O as VaultSimulateOptions, Q as VaultTrackedOutcomeForVerb, j as VaultUnlockDepositParams, R as VaultUnlockOutcome, S as VaultWaitReceiptOptions, T as VaultWithdrawCancelOutcome, U as VaultWithdrawOutcome, f as VaultWithdrawParams, W as VaultWithdrawRequestOutcome } from './types-x1MvxSdy.cjs';
5
+ import { DomfiChainProfile } from './config.cjs';
6
+ import './units.cjs';
7
+ import './types-DQft82W7.cjs';
8
+ import './errors.cjs';
9
+ import '@domfi/sdk/errors';
10
+ import './referrals.cjs';
11
+ import './types-DJBX-p4X.cjs';
12
+ import 'viem';
13
+
14
+ type VaultReadDeps = {
15
+ raw: Pick<DomfiRawClient, "vault">;
16
+ chainId?: number;
17
+ onEvent?: (event: ReadinessWarningEvent) => void;
18
+ };
19
+ declare function mapVaultStats(raw: RawVaultStatsData): VaultStats;
20
+ declare function mapVaultEvent(raw: RawVaultEvent): VaultEvent;
21
+ declare function mapVaultAccount(raw: RawVaultAccountData): VaultAccount;
22
+ declare function mapVaultAccountHistory(raw: RawVaultAccountHistoryData): VaultAccountHistory;
23
+ declare function mapVaultTransactionEvents(raw: RawVaultTransactionEventsData): VaultTransactionEvents;
24
+ declare function createVaultReadClient(deps: VaultReadDeps): VaultReadClient;
25
+
26
+ type VaultTrackDeps = {
27
+ chain: DomfiChainProfile;
28
+ vault: Pick<VaultReadClient, "account"> & Partial<Pick<VaultReadClient, "accountHistory" | "transactionEvents">>;
29
+ };
30
+ declare function expectedVaultOpType(verb: VaultVerb): VaultEvent["opType"];
31
+ declare function waitVaultIndexed<Verb extends VaultVerb>(deps: VaultTrackDeps, outcome: VaultOutcomeForVerb<Verb>, opts?: VaultTrackOptions): Promise<VaultIndexedOutcome<Verb>>;
32
+ declare function trackVaultOutcome<Verb extends VaultVerb>(deps: VaultTrackDeps, handle: VaultTxHandle<Verb>, opts?: VaultTrackOptions): Promise<VaultTrackedOutcome<Verb>>;
33
+
34
+ export { VaultAccount, VaultAccountHistory, VaultEvent, VaultIndexedOutcome, VaultOutcomeForVerb, VaultReadClient, type VaultReadDeps, VaultStats, type VaultTrackDeps, VaultTrackOptions, VaultTrackedOutcome, VaultTransactionEvents, VaultTxHandle, VaultVerb, createVaultReadClient, expectedVaultOpType, mapVaultAccount, mapVaultAccountHistory, mapVaultEvent, mapVaultStats, mapVaultTransactionEvents, trackVaultOutcome, waitVaultIndexed };
@@ -0,0 +1,34 @@
1
+ export { Address, Hex, VaultAsset, VaultShare, VaultSharePrice } from '@domfi/sdk/units';
2
+ import { DomfiRawClient, ReadinessWarningEvent, RawVaultAccountData, RawVaultAccountHistoryData, RawVaultEvent, RawVaultStatsData, RawVaultTransactionEventsData } from './api.js';
3
+ import { l as VaultReadClient, m as VaultAccount, n as VaultAccountHistory, o as VaultEvent, p as VaultStats, q as VaultTransactionEvents, V as VaultVerb, r as VaultTxHandle, s as VaultTrackOptions, t as VaultTrackedOutcome, a as VaultOutcomeForVerb, u as VaultIndexedOutcome } from './types-veTDfbhq.js';
4
+ export { P as PreparedVaultTx, v as VaultAccountHistoryOptions, w as VaultAccountOptions, x as VaultApprovalAction, y as VaultApprovalNeed, e as VaultCancelWithdrawRequestParams, k as VaultClient, z as VaultDepositOutcome, b as VaultDepositParams, h as VaultDepositWithDiscountAndLockParams, A as VaultDirectSendOptions, B as VaultIndexedOutcomeForVerb, C as VaultLockedDeposit, D as VaultLockedDepositOutcome, d as VaultMakeWithdrawRequestParams, c as VaultMintParams, i as VaultMintWithDiscountAndLockParams, E as VaultNormalizedParams, F as VaultOperationType, G as VaultOutcomeBase, H as VaultPreflightReport, I as VaultPreflightWarning, J as VaultPrepareOptions, K as VaultPreparedSendOptions, L as VaultReceiptOutcome, g as VaultRedeemParams, M as VaultSendOptions, N as VaultSimResult, O as VaultSimulateOptions, Q as VaultTrackedOutcomeForVerb, j as VaultUnlockDepositParams, R as VaultUnlockOutcome, S as VaultWaitReceiptOptions, T as VaultWithdrawCancelOutcome, U as VaultWithdrawOutcome, f as VaultWithdrawParams, W as VaultWithdrawRequestOutcome } from './types-veTDfbhq.js';
5
+ import { DomfiChainProfile } from './config.js';
6
+ import './units.js';
7
+ import './types-7s13ZSql.js';
8
+ import './errors.js';
9
+ import '@domfi/sdk/errors';
10
+ import './referrals.js';
11
+ import './types-DDgJiEFg.js';
12
+ import 'viem';
13
+
14
+ type VaultReadDeps = {
15
+ raw: Pick<DomfiRawClient, "vault">;
16
+ chainId?: number;
17
+ onEvent?: (event: ReadinessWarningEvent) => void;
18
+ };
19
+ declare function mapVaultStats(raw: RawVaultStatsData): VaultStats;
20
+ declare function mapVaultEvent(raw: RawVaultEvent): VaultEvent;
21
+ declare function mapVaultAccount(raw: RawVaultAccountData): VaultAccount;
22
+ declare function mapVaultAccountHistory(raw: RawVaultAccountHistoryData): VaultAccountHistory;
23
+ declare function mapVaultTransactionEvents(raw: RawVaultTransactionEventsData): VaultTransactionEvents;
24
+ declare function createVaultReadClient(deps: VaultReadDeps): VaultReadClient;
25
+
26
+ type VaultTrackDeps = {
27
+ chain: DomfiChainProfile;
28
+ vault: Pick<VaultReadClient, "account"> & Partial<Pick<VaultReadClient, "accountHistory" | "transactionEvents">>;
29
+ };
30
+ declare function expectedVaultOpType(verb: VaultVerb): VaultEvent["opType"];
31
+ declare function waitVaultIndexed<Verb extends VaultVerb>(deps: VaultTrackDeps, outcome: VaultOutcomeForVerb<Verb>, opts?: VaultTrackOptions): Promise<VaultIndexedOutcome<Verb>>;
32
+ declare function trackVaultOutcome<Verb extends VaultVerb>(deps: VaultTrackDeps, handle: VaultTxHandle<Verb>, opts?: VaultTrackOptions): Promise<VaultTrackedOutcome<Verb>>;
33
+
34
+ export { VaultAccount, VaultAccountHistory, VaultEvent, VaultIndexedOutcome, VaultOutcomeForVerb, VaultReadClient, type VaultReadDeps, VaultStats, type VaultTrackDeps, VaultTrackOptions, VaultTrackedOutcome, VaultTransactionEvents, VaultTxHandle, VaultVerb, createVaultReadClient, expectedVaultOpType, mapVaultAccount, mapVaultAccountHistory, mapVaultEvent, mapVaultStats, mapVaultTransactionEvents, trackVaultOutcome, waitVaultIndexed };
package/dist/vault.js ADDED
@@ -0,0 +1 @@
1
+ export{m as createVaultReadClient,p as expectedVaultOpType,j as mapVaultAccount,k as mapVaultAccountHistory,i as mapVaultEvent,h as mapVaultStats,l as mapVaultTransactionEvents,s as trackVaultOutcome,r as waitVaultIndexed}from'./chunk-XHQVWI2J.js';import'./chunk-BMYMNNJK.js';import'./chunk-LDE3JHVE.js';import'./chunk-D5VE2O4F.js';import'./chunk-C5Y2WM7C.js';export{VaultAsset,VaultShare,VaultSharePrice}from'@domfi/sdk/units';