@0xmonaco/core 1.0.42 → 1.0.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/perp/routes.d.ts +9 -0
- package/dist/api/perp/routes.js +4 -0
- package/dist/api/trading/api.d.ts +117 -3
- package/dist/api/trading/api.js +176 -4
- package/dist/api/vault/api.d.ts +37 -6
- package/dist/api/vault/api.js +60 -14
- package/dist/api/websocket/types.d.ts +4 -2
- package/dist/api/websocket/websocket.js +96 -3
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +4 -0
- package/package.json +4 -8
|
@@ -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;
|
package/dist/api/perp/routes.js
CHANGED
|
@@ -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
|
-
*
|
|
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
|
|
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
|
}
|
package/dist/api/trading/api.js
CHANGED
|
@@ -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
|
-
*
|
|
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
|
}
|
package/dist/api/vault/api.d.ts
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* console.log(`Deposit transaction: ${result.hash}`);
|
|
24
24
|
* ```
|
|
25
25
|
*/
|
|
26
|
-
import type { ApplicationsAPI, Balance, DepositTarget, ProfileAPI, TransactionResult, VaultAPI, WithdrawalRetryOptions, WithdrawalSource, WithdrawResult } from "@0xmonaco/types";
|
|
26
|
+
import type { ApplicationsAPI, Balance, DepositOptions, DepositTarget, ProfileAPI, TransactionResult, VaultAPI, WithdrawalRetryOptions, WithdrawalSource, WithdrawResult } from "@0xmonaco/types";
|
|
27
27
|
import { type Address, type Chain, type PublicClient, type WalletClient } from "viem";
|
|
28
28
|
import { BaseAPI } from "../base";
|
|
29
29
|
/**
|
|
@@ -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
|
|
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
|
|
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,15 @@ 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. A wallet holding
|
|
143
|
+
* the wrapped ERC20 itself can pass `options.asErc20` to deposit it through
|
|
144
|
+
* the standard `approve()` + `depositERC20` path instead. Either way,
|
|
145
|
+
* withdrawals of the wrapped-native asset pay out native coin (the vault
|
|
146
|
+
* unwraps).
|
|
132
147
|
*
|
|
133
148
|
* @param assetId - The asset identifier (UUID) to deposit
|
|
134
149
|
* @param amount - The amount of tokens to deposit (as bigint)
|
|
@@ -137,6 +152,9 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
|
|
|
137
152
|
* wallet; `"margin"` routes the deposit into the parent margin account's
|
|
138
153
|
* collateral (auto-creating the account if needed). Margin deposits that
|
|
139
154
|
* cannot be routed safely fall back to spot.
|
|
155
|
+
* @param options - Deposit options; `asErc20` deposits the wrapped-native
|
|
156
|
+
* asset as its ERC20 via `depositERC20` (requires approval) instead of in
|
|
157
|
+
* native coin. No effect on other assets.
|
|
140
158
|
* @returns Promise resolving to TransactionResult with transaction details
|
|
141
159
|
* @throws {ContractError} When deposit fails or approval is insufficient
|
|
142
160
|
* @throws {APIError} When the asset is not found or the assetId is invalid
|
|
@@ -170,7 +188,7 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
|
|
|
170
188
|
* const receipt = await sdk.waitForTransaction(result.hash);
|
|
171
189
|
* ```
|
|
172
190
|
*/
|
|
173
|
-
deposit(assetId: string, amount: bigint, autoWait?: boolean, target?: DepositTarget): Promise<TransactionResult>;
|
|
191
|
+
deposit(assetId: string, amount: bigint, autoWait?: boolean, target?: DepositTarget, options?: DepositOptions): Promise<TransactionResult>;
|
|
174
192
|
/**
|
|
175
193
|
* Polls `GET /api/v1/withdrawals/{index}` until the gateway can serve the
|
|
176
194
|
* `executeWithdrawal` calldata, then returns it with the vault address.
|
|
@@ -209,6 +227,10 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
|
|
|
209
227
|
* the index would strand the funds; the caller keeps it and finishes the
|
|
210
228
|
* withdrawal later with `retryWithdrawal(withdrawalIndex)`.
|
|
211
229
|
*
|
|
230
|
+
* Withdrawals of the wrapped-native asset (e.g. WSEI) pay out native coin —
|
|
231
|
+
* the vault unwraps on exit. This is decided server-side; no request change
|
|
232
|
+
* is needed.
|
|
233
|
+
*
|
|
212
234
|
* @param assetId - The asset identifier (UUID) to withdraw
|
|
213
235
|
* @param amount - The raw token amount to withdraw (as bigint)
|
|
214
236
|
* @param autoWait - When `true` (default) polls for the merkle-proof calldata
|
|
@@ -309,8 +331,17 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
|
|
|
309
331
|
* Compares the current allowance with the requested amount to determine if
|
|
310
332
|
* the user needs to approve more tokens before performing operations.
|
|
311
333
|
*
|
|
334
|
+
* The wrapped-native asset (e.g. WSEI) does not need approval by default:
|
|
335
|
+
* its deposits are made in native coin via the payable `depositNative` (the
|
|
336
|
+
* vault wraps on entry), so no ERC20 allowance is consumed and this method
|
|
337
|
+
* returns `false` without reading the chain. An `options.asErc20` deposit of
|
|
338
|
+
* that asset goes through `depositERC20` and consumes a real allowance, so
|
|
339
|
+
* pass the same options here to check it.
|
|
340
|
+
*
|
|
312
341
|
* @param assetId - The asset identifier (UUID) to check for
|
|
313
342
|
* @param amount - The amount to check approval for (as bigint)
|
|
343
|
+
* @param options - Deposit options the approval is for; with `asErc20` the
|
|
344
|
+
* wrapped-native asset's real ERC20 allowance is read.
|
|
314
345
|
* @returns Promise resolving to true if approval is needed, false otherwise
|
|
315
346
|
* @throws {ContractError} When approval check fails or asset not found
|
|
316
347
|
*
|
|
@@ -327,6 +358,6 @@ export declare class VaultAPIImpl extends BaseAPI implements VaultAPI {
|
|
|
327
358
|
* }
|
|
328
359
|
* ```
|
|
329
360
|
*/
|
|
330
|
-
needsApproval(assetId: string, amount: bigint): Promise<boolean>;
|
|
361
|
+
needsApproval(assetId: string, amount: bigint, options?: DepositOptions): Promise<boolean>;
|
|
331
362
|
private waitForTransaction;
|
|
332
363
|
}
|
package/dist/api/vault/api.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
-
|
|
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,15 @@ 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. A wallet holding
|
|
232
|
+
* the wrapped ERC20 itself can pass `options.asErc20` to deposit it through
|
|
233
|
+
* the standard `approve()` + `depositERC20` path instead. Either way,
|
|
234
|
+
* withdrawals of the wrapped-native asset pay out native coin (the vault
|
|
235
|
+
* unwraps).
|
|
220
236
|
*
|
|
221
237
|
* @param assetId - The asset identifier (UUID) to deposit
|
|
222
238
|
* @param amount - The amount of tokens to deposit (as bigint)
|
|
@@ -225,6 +241,9 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
225
241
|
* wallet; `"margin"` routes the deposit into the parent margin account's
|
|
226
242
|
* collateral (auto-creating the account if needed). Margin deposits that
|
|
227
243
|
* cannot be routed safely fall back to spot.
|
|
244
|
+
* @param options - Deposit options; `asErc20` deposits the wrapped-native
|
|
245
|
+
* asset as its ERC20 via `depositERC20` (requires approval) instead of in
|
|
246
|
+
* native coin. No effect on other assets.
|
|
228
247
|
* @returns Promise resolving to TransactionResult with transaction details
|
|
229
248
|
* @throws {ContractError} When deposit fails or approval is insufficient
|
|
230
249
|
* @throws {APIError} When the asset is not found or the assetId is invalid
|
|
@@ -258,21 +277,25 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
258
277
|
* const receipt = await sdk.waitForTransaction(result.hash);
|
|
259
278
|
* ```
|
|
260
279
|
*/
|
|
261
|
-
async deposit(assetId, amount, autoWait = true, target = "spot") {
|
|
280
|
+
async deposit(assetId, amount, autoWait = true, target = "spot", options = {}) {
|
|
262
281
|
if (!this.walletClient) {
|
|
263
282
|
throw new InvalidConfigError("Wallet client not set. Connect a wallet first.", "walletClient");
|
|
264
283
|
}
|
|
265
284
|
// Validate inputs
|
|
266
|
-
validate(DepositSchema, { assetId, amount, autoWait, target });
|
|
285
|
+
validate(DepositSchema, { assetId, amount, autoWait, target, options });
|
|
267
286
|
const vaultAddress = await this.getVaultAddress();
|
|
268
287
|
const clientId = await this.getClientId();
|
|
269
288
|
// The on-chain applicationData carries the client id plus, for margin
|
|
270
289
|
// deposits, the routing hint the indexer decodes.
|
|
271
290
|
const applicationData = encodeDepositApplicationData(clientId, target);
|
|
272
|
-
const { tokenAddress,
|
|
273
|
-
|
|
291
|
+
const { tokenAddress, isWrappedNative } = await this.resolveAsset(assetId);
|
|
292
|
+
// The wrapped-native asset normally deposits in native coin, but asErc20
|
|
293
|
+
// opts into the standard ERC20 path for wallets holding the wrapped ERC20
|
|
294
|
+
// itself (the vault accepts it like any enabled token).
|
|
295
|
+
const useNativePath = isWrappedNative && options.asErc20 !== true;
|
|
296
|
+
if (!useNativePath) {
|
|
274
297
|
// Check if approval is needed before proceeding
|
|
275
|
-
const needsApproval = await this.needsApproval(assetId, amount);
|
|
298
|
+
const needsApproval = await this.needsApproval(assetId, amount, options);
|
|
276
299
|
if (needsApproval) {
|
|
277
300
|
throw new ContractError(`Approval required before deposit. Please invoke approve() first for asset ${assetId} (token address: ${tokenAddress}).`, {
|
|
278
301
|
revertReason: "APPROVAL_REQUIRED",
|
|
@@ -283,9 +306,12 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
283
306
|
if (!walletAccount) {
|
|
284
307
|
throw new InvalidConfigError("No account available in wallet client", "account");
|
|
285
308
|
}
|
|
286
|
-
// For native
|
|
309
|
+
// For the wrapped-native asset (e.g. WSEI), use depositNative (payable) — the
|
|
310
|
+
// vault wraps the native coin into the ERC20 on entry, so no allowance is
|
|
311
|
+
// involved. All other ERC20 tokens (and asErc20 wrapped-native deposits) go
|
|
312
|
+
// through approve + depositERC20.
|
|
287
313
|
let hash;
|
|
288
|
-
if (
|
|
314
|
+
if (useNativePath) {
|
|
289
315
|
hash = await this.walletClient.writeContract({
|
|
290
316
|
address: vaultAddress,
|
|
291
317
|
abi: CONTRACT_ABIS.vault,
|
|
@@ -380,6 +406,10 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
380
406
|
* the index would strand the funds; the caller keeps it and finishes the
|
|
381
407
|
* withdrawal later with `retryWithdrawal(withdrawalIndex)`.
|
|
382
408
|
*
|
|
409
|
+
* Withdrawals of the wrapped-native asset (e.g. WSEI) pay out native coin —
|
|
410
|
+
* the vault unwraps on exit. This is decided server-side; no request change
|
|
411
|
+
* is needed.
|
|
412
|
+
*
|
|
383
413
|
* @param assetId - The asset identifier (UUID) to withdraw
|
|
384
414
|
* @param amount - The raw token amount to withdraw (as bigint)
|
|
385
415
|
* @param autoWait - When `true` (default) polls for the merkle-proof calldata
|
|
@@ -597,8 +627,17 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
597
627
|
* Compares the current allowance with the requested amount to determine if
|
|
598
628
|
* the user needs to approve more tokens before performing operations.
|
|
599
629
|
*
|
|
630
|
+
* The wrapped-native asset (e.g. WSEI) does not need approval by default:
|
|
631
|
+
* its deposits are made in native coin via the payable `depositNative` (the
|
|
632
|
+
* vault wraps on entry), so no ERC20 allowance is consumed and this method
|
|
633
|
+
* returns `false` without reading the chain. An `options.asErc20` deposit of
|
|
634
|
+
* that asset goes through `depositERC20` and consumes a real allowance, so
|
|
635
|
+
* pass the same options here to check it.
|
|
636
|
+
*
|
|
600
637
|
* @param assetId - The asset identifier (UUID) to check for
|
|
601
638
|
* @param amount - The amount to check approval for (as bigint)
|
|
639
|
+
* @param options - Deposit options the approval is for; with `asErc20` the
|
|
640
|
+
* wrapped-native asset's real ERC20 allowance is read.
|
|
602
641
|
* @returns Promise resolving to true if approval is needed, false otherwise
|
|
603
642
|
* @throws {ContractError} When approval check fails or asset not found
|
|
604
643
|
*
|
|
@@ -615,7 +654,14 @@ export class VaultAPIImpl extends BaseAPI {
|
|
|
615
654
|
* }
|
|
616
655
|
* ```
|
|
617
656
|
*/
|
|
618
|
-
async needsApproval(assetId, amount) {
|
|
657
|
+
async needsApproval(assetId, amount, options = {}) {
|
|
658
|
+
const { isWrappedNative } = await this.resolveAsset(assetId);
|
|
659
|
+
if (isWrappedNative && options.asErc20 !== true) {
|
|
660
|
+
// Wrapped-native deposits route to the payable depositNative — no ERC20
|
|
661
|
+
// allowance is consumed, so approval is never needed. asErc20 deposits
|
|
662
|
+
// go through depositERC20 and fall through to the real allowance read.
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
619
665
|
const allowance = await this.getAllowance(assetId);
|
|
620
666
|
return allowance < amount;
|
|
621
667
|
}
|
|
@@ -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
|
|
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 (
|
|
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
|
-
|
|
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,
|
package/dist/coverage.d.ts
CHANGED
|
@@ -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,12 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xmonaco/core",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"
|
|
6
|
-
"type": "git",
|
|
7
|
-
"url": "https://github.com/Monaco-Research/monaco-sdk.git",
|
|
8
|
-
"directory": "packages/core"
|
|
9
|
-
},
|
|
5
|
+
"homepage": "https://docs.0xmonaco.com/sdk/typescript",
|
|
10
6
|
"main": "./dist/index.js",
|
|
11
7
|
"module": "./dist/index.js",
|
|
12
8
|
"types": "./dist/index.d.ts",
|
|
@@ -23,8 +19,8 @@
|
|
|
23
19
|
"viem": "^2.45.2"
|
|
24
20
|
},
|
|
25
21
|
"dependencies": {
|
|
26
|
-
"@0xmonaco/contracts": "1.0.
|
|
27
|
-
"@0xmonaco/types": "1.0.
|
|
22
|
+
"@0xmonaco/contracts": "1.0.44",
|
|
23
|
+
"@0xmonaco/types": "1.0.44",
|
|
28
24
|
"@noble/curves": "^1.9.1",
|
|
29
25
|
"@noble/hashes": "^1.8.0",
|
|
30
26
|
"http-status-codes": "^2.3.0"
|