@0xmonaco/core 1.0.42 → 1.0.43

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.
@@ -26,6 +26,15 @@ export declare const perpRoutes: {
26
26
  }) => string;
27
27
  readonly cancelConditional: (conditionalOrderId: string) => string;
28
28
  readonly getConditional: (conditionalOrderId: string) => string;
29
+ readonly createTwap: () => string;
30
+ readonly listTwap: (params?: {
31
+ state?: string;
32
+ tradingPairId?: string;
33
+ page?: number;
34
+ pageSize?: number;
35
+ }) => string;
36
+ readonly getTwap: (twapOrderId: string) => string;
37
+ readonly cancelTwap: (twapOrderId: string) => string;
29
38
  };
30
39
  readonly delegatedAgents: {
31
40
  readonly list: () => string;
@@ -29,6 +29,10 @@ export const perpRoutes = {
29
29
  listConditional: (params) => withQuery(`${API_V1}/orders/conditional`, params),
30
30
  cancelConditional: (conditionalOrderId) => `${API_V1}/orders/conditional/${encodeSegment(conditionalOrderId)}`,
31
31
  getConditional: (conditionalOrderId) => `${API_V1}/orders/conditional/${encodeSegment(conditionalOrderId)}`,
32
+ createTwap: () => `${API_V1}/orders/twap`,
33
+ listTwap: (params) => withQuery(`${API_V1}/orders/twap`, params),
34
+ getTwap: (twapOrderId) => `${API_V1}/orders/twap/${encodeSegment(twapOrderId)}`,
35
+ cancelTwap: (twapOrderId) => `${API_V1}/orders/twap/${encodeSegment(twapOrderId)}/cancel`,
32
36
  },
33
37
  delegatedAgents: {
34
38
  list: () => `${API_V1}/delegated-agents`,
@@ -21,7 +21,7 @@
21
21
  * );
22
22
  * ```
23
23
  */
24
- import type { BatchCancelOrdersResponse, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchReplaceOrderParams, BatchReplaceOrdersResponse, CancelConditionalOrderResponse, CancelOrderResponse, ConditionalOrder, CreateOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, MarginMode, OrderSide, ParentTpSlLegParams, PositionSide, ReplaceOrderResponse, TimeInForce, TradingAPI, TradingMode } from "@0xmonaco/types";
24
+ import type { BatchCancelOrdersResponse, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchReplaceOrderParams, BatchReplaceOrdersResponse, CancelConditionalOrderResponse, CancelOrderResponse, CancelTwapOrderResponse, ConditionalOrder, CreateOrderResponse, CreateTwapOrderOptions, CreateTwapOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, ListTwapOrdersParams, ListTwapOrdersResponse, MarginMode, OrderSide, ParentTpSlLegParams, PositionSide, ReplaceOrderResponse, TimeInForce, TradingAPI, TradingMode, TwapOrder } from "@0xmonaco/types";
25
25
  import { BaseAPI } from "../base";
26
26
  export declare class TradingAPIImpl extends BaseAPI implements TradingAPI {
27
27
  /**
@@ -157,16 +157,25 @@ export declare class TradingAPIImpl extends BaseAPI implements TradingAPI {
157
157
  * Canceled orders cannot be recovered.
158
158
  *
159
159
  * @param orderId - The ID of the order to cancel
160
+ * @param options - Optional partial-cancel: `remainingQuantityTarget` reduces
161
+ * the resting order in place to that remaining quantity, KEEPING its queue
162
+ * position — a target ("leave this much resting"), not an amount to
163
+ * remove, so a retried request converges. Must be a positive multiple of
164
+ * the market's quantity step, strictly below the current remaining
165
+ * quantity. Omit for a full cancel.
160
166
  * @returns Promise resolving to CancelOrderResponse with cancellation details
161
167
  * @throws {APIError} When API communication fails
162
168
  *
163
169
  * @example
164
170
  * ```typescript
165
171
  * const result = await tradingAPI.cancelOrder("order_123");
166
- * console.log(`Order canceled: ${result.status}`);
172
+ * // Partial: keep 0.5 resting at the same queue position
173
+ * await tradingAPI.cancelOrder("order_123", { remainingQuantityTarget: "0.5" });
167
174
  * ```
168
175
  */
169
- cancelOrder(orderId: string): Promise<CancelOrderResponse>;
176
+ cancelOrder(orderId: string, options?: {
177
+ remainingQuantityTarget?: string;
178
+ }): Promise<CancelOrderResponse>;
170
179
  cancelConditionalOrder(conditionalOrderId: string): Promise<CancelConditionalOrderResponse>;
171
180
  getConditionalOrder(conditionalOrderId: string): Promise<ConditionalOrder>;
172
181
  listConditionalOrders(params?: ListConditionalOrdersParams): Promise<ListConditionalOrdersResponse>;
@@ -344,4 +353,109 @@ export declare class TradingAPIImpl extends BaseAPI implements TradingAPI {
344
353
  * ```
345
354
  */
346
355
  getOrder(orderId: string): Promise<GetOrderResponse>;
356
+ /**
357
+ * Creates a server-side TWAP (time-weighted average price) parent order.
358
+ *
359
+ * The matching engine executes the parent as a schedule of MARKET child
360
+ * orders across the window, with seeded size (±30%) and timing (±30%)
361
+ * randomization when `randomize` is enabled (the default). Execution stops
362
+ * hard at the window end — any unfilled remainder is reported as shortfall,
363
+ * never traded past the end.
364
+ *
365
+ * @param tradingPairId - The trading pair UUID
366
+ * @param side - The order side ("BUY" or "SELL")
367
+ * @param quantity - Total quantity to execute across the window as string
368
+ * (must be at least 2x the pair's minimum order size so it can be sliced)
369
+ * @param options - Window and execution parameters
370
+ * @param options.durationSeconds - Window length in seconds from launch;
371
+ * exactly one of `durationSeconds` or `endTime` must be set
372
+ * @param options.endTime - Window end (ISO 8601); exactly one of
373
+ * `durationSeconds` or `endTime` must be set
374
+ * @param options.startTime - Window start (ISO 8601); only valid together
375
+ * with `endTime`, defaults to now
376
+ * @param options.limitPrice - Optional parent-level limit price; BUY child
377
+ * orders never execute above it, SELL children never below it
378
+ * @param options.slippageToleranceBps - Per-slice protective price band in
379
+ * basis points (default 100 = 1%)
380
+ * @param options.clientTwapId - Idempotency key (max 36 chars), unique per
381
+ * user and application; a duplicate is rejected with 409
382
+ * @returns Promise resolving to CreateTwapOrderResponse with the parent id,
383
+ * initial state, and the planned schedule summary
384
+ * @throws {APIError} When API communication fails
385
+ *
386
+ * @example
387
+ * ```typescript
388
+ * // Buy 10 units spread across one hour
389
+ * const twap = await tradingAPI.createTwapOrder(
390
+ * "123e4567-e89b-12d3-a456-426614174000",
391
+ * "BUY",
392
+ * "10",
393
+ * { durationSeconds: 3600 }
394
+ * );
395
+ *
396
+ * // Margin TWAP with an explicit window and a parent limit price
397
+ * const marginTwap = await tradingAPI.createTwapOrder(
398
+ * "123e4567-e89b-12d3-a456-426614174000",
399
+ * "SELL",
400
+ * "5",
401
+ * {
402
+ * startTime: "2026-08-01T10:00:00Z",
403
+ * endTime: "2026-08-01T11:00:00Z",
404
+ * limitPrice: "35000.00",
405
+ * tradingMode: "MARGIN",
406
+ * leverage: "5",
407
+ * }
408
+ * );
409
+ * ```
410
+ */
411
+ createTwapOrder(tradingPairId: string, side: OrderSide, quantity: string, options: CreateTwapOrderOptions): Promise<CreateTwapOrderResponse>;
412
+ /**
413
+ * Cancels a TWAP parent order.
414
+ *
415
+ * Child orders are IOC and never rest, so the cancel is atomic and
416
+ * immediate; executed quantity stands.
417
+ *
418
+ * @param twapOrderId - The TWAP parent order UUID to cancel
419
+ * @returns Promise resolving to CancelTwapOrderResponse with cancellation details
420
+ * @throws {APIError} When API communication fails or the parent is already terminal
421
+ *
422
+ * @example
423
+ * ```typescript
424
+ * const result = await tradingAPI.cancelTwapOrder("123e4567-e89b-12d3-a456-426614174000");
425
+ * console.log(`TWAP cancelled: ${result.status}`);
426
+ * ```
427
+ */
428
+ cancelTwapOrder(twapOrderId: string): Promise<CancelTwapOrderResponse>;
429
+ /**
430
+ * Gets a single TWAP parent order by its UUID.
431
+ *
432
+ * Users can only access their own TWAP orders. The read model carries the
433
+ * live execution progress (executed quantity/notional, VWAP, slice
434
+ * counters) alongside the immutable schedule configuration.
435
+ *
436
+ * @param twapOrderId - The TWAP parent order UUID to retrieve
437
+ * @returns Promise resolving to the TwapOrder read model
438
+ * @throws {APIError} When API communication fails or the order is not found
439
+ *
440
+ * @example
441
+ * ```typescript
442
+ * const twap = await tradingAPI.getTwapOrder("123e4567-e89b-12d3-a456-426614174000");
443
+ * console.log(`State: ${twap.state}, progress: ${twap.progress}`);
444
+ * ```
445
+ */
446
+ getTwapOrder(twapOrderId: string): Promise<TwapOrder>;
447
+ /**
448
+ * Lists TWAP parent orders for the authenticated user.
449
+ *
450
+ * @param params - Optional pagination and state / trading-pair filters
451
+ * @returns Promise resolving to ListTwapOrdersResponse with orders and pagination info
452
+ * @throws {APIError} When API communication fails
453
+ *
454
+ * @example
455
+ * ```typescript
456
+ * const active = await tradingAPI.listTwapOrders({ state: "ACTIVE", pageSize: 50 });
457
+ * console.log(`Found ${active.total} active TWAP orders`);
458
+ * ```
459
+ */
460
+ listTwapOrders(params?: ListTwapOrdersParams): Promise<ListTwapOrdersResponse>;
347
461
  }
