@0xmonaco/react 1.0.88 → 1.0.91

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/README.md CHANGED
@@ -21,6 +21,7 @@ yarn add @0xmonaco/react react wagmi@^2.17.5 viem@^2.31.7
21
21
  - 🔐 **Authentication**: `useAuth` hook for wallet-based login and session management
22
22
  - 📈 **Trading**: `useTrade` hook for placing and managing orders
23
23
  - 📊 **Market Data**: `useMarket` hook for trading pairs and candlestick data
24
+ - ⚡ **Liquidation Feed**: `useLiquidationFeed` combines public history pages with the live pair event channel
24
25
  - 👤 **Profile**: `useProfile` hook for user account information
25
26
  - 🔄 **WebSocket**: Real-time hooks for orders, OHLCV, and orderbook updates
26
27
  - 💼 **Vault**: `useVault` hook for token deposits and withdrawals
@@ -56,6 +56,9 @@ export declare const COVERED: {
56
56
  get_my_referral_tree: string;
57
57
  get_trader_code_info: string;
58
58
  get_trades: string;
59
+ get_trade_flow: string;
60
+ get_liquidation_metrics: string;
61
+ get_trader_metrics: string;
59
62
  get_user_balance_by_asset: string;
60
63
  get_user_balances: string;
61
64
  get_user_movements: string;
@@ -65,6 +68,7 @@ export declare const COVERED: {
65
68
  list_pending_withdrawals: string;
66
69
  list_conditional_orders: string;
67
70
  list_funding_history: string;
71
+ list_liquidation_events: string;
68
72
  list_position_history: string;
69
73
  list_positions: string;
70
74
  list_trading_pairs: string;
@@ -109,6 +113,8 @@ export declare const INTENTIONALLY_EXCLUDED: {
109
113
  get_screener: string;
110
114
  get_self_trade_prevention_default: string;
111
115
  get_sweeper_chains: string;
116
+ list_sweeper_deposits: string;
117
+ get_sweeper_deposit_status: string;
112
118
  set_self_trade_prevention_default: string;
113
119
  get_sub_account_limits: string;
114
120
  get_trade_by_id: string;
package/dist/coverage.js CHANGED
@@ -56,6 +56,9 @@ export const COVERED = {
56
56
  get_my_referral_tree: "useMyReferralTree",
57
57
  get_trader_code_info: "useTraderCodeInfo",
58
58
  get_trades: "useTradeFeed",
59
+ get_trade_flow: "useMarket",
60
+ get_liquidation_metrics: "useMarket",
61
+ get_trader_metrics: "useMarket",
59
62
  get_user_balance_by_asset: "useProfile",
60
63
  get_user_balances: "useUserBalances",
61
64
  get_user_movements: "useUserMovements",
@@ -65,6 +68,7 @@ export const COVERED = {
65
68
  list_pending_withdrawals: "useVault (listPendingWithdrawals)",
66
69
  list_conditional_orders: "useTrade",
67
70
  list_funding_history: "useMarket",
71
+ list_liquidation_events: "useMarket",
68
72
  list_position_history: "usePositions",
69
73
  list_positions: "usePositions",
70
74
  list_trading_pairs: "useMarket",
@@ -109,6 +113,8 @@ export const INTENTIONALLY_EXCLUDED = {
109
113
  get_screener: "Market lookup available via the core client / list+symbol hooks; no dedicated React hook.",
110
114
  get_self_trade_prevention_default: "Wallet trading-settings surface (covered by @0xmonaco/core); no React hook yet.",
111
115
  get_sweeper_chains: "Sweeper chain/asset listing; deposit-onboarding data available via the core client, not a UI action. No React hook.",
116
+ list_sweeper_deposits: "Sweeper deposit listing by cursor; deposit-history data available via the core client, not a UI action. No React hook.",
117
+ get_sweeper_deposit_status: "Sweeper deposit-status lookup by transaction hash; a polling read available via the core client, not a UI action. No React hook.",
112
118
  set_self_trade_prevention_default: "Wallet trading-settings surface (covered by @0xmonaco/core); no React hook yet.",
113
119
  get_sub_account_limits: "Sub-account administration; no React hook.",
114
120
  get_trade_by_id: "Trade-history lookup with a core client method but no dedicated React hook yet.",
@@ -3,6 +3,7 @@ export * from "./useCopyEvents";
3
3
  export * from "./useCopyTrading";
4
4
  export * from "./useFees";
5
5
  export * from "./useInstruments";
6
+ export * from "./useLiquidationFeed";
6
7
  export * from "./useMarket";
7
8
  export * from "./useMonaco";
8
9
  export * from "./useOHLCV";
@@ -3,6 +3,7 @@ export * from "./useCopyEvents";
3
3
  export * from "./useCopyTrading";
4
4
  export * from "./useFees";
5
5
  export * from "./useInstruments";
6
+ export * from "./useLiquidationFeed";
6
7
  export * from "./useMarket";
7
8
  export * from "./useMonaco";
8
9
  export * from "./useOHLCV";
@@ -0,0 +1,5 @@
1
+ import type { ListLiquidationEventsParams, ListLiquidationEventsResponse, MarketLiquidationEvent } from "@0xmonaco/types";
2
+ type ListEvents = (params?: ListLiquidationEventsParams) => Promise<ListLiquidationEventsResponse>;
3
+ /** Fetch newest-first history pages, with an optional page bound for initial loading. */
4
+ export declare function fetchMarketLiquidationHistory(listEvents: ListEvents, startTime?: number, maxPages?: number): Promise<MarketLiquidationEvent[]>;
5
+ export {};
@@ -0,0 +1,19 @@
1
+ import { LIQUIDATION_EVENTS_PAGE_SIZE, marketLiquidationFromHistory } from "./mergeMarketLiquidationEvents";
2
+ /** Fetch newest-first history pages, with an optional page bound for initial loading. */
3
+ export async function fetchMarketLiquidationHistory(listEvents, startTime, maxPages) {
4
+ const events = [];
5
+ let pageToken;
6
+ let pagesFetched = 0;
7
+ do {
8
+ const params = { pageSize: LIQUIDATION_EVENTS_PAGE_SIZE };
9
+ if (startTime !== undefined)
10
+ params.startTime = startTime;
11
+ if (pageToken !== undefined)
12
+ params.pageToken = pageToken;
13
+ const response = await listEvents(params);
14
+ events.push(...response.events.map(marketLiquidationFromHistory));
15
+ pageToken = response.nextPageToken || undefined;
16
+ pagesFetched += 1;
17
+ } while (pageToken && (maxPages === undefined || pagesFetched < maxPages));
18
+ return events;
19
+ }
@@ -0,0 +1,2 @@
1
+ export type { UseLiquidationFeedReturn } from "./types";
2
+ export { useLiquidationFeed } from "./useLiquidationFeed";
@@ -0,0 +1 @@
1
+ export { useLiquidationFeed } from "./useLiquidationFeed";
@@ -0,0 +1,6 @@
1
+ import type { LiquidationHistoryEvent, MarketLiquidationEvent } from "@0xmonaco/types";
2
+ export declare const LIQUIDATION_EVENTS_PAGE_SIZE = 100;
3
+ /** Newest events a mounted feed keeps; older ones are dropped so memory and per-event sorting stay bounded. */
4
+ export declare const MAX_RETAINED_LIQUIDATION_EVENTS: number;
5
+ export declare function marketLiquidationFromHistory(event: LiquidationHistoryEvent): MarketLiquidationEvent;
6
+ export declare function mergeMarketLiquidationEvents(current: MarketLiquidationEvent[], incoming: MarketLiquidationEvent[], limit?: number): MarketLiquidationEvent[];
@@ -0,0 +1,35 @@
1
+ export const LIQUIDATION_EVENTS_PAGE_SIZE = 100;
2
+ /** Newest events a mounted feed keeps; older ones are dropped so memory and per-event sorting stay bounded. */
3
+ export const MAX_RETAINED_LIQUIDATION_EVENTS = 5 * LIQUIDATION_EVENTS_PAGE_SIZE;
4
+ export function marketLiquidationFromHistory(event) {
5
+ return {
6
+ eventType: "liquidation_event",
7
+ tradingPairId: event.tradingPairId,
8
+ data: {
9
+ eventId: event.eventId,
10
+ timestamp: event.timestamp,
11
+ wallet: event.wallet,
12
+ side: event.side,
13
+ positionSize: event.positionSize,
14
+ markPrice: event.markPrice,
15
+ markNotional: event.markNotional,
16
+ quoteAssetSymbol: event.quoteAssetSymbol,
17
+ },
18
+ };
19
+ }
20
+ export function mergeMarketLiquidationEvents(current, incoming, limit = MAX_RETAINED_LIQUIDATION_EVENTS) {
21
+ const byId = new Map(current.map((event) => [event.data.eventId, event]));
22
+ for (const event of incoming)
23
+ byId.set(event.data.eventId, event);
24
+ const merged = [...byId.values()].sort((left, right) => {
25
+ const timeOrder = right.data.timestamp - left.data.timestamp;
26
+ if (timeOrder !== 0)
27
+ return timeOrder;
28
+ // REST orders equal-time rows by UUID descending. Canonical UUID strings
29
+ // preserve PostgreSQL UUID order under code-unit comparison.
30
+ if (left.data.eventId === right.data.eventId)
31
+ return 0;
32
+ return left.data.eventId < right.data.eventId ? 1 : -1;
33
+ });
34
+ return merged.length > limit ? merged.slice(0, limit) : merged;
35
+ }
@@ -0,0 +1,9 @@
1
+ import type { MarketLiquidationEvent } from "@0xmonaco/types";
2
+ export interface UseLiquidationFeedReturn {
3
+ /** Recent persisted events merged with live pair-scoped WebSocket events. */
4
+ events: MarketLiquidationEvent[];
5
+ /** Whether the initial history page is loading. */
6
+ isLoading: boolean;
7
+ /** Most recent history or subscription setup error. */
8
+ error: Error | null;
9
+ }
File without changes
@@ -0,0 +1,10 @@
1
+ import type { UseLiquidationFeedReturn } from "./types";
2
+ /**
3
+ * Load the newest persisted events for a pair and keep them current from the
4
+ * public WebSocket feed. On each server subscription acknowledgement, backfill
5
+ * the gap from the latest seen event timestamp (up to the retained list's
6
+ * worth of pages), retry with backoff until persistence catches up with the
7
+ * live feed, and deduplicate by persisted ID. At most the newest
8
+ * `MAX_RETAINED_LIQUIDATION_EVENTS` are kept.
9
+ */
10
+ export declare function useLiquidationFeed(tradingPairId: string): UseLiquidationFeedReturn;
@@ -0,0 +1,172 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { useMonacoSDK } from "../useMonaco";
3
+ import { fetchMarketLiquidationHistory } from "./fetchMarketLiquidationHistory";
4
+ import { LIQUIDATION_EVENTS_PAGE_SIZE, MAX_RETAINED_LIQUIDATION_EVENTS, mergeMarketLiquidationEvents } from "./mergeMarketLiquidationEvents";
5
+ /**
6
+ * Delays between reconnect backfill reads, each counted from the end of the
7
+ * previous read. Retrying stops once persisted history contains the first
8
+ * live event received after the acknowledgement (proof every event from the
9
+ * disconnect is stored); once two retries in a row find nothing new while no
10
+ * live event has arrived (a quiet market, or storage more than a few seconds
11
+ * behind with nothing live to prove it); or when the schedule runs out.
12
+ */
13
+ const SUBSCRIPTION_BACKFILL_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000];
14
+ /** Consecutive unchanged retries, with nothing live, that end a quiet catch-up. */
15
+ const QUIET_RETRIES_TO_STOP = 2;
16
+ /** Gap reads stop at the page that fills the retained event list. */
17
+ const MAX_GAP_PAGES = MAX_RETAINED_LIQUIDATION_EVENTS / LIQUIDATION_EVENTS_PAGE_SIZE;
18
+ /**
19
+ * Load the newest persisted events for a pair and keep them current from the
20
+ * public WebSocket feed. On each server subscription acknowledgement, backfill
21
+ * the gap from the latest seen event timestamp (up to the retained list's
22
+ * worth of pages), retry with backoff until persistence catches up with the
23
+ * live feed, and deduplicate by persisted ID. At most the newest
24
+ * `MAX_RETAINED_LIQUIDATION_EVENTS` are kept.
25
+ */
26
+ export function useLiquidationFeed(tradingPairId) {
27
+ const { sdk } = useMonacoSDK();
28
+ const [events, setEvents] = useState([]);
29
+ const [isLoading, setIsLoading] = useState(Boolean(tradingPairId));
30
+ const [error, setError] = useState(null);
31
+ const latestTimestamp = useRef(undefined);
32
+ useEffect(() => {
33
+ if (!tradingPairId || !sdk?.market) {
34
+ setEvents([]);
35
+ setIsLoading(false);
36
+ setError(null);
37
+ return;
38
+ }
39
+ let active = true;
40
+ setEvents([]);
41
+ setIsLoading(true);
42
+ setError(null);
43
+ latestTimestamp.current = undefined;
44
+ let unsubscribe;
45
+ let unsubscribeChanges;
46
+ let backfillRetryTimer;
47
+ let initialBackfillCompleted = false;
48
+ // Each acknowledgement starts a new catch-up; an older chain still in
49
+ // flight sees a newer generation and stops without scheduling anything.
50
+ let ackGeneration = 0;
51
+ let catchUpPending = false;
52
+ // The ID of the first live event after the latest acknowledgement; once
53
+ // persisted history contains it, the reconnect gap is complete.
54
+ let firstLiveAfterAck;
55
+ const channel = `market_liquidations:${tradingPairId}`;
56
+ const backfill = async (startTime, maxPages) => {
57
+ try {
58
+ const rows = await fetchMarketLiquidationHistory((params) => sdk.market.listLiquidationEvents(tradingPairId, params), startTime, maxPages);
59
+ if (!active)
60
+ return undefined;
61
+ setError(null);
62
+ let oldest;
63
+ let newest;
64
+ for (const event of rows) {
65
+ latestTimestamp.current = Math.max(latestTimestamp.current ?? 0, event.data.timestamp);
66
+ oldest = Math.min(oldest ?? event.data.timestamp, event.data.timestamp);
67
+ newest = Math.max(newest ?? event.data.timestamp, event.data.timestamp);
68
+ }
69
+ setEvents((current) => mergeMarketLiquidationEvents(current, rows));
70
+ return { oldest, newest, ids: new Set(rows.map((event) => event.data.eventId)) };
71
+ }
72
+ catch (cause) {
73
+ if (active)
74
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
75
+ }
76
+ finally {
77
+ if (active)
78
+ setIsLoading(false);
79
+ }
80
+ };
81
+ // Mount with a bounded recent page; reconnect backfills below can page the
82
+ // entire gap without turning a first load into an all-history query.
83
+ const initialBackfill = backfill(undefined, 1).then((range) => {
84
+ initialBackfillCompleted = true;
85
+ return range?.oldest;
86
+ });
87
+ // Read the gap, then retry on the backoff schedule until caught up. A
88
+ // retry starts from the newest persisted row seen so far (inclusive), so
89
+ // it reads only what may have been stored since.
90
+ const readGap = (generation, startTime, maxPages, attempt, previousNewest, quietRetries = 0) => {
91
+ void backfill(startTime, maxPages).then((range) => {
92
+ if (!active || generation !== ackGeneration)
93
+ return;
94
+ const finish = () => {
95
+ catchUpPending = false;
96
+ };
97
+ if (firstLiveAfterAck !== undefined && range?.ids.has(firstLiveAfterAck))
98
+ return finish();
99
+ const unchanged = attempt >= 0 && firstLiveAfterAck === undefined && range?.newest === previousNewest;
100
+ const quiet = unchanged ? quietRetries + 1 : 0;
101
+ if (quiet >= QUIET_RETRIES_TO_STOP)
102
+ return finish();
103
+ const delay = SUBSCRIPTION_BACKFILL_RETRY_DELAYS_MS[attempt + 1];
104
+ if (delay === undefined)
105
+ return finish();
106
+ const newest = range?.newest ?? previousNewest;
107
+ backfillRetryTimer = setTimeout(() => {
108
+ backfillRetryTimer = undefined;
109
+ if (generation === ackGeneration)
110
+ readGap(generation, newest ?? startTime, maxPages, attempt + 1, newest, quiet);
111
+ }, delay);
112
+ });
113
+ };
114
+ const backfillAfterSubscription = () => {
115
+ if (backfillRetryTimer !== undefined) {
116
+ clearTimeout(backfillRetryTimer);
117
+ backfillRetryTimer = undefined;
118
+ }
119
+ ackGeneration += 1;
120
+ const generation = ackGeneration;
121
+ catchUpPending = true;
122
+ firstLiveAfterAck = undefined;
123
+ const startTimeAtAck = latestTimestamp.current;
124
+ const initialRequestWasPending = !initialBackfillCompleted;
125
+ void initialBackfill.then((initialHistoryFloor) => {
126
+ if (!active || generation !== ackGeneration)
127
+ return;
128
+ // If the acknowledgement arrived during the initial read, use its
129
+ // oldest row as an overlap point so events at the transition are not
130
+ // lost behind live events received while that read was in flight.
131
+ const startTime = initialRequestWasPending ? (initialHistoryFloor ?? startTimeAtAck) : startTimeAtAck;
132
+ // With no checkpoint, this is a first-load read, not an outage gap.
133
+ // Keep it bounded to the newest page instead of walking all history.
134
+ // A gap read stops once it fills the retained list: older rows would
135
+ // be dropped by the merge anyway.
136
+ const maxPages = startTime === undefined ? 1 : MAX_GAP_PAGES;
137
+ readGap(generation, startTime, maxPages, -1);
138
+ });
139
+ };
140
+ if (sdk.ws) {
141
+ try {
142
+ unsubscribeChanges = sdk.ws.onSubscriptionChange((change) => {
143
+ if (change.channel === channel && change.state === "subscribed")
144
+ backfillAfterSubscription();
145
+ });
146
+ unsubscribe = sdk.ws.marketLiquidations(tradingPairId, (event) => {
147
+ if (!active)
148
+ return;
149
+ if (catchUpPending && firstLiveAfterAck === undefined)
150
+ firstLiveAfterAck = event.data.eventId;
151
+ latestTimestamp.current = Math.max(latestTimestamp.current ?? 0, event.data.timestamp);
152
+ setEvents((current) => mergeMarketLiquidationEvents(current, [event]));
153
+ });
154
+ if (sdk.ws.getSubscriptionState(channel) === "subscribed")
155
+ backfillAfterSubscription();
156
+ }
157
+ catch (cause) {
158
+ unsubscribeChanges?.();
159
+ if (active)
160
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
161
+ }
162
+ }
163
+ return () => {
164
+ active = false;
165
+ if (backfillRetryTimer !== undefined)
166
+ clearTimeout(backfillRetryTimer);
167
+ unsubscribe?.();
168
+ unsubscribeChanges?.();
169
+ };
170
+ }, [sdk, sdk?.ws, tradingPairId]);
171
+ return { events, isLoading, error };
172
+ }
@@ -1,4 +1,4 @@
1
- import type { Candlestick, FundingState, GetCandlesticksParams, GetTradingPairsParams, GetTradingPairsResponse, IndexPrice, Interval, ListFundingHistoryParams, ListFundingHistoryResponse, MarketMetadata, MarkPrice, OpenInterest, PerpMarketConfig, PerpMarketSummary, TradingPair } from "@0xmonaco/types";
1
+ import type { Candlestick, FundingState, GetCandlesticksParams, GetLiquidationMetricsParams, GetTradeFlowParams, GetTradingPairsParams, GetTradingPairsResponse, IndexPrice, Interval, LiquidationMetrics, ListFundingHistoryParams, ListFundingHistoryResponse, ListLiquidationEventsParams, ListLiquidationEventsResponse, MarketMetadata, MarkPrice, OpenInterest, PerpMarketConfig, PerpMarketSummary, TradeFlow, TraderMetrics, TradingPair } from "@0xmonaco/types";
2
2
  export interface UseMarketReturn {
3
3
  /** Get all available trading pairs with optional filtering and pagination */
4
4
  getPaginatedTradingPairs: (params?: GetTradingPairsParams) => Promise<GetTradingPairsResponse>;
@@ -27,4 +27,8 @@ export interface UseMarketReturn {
27
27
  getFundingState: (tradingPairId: string) => Promise<FundingState>;
28
28
  listFundingHistory: (tradingPairId: string, params?: ListFundingHistoryParams) => Promise<ListFundingHistoryResponse>;
29
29
  getOpenInterest: (tradingPairId: string) => Promise<OpenInterest>;
30
+ getTraderMetrics: (tradingPairId: string) => Promise<TraderMetrics>;
31
+ getTradeFlow: (tradingPairId: string, params: GetTradeFlowParams) => Promise<TradeFlow>;
32
+ listLiquidationEvents: (tradingPairId: string, params?: ListLiquidationEventsParams) => Promise<ListLiquidationEventsResponse>;
33
+ getLiquidationMetrics: (tradingPairId: string, params: GetLiquidationMetricsParams) => Promise<LiquidationMetrics>;
30
34
  }
@@ -76,6 +76,30 @@ export const useMarket = () => {
76
76
  requireTradingPairId(tradingPairId);
77
77
  return await sdk.market.getOpenInterest(tradingPairId);
78
78
  }, [sdk]);
79
+ const getTraderMetrics = useCallback(async (tradingPairId) => {
80
+ if (!sdk)
81
+ throw new Error("SDK not available");
82
+ requireTradingPairId(tradingPairId);
83
+ return await sdk.market.getTraderMetrics(tradingPairId);
84
+ }, [sdk]);
85
+ const getTradeFlow = useCallback(async (tradingPairId, params) => {
86
+ if (!sdk)
87
+ throw new Error("SDK not available");
88
+ requireTradingPairId(tradingPairId);
89
+ return await sdk.market.getTradeFlow(tradingPairId, params);
90
+ }, [sdk]);
91
+ const listLiquidationEvents = useCallback(async (tradingPairId, params) => {
92
+ if (!sdk)
93
+ throw new Error("SDK not available");
94
+ requireTradingPairId(tradingPairId);
95
+ return await sdk.market.listLiquidationEvents(tradingPairId, params);
96
+ }, [sdk]);
97
+ const getLiquidationMetrics = useCallback(async (tradingPairId, params) => {
98
+ if (!sdk)
99
+ throw new Error("SDK not available");
100
+ requireTradingPairId(tradingPairId);
101
+ return await sdk.market.getLiquidationMetrics(tradingPairId, params);
102
+ }, [sdk]);
79
103
  return {
80
104
  getPaginatedTradingPairs,
81
105
  getTradingPairBySymbol,
@@ -88,5 +112,9 @@ export const useMarket = () => {
88
112
  getFundingState,
89
113
  listFundingHistory,
90
114
  getOpenInterest,
115
+ getTraderMetrics,
116
+ getTradeFlow,
117
+ listLiquidationEvents,
118
+ getLiquidationMetrics,
91
119
  };
92
120
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/react",
3
- "version": "1.0.88",
3
+ "version": "1.0.91",
4
4
  "type": "module",
5
5
  "homepage": "https://docs.0xmonaco.com/sdk/typescript",
6
6
  "main": "./dist/index.js",
@@ -16,8 +16,8 @@
16
16
  "lint": "biome lint ."
17
17
  },
18
18
  "dependencies": {
19
- "@0xmonaco/core": "1.0.88",
20
- "@0xmonaco/types": "1.0.88"
19
+ "@0xmonaco/core": "1.0.91",
20
+ "@0xmonaco/types": "1.0.91"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@types/react": "^19.2.18",