@0xmonaco/types 0.8.10 → 0.8.14

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.
@@ -15,6 +15,11 @@ export const GetMarginAccountSummarySchema = z.object({
15
15
  marginAccountId: UUIDSchema,
16
16
  tradingPairId: UUIDSchema.optional(),
17
17
  });
18
+ export const GetParentMarginAccountSummarySchema = z
19
+ .object({
20
+ tradingPairId: UUIDSchema.optional(),
21
+ })
22
+ .optional();
18
23
  export const GetAvailableCollateralSchema = z
19
24
  .object({
20
25
  asset: z.string().trim().min(1, "Asset cannot be empty").optional(),
@@ -26,7 +31,11 @@ const TransferCollateralRequestSchema = z.object({
26
31
  tradingPairId: UUIDSchema.optional(),
27
32
  strategyKey: z.string().trim().min(1, "Strategy key cannot be empty").optional(),
28
33
  });
29
- const AutoMarginBucketRequestSchema = z.object({
34
+ const ParentMarginAccountCollateralRequestSchema = z.object({
35
+ asset: z.string().trim().min(1, "Asset cannot be empty"),
36
+ amount: PositiveDecimalStringSchema,
37
+ });
38
+ const RiskBucketRequestSchema = z.object({
30
39
  tradingPairId: UUIDSchema,
31
40
  strategyKey: z.string().trim().min(1, "Strategy key cannot be empty").optional(),
32
41
  });
@@ -34,13 +43,22 @@ export const TransferCollateralSchema = z.object({
34
43
  marginAccountId: UUIDSchema,
35
44
  request: TransferCollateralRequestSchema,
36
45
  });
37
- export const TransferCollateralToAutoMarginAccountSchema = z.object({
38
- request: TransferCollateralRequestSchema.merge(AutoMarginBucketRequestSchema),
46
+ export const TransferCollateralToParentMarginAccountSchema = z.object({
47
+ request: ParentMarginAccountCollateralRequestSchema,
48
+ });
49
+ export const TransferCollateralToRiskBucketSchema = z.object({
50
+ request: ParentMarginAccountCollateralRequestSchema.merge(RiskBucketRequestSchema),
51
+ });
52
+ export const TransferCollateralFromParentMarginAccountSchema = z.object({
53
+ request: ParentMarginAccountCollateralRequestSchema,
39
54
  });
40
55
  export const GetMarginAccountMovementsSchema = PaginationSchema.extend({
41
56
  marginAccountId: UUIDSchema,
42
57
  movement_type: z.string().trim().min(1, "Movement type cannot be empty").optional(),
43
58
  });
59
+ export const GetParentMarginAccountMovementsSchema = PaginationSchema.extend({
60
+ movement_type: z.string().trim().min(1, "Movement type cannot be empty").optional(),
61
+ }).optional();
44
62
  const BaseSimulateOrderRiskRequestSchema = z.object({
45
63
  tradingPairId: UUIDSchema,
46
64
  side: OrderSideSchema,
@@ -52,7 +70,7 @@ const BaseSimulateOrderRiskRequestSchema = z.object({
52
70
  reduceOnly: z.boolean().optional(),
53
71
  });
54
72
  const SimulateOrderRiskRequestSchema = BaseSimulateOrderRiskRequestSchema.strict();
55
- const SimulateAutoMarginOrderRiskRequestSchema = BaseSimulateOrderRiskRequestSchema.merge(AutoMarginBucketRequestSchema).strict();
73
+ const SimulateRiskBucketOrderRiskRequestSchema = BaseSimulateOrderRiskRequestSchema.merge(RiskBucketRequestSchema).strict();
56
74
  export const SimulateOrderRiskSchema = z
57
75
  .object({
58
76
  marginAccountId: UUIDSchema,
@@ -62,9 +80,17 @@ export const SimulateOrderRiskSchema = z
62
80
  message: "price is required for LIMIT risk simulations",
63
81
  path: ["request", "price"],
64
82
  });
65
- export const SimulateAutoMarginOrderRiskSchema = z
83
+ export const SimulateParentMarginOrderRiskSchema = z
84
+ .object({
85
+ request: SimulateOrderRiskRequestSchema,
86
+ })
87
+ .refine((data) => data.request.orderType !== "LIMIT" || data.request.price !== undefined, {
88
+ message: "price is required for LIMIT risk simulations",
89
+ path: ["request", "price"],
90
+ });
91
+ export const SimulateRiskBucketOrderRiskSchema = z
66
92
  .object({
67
- request: SimulateAutoMarginOrderRiskRequestSchema,
93
+ request: SimulateRiskBucketOrderRiskRequestSchema,
68
94
  })
69
95
  .refine((data) => data.request.orderType !== "LIMIT" || data.request.price !== undefined, {
70
96
  message: "price is required for LIMIT risk simulations",
@@ -29,6 +29,10 @@ export declare const ClosePositionSchema: z.ZodObject<{
29
29
  quantity: z.ZodOptional<z.ZodString>;
30
30
  }, z.core.$strip>;
31
31
  }, z.core.$strip>;
32
+ export declare const BatchCloseAllSchema: z.ZodObject<{
33
+ tradingPairId: z.ZodOptional<z.ZodUUID>;
34
+ slippageToleranceBps: z.ZodOptional<z.ZodNumber>;
35
+ }, z.core.$strip>;
32
36
  export declare const GetPositionRiskSchema: z.ZodObject<{
33
37
  positionId: z.ZodUUID;
34
38
  }, z.core.$strip>;
@@ -38,6 +38,10 @@ export const ClosePositionSchema = PositionIdSchema.extend({
38
38
  message: "limitPrice is only allowed for LIMIT close requests",
39
39
  path: ["request", "limitPrice"],
40
40
  });
41
+ export const BatchCloseAllSchema = z.object({
42
+ tradingPairId: UUIDSchema.optional(),
43
+ slippageToleranceBps: SlippageToleranceBpsSchema.optional(),
44
+ });
41
45
  export const GetPositionRiskSchema = PositionIdSchema;
42
46
  export const AddPositionMarginSchema = PositionIdSchema.extend({
43
47
  request: z.object({
@@ -101,8 +101,8 @@ export declare const PlaceLimitOrderSchema: z.ZodObject<{
101
101
  FOK: "FOK";
102
102
  }>>;
103
103
  marginAccountId: z.ZodOptional<z.ZodUUID>;
104
- marginBucketId: z.ZodOptional<z.ZodUUID>;
105
- marginBucketCollateral: z.ZodOptional<z.ZodString>;
104
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
105
+ riskBucketCollateral: z.ZodOptional<z.ZodString>;
106
106
  strategyKey: z.ZodOptional<z.ZodString>;
107
107
  positionSide: z.ZodOptional<z.ZodEnum<{
108
108
  LONG: "LONG";
@@ -158,8 +158,8 @@ export declare const PlaceMarketOrderSchema: z.ZodObject<{
158
158
  }>>;
159
159
  slippageTolerance: z.ZodOptional<z.ZodNumber>;
160
160
  marginAccountId: z.ZodOptional<z.ZodUUID>;
161
- marginBucketId: z.ZodOptional<z.ZodUUID>;
162
- marginBucketCollateral: z.ZodOptional<z.ZodString>;
161
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
162
+ riskBucketCollateral: z.ZodOptional<z.ZodString>;
163
163
  strategyKey: z.ZodOptional<z.ZodString>;
164
164
  positionSide: z.ZodOptional<z.ZodEnum<{
165
165
  LONG: "LONG";
@@ -320,8 +320,8 @@ export declare const BatchCreateOrderItemSchema: z.ZodObject<{
320
320
  FOK: "FOK";
321
321
  }>>;
322
322
  marginAccountId: z.ZodOptional<z.ZodUUID>;
323
- marginBucketId: z.ZodOptional<z.ZodUUID>;
324
- marginBucketCollateral: z.ZodOptional<z.ZodString>;
323
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
324
+ riskBucketCollateral: z.ZodOptional<z.ZodString>;
325
325
  strategyKey: z.ZodOptional<z.ZodString>;
326
326
  positionSide: z.ZodOptional<z.ZodEnum<{
327
327
  LONG: "LONG";
@@ -362,8 +362,8 @@ export declare const BatchCreateOrdersSchema: z.ZodObject<{
362
362
  FOK: "FOK";
363
363
  }>>;
364
364
  marginAccountId: z.ZodOptional<z.ZodUUID>;
365
- marginBucketId: z.ZodOptional<z.ZodUUID>;
366
- marginBucketCollateral: z.ZodOptional<z.ZodString>;
365
+ riskBucketId: z.ZodOptional<z.ZodUUID>;
366
+ riskBucketCollateral: z.ZodOptional<z.ZodString>;
367
367
  strategyKey: z.ZodOptional<z.ZodString>;
368
368
  positionSide: z.ZodOptional<z.ZodEnum<{
369
369
  LONG: "LONG";
@@ -117,8 +117,8 @@ export const PlaceLimitOrderSchema = z
117
117
  expirationDate: ISO8601DateSchema.optional(),
118
118
  timeInForce: TimeInForceSchema.optional(),
119
119
  marginAccountId: UUIDSchema.optional(),
120
- marginBucketId: UUIDSchema.optional(),
121
- marginBucketCollateral: PositiveDecimalStringSchema.optional(),
120
+ riskBucketId: UUIDSchema.optional(),
121
+ riskBucketCollateral: PositiveDecimalStringSchema.optional(),
122
122
  strategyKey: z.string().min(1).max(128).optional(),
123
123
  positionSide: PositionSideSchema.optional(),
124
124
  leverage: PositiveDecimalStringSchema.optional(),
@@ -148,16 +148,16 @@ export const PlaceLimitOrderSchema = z
148
148
  message: "Parent TP/SL cannot be attached to reduceOnly orders",
149
149
  path: ["options", "reduceOnly"],
150
150
  })
151
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.tradingMode === "MARGIN", {
152
- message: "marginBucketCollateral is only supported for MARGIN orders",
151
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.tradingMode === "MARGIN", {
152
+ message: "riskBucketCollateral is only supported for MARGIN orders",
153
153
  path: ["options", "tradingMode"],
154
154
  })
155
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.marginBucketId === undefined, {
156
- message: "marginBucketCollateral creates a new bucket and cannot be combined with marginBucketId",
157
- path: ["options", "marginBucketId"],
155
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.riskBucketId === undefined, {
156
+ message: "riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",
157
+ path: ["options", "riskBucketId"],
158
158
  })
159
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.reduceOnly !== true, {
160
- message: "reduceOnly orders cannot create a new margin bucket",
159
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.reduceOnly !== true, {
160
+ message: "reduceOnly orders cannot create a new risk bucket",
161
161
  path: ["options", "reduceOnly"],
162
162
  });
163
163
  /**
@@ -173,8 +173,8 @@ export const PlaceMarketOrderSchema = z
173
173
  tradingMode: TradingModeSchema.optional(),
174
174
  slippageTolerance: SlippageToleranceSchema,
175
175
  marginAccountId: UUIDSchema.optional(),
176
- marginBucketId: UUIDSchema.optional(),
177
- marginBucketCollateral: PositiveDecimalStringSchema.optional(),
176
+ riskBucketId: UUIDSchema.optional(),
177
+ riskBucketCollateral: PositiveDecimalStringSchema.optional(),
178
178
  strategyKey: z.string().min(1).max(128).optional(),
179
179
  positionSide: PositionSideSchema.optional(),
180
180
  leverage: PositiveDecimalStringSchema.optional(),
@@ -204,16 +204,16 @@ export const PlaceMarketOrderSchema = z
204
204
  message: "Parent TP/SL cannot be attached to reduceOnly orders",
205
205
  path: ["options", "reduceOnly"],
206
206
  })
207
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.tradingMode === "MARGIN", {
208
- message: "marginBucketCollateral is only supported for MARGIN orders",
207
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.tradingMode === "MARGIN", {
208
+ message: "riskBucketCollateral is only supported for MARGIN orders",
209
209
  path: ["options", "tradingMode"],
210
210
  })
211
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.marginBucketId === undefined, {
212
- message: "marginBucketCollateral creates a new bucket and cannot be combined with marginBucketId",
213
- path: ["options", "marginBucketId"],
211
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.riskBucketId === undefined, {
212
+ message: "riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",
213
+ path: ["options", "riskBucketId"],
214
214
  })
215
- .refine((data) => data.options?.marginBucketCollateral === undefined || data.options?.reduceOnly !== true, {
216
- message: "reduceOnly orders cannot create a new margin bucket",
215
+ .refine((data) => data.options?.riskBucketCollateral === undefined || data.options?.reduceOnly !== true, {
216
+ message: "reduceOnly orders cannot create a new risk bucket",
217
217
  path: ["options", "reduceOnly"],
218
218
  });
219
219
  /**
@@ -298,8 +298,8 @@ export const BatchCreateOrderItemSchema = z
298
298
  expirationDate: ISO8601DateSchema.optional(),
299
299
  timeInForce: TimeInForceSchema.optional(),
300
300
  marginAccountId: UUIDSchema.optional(),
301
- marginBucketId: UUIDSchema.optional(),
302
- marginBucketCollateral: PositiveDecimalStringSchema.optional(),
301
+ riskBucketId: UUIDSchema.optional(),
302
+ riskBucketCollateral: PositiveDecimalStringSchema.optional(),
303
303
  strategyKey: z.string().min(1).max(128).optional(),
304
304
  positionSide: PositionSideSchema.optional(),
305
305
  leverage: PositiveDecimalStringSchema.optional(),
@@ -313,16 +313,16 @@ export const BatchCreateOrderItemSchema = z
313
313
  message: "Price must not be provided for MARKET orders",
314
314
  path: ["price"],
315
315
  })
316
- .refine((data) => data.marginBucketCollateral === undefined || data.tradingMode === "MARGIN", {
317
- message: "marginBucketCollateral is only supported for MARGIN orders",
316
+ .refine((data) => data.riskBucketCollateral === undefined || data.tradingMode === "MARGIN", {
317
+ message: "riskBucketCollateral is only supported for MARGIN orders",
318
318
  path: ["tradingMode"],
319
319
  })
320
- .refine((data) => data.marginBucketCollateral === undefined || data.marginBucketId === undefined, {
321
- message: "marginBucketCollateral creates a new bucket and cannot be combined with marginBucketId",
322
- path: ["marginBucketId"],
320
+ .refine((data) => data.riskBucketCollateral === undefined || data.riskBucketId === undefined, {
321
+ message: "riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",
322
+ path: ["riskBucketId"],
323
323
  })
324
- .refine((data) => data.marginBucketCollateral === undefined || data.reduceOnly !== true, {
325
- message: "reduceOnly orders cannot create a new margin bucket",
324
+ .refine((data) => data.riskBucketCollateral === undefined || data.reduceOnly !== true, {
325
+ message: "reduceOnly orders cannot create a new risk bucket",
326
326
  path: ["reduceOnly"],
327
327
  })
328
328
  .refine((data) => data.tradingMode !== "MARGIN" || data.positionSide !== undefined, {
@@ -44,6 +44,10 @@ export declare const DepositSchema: z.ZodObject<{
44
44
  assetId: z.ZodUUID;
45
45
  amount: z.ZodUnion<readonly [z.ZodString, z.ZodBigInt]>;
46
46
  autoWait: z.ZodOptional<z.ZodBoolean>;
47
+ target: z.ZodOptional<z.ZodEnum<{
48
+ spot: "spot";
49
+ margin: "margin";
50
+ }>>;
47
51
  }, z.core.$strip>;
48
52
  /**
49
53
  * Withdraw validation schema.
@@ -57,6 +61,10 @@ export declare const WithdrawSchema: z.ZodObject<{
57
61
  amount: z.ZodUnion<readonly [z.ZodString, z.ZodBigInt]>;
58
62
  destination: z.ZodString;
59
63
  autoWait: z.ZodOptional<z.ZodBoolean>;
64
+ source: z.ZodOptional<z.ZodEnum<{
65
+ spot: "spot";
66
+ margin: "margin";
67
+ }>>;
60
68
  }, z.core.$strip>;
61
69
  /**
62
70
  * Get Balance validation schema
@@ -57,6 +57,8 @@ export const DepositSchema = z.object({
57
57
  assetId: UUIDSchema,
58
58
  amount: PositiveBigIntStringSchema,
59
59
  autoWait: z.boolean().optional(),
60
+ // Destination ledger: "spot" (default) or "margin" to route into margin collateral.
61
+ target: z.enum(["spot", "margin"]).optional(),
60
62
  });
61
63
  /**
62
64
  * Withdraw validation schema.
@@ -70,6 +72,7 @@ export const WithdrawSchema = z.object({
70
72
  amount: PositiveBigIntStringSchema,
71
73
  destination: z.string().regex(/^0x[a-fA-F0-9]{40}$/, "destination must be a 0x-prefixed 20-byte hex address"),
72
74
  autoWait: z.boolean().optional(),
75
+ source: z.enum(["spot", "margin"]).optional(),
73
76
  });
74
77
  /**
75
78
  * Get Balance validation schema
@@ -3,8 +3,25 @@
3
3
  *
4
4
  * Types for vault operations including deposits, withdrawals, and balance management.
5
5
  */
6
+ import type { Address } from "viem";
6
7
  import type { BaseAPI } from "../api/index";
7
- import type { Balance, TransactionResult, WithdrawResult } from "./responses";
8
+ import type { Balance, TransactionResult, WithdrawalRetryOptions, WithdrawResult } from "./responses";
9
+ /**
10
+ * Destination ledger for a deposit.
11
+ * - `"spot"` (default): credit the spot/main wallet — unchanged behavior.
12
+ * - `"margin"`: route the deposit straight into the parent margin account's
13
+ * collateral (auto-creating the account if it does not exist yet). A deposit
14
+ * that cannot be routed to margin (unsupported asset, etc.) safely falls back
15
+ * to spot — funds are never lost.
16
+ */
17
+ export type DepositTarget = "spot" | "margin";
18
+ /**
19
+ * Source ledger for an external withdrawal.
20
+ * - `"spot"` (default): withdraw from the spot/main wallet.
21
+ * - `"margin"`: directly withdraw from the parent margin account's
22
+ * withdrawable collateral.
23
+ */
24
+ export type WithdrawalSource = "spot" | "margin";
8
25
  /**
9
26
  * Vault API interface.
10
27
  * Provides methods for managing token deposits and withdrawals.
@@ -24,31 +41,47 @@ export interface VaultAPI extends BaseAPI {
24
41
  * @param assetId - Asset identifier (UUID) to deposit
25
42
  * @param amount - Amount to deposit
26
43
  * @param autoWait - Whether to automatically wait for transaction confirmation (defaults to true)
44
+ * @param target - Destination ledger: `"spot"` (default) or `"margin"` to
45
+ * route the deposit into the parent margin account's collateral. Margin
46
+ * deposits that cannot be routed fall back to spot.
27
47
  * @returns Promise resolving to the transaction result
28
48
  */
29
- deposit(assetId: string, amount: bigint, autoWait?: boolean): Promise<TransactionResult>;
49
+ deposit(assetId: string, amount: bigint, autoWait?: boolean, target?: DepositTarget): Promise<TransactionResult>;
30
50
  /**
31
- * Initiates a withdrawal: allocates a `withdrawalIndex` via the API Gateway,
32
- * receives pre-signed calldata for `executeSignedWithdrawal(...)`, and
33
- * submits it on-chain through the connected wallet.
51
+ * Initiates a withdrawal and submits its `executeWithdrawal(...)` calldata
52
+ * on-chain through the connected wallet.
53
+ *
54
+ * The API Gateway allocates a `withdrawalIndex` and debits the balance, but
55
+ * the executable calldata requires the withdrawal's merkle proof, which only
56
+ * exists once its root is confirmed on-chain (a process that can take a
57
+ * while). This method polls `GET /withdrawals/{index}` until the calldata is
58
+ * available — retrying while the gateway reports it is not yet confirmed —
59
+ * then submits it.
34
60
  *
35
61
  * @param assetId - Asset identifier (UUID) to withdraw
36
62
  * @param amount - Raw token amount (smallest unit, as bigint)
37
63
  * @param autoWait - Whether to await on-chain confirmation (defaults to true)
64
+ * @param source - Source ledger: `"spot"` (default) or `"margin"` to source
65
+ * funds directly from the parent margin account's withdrawable collateral
66
+ * @param retry - Polling cadence/timeout while waiting for the proof
38
67
  * @returns Promise resolving to `{ withdrawalIndex, transaction }`
39
68
  */
40
- withdraw(assetId: string, amount: bigint, autoWait?: boolean): Promise<WithdrawResult>;
69
+ withdraw(assetId: string, amount: bigint, autoWait?: boolean, source?: WithdrawalSource, retry?: WithdrawalRetryOptions): Promise<WithdrawResult>;
70
+ withdraw(assetId: string, amount: bigint, autoWait?: boolean, retry?: WithdrawalRetryOptions): Promise<WithdrawResult>;
41
71
  /**
42
- * Retries a previously-initiated withdrawal whose on-chain submission never
43
- * landed (wallet rejected, page reloaded before receipt, stuck mempool).
44
- * Re-fetches the same signed calldata and resubmits via the connected wallet
45
- * does NOT initiate a new withdrawal.
72
+ * Submits (or resubmits) a previously-initiated withdrawal on-chain. Polls
73
+ * for the `executeWithdrawal` calldata the same way as `withdraw` — useful
74
+ * when the original submission never landed (wallet rejected, page reloaded
75
+ * before receipt, stuck mempool) or when the proof was not yet available at
76
+ * the time of the original `withdraw()` call. Does NOT initiate a new
77
+ * withdrawal.
46
78
  *
47
79
  * @param withdrawalIndex - Index returned by the original `withdraw()` call
48
80
  * @param autoWait - Whether to await on-chain confirmation (defaults to true)
81
+ * @param retry - Polling cadence/timeout while waiting for the proof
49
82
  * @returns Promise resolving to `{ withdrawalIndex, ...transaction }`
50
83
  */
51
- retryWithdrawal(withdrawalIndex: number, autoWait?: boolean): Promise<WithdrawResult>;
84
+ retryWithdrawal(withdrawalIndex: number, autoWait?: boolean, retry?: WithdrawalRetryOptions): Promise<WithdrawResult>;
52
85
  /**
53
86
  * Gets the balance of a token in the vault.
54
87
  * @param assetId - Asset identifier (UUID) to check
@@ -73,7 +106,7 @@ export interface VaultAPI extends BaseAPI {
73
106
  * Gets the address of the vault.
74
107
  * @returns Promise resolving to the address of the vault
75
108
  */
76
- getVaultAddress(): Promise<string>;
109
+ getVaultAddress(): Promise<Address>;
77
110
  /**
78
111
  * Sets the wallet client for signing transactions.
79
112
  * Used when the wallet becomes available after SDK initialization.
@@ -81,4 +114,4 @@ export interface VaultAPI extends BaseAPI {
81
114
  */
82
115
  setWalletClient(walletClient: unknown): void;
83
116
  }
84
- export type { Balance, TransactionResult, WithdrawResult } from "./responses";
117
+ export type { Balance, TransactionResult, WithdrawalRetryOptions, WithdrawResult } from "./responses";
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Response types for vault operations.
5
5
  */
6
+ import type { Address } from "viem";
6
7
  /**
7
8
  * Response from a transaction.
8
9
  */
@@ -17,29 +18,66 @@ export interface TransactionResult {
17
18
  receipt?: import("viem").TransactionReceipt;
18
19
  }
19
20
  /**
20
- * Result of initiating a withdrawal.
21
+ * Result of a withdrawal.
21
22
  *
22
23
  * The API gateway allocates a `withdrawalIndex` via the matching engine and
23
- * returns pre-signed calldata for the vault contract's
24
- * `executeSignedWithdrawal(...)` function. The SDK submits that calldata on
25
- * behalf of the connected wallet the user is the on-chain caller, but the
26
- * `WITHDRAWAL_SIGNER` signature embedded in the calldata is what the contract
27
- * authenticates against.
24
+ * debits the balance immediately. The executable `executeWithdrawal(...)`
25
+ * calldata only exists once the withdrawal's root is confirmed on-chain and its
26
+ * merkle proof is persisted; the SDK polls for it and submits it through the
27
+ * connected wallet.
28
28
  *
29
- * Extends [`TransactionResult`] so callers can read `hash`, `status`, `nonce`
30
- * (and `receipt` when `autoWait` is true) directly off the result, just like
31
- * `approve` / `deposit`.
29
+ * `withdrawalIndex` is therefore ALWAYS present even when the proof did not
30
+ * become available within the poll window. In that case `status` is
31
+ * `"awaiting_proof"` and no transaction was submitted (`hash`, `nonce`, and
32
+ * `receipt` are absent); the caller keeps `withdrawalIndex` and finishes the
33
+ * withdrawal later with `retryWithdrawal(withdrawalIndex)`. This is why the
34
+ * transaction fields are optional rather than inherited as required from
35
+ * [`TransactionResult`]: a debited-but-unproven withdrawal must never strand the
36
+ * index inside a thrown error.
32
37
  */
33
- export interface WithdrawResult extends TransactionResult {
34
- /** Allocated withdrawal index — matches `executeSignedWithdrawal.index`. */
38
+ export interface WithdrawResult {
39
+ /** Allocated withdrawal index — matches `executeWithdrawal.index`. Always present. */
35
40
  withdrawalIndex: number;
41
+ /**
42
+ * Outcome of the withdrawal:
43
+ * - `"awaiting_proof"` — index allocated and balance debited, but the merkle
44
+ * proof was not available within the poll window, so nothing was submitted
45
+ * on-chain. Call `retryWithdrawal(withdrawalIndex)` once the root confirms.
46
+ * - `"pending" | "confirmed" | "failed"` — the calldata was submitted on-chain;
47
+ * semantics match [`TransactionResult.status`].
48
+ */
49
+ status: TransactionResult["status"] | "awaiting_proof";
50
+ /** Transaction hash — absent when `status === "awaiting_proof"`. */
51
+ hash?: string;
52
+ /** Nonce used for the on-chain submission — absent when `status === "awaiting_proof"`. */
53
+ nonce?: bigint;
54
+ /** Transaction receipt (only when `autoWait` is enabled and the tx was submitted). */
55
+ receipt?: import("viem").TransactionReceipt;
56
+ }
57
+ /**
58
+ * Controls how the SDK polls for a withdrawal's `executeWithdrawal` calldata
59
+ * while its merkle proof is not yet available (the withdrawal root has not been
60
+ * confirmed on-chain). The gateway returns 404 (row not persisted yet) or 409
61
+ * (proof not confirmed yet) until ready; the SDK retries on both.
62
+ */
63
+ export interface WithdrawalRetryOptions {
64
+ /** Delay between polls, in milliseconds. Defaults to 5000. */
65
+ pollIntervalMs?: number;
66
+ /**
67
+ * Maximum total time to wait for the proof, in milliseconds. Defaults to
68
+ * 300_000 (5 minutes). On timeout the SDK does not throw — `withdraw` /
69
+ * `retryWithdrawal` return `{ status: "awaiting_proof", withdrawalIndex }` so
70
+ * the caller can retry later. Pass `Infinity` to poll indefinitely until the
71
+ * proof is available.
72
+ */
73
+ timeoutMs?: number;
36
74
  }
37
75
  /**
38
76
  * Token balance information.
39
77
  */
40
78
  export interface Balance {
41
79
  /** Token address */
42
- token: string;
80
+ token: Address;
43
81
  /** Balance amount */
44
82
  amount: bigint;
45
83
  /** Formatted balance string */
@@ -4,6 +4,7 @@
4
4
  * Types for real-time user balance update events.
5
5
  * This is an authenticated channel - requires JWT token.
6
6
  */
7
+ import type { Address } from "viem";
7
8
  /**
8
9
  * Reason for the balance update
9
10
  */
@@ -13,7 +14,7 @@ export type BalanceUpdateReason = "lock" | "unlock" | "deposit" | "withdrawal" |
13
14
  */
14
15
  export interface UserBalanceEventData {
15
16
  /** Token contract address */
16
- tokenAddress: string;
17
+ tokenAddress: Address;
17
18
  /** Token symbol */
18
19
  tokenSymbol: string | null;
19
20
  /** Available balance for trading (normalized) */
@@ -4,6 +4,7 @@
4
4
  * Types for real-time user ledger movement events (deposits, withdrawals, transfers).
5
5
  * This is an authenticated channel - requires JWT token.
6
6
  */
7
+ import type { Address } from "viem";
7
8
  /**
8
9
  * User movement event data containing ledger entry details
9
10
  */
@@ -15,7 +16,7 @@ export interface UserMovementEventData {
15
16
  /** Transaction type (e.g., "deposit", "withdrawal", "trade") */
16
17
  transactionType: string;
17
18
  /** Token contract address */
18
- tokenAddress: string;
19
+ tokenAddress: Address;
19
20
  /** Token symbol */
20
21
  symbol?: string;
21
22
  /** Token decimals */
@@ -10,6 +10,6 @@
10
10
  * hand-written SDK surface. CI regenerates it and fails on a diff, identical to
11
11
  * the `schema.ts` wire-types tripwire (MON-1476), so it can never go stale.
12
12
  */
13
- export declare const OPERATION_IDS: readonly ["add_position_margin", "attach_position_tp_sl", "authenticate_backend", "batch_cancel_all", "batch_cancel_all_by_pair", "batch_cancel_orders", "batch_create_orders", "batch_replace_orders", "cancel_conditional_order", "cancel_order", "close_position", "create_challenge", "create_delegated_session", "create_order", "create_sub_account_limit", "delete_sub_account_limit", "get_application_config", "get_application_stats", "get_available_collateral", "get_candles", "get_funding_state", "get_index_price", "get_margin_account_movements", "get_margin_account_summary", "get_mark_price", "get_market_metadata", "get_open_interest", "get_order_by_id", "get_orderbook_snapshot", "get_orders", "get_perp_market_config", "get_perp_market_summary", "get_portfolio_chart", "get_portfolio_stats", "get_position", "get_position_risk", "get_screener", "get_sub_account_limits", "get_trade_by_id", "get_trades", "get_trading_pair_by_id", "get_user_balance_by_asset", "get_user_balances", "get_user_movements", "get_user_profile", "get_user_trades", "get_withdrawal", "health_check", "initiate_withdrawal", "list_application_balances", "list_application_movements", "list_application_orders", "list_application_users", "list_conditional_orders", "list_delegated_agent_owners", "list_delegated_agents", "list_funding_history", "list_funding_payments", "list_margin_accounts", "list_position_history", "list_positions", "list_sub_accounts_with_balances", "list_trading_pairs", "mint_tokens", "reduce_position_margin", "refresh_session", "replace_order", "revoke_delegated_agent", "revoke_session", "simulate_auto_margin_order_risk", "simulate_fees", "simulate_order_risk", "submit_whitelist", "transfer_collateral_from_margin_account", "transfer_collateral_to_auto_margin_account", "transfer_collateral_to_margin_account", "update_sub_account_limit", "upsert_delegated_agent", "verify_signature"];
13
+ export declare const OPERATION_IDS: readonly ["add_position_margin", "attach_position_tp_sl", "authenticate_backend", "batch_cancel_all", "batch_cancel_all_by_pair", "batch_cancel_orders", "batch_close_all_positions", "batch_create_orders", "batch_replace_orders", "cancel_conditional_order", "cancel_order", "close_position", "create_challenge", "create_delegated_session", "create_order", "create_sub_account_limit", "delete_sub_account_limit", "get_application_config", "get_application_stats", "get_available_collateral", "get_candles", "get_funding_state", "get_index_price", "get_margin_account_movements", "get_margin_account_summary", "get_mark_price", "get_market_metadata", "get_market_stats", "get_open_interest", "get_order_by_id", "get_orderbook_snapshot", "get_orders", "get_parent_margin_account_movements", "get_parent_margin_account_summary", "get_perp_market_config", "get_perp_market_summary", "get_portfolio_chart", "get_portfolio_stats", "get_position", "get_position_risk", "get_screener", "get_sub_account_limits", "get_trade_by_id", "get_trades", "get_trading_pair_by_id", "get_user_balance_by_asset", "get_user_balances", "get_user_movements", "get_user_profile", "get_user_trades", "get_withdrawal", "health_check", "initiate_withdrawal", "list_application_balances", "list_application_movements", "list_application_orders", "list_application_users", "list_conditional_orders", "list_delegated_agent_owners", "list_delegated_agents", "list_funding_history", "list_funding_payments", "list_margin_accounts", "list_position_history", "list_positions", "list_sub_accounts_with_balances", "list_trading_pairs", "mint_tokens", "reduce_position_margin", "refresh_session", "replace_order", "revoke_delegated_agent", "revoke_session", "simulate_fees", "simulate_order_risk", "simulate_parent_margin_order_risk", "simulate_risk_bucket_order_risk", "submit_whitelist", "transfer_collateral_from_margin_account", "transfer_collateral_from_parent_margin_account", "transfer_collateral_to_margin_account", "transfer_collateral_to_parent_margin_account", "transfer_collateral_to_risk_bucket", "update_sub_account_limit", "upsert_delegated_agent", "verify_signature"];
14
14
  /** Union of every OpenAPI operationId in the spec. */
15
15
  export type OperationId = (typeof OPERATION_IDS)[number];
@@ -17,6 +17,7 @@ export const OPERATION_IDS = [
17
17
  "batch_cancel_all",
18
18
  "batch_cancel_all_by_pair",
19
19
  "batch_cancel_orders",
20
+ "batch_close_all_positions",
20
21
  "batch_create_orders",
21
22
  "batch_replace_orders",
22
23
  "cancel_conditional_order",
@@ -37,10 +38,13 @@ export const OPERATION_IDS = [
37
38
  "get_margin_account_summary",
38
39
  "get_mark_price",
39
40
  "get_market_metadata",
41
+ "get_market_stats",
40
42
  "get_open_interest",
41
43
  "get_order_by_id",
42
44
  "get_orderbook_snapshot",
43
45
  "get_orders",
46
+ "get_parent_margin_account_movements",
47
+ "get_parent_margin_account_summary",
44
48
  "get_perp_market_config",
45
49
  "get_perp_market_summary",
46
50
  "get_portfolio_chart",
@@ -80,13 +84,16 @@ export const OPERATION_IDS = [
80
84
  "replace_order",
81
85
  "revoke_delegated_agent",
82
86
  "revoke_session",
83
- "simulate_auto_margin_order_risk",
84
87
  "simulate_fees",
85
88
  "simulate_order_risk",
89
+ "simulate_parent_margin_order_risk",
90
+ "simulate_risk_bucket_order_risk",
86
91
  "submit_whitelist",
87
92
  "transfer_collateral_from_margin_account",
88
- "transfer_collateral_to_auto_margin_account",
93
+ "transfer_collateral_from_parent_margin_account",
89
94
  "transfer_collateral_to_margin_account",
95
+ "transfer_collateral_to_parent_margin_account",
96
+ "transfer_collateral_to_risk_bucket",
90
97
  "update_sub_account_limit",
91
98
  "upsert_delegated_agent",
92
99
  "verify_signature",