@@ -21,7 +21,7 @@
21
21
  * );
22
22
  * ```
23
23
  */
24
- import { BatchCreateOrdersSchema, BatchReplaceOrdersSchema, CancelConditionalOrderSchema, CancelOrderSchema, GetPaginatedOrdersSchema, ListConditionalOrdersSchema, PlaceLimitOrderSchema, PlaceMarketOrderSchema, ReplaceOrderSchema, validate, } from "@0xmonaco/types";
24
+ import { BatchCreateOrdersSchema, BatchReplaceOrdersSchema, CancelConditionalOrderSchema, CancelOrderSchema, CancelTwapOrderSchema, CreateTwapOrderSchema, GetPaginatedOrdersSchema, ListConditionalOrdersSchema, ListTwapOrdersSchema, PlaceLimitOrderSchema, PlaceMarketOrderSchema, ReplaceOrderSchema, validate, } from "@0xmonaco/types";
25
25
  import { BaseAPI } from "../base";
26
26
  import { perpRoutes } from "../perp";
27
27
  function parentTpSlLegToRequest(leg) {
@@ -212,20 +212,30 @@ export class TradingAPIImpl extends BaseAPI {
212
212
  * Canceled orders cannot be recovered.
213
213
  *
214
214
  * @param orderId - The ID of the order to cancel
215
+ * @param options - Optional partial-cancel: `remainingQuantityTarget` reduces
216
+ * the resting order in place to that remaining quantity, KEEPING its queue
217
+ * position — a target ("leave this much resting"), not an amount to
218
+ * remove, so a retried request converges. Must be a positive multiple of
219
+ * the market's quantity step, strictly below the current remaining
220
+ * quantity. Omit for a full cancel.
215
221
  * @returns Promise resolving to CancelOrderResponse with cancellation details
216
222
  * @throws {APIError} When API communication fails
217
223
  *
218
224
  * @example
219
225
  * ```typescript
220
226
  * const result = await tradingAPI.cancelOrder("order_123");
221
- * console.log(`Order canceled: ${result.status}`);
227
+ * // Partial: keep 0.5 resting at the same queue position
228
+ * await tradingAPI.cancelOrder("order_123", { remainingQuantityTarget: "0.5" });
222
229
  * ```
223
230
  */
224
- async cancelOrder(orderId) {
231
+ async cancelOrder(orderId, options) {
225
232
  // Validate inputs before making API call
226
- validate(CancelOrderSchema, { orderId });
233
+ validate(CancelOrderSchema, { orderId, remainingQuantityTarget: options?.remainingQuantityTarget });
227
234
  const requestBody = {
228
235
  orderId: orderId,
236
+ ...(options?.remainingQuantityTarget !== undefined && {
237
+ remainingQuantityTarget: options.remainingQuantityTarget,
238
+ }),
229
239
  };
230
240
  return await this.makeAuthenticatedRequest(perpRoutes.orders.cancel(), {
231
241
  method: "POST",
@@ -573,4 +583,166 @@ export class TradingAPIImpl extends BaseAPI {
573
583
  const order = await this.makeAuthenticatedRequest(perpRoutes.orders.get(orderId), { method: "GET" });
574
584
  return { order, status: "SUCCESS" };
575
585
  }
586
+ /**
587
+ * Creates a server-side TWAP (time-weighted average price) parent order.
588
+ *
589
+ * The matching engine executes the parent as a schedule of MARKET child
590
+ * orders across the window, with seeded size (±30%) and timing (±30%)
591
+ * randomization when `randomize` is enabled (the default). Execution stops
592
+ * hard at the window end — any unfilled remainder is reported as shortfall,
593
+ * never traded past the end.
594
+ *
595
+ * @param tradingPairId - The trading pair UUID
596
+ * @param side - The order side ("BUY" or "SELL")
597
+ * @param quantity - Total quantity to execute across the window as string
598
+ * (must be at least 2x the pair's minimum order size so it can be sliced)
599
+ * @param options - Window and execution parameters
600
+ * @param options.durationSeconds - Window length in seconds from launch;
601
+ * exactly one of `durationSeconds` or `endTime` must be set
602
+ * @param options.endTime - Window end (ISO 8601); exactly one of
603
+ * `durationSeconds` or `endTime` must be set
604
+ * @param options.startTime - Window start (ISO 8601); only valid together
605
+ * with `endTime`, defaults to now
606
+ * @param options.limitPrice - Optional parent-level limit price; BUY child
607
+ * orders never execute above it, SELL children never below it
608
+ * @param options.slippageToleranceBps - Per-slice protective price band in
609
+ * basis points (default 100 = 1%)
610
+ * @param options.clientTwapId - Idempotency key (max 36 chars), unique per
611
+ * user and application; a duplicate is rejected with 409
612
+ * @returns Promise resolving to CreateTwapOrderResponse with the parent id,
613
+ * initial state, and the planned schedule summary
614
+ * @throws {APIError} When API communication fails
615
+ *
616
+ * @example
617
+ * ```typescript
618
+ * // Buy 10 units spread across one hour
619
+ * const twap = await tradingAPI.createTwapOrder(
620
+ * "123e4567-e89b-12d3-a456-426614174000",
621
+ * "BUY",
622
+ * "10",
623
+ * { durationSeconds: 3600 }
624
+ * );
625
+ *
626
+ * // Margin TWAP with an explicit window and a parent limit price
627
+ * const marginTwap = await tradingAPI.createTwapOrder(
628
+ * "123e4567-e89b-12d3-a456-426614174000",
629
+ * "SELL",
630
+ * "5",
631
+ * {
632
+ * startTime: "2026-08-01T10:00:00Z",
633
+ * endTime: "2026-08-01T11:00:00Z",
634
+ * limitPrice: "35000.00",
635
+ * tradingMode: "MARGIN",
636
+ * leverage: "5",
637
+ * }
638
+ * );
639
+ * ```
640
+ */
641
+ async createTwapOrder(tradingPairId, side, quantity, options) {
642
+ // Validate inputs before making API call
643
+ validate(CreateTwapOrderSchema, {
644
+ tradingPairId,
645
+ side,
646
+ quantity,
647
+ options,
648
+ });
649
+ const requestBody = {
650
+ tradingPairId: tradingPairId,
651
+ side,
652
+ quantity,
653
+ // The server deserializes durationSeconds into an int64 with plain
654
+ // serde, which rejects strings — send a JSON number (durations are
655
+ // bounded at 30 days = 2,592,000, far inside the safe-integer range).
656
+ durationSeconds: options.durationSeconds !== undefined ? Number(options.durationSeconds) : undefined,
657
+ startTime: options.startTime,
658
+ endTime: options.endTime,
659
+ limitPrice: options.limitPrice,
660
+ slippageToleranceBps: options.slippageToleranceBps,
661
+ randomize: options.randomize,
662
+ reduceOnly: options.reduceOnly,
663
+ tradingMode: options.tradingMode || "SPOT",
664
+ marginAccountId: options.marginAccountId,
665
+ riskBucketId: options.riskBucketId,
666
+ marginMode: options.marginMode,
667
+ leverage: options.leverage,
668
+ strategyKey: options.strategyKey,
669
+ useMasterBalance: options.useMasterBalance,
670
+ clientTwapId: options.clientTwapId,
671
+ };
672
+ return await this.makeAuthenticatedRequest(perpRoutes.orders.createTwap(), {
673
+ method: "POST",
674
+ body: JSON.stringify(requestBody),
675
+ });
676
+ }
677
+ /**
678
+ * Cancels a TWAP parent order.
679
+ *
680
+ * Child orders are IOC and never rest, so the cancel is atomic and
681
+ * immediate; executed quantity stands.
682
+ *
683
+ * @param twapOrderId - The TWAP parent order UUID to cancel
684
+ * @returns Promise resolving to CancelTwapOrderResponse with cancellation details
685
+ * @throws {APIError} When API communication fails or the parent is already terminal
686
+ *
687
+ * @example
688
+ * ```typescript
689
+ * const result = await tradingAPI.cancelTwapOrder("123e4567-e89b-12d3-a456-426614174000");
690
+ * console.log(`TWAP cancelled: ${result.status}`);
691
+ * ```
692
+ */
693
+ async cancelTwapOrder(twapOrderId) {
694
+ // Validate inputs before making API call
695
+ validate(CancelTwapOrderSchema, { twapOrderId });
696
+ return await this.makeAuthenticatedRequest(perpRoutes.orders.cancelTwap(twapOrderId), {
697
+ method: "POST",
698
+ });
699
+ }
700
+ /**
701
+ * Gets a single TWAP parent order by its UUID.
702
+ *
703
+ * Users can only access their own TWAP orders. The read model carries the
704
+ * live execution progress (executed quantity/notional, VWAP, slice
705
+ * counters) alongside the immutable schedule configuration.
706
+ *
707
+ * @param twapOrderId - The TWAP parent order UUID to retrieve
708
+ * @returns Promise resolving to the TwapOrder read model
709
+ * @throws {APIError} When API communication fails or the order is not found
710
+ *
711
+ * @example
712
+ * ```typescript
713
+ * const twap = await tradingAPI.getTwapOrder("123e4567-e89b-12d3-a456-426614174000");
714
+ * console.log(`State: ${twap.state}, progress: ${twap.progress}`);
715
+ * ```
716
+ */
717
+ async getTwapOrder(twapOrderId) {
718
+ validate(CancelTwapOrderSchema, { twapOrderId });
719
+ return await this.makeAuthenticatedRequest(perpRoutes.orders.getTwap(twapOrderId), {
720
+ method: "GET",
721
+ });
722
+ }
723
+ /**
724
+ * Lists TWAP parent orders for the authenticated user.
725
+ *
726
+ * @param params - Optional pagination and state / trading-pair filters
727
+ * @returns Promise resolving to ListTwapOrdersResponse with orders and pagination info
728
+ * @throws {APIError} When API communication fails
729
+ *
730
+ * @example
731
+ * ```typescript
732
+ * const active = await tradingAPI.listTwapOrders({ state: "ACTIVE", pageSize: 50 });
733
+ * console.log(`Found ${active.total} active TWAP orders`);
734
+ * ```
735
+ */
736
+ async listTwapOrders(params) {
737
+ if (params) {
738
+ validate(ListTwapOrdersSchema, params);
739
+ }
740
+ const { page = 1, pageSize = 20, state, tradingPairId } = params || {};
741
+ return await this.makeAuthenticatedRequest(perpRoutes.orders.listTwap({
742
+ page,
743
+ pageSize: Math.min(Math.max(pageSize, 1), 100),
744
+ state,
745
+ tradingPairId,
746
+ }), { method: "GET" });
747
+ }
576
748
  }
@@ -78,10 +78,17 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
78
78
  */
79
79
  private getClientId;
80
80
  /**
81
- * Resolves an asset ID to its token address and determines if it's a native token.
81
+ * Resolves an asset ID to its token address and determines whether it is the
82
+ * chain's wrapped-native asset (e.g. WSEI).
83
+ *
84
+ * The wrapped-native asset is a real ERC20 — its token address is never the
85
+ * zero address — so native handling keys on the balance response's
86
+ * `wrappedNative` flag, not on the address. Deposits of that asset are made
87
+ * in native coin via the payable `depositNative` (the vault wraps on entry);
88
+ * withdrawals of it pay out native coin (the vault unwraps).
82
89
  *
83
90
  * @param assetId - The asset identifier (UUID) to resolve
84
- * @returns Promise resolving to object with tokenAddress and isNativeToken flag
91
+ * @returns Promise resolving to object with tokenAddress and isWrappedNative flag
85
92
  * @throws {ContractError} When asset ID cannot be resolved
86
93
  * @private
87
94
  */
@@ -128,7 +135,12 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
128
135
  * first checks if sufficient approval exists, then obtains a signature from the
129
136
  * API Gateway, and finally executes the deposit transaction on-chain.
130
137
  *
131
- * Note: This method requires prior approval via the `approve()` method.
138
+ * Note: This method requires prior approval via the `approve()` method for
139
+ * standard ERC20 assets. The wrapped-native asset (e.g. WSEI, flagged
140
+ * `wrappedNative` in the balances API) is deposited in native coin via the
141
+ * payable `depositNative` — the vault wraps it into the ERC20 on entry — so
142
+ * no approval is needed and `amount` is sent as msg.value. Withdrawals of the
143
+ * wrapped-native asset pay out native coin (the vault unwraps).
132
144
  *
133
145
  * @param assetId - The asset identifier (UUID) to deposit
134
146
  * @param amount - The amount of tokens to deposit (as bigint)
@@ -209,6 +221,10 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
209
221
  * the index would strand the funds; the caller keeps it and finishes the
210
222
  * withdrawal later with `retryWithdrawal(withdrawalIndex)`.
211
223
  *
224
+ * Withdrawals of the wrapped-native asset (e.g. WSEI) pay out native coin —
225
+ * the vault unwraps on exit. This is decided server-side; no request change
226
+ * is needed.
227
+ *
212
228
  * @param assetId - The asset identifier (UUID) to withdraw
213
229
  * @param amount - The raw token amount to withdraw (as bigint)
214
230
  * @param autoWait - When `true` (default) polls for the merkle-proof calldata
@@ -309,6 +325,11 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
309
325
  * Compares the current allowance with the requested amount to determine if
310
326
  * the user needs to approve more tokens before performing operations.
311
327
  *
328
+ * The wrapped-native asset (e.g. WSEI) never needs approval: its deposits
329
+ * are made in native coin via the payable `depositNative` (the vault wraps
330
+ * on entry), so no ERC20 allowance is consumed and this method returns
331
+ * `false` without reading the chain.
332
+ *
312
333
  * @param assetId - The asset identifier (UUID) to check for
313
334
  * @param amount - The amount to check approval for (as bigint)
314
335
  * @returns Promise resolving to true if approval is needed, false otherwise
@@ -25,7 +25,7 @@
25
25
  */
26
26
  import { CONTRACT_ABIS } from "@0xmonaco/contracts";
27
27
  import { ApproveTokenSchema, DepositSchema, validate, WithdrawSchema } from "@0xmonaco/types";
28
- import { erc20Abi, zeroAddress } from "viem";
28
+ import { erc20Abi } from "viem";
29
29
  import { APIError, ContractError, InvalidConfigError } from "../../errors";
30
30
  import { BaseAPI } from "../base";
31
31
  /** Default delay between polls while waiting for a withdrawal's proof. */
@@ -108,18 +108,27 @@ export class VaultAPIImpl extends BaseAPI {
108
108
  return config.clientId;
109
109
  }
110
110
  /**
111
- * Resolves an asset ID to its token address and determines if it's a native token.
111
+ * Resolves an asset ID to its token address and determines whether it is the
112
+ * chain's wrapped-native asset (e.g. WSEI).
113
+ *
114
+ * The wrapped-native asset is a real ERC20 — its token address is never the
115
+ * zero address — so native handling keys on the balance response's
116
+ * `wrappedNative` flag, not on the address. Deposits of that asset are made
117
+ * in native coin via the payable `depositNative` (the vault wraps on entry);
118
+ * withdrawals of it pay out native coin (the vault unwraps).
112
119
  *
113
120
  * @param assetId - The asset identifier (UUID) to resolve
114
- * @returns Promise resolving to object with tokenAddress and isNativeToken flag
121
+ * @returns Promise resolving to object with tokenAddress and isWrappedNative flag
115
122
  * @throws {ContractError} When asset ID cannot be resolved
116
123
  * @private
117
124
  */
118
125
  async resolveAsset(assetId) {
119
126
  let tokenAddress;
127
+ let isWrappedNative;
120
128
  try {
121
129
  const assetBalance = await this.profileAPI.getUserBalanceByAssetId(assetId);
122
130
  tokenAddress = assetBalance.token;
131
+ isWrappedNative = assetBalance.wrappedNative === true;
123
132
  }
124
133
  catch (error) {
125
134
  // Differentiate between network errors and asset not found
@@ -142,8 +151,7 @@ export class VaultAPIImpl extends BaseAPI {
142
151
  cause: error instanceof Error ? error : undefined,
143
152
  });
144
153
  }
145
- const isNativeToken = tokenAddress === zeroAddress;
146
- return { tokenAddress, isNativeToken };
154
+ return { tokenAddress, isWrappedNative };
147
155
  }
148
156
  /**
149
157
  * Approves the vault contract to spend tokens on behalf of the user.
@@ -216,7 +224,12 @@ export class VaultAPIImpl extends BaseAPI {
216
224
  * first checks if sufficient approval exists, then obtains a signature from the
217
225
  * API Gateway, and finally executes the deposit transaction on-chain.
218
226
  *
219
- * Note: This method requires prior approval via the `approve()` method.
227
+ * Note: This method requires prior approval via the `approve()` method for
228
+ * standard ERC20 assets. The wrapped-native asset (e.g. WSEI, flagged
229
+ * `wrappedNative` in the balances API) is deposited in native coin via the
230
+ * payable `depositNative` — the vault wraps it into the ERC20 on entry — so
231
+ * no approval is needed and `amount` is sent as msg.value. Withdrawals of the
232
+ * wrapped-native asset pay out native coin (the vault unwraps).
220
233
  *
221
234
  * @param assetId - The asset identifier (UUID) to deposit
222
235
  * @param amount - The amount of tokens to deposit (as bigint)
@@ -269,8 +282,8 @@ export class VaultAPIImpl extends BaseAPI {
269
282
  // The on-chain applicationData carries the client id plus, for margin
270
283
  // deposits, the routing hint the indexer decodes.
271
284
  const applicationData = encodeDepositApplicationData(clientId, target);
272
- const { tokenAddress, isNativeToken } = await this.resolveAsset(assetId);
273
- if (!isNativeToken) {
285
+ const { tokenAddress, isWrappedNative } = await this.resolveAsset(assetId);
286
+ if (!isWrappedNative) {
274
287
  // Check if approval is needed before proceeding
275
288
  const needsApproval = await this.needsApproval(assetId, amount);
276
289
  if (needsApproval) {
@@ -283,9 +296,11 @@ export class VaultAPIImpl extends BaseAPI {
283
296
  if (!walletAccount) {
284
297
  throw new InvalidConfigError("No account available in wallet client", "account");
285
298
  }
286
- // For native SEI (zero address), use depositNative (payable); for ERC20 tokens, use depositERC20
299
+ // For the wrapped-native asset (e.g. WSEI), use depositNative (payable) — the
300
+ // vault wraps the native coin into the ERC20 on entry, so no allowance is
301
+ // involved. All other ERC20 tokens go through approve + depositERC20.
287
302
  let hash;
288
- if (isNativeToken) {
303
+ if (isWrappedNative) {
289
304
  hash = await this.walletClient.writeContract({
290
305
  address: vaultAddress,
291
306
  abi: CONTRACT_ABIS.vault,
@@ -380,6 +395,10 @@ export class VaultAPIImpl extends BaseAPI {
380
395
  * the index would strand the funds; the caller keeps it and finishes the
381
396
  * withdrawal later with `retryWithdrawal(withdrawalIndex)`.
382
397
  *
398
+ * Withdrawals of the wrapped-native asset (e.g. WSEI) pay out native coin —
399
+ * the vault unwraps on exit. This is decided server-side; no request change
400
+ * is needed.
401
+ *
383
402
  * @param assetId - The asset identifier (UUID) to withdraw
384
403
  * @param amount - The raw token amount to withdraw (as bigint)
385
404
  * @param autoWait - When `true` (default) polls for the merkle-proof calldata
@@ -597,6 +616,11 @@ export class VaultAPIImpl extends BaseAPI {
597
616
  * Compares the current allowance with the requested amount to determine if
598
617
  * the user needs to approve more tokens before performing operations.
599
618
  *
619
+ * The wrapped-native asset (e.g. WSEI) never needs approval: its deposits
620
+ * are made in native coin via the payable `depositNative` (the vault wraps
621
+ * on entry), so no ERC20 allowance is consumed and this method returns
622
+ * `false` without reading the chain.
623
+ *
600
624
  * @param assetId - The asset identifier (UUID) to check for
601
625
  * @param amount - The amount to check approval for (as bigint)
602
626
  * @returns Promise resolving to true if approval is needed, false otherwise
@@ -616,6 +640,12 @@ export class VaultAPIImpl extends BaseAPI {
616
640
  * ```
617
641
  */
618
642
  async needsApproval(assetId, amount) {
643
+ const { isWrappedNative } = await this.resolveAsset(assetId);
644
+ if (isWrappedNative) {
645
+ // Wrapped-native deposits route to the payable depositNative — no ERC20
646
+ // allowance is consumed, so approval is never needed.
647
+ return false;
648
+ }
619
649
  const allowance = await this.getAllowance(assetId);
620
650
  return allowance < amount;
621
651
  }
@@ -1,4 +1,4 @@
1
- import type { AccountEvent, ConditionalOrderEvent, Interval, LiquidationEvent, MarketStatsAllEvent, MarketStatsEvent, MonacoWebSocketConfig, OHLCVEvent, OrderbookEvent, OrderbookQuotationMode, OrderEvent, PositionEvent, SessionCredentials, TradeEvent, TradingMode, UserBalanceEvent, UserMovementEvent, WebSocketStatus } from "@0xmonaco/types";
1
+ import type { AccountEvent, ConditionalOrderEvent, Interval, LiquidationEvent, MarketStatsAllEvent, MarketStatsEvent, MonacoWebSocketConfig, OHLCVEvent, OHLCVPriceType, OrderbookEvent, OrderbookQuotationMode, OrderEvent, PositionEvent, SessionCredentials, TradeEvent, TradingMode, TwapOrderEvent, UserBalanceEvent, UserMovementEvent, WebSocketStatus } from "@0xmonaco/types";
2
2
  export type { ResyncHandler, StatusHandler, WebSocketResyncInfo } from "@0xmonaco/types";
3
3
  export type MessageHandler<T> = (data: T) => void;
4
4
  /**
@@ -27,7 +27,7 @@ export interface MonacoWebSocket {
27
27
  /** Subscribe to orderbook events (public) */
28
28
  orderbook: (tradingPairId: string, tradingMode: TradingMode, magnitude: number, quotationMode: OrderbookQuotationMode, handler: MessageHandler<OrderbookEvent>) => () => void;
29
29
  /** Subscribe to OHLCV candlestick events (public) */
30
- ohlcv: (tradingPairId: string, tradingMode: TradingMode, interval: Interval, handler: MessageHandler<OHLCVEvent>) => () => void;
30
+ ohlcv: (tradingPairId: string, tradingMode: TradingMode, interval: Interval, handler: MessageHandler<OHLCVEvent>, priceType?: OHLCVPriceType) => () => void;
31
31
  /** Subscribe to trade events (public) */
32
32
  trades: (tradingPairId: string, handler: MessageHandler<TradeEvent>) => () => void;
33
33
  /** Subscribe to user movement events (requires authentication) */
@@ -38,6 +38,8 @@ export interface MonacoWebSocket {
38
38
  balances: (handler: MessageHandler<UserBalanceEvent>) => () => void;
39
39
  /** Subscribe to conditional TP/SL lifecycle events (requires authentication) */
40
40
  conditionalOrders: (handler: MessageHandler<ConditionalOrderEvent>, tradingPairId?: string) => () => void;
41
+ /** Subscribe to TWAP parent-order lifecycle events (requires authentication) */
42
+ twapOrders: (handler: MessageHandler<TwapOrderEvent>, tradingPairId?: string) => () => void;
41
43
  /** Subscribe to position state updates (requires authentication); omit `tradingPairId` for all pairs */
42
44
  positions: (handler: MessageHandler<PositionEvent>, tradingPairId?: string) => () => void;
43
45
  /** Subscribe to liquidation alerts (requires authentication); omit `tradingPairId` for all pairs */
@@ -12,6 +12,7 @@ const CONDITIONAL_ORDER_CONDITION_TYPES = ["STOP_LOSS", "TAKE_PROFIT"];
12
12
  const CONDITIONAL_ORDER_TRIGGER_SOURCES = ["MARK_PRICE"];
13
13
  const CONDITIONAL_ORDER_STATES = ["PENDING_PARENT", "ACTIVE", "TRIGGERING", "TRIGGERED", "CANCELLED", "EXPIRED", "FAILED"];
14
14
  const CONDITIONAL_ORDER_ASSOCIATION_TYPES = ["POSITION", "PARENT_ORDER"];
15
+ const TWAP_ORDER_STATES = ["PENDING", "ACTIVE", "COMPLETED", "CANCELLED"];
15
16
  function isRecord(value) {
16
17
  return typeof value === "object" && value !== null && !Array.isArray(value);
17
18
  }
@@ -268,6 +269,49 @@ function parseMarketStatsAllEvent(rawData) {
268
269
  markets: rawData.markets.map(parseMarketStatsSummary),
269
270
  };
270
271
  }
272
+ /**
273
+ * Parse a `twap_orders` channel frame into a typed event. Only the envelope
274
+ * and the snapshot's identity/state fields are validated strictly — the rest
275
+ * of the TwapOrder snapshot is passed through camelCased, so additive server
276
+ * fields never break older clients. The server serializes absent optional
277
+ * fields as explicit `null`; those are dropped so the parsed snapshot matches
278
+ * the optional (`?:`) fields of `TwapOrderEventData`.
279
+ */
280
+ function parseTwapOrderEvent(rawData) {
281
+ if (!isRecord(rawData)) {
282
+ throw new Error("Invalid TWAP order event: payload must be an object");
283
+ }
284
+ if (!isRecord(rawData.data)) {
285
+ throw new Error("Invalid TWAP order event: data must be an object");
286
+ }
287
+ const eventType = rawData.event_type;
288
+ if (eventType !== "twap_order_update") {
289
+ throw new Error("Invalid TWAP order event: event_type must be twap_order_update");
290
+ }
291
+ const userId = rawData.user_id;
292
+ if (typeof userId !== "string" || userId.length === 0) {
293
+ throw new Error("Invalid TWAP order event: user_id must be a non-empty string");
294
+ }
295
+ const data = keysToCamelCase(rawData.data);
296
+ for (const key of Object.keys(data)) {
297
+ if (data[key] === null) {
298
+ delete data[key];
299
+ }
300
+ }
301
+ const twapOrderId = data.twapOrderId;
302
+ if (typeof twapOrderId !== "string" || twapOrderId.length === 0) {
303
+ throw new Error("Invalid TWAP order event: twapOrderId must be a non-empty string");
304
+ }
305
+ const state = data.state;
306
+ if (typeof state !== "string" || !TWAP_ORDER_STATES.includes(state)) {
307
+ throw new Error(`Invalid TWAP order event: state must be one of ${TWAP_ORDER_STATES.join(", ")}`);
308
+ }
309
+ return {
310
+ eventType: "twap_order_update",
311
+ userId,
312
+ data: data,
313
+ };
314
+ }
271
315
  /**
272
316
  * Create a Monaco WebSocket client
273
317
  */
@@ -392,12 +436,35 @@ export function createMonacoWebSocket(baseUrl, options = {}) {
392
436
  send({ type: "Subscribe", channels });
393
437
  }
394
438
  };
439
+ // A subscription channel matches a frame when it is identical, is a prefix of
440
+ // the frame's dotted-by-colon path, or ends in a `:*` wildcard segment whose
441
+ // prefix the frame shares. The wildcard case exists because a `*` price-series
442
+ // subscription (`ohlcv:...:interval:*`) must receive the concrete series
443
+ // frames the server publishes (`ohlcv:...:interval:trade` / `:mark`), which are
444
+ // neither equal to nor prefixed by the literal `:*` channel.
445
+ // A legacy four-token OHLCV subscription (`ohlcv:pair:mode:interval`, no price
446
+ // series) is trade-only by contract. The server suffixes every OHLCV frame
447
+ // with a series, so it must match the bare four-token frame or the explicit
448
+ // `:trade` frame — never `:mark` — otherwise a connection that also holds a
449
+ // mark or wildcard subscription for the same pair would leak mark frames into
450
+ // the legacy handler via the generic prefix match.
451
+ const isLegacyOhlcvKey = (channel) => channel.startsWith("ohlcv:") && channel.split(":").length === 4;
452
+ const channelMatches = (subscriptionChannel, frameChannel) => {
453
+ if (subscriptionChannel.endsWith(":*")) {
454
+ // Keep the trailing colon so only frames with a further segment match.
455
+ return frameChannel.startsWith(subscriptionChannel.slice(0, -1));
456
+ }
457
+ if (isLegacyOhlcvKey(subscriptionChannel)) {
458
+ return frameChannel === subscriptionChannel || frameChannel === `${subscriptionChannel}:trade`;
459
+ }
460
+ return frameChannel === subscriptionChannel || frameChannel.startsWith(`${subscriptionChannel}:`);
461
+ };
395
462
  const routeMessage = (msg) => {
396
463
  if (msg.type !== "Event" || !msg.channel)
397
464
  return;
398
465
  // Find matching handlers and call all of them
399
466
  for (const [subscriptionChannel, channelHandlers] of handlers) {
400
- if (msg.channel === subscriptionChannel || msg.channel.startsWith(`${subscriptionChannel}:`)) {
467
+ if (channelMatches(subscriptionChannel, msg.channel)) {
401
468
  for (const handler of channelHandlers) {
402
469
  handler(msg.data);
403
470
  }
@@ -619,18 +686,26 @@ export function createMonacoWebSocket(baseUrl, options = {}) {
619
686
  }
620
687
  });
621
688
  };
622
- const subscribeOHLCV = (tradingPairId, tradingMode, interval, handler) => {
623
- const channel = `ohlcv:${tradingPairId}:${tradingMode}:${interval}`;
689
+ const subscribeOHLCV = (tradingPairId, tradingMode, interval, handler, priceType) => {
690
+ // Four-token channel selects the trade-derived candles (back-compat); the
691
+ // optional fifth token selects the price series (`mark` = close-only mark
692
+ // series, `*` = both).
693
+ const channel = priceType === undefined ? `ohlcv:${tradingPairId}:${tradingMode}:${interval}` : `ohlcv:${tradingPairId}:${tradingMode}:${interval}:${priceType}`;
624
694
  return subscribe(channel, (rawData) => {
625
695
  try {
626
696
  const data = rawData;
627
697
  const ohlcvData = data.data;
698
+ // Concrete price series of this candle (`trade`/`mark`). Present on
699
+ // every current frame; a wildcard (`*`) subscriber reads it to tell the
700
+ // two streams apart. Omitted when a legacy frame carries no `price_type`.
701
+ const priceType = data.price_type === "trade" || data.price_type === "mark" ? data.price_type : undefined;
628
702
  const event = {
629
703
  // `trading_pair_id` is the pair UUID; `symbol` is the display string.
630
704
  // `tradingPairId` must carry the UUID (the symbol lives in `candlestick.s`).
631
705
  tradingPairId: data.trading_pair_id,
632
706
  tradingMode: data.trading_mode,
633
707
  interval: data.interval,
708
+ priceType,
634
709
  candlestick: {
635
710
  T: ohlcvData.period_start || 0,
636
711
  t: ohlcvData.period_end || 0,
@@ -791,6 +866,23 @@ export function createMonacoWebSocket(baseUrl, options = {}) {
791
866
  }
792
867
  });
793
868
  };
869
+ const subscribeTwapOrders = (handler, tradingPairId) => {
870
+ if (!handler) {
871
+ throw new Error("twapOrders subscription requires a handler");
872
+ }
873
+ if (tradingPairId !== undefined && tradingPairId.length === 0) {
874
+ throw new Error("twapOrders tradingPairId cannot be empty");
875
+ }
876
+ const channel = tradingPairId ? `twap_orders:${tradingPairId}` : "twap_orders";
877
+ return subscribe(channel, (rawData) => {
878
+ try {
879
+ handler(parseTwapOrderEvent(rawData));
880
+ }
881
+ catch (err) {
882
+ console.error("WebSocket: Error processing TWAP order event", err);
883
+ }
884
+ });
885
+ };
794
886
  /**
795
887
  * Subscribe to authenticated user's position updates.
796
888
  * Requires authentication - user is identified from the signed session-key
@@ -933,6 +1025,7 @@ export function createMonacoWebSocket(baseUrl, options = {}) {
933
1025
  userOrders: subscribeUserOrders,
934
1026
  balances: subscribeBalances,
935
1027
  conditionalOrders: subscribeConditionalOrders,
1028
+ twapOrders: subscribeTwapOrders,
936
1029
  positions: subscribePositions,
937
1030
  liquidations: subscribeLiquidations,
938
1031
  account: subscribeAccount,
@@ -10,6 +10,10 @@ export declare const COVERED: {
10
10
  cancel_conditional_order: string;
11
11
  get_conditional_order: string;
12
12
  cancel_order: string;
13
+ cancel_twap_order: string;
14
+ create_twap_order: string;
15
+ get_twap_order: string;
16
+ list_twap_orders: string;
13
17
  close_position: string;
14
18
  create_challenge: string;
15
19
  create_delegated_session: string;
package/dist/coverage.js CHANGED
@@ -10,6 +10,10 @@ export const COVERED = {
10
10
  cancel_conditional_order: "cancelConditionalOrder",
11
11
  get_conditional_order: "getConditionalOrder",
12
12
  cancel_order: "cancelOrder",
13
+ cancel_twap_order: "cancelTwapOrder",
14
+ create_twap_order: "createTwapOrder",
15
+ get_twap_order: "getTwapOrder",
16
+ list_twap_orders: "listTwapOrders",
13
17
  close_position: "closePosition",
14
18
  create_challenge: "createChallenge",
15
19
  create_delegated_session: "createDelegatedSession",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/core",
3
- "version": "1.0.42",
3
+ "version": "1.0.43",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,8 +23,8 @@
23
23
  "viem": "^2.45.2"
24
24
  },
25
25
  "dependencies": {
26
- "@0xmonaco/contracts": "1.0.42",
27
- "@0xmonaco/types": "1.0.42",
26
+ "@0xmonaco/contracts": "1.0.43",
27
+ "@0xmonaco/types": "1.0.43",
28
28
  "@noble/curves": "^1.9.1",
29
29
  "@noble/hashes": "^1.8.0",
30
30
  "http-status-codes": "^2.3.0"