@0xmonaco/react 0.7.5 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/package.json +3 -3
  2. package/dist/hooks/index.d.ts +0 -15
  3. package/dist/hooks/index.js +0 -15
  4. package/dist/hooks/useAuth/index.d.ts +0 -2
  5. package/dist/hooks/useAuth/index.js +0 -1
  6. package/dist/hooks/useAuth/types.d.ts +0 -30
  7. package/dist/hooks/useAuth/types.js +0 -0
  8. package/dist/hooks/useAuth/useAuth.d.ts +0 -2
  9. package/dist/hooks/useAuth/useAuth.js +0 -145
  10. package/dist/hooks/useFees/index.d.ts +0 -2
  11. package/dist/hooks/useFees/index.js +0 -1
  12. package/dist/hooks/useFees/types.d.ts +0 -5
  13. package/dist/hooks/useFees/types.js +0 -0
  14. package/dist/hooks/useFees/useFees.d.ts +0 -2
  15. package/dist/hooks/useFees/useFees.js +0 -14
  16. package/dist/hooks/useMarket/index.d.ts +0 -2
  17. package/dist/hooks/useMarket/index.js +0 -1
  18. package/dist/hooks/useMarket/types.d.ts +0 -30
  19. package/dist/hooks/useMarket/types.js +0 -0
  20. package/dist/hooks/useMarket/useMarket.d.ts +0 -2
  21. package/dist/hooks/useMarket/useMarket.js +0 -92
  22. package/dist/hooks/useMonaco/index.d.ts +0 -2
  23. package/dist/hooks/useMonaco/index.js +0 -1
  24. package/dist/hooks/useMonaco/types.d.ts +0 -13
  25. package/dist/hooks/useMonaco/types.js +0 -0
  26. package/dist/hooks/useMonaco/useMonaco.d.ts +0 -2
  27. package/dist/hooks/useMonaco/useMonaco.js +0 -13
  28. package/dist/hooks/useOHLCV/index.d.ts +0 -2
  29. package/dist/hooks/useOHLCV/index.js +0 -2
  30. package/dist/hooks/useOHLCV/types.d.ts +0 -29
  31. package/dist/hooks/useOHLCV/types.js +0 -0
  32. package/dist/hooks/useOHLCV/useOHLCV.d.ts +0 -11
  33. package/dist/hooks/useOHLCV/useOHLCV.js +0 -76
  34. package/dist/hooks/useOrderbook/index.d.ts +0 -2
  35. package/dist/hooks/useOrderbook/index.js +0 -1
  36. package/dist/hooks/useOrderbook/types.d.ts +0 -27
  37. package/dist/hooks/useOrderbook/types.js +0 -0
  38. package/dist/hooks/useOrderbook/useOrderbook.d.ts +0 -3
  39. package/dist/hooks/useOrderbook/useOrderbook.js +0 -31
  40. package/dist/hooks/usePositions/index.d.ts +0 -2
  41. package/dist/hooks/usePositions/index.js +0 -1
  42. package/dist/hooks/usePositions/types.d.ts +0 -11
  43. package/dist/hooks/usePositions/types.js +0 -0
  44. package/dist/hooks/usePositions/usePositions.d.ts +0 -2
  45. package/dist/hooks/usePositions/usePositions.js +0 -65
  46. package/dist/hooks/useProfile/index.d.ts +0 -2
  47. package/dist/hooks/useProfile/index.js +0 -1
  48. package/dist/hooks/useProfile/types.d.ts +0 -23
  49. package/dist/hooks/useProfile/types.js +0 -0
  50. package/dist/hooks/useProfile/useProfile.d.ts +0 -2
  51. package/dist/hooks/useProfile/useProfile.js +0 -128
  52. package/dist/hooks/useTokenLifecycle/index.d.ts +0 -2
  53. package/dist/hooks/useTokenLifecycle/index.js +0 -1
  54. package/dist/hooks/useTokenLifecycle/types.d.ts +0 -23
  55. package/dist/hooks/useTokenLifecycle/types.js +0 -0
  56. package/dist/hooks/useTokenLifecycle/useTokenLifecycle.d.ts +0 -20
  57. package/dist/hooks/useTokenLifecycle/useTokenLifecycle.js +0 -125
  58. package/dist/hooks/useTokenLifecycle/utils.d.ts +0 -7
  59. package/dist/hooks/useTokenLifecycle/utils.js +0 -15
  60. package/dist/hooks/useTrade/index.d.ts +0 -2
  61. package/dist/hooks/useTrade/index.js +0 -1
  62. package/dist/hooks/useTrade/types.d.ts +0 -49
  63. package/dist/hooks/useTrade/types.js +0 -0
  64. package/dist/hooks/useTrade/useTrade.d.ts +0 -2
  65. package/dist/hooks/useTrade/useTrade.js +0 -132
  66. package/dist/hooks/useTradeFeed/index.d.ts +0 -2
  67. package/dist/hooks/useTradeFeed/index.js +0 -2
  68. package/dist/hooks/useTradeFeed/types.d.ts +0 -14
  69. package/dist/hooks/useTradeFeed/types.js +0 -0
  70. package/dist/hooks/useTradeFeed/useTradeFeed.d.ts +0 -12
  71. package/dist/hooks/useTradeFeed/useTradeFeed.js +0 -32
  72. package/dist/hooks/useUserBalances/index.d.ts +0 -2
  73. package/dist/hooks/useUserBalances/index.js +0 -2
  74. package/dist/hooks/useUserBalances/types.d.ts +0 -18
  75. package/dist/hooks/useUserBalances/types.js +0 -0
  76. package/dist/hooks/useUserBalances/useUserBalances.d.ts +0 -9
  77. package/dist/hooks/useUserBalances/useUserBalances.js +0 -171
  78. package/dist/hooks/useUserMovements/index.d.ts +0 -2
  79. package/dist/hooks/useUserMovements/index.js +0 -2
  80. package/dist/hooks/useUserMovements/types.d.ts +0 -23
  81. package/dist/hooks/useUserMovements/types.js +0 -0
  82. package/dist/hooks/useUserMovements/useUserMovements.d.ts +0 -18
  83. package/dist/hooks/useUserMovements/useUserMovements.js +0 -122
  84. package/dist/hooks/useUserOrders/index.d.ts +0 -2
  85. package/dist/hooks/useUserOrders/index.js +0 -2
  86. package/dist/hooks/useUserOrders/types.d.ts +0 -18
  87. package/dist/hooks/useUserOrders/types.js +0 -0
  88. package/dist/hooks/useUserOrders/useUserOrders.d.ts +0 -11
  89. package/dist/hooks/useUserOrders/useUserOrders.js +0 -191
  90. package/dist/hooks/useVault/index.d.ts +0 -2
  91. package/dist/hooks/useVault/index.js +0 -1
  92. package/dist/hooks/useVault/types.d.ts +0 -15
  93. package/dist/hooks/useVault/types.js +0 -0
  94. package/dist/hooks/useVault/useVault.d.ts +0 -2
  95. package/dist/hooks/useVault/useVault.js +0 -66
  96. package/dist/index.d.ts +0 -3
  97. package/dist/index.js +0 -3
  98. package/dist/provider/MonacoProvider.d.ts +0 -3
  99. package/dist/provider/MonacoProvider.js +0 -142
  100. package/dist/provider/TradeFeedProvider.d.ts +0 -22
  101. package/dist/provider/TradeFeedProvider.js +0 -143
  102. package/dist/provider/index.d.ts +0 -3
  103. package/dist/provider/index.js +0 -3
  104. package/dist/provider/types.d.ts +0 -49
  105. package/dist/provider/types.js +0 -9
  106. package/dist/utils/index.d.ts +0 -1
  107. package/dist/utils/index.js +0 -1
  108. package/dist/utils/tokenStorage.d.ts +0 -38
  109. package/dist/utils/tokenStorage.js +0 -102
@@ -1,31 +0,0 @@
1
- import { useCallback, useEffect, useState } from "react";
2
- import { useMonacoSDK } from "../useMonaco";
3
- export function useOrderbook(tradingPairId, tradingMode, magnitude, quotationMode, depth = 10) {
4
- const { sdk } = useMonacoSDK();
5
- const [orderbook, setOrderbook] = useState(null);
6
- const [error, setError] = useState(null);
7
- const [subscribed, setSubscribed] = useState(false);
8
- const clearError = useCallback(() => setError(null), []);
9
- // Connect and subscribe to orderbook updates
10
- useEffect(() => {
11
- if (!sdk?.ws || !sdk?.orderbook || !tradingPairId) {
12
- setSubscribed(false);
13
- return;
14
- }
15
- setOrderbook(null);
16
- setError(null);
17
- // Fetch initial orderbook via REST
18
- sdk.orderbook
19
- .getOrderbook(tradingPairId, { depth, tradingMode, magnitude, denomination: quotationMode })
20
- .then((initial) => setOrderbook(initial))
21
- .catch((err) => setError(err instanceof Error ? err : new Error(String(err))));
22
- // Subscribe to WebSocket updates (ws connection handled by MonacoProvider)
23
- const unsubscribe = sdk.ws.orderbook(tradingPairId, tradingMode, magnitude, quotationMode, setOrderbook);
24
- setSubscribed(true);
25
- return () => {
26
- unsubscribe();
27
- setSubscribed(false);
28
- };
29
- }, [sdk?.ws, sdk?.orderbook, tradingPairId, tradingMode, magnitude, quotationMode, depth]);
30
- return { orderbook, subscribed, error, clearError };
31
- }
@@ -1,2 +0,0 @@
1
- export type { UsePositionsReturn } from "./types";
2
- export { usePositions } from "./usePositions";
@@ -1 +0,0 @@
1
- export { usePositions } from "./usePositions";
@@ -1,11 +0,0 @@
1
- import type { AddPositionMarginRequest, AttachPositionTpSlRequest, AttachPositionTpSlResponse, ClosePositionRequest, ClosePositionResponse, GetPositionResponse, ListPositionHistoryParams, ListPositionHistoryResponse, ListPositionsParams, ListPositionsResponse, PositionMarginResponse, PositionRisk, ReducePositionMarginRequest } from "@0xmonaco/types";
2
- export interface UsePositionsReturn {
3
- listPositions: (params?: ListPositionsParams) => Promise<ListPositionsResponse>;
4
- getPosition: (positionId: string) => Promise<GetPositionResponse>;
5
- closePosition: (positionId: string, request: ClosePositionRequest) => Promise<ClosePositionResponse>;
6
- getPositionRisk: (positionId: string) => Promise<PositionRisk>;
7
- addPositionMargin: (positionId: string, request: AddPositionMarginRequest) => Promise<PositionMarginResponse>;
8
- reducePositionMargin: (positionId: string, request: ReducePositionMarginRequest) => Promise<PositionMarginResponse>;
9
- attachPositionTpSl: (positionId: string, request: AttachPositionTpSlRequest) => Promise<AttachPositionTpSlResponse>;
10
- listPositionHistory: (params?: ListPositionHistoryParams) => Promise<ListPositionHistoryResponse>;
11
- }
File without changes
@@ -1,2 +0,0 @@
1
- import type { UsePositionsReturn } from "./types";
2
- export declare const usePositions: () => UsePositionsReturn;
@@ -1,65 +0,0 @@
1
- import { useCallback } from "react";
2
- import { useMonacoSDK } from "../useMonaco";
3
- function requirePositionId(positionId) {
4
- if (!positionId?.trim())
5
- throw new Error("Position ID is required and cannot be empty");
6
- }
7
- export const usePositions = () => {
8
- const { sdk } = useMonacoSDK();
9
- const listPositions = useCallback(async (params) => {
10
- if (!sdk)
11
- throw new Error("SDK not available");
12
- return await sdk.positions.listPositions(params);
13
- }, [sdk]);
14
- const getPosition = useCallback(async (positionId) => {
15
- if (!sdk)
16
- throw new Error("SDK not available");
17
- requirePositionId(positionId);
18
- return await sdk.positions.getPosition(positionId);
19
- }, [sdk]);
20
- const closePosition = useCallback(async (positionId, request) => {
21
- if (!sdk)
22
- throw new Error("SDK not available");
23
- requirePositionId(positionId);
24
- return await sdk.positions.closePosition(positionId, request);
25
- }, [sdk]);
26
- const getPositionRisk = useCallback(async (positionId) => {
27
- if (!sdk)
28
- throw new Error("SDK not available");
29
- requirePositionId(positionId);
30
- return await sdk.positions.getPositionRisk(positionId);
31
- }, [sdk]);
32
- const addPositionMargin = useCallback(async (positionId, request) => {
33
- if (!sdk)
34
- throw new Error("SDK not available");
35
- requirePositionId(positionId);
36
- return await sdk.positions.addPositionMargin(positionId, request);
37
- }, [sdk]);
38
- const reducePositionMargin = useCallback(async (positionId, request) => {
39
- if (!sdk)
40
- throw new Error("SDK not available");
41
- requirePositionId(positionId);
42
- return await sdk.positions.reducePositionMargin(positionId, request);
43
- }, [sdk]);
44
- const attachPositionTpSl = useCallback(async (positionId, request) => {
45
- if (!sdk)
46
- throw new Error("SDK not available");
47
- requirePositionId(positionId);
48
- return await sdk.positions.attachPositionTpSl(positionId, request);
49
- }, [sdk]);
50
- const listPositionHistory = useCallback(async (params) => {
51
- if (!sdk)
52
- throw new Error("SDK not available");
53
- return await sdk.positions.listPositionHistory(params);
54
- }, [sdk]);
55
- return {
56
- listPositions,
57
- getPosition,
58
- closePosition,
59
- getPositionRisk,
60
- addPositionMargin,
61
- reducePositionMargin,
62
- attachPositionTpSl,
63
- listPositionHistory,
64
- };
65
- };
@@ -1,2 +0,0 @@
1
- export type { UseProfileReturn } from "./types";
2
- export { useProfile } from "./useProfile";
@@ -1 +0,0 @@
1
- export { useProfile } from "./useProfile";
@@ -1,23 +0,0 @@
1
- import type { AccountBalance, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, GetPaginatedUserMovementsResponse, GetUserBalancesParams, GetUserBalancesResponse, GetUserMovementsParams, UserProfile } from "@0xmonaco/types";
2
- export interface UseProfileReturn {
3
- /** User profile data (from /me — does not include balances, movements, or orders) */
4
- profile?: UserProfile;
5
- /** User's token balances (fetched from /balances) */
6
- balances: AccountBalance[];
7
- /** User's ledger movements (fetched from /movements) */
8
- movements: GetPaginatedUserMovementsResponse | undefined;
9
- /** User's orders (fetched from /orders) */
10
- orders: GetPaginatedOrdersResponse | undefined;
11
- /** Whether the initial profile + data fetch is in progress */
12
- loading: boolean;
13
- /** Fetch profile and first page of balances, movements, and orders */
14
- fetchProfile: () => Promise<UserProfile>;
15
- /** Get user's ledger movements (transaction history) with pagination */
16
- getPaginatedUserMovements: (params?: GetUserMovementsParams) => Promise<GetPaginatedUserMovementsResponse>;
17
- /** Get user's token balances with pagination */
18
- getUserBalances: (params?: GetUserBalancesParams) => Promise<GetUserBalancesResponse>;
19
- /** Get user's balance for a specific asset */
20
- getUserBalanceByAssetId: (assetId: string) => Promise<AccountBalance>;
21
- /** Get user's orders with pagination */
22
- getPaginatedOrders: (params?: GetPaginatedOrdersParams) => Promise<GetPaginatedOrdersResponse>;
23
- }
File without changes
@@ -1,2 +0,0 @@
1
- import type { UseProfileReturn } from "./types";
2
- export declare const useProfile: () => UseProfileReturn;
@@ -1,128 +0,0 @@
1
- import { useCallback, useEffect, useRef, useState } from "react";
2
- import { AuthenticationStatus } from "../../provider";
3
- import { useAuth } from "../useAuth";
4
- import { useMonacoSDK } from "../useMonaco";
5
- /** Default pagination page size used for initial fetches */
6
- const DEFAULT_PAGE_SIZE = 20;
7
- const getFulfilledValue = (result) => {
8
- return result.status === "fulfilled" ? result.value : undefined;
9
- };
10
- const getSettledValueOrThrow = (result) => {
11
- if (result.status === "fulfilled")
12
- return result.value;
13
- throw result.reason;
14
- };
15
- export const useProfile = () => {
16
- const { sdk } = useMonacoSDK();
17
- const { authenticationStatus } = useAuth();
18
- const [profile, setProfile] = useState();
19
- const [balances, setBalances] = useState([]);
20
- const [movements, setMovements] = useState();
21
- const [orders, setOrders] = useState();
22
- const [loading, setLoading] = useState(false);
23
- const isAuthenticatedRef = useRef(authenticationStatus === AuthenticationStatus.AUTHENTICATED);
24
- const authSessionVersionRef = useRef(0);
25
- const fetchProfileRequestIdRef = useRef(0);
26
- const canApplySessionState = useCallback((authSessionVersion) => {
27
- return isAuthenticatedRef.current && authSessionVersion === authSessionVersionRef.current;
28
- }, []);
29
- const canApplyFetchProfileState = useCallback((authSessionVersion, requestId) => {
30
- return canApplySessionState(authSessionVersion) && requestId === fetchProfileRequestIdRef.current;
31
- }, [canApplySessionState]);
32
- useEffect(() => {
33
- const isAuthenticated = authenticationStatus === AuthenticationStatus.AUTHENTICATED;
34
- isAuthenticatedRef.current = isAuthenticated;
35
- if (!isAuthenticated) {
36
- authSessionVersionRef.current += 1;
37
- fetchProfileRequestIdRef.current += 1;
38
- setProfile(undefined);
39
- setBalances([]);
40
- setMovements(undefined);
41
- setOrders(undefined);
42
- setLoading(false);
43
- }
44
- }, [authenticationStatus]);
45
- const fetchProfile = useCallback(async () => {
46
- if (!sdk)
47
- throw new Error("SDK not available");
48
- const authSessionVersion = authSessionVersionRef.current;
49
- const requestId = ++fetchProfileRequestIdRef.current;
50
- setLoading(true);
51
- try {
52
- const [userProfileResult, balancesResult, movementsResult, ordersResult] = await Promise.allSettled([
53
- sdk.profile.getProfile(),
54
- sdk.profile.getUserBalances({ page_size: DEFAULT_PAGE_SIZE, page: 1 }),
55
- sdk.profile.getPaginatedUserMovements({ page: 1, page_size: DEFAULT_PAGE_SIZE }),
56
- sdk.trading.getPaginatedOrders({ page: 1, page_size: DEFAULT_PAGE_SIZE }),
57
- ]);
58
- const userProfile = getSettledValueOrThrow(userProfileResult);
59
- const balances = getFulfilledValue(balancesResult);
60
- const userMovements = getFulfilledValue(movementsResult);
61
- const userOrders = getFulfilledValue(ordersResult);
62
- if (canApplyFetchProfileState(authSessionVersion, requestId)) {
63
- setProfile(userProfile);
64
- if (balances)
65
- setBalances(balances.balances);
66
- if (userMovements)
67
- setMovements(userMovements);
68
- if (userOrders)
69
- setOrders(userOrders);
70
- }
71
- return userProfile;
72
- }
73
- finally {
74
- if (requestId === fetchProfileRequestIdRef.current) {
75
- setLoading(false);
76
- }
77
- }
78
- }, [canApplyFetchProfileState, sdk]);
79
- const getPaginatedUserMovements = useCallback(async (params) => {
80
- if (!sdk)
81
- throw new Error("SDK not available");
82
- const authSessionVersion = authSessionVersionRef.current;
83
- const result = await sdk.profile.getPaginatedUserMovements(params);
84
- if (canApplySessionState(authSessionVersion)) {
85
- setMovements(result);
86
- }
87
- return result;
88
- }, [canApplySessionState, sdk]);
89
- const getUserBalances = useCallback(async (params) => {
90
- if (!sdk)
91
- throw new Error("SDK not available");
92
- const authSessionVersion = authSessionVersionRef.current;
93
- const result = await sdk.profile.getUserBalances(params);
94
- if (canApplySessionState(authSessionVersion)) {
95
- setBalances(result.balances);
96
- }
97
- return result;
98
- }, [canApplySessionState, sdk]);
99
- const getUserBalanceByAssetId = useCallback(async (assetId) => {
100
- if (!sdk)
101
- throw new Error("SDK not available");
102
- return await sdk.profile.getUserBalanceByAssetId(assetId);
103
- }, [sdk]);
104
- const getPaginatedOrders = useCallback(async (params) => {
105
- if (!sdk)
106
- throw new Error("SDK not available");
107
- const authSessionVersion = authSessionVersionRef.current;
108
- const result = await sdk.trading.getPaginatedOrders(params);
109
- if (canApplySessionState(authSessionVersion)) {
110
- setOrders(result);
111
- }
112
- return result;
113
- }, [canApplySessionState, sdk]);
114
- return {
115
- // State
116
- profile,
117
- balances,
118
- movements,
119
- orders,
120
- loading,
121
- // Actions
122
- fetchProfile,
123
- getPaginatedUserMovements,
124
- getUserBalances,
125
- getUserBalanceByAssetId,
126
- getPaginatedOrders,
127
- };
128
- };
@@ -1,2 +0,0 @@
1
- export type { TokenLifecycleConfig, UseTokenLifecycleReturn } from "./types";
2
- export { useTokenLifecycle } from "./useTokenLifecycle";
@@ -1 +0,0 @@
1
- export { useTokenLifecycle } from "./useTokenLifecycle";
@@ -1,23 +0,0 @@
1
- import type { AuthState } from "@0xmonaco/types";
2
- export interface TokenLifecycleConfig {
3
- /** Enable automatic token refresh (default: true) */
4
- autoRefresh?: boolean;
5
- /** Enable token persistence in localStorage (default: true) */
6
- persistTokens?: boolean;
7
- /** Buffer time in seconds before token expiry to trigger refresh (default: 300 = 5 minutes) */
8
- refreshBufferSeconds?: number;
9
- /** Callback when token refresh fails */
10
- onRefreshError?: (error: Error) => void;
11
- /** Callback when token is refreshed successfully */
12
- onRefreshSuccess?: (authState: AuthState) => void;
13
- }
14
- export interface UseTokenLifecycleReturn {
15
- /** Initialize token lifecycle with auth state */
16
- initializeTokens: (authState: AuthState) => void;
17
- /** Clear tokens and stop lifecycle management */
18
- clearTokens: () => void;
19
- /** Manually trigger token refresh */
20
- refreshTokens: () => Promise<AuthState | null>;
21
- /** Check if token is expired or near expiry */
22
- isTokenExpired: (authState: AuthState | null) => boolean;
23
- }
File without changes
@@ -1,20 +0,0 @@
1
- import type { MonacoSDK } from "@0xmonaco/core";
2
- import type { TokenLifecycleConfig, UseTokenLifecycleReturn } from "./types";
3
- /**
4
- * Hook for managing token lifecycle including automatic refresh and persistence
5
- *
6
- * @param sdk - Monaco SDK instance
7
- * @param config - Configuration options for token lifecycle
8
- * @returns Token lifecycle management functions
9
- *
10
- * @example
11
- * ```tsx
12
- * const { initializeTokens, clearTokens, refreshTokens } = useTokenLifecycle(sdk, {
13
- * autoRefresh: true,
14
- * persistTokens: true,
15
- * refreshBufferSeconds: 300, // 5 minutes
16
- * onRefreshError: (error) => console.error('Token refresh failed:', error),
17
- * });
18
- * ```
19
- */
20
- export declare const useTokenLifecycle: (sdk: MonacoSDK | null, config?: TokenLifecycleConfig) => UseTokenLifecycleReturn;
@@ -1,125 +0,0 @@
1
- import { useCallback, useEffect, useMemo, useRef } from "react";
2
- import { clearAuthState, getTimeUntilExpiry, isTokenExpired, saveAuthState } from "../../utils";
3
- import { validateRefreshBuffer } from "./utils";
4
- /**
5
- * Hook for managing token lifecycle including automatic refresh and persistence
6
- *
7
- * @param sdk - Monaco SDK instance
8
- * @param config - Configuration options for token lifecycle
9
- * @returns Token lifecycle management functions
10
- *
11
- * @example
12
- * ```tsx
13
- * const { initializeTokens, clearTokens, refreshTokens } = useTokenLifecycle(sdk, {
14
- * autoRefresh: true,
15
- * persistTokens: true,
16
- * refreshBufferSeconds: 300, // 5 minutes
17
- * onRefreshError: (error) => console.error('Token refresh failed:', error),
18
- * });
19
- * ```
20
- */
21
- export const useTokenLifecycle = (sdk, config = {}) => {
22
- const { autoRefresh = true, persistTokens = true, onRefreshError, onRefreshSuccess } = config;
23
- const refreshBufferSeconds = validateRefreshBuffer(config.refreshBufferSeconds);
24
- const refreshTimerRef = useRef(null);
25
- const currentAuthStateRef = useRef(null);
26
- const refreshPromiseRef = useRef(null);
27
- const clearRefreshTimer = useCallback(() => {
28
- if (refreshTimerRef.current) {
29
- clearTimeout(refreshTimerRef.current);
30
- refreshTimerRef.current = null;
31
- }
32
- }, []);
33
- const isTokenExpiredCheck = useCallback((authState) => {
34
- if (!authState)
35
- return true;
36
- return isTokenExpired(authState, refreshBufferSeconds);
37
- }, [refreshBufferSeconds]);
38
- const scheduleRefresh = useCallback((authState) => {
39
- if (!autoRefresh)
40
- return;
41
- clearRefreshTimer();
42
- const timeUntilExpiry = getTimeUntilExpiry(authState);
43
- const refreshIn = Math.max(0, timeUntilExpiry - refreshBufferSeconds);
44
- const refreshInMs = refreshIn * 1000;
45
- refreshTimerRef.current = setTimeout(() => {
46
- refreshTokensRef.current?.();
47
- }, refreshInMs);
48
- }, [autoRefresh, refreshBufferSeconds, clearRefreshTimer]);
49
- const refreshTokens = useCallback(async () => {
50
- if (!sdk)
51
- return null;
52
- if (refreshPromiseRef.current) {
53
- return refreshPromiseRef.current;
54
- }
55
- const currentAuthState = currentAuthStateRef.current;
56
- if (!currentAuthState?.refreshToken) {
57
- console.warn("No refresh token available for token refresh");
58
- return null;
59
- }
60
- const refreshPromise = (async () => {
61
- try {
62
- // Re-check SDK in case it became null during async operations
63
- if (!sdk) {
64
- console.warn("SDK became null during token refresh");
65
- return null;
66
- }
67
- const newAuthState = await sdk.refreshAuth();
68
- currentAuthStateRef.current = newAuthState;
69
- if (persistTokens) {
70
- saveAuthState(newAuthState);
71
- }
72
- scheduleRefresh(newAuthState);
73
- onRefreshSuccess?.(newAuthState);
74
- return newAuthState;
75
- }
76
- catch (error) {
77
- const err = error instanceof Error ? error : new Error(String(error));
78
- console.error("Failed to refresh tokens:", err);
79
- if (persistTokens) {
80
- clearAuthState();
81
- }
82
- currentAuthStateRef.current = null;
83
- clearRefreshTimer();
84
- onRefreshError?.(err);
85
- return null;
86
- }
87
- finally {
88
- refreshPromiseRef.current = null;
89
- }
90
- })();
91
- refreshPromiseRef.current = refreshPromise;
92
- return refreshPromise;
93
- }, [sdk, persistTokens, onRefreshError, onRefreshSuccess, scheduleRefresh, clearRefreshTimer]);
94
- const refreshTokensRef = useRef(refreshTokens);
95
- useEffect(() => {
96
- refreshTokensRef.current = refreshTokens;
97
- }, [refreshTokens]);
98
- const initializeTokens = useCallback((authState) => {
99
- currentAuthStateRef.current = authState;
100
- if (persistTokens) {
101
- saveAuthState(authState);
102
- }
103
- if (autoRefresh) {
104
- scheduleRefresh(authState);
105
- }
106
- }, [persistTokens, autoRefresh, scheduleRefresh]);
107
- const clearTokens = useCallback(() => {
108
- currentAuthStateRef.current = null;
109
- clearRefreshTimer();
110
- if (persistTokens) {
111
- clearAuthState();
112
- }
113
- }, [persistTokens, clearRefreshTimer]);
114
- useEffect(() => {
115
- return () => {
116
- clearRefreshTimer();
117
- };
118
- }, [clearRefreshTimer]);
119
- return useMemo(() => ({
120
- initializeTokens,
121
- clearTokens,
122
- refreshTokens,
123
- isTokenExpired: isTokenExpiredCheck,
124
- }), [initializeTokens, clearTokens, refreshTokens, isTokenExpiredCheck]);
125
- };
@@ -1,7 +0,0 @@
1
- /**
2
- * Validates and returns a safe refreshBufferSeconds value
3
- *
4
- * @param value - The refresh buffer value to validate (in seconds)
5
- * @returns A safe refresh buffer value between 1-3600 seconds
6
- */
7
- export declare const validateRefreshBuffer: (value: number | undefined) => number;
@@ -1,15 +0,0 @@
1
- /**
2
- * Validates and returns a safe refreshBufferSeconds value
3
- *
4
- * @param value - The refresh buffer value to validate (in seconds)
5
- * @returns A safe refresh buffer value between 1-3600 seconds
6
- */
7
- export const validateRefreshBuffer = (value) => {
8
- const defaultValue = 300;
9
- const buffer = value ?? defaultValue;
10
- if (buffer < 1 || buffer > 3600) {
11
- console.warn(`Invalid refreshBufferSeconds: ${buffer}. Must be between 1-3600 seconds. Using default: ${defaultValue}`);
12
- return defaultValue;
13
- }
14
- return buffer;
15
- };
@@ -1,2 +0,0 @@
1
- export type { UseTradeReturn } from "./types";
2
- export { useTrade } from "./useTrade";
@@ -1 +0,0 @@
1
- export { useTrade } from "./useTrade";
@@ -1,49 +0,0 @@
1
- import type { BatchCancelOrdersResponse, BatchCreateOrderParams, BatchCreateOrdersResponse, BatchReplaceOrderParams, BatchReplaceOrdersResponse, CancelConditionalOrderResponse, CancelOrderResponse, CreateConditionalOrderParams, CreateConditionalOrderResponse, CreateOrderResponse, GetOrderResponse, GetPaginatedOrdersParams, GetPaginatedOrdersResponse, ListConditionalOrdersParams, ListConditionalOrdersResponse, OrderSide, PositionSide, ReplaceOrderResponse, TimeInForce, TradingMode } from "@0xmonaco/types";
2
- export interface UseTradeReturn {
3
- /** Place a limit order */
4
- placeLimitOrder: (tradingPairId: string, side: OrderSide, quantity: string, price: string, options?: {
5
- tradingMode?: TradingMode;
6
- useMasterBalance?: boolean;
7
- expirationDate?: string;
8
- timeInForce?: TimeInForce;
9
- marginAccountId?: string;
10
- positionSide?: PositionSide;
11
- leverage?: string;
12
- reduceOnly?: boolean;
13
- }) => Promise<CreateOrderResponse>;
14
- /** Place a market order */
15
- placeMarketOrder: (tradingPairId: string, side: OrderSide, quantity: string, options?: {
16
- tradingMode?: TradingMode;
17
- slippageTolerance?: number;
18
- marginAccountId?: string;
19
- positionSide?: PositionSide;
20
- leverage?: string;
21
- reduceOnly?: boolean;
22
- }) => Promise<CreateOrderResponse>;
23
- /** Cancel an existing order */
24
- cancelOrder: (orderId: string) => Promise<CancelOrderResponse>;
25
- /** Create a standalone conditional TP/SL order */
26
- createConditionalOrder: (params: CreateConditionalOrderParams) => Promise<CreateConditionalOrderResponse>;
27
- /** Cancel an active conditional TP/SL order */
28
- cancelConditionalOrder: (conditionalOrderId: string) => Promise<CancelConditionalOrderResponse>;
29
- /** List conditional TP/SL orders */
30
- listConditionalOrders: (params?: ListConditionalOrdersParams) => Promise<ListConditionalOrdersResponse>;
31
- /** Batch cancel specific orders by their IDs */
32
- batchCancel: (orderIds: string[]) => Promise<BatchCancelOrdersResponse>;
33
- /** Cancel all active orders, optionally filtered by trading pair */
34
- batchCancelAll: (tradingPairId?: string) => Promise<BatchCancelOrdersResponse>;
35
- /** Replace an existing order */
36
- replaceOrder: (orderId: string, newOrder: {
37
- price?: string;
38
- quantity?: string;
39
- useMasterBalance?: boolean;
40
- }) => Promise<ReplaceOrderResponse>;
41
- /** Batch create multiple orders */
42
- batchCreate: (orders: BatchCreateOrderParams[]) => Promise<BatchCreateOrdersResponse>;
43
- /** Batch replace multiple orders */
44
- batchReplace: (orders: BatchReplaceOrderParams[]) => Promise<BatchReplaceOrdersResponse>;
45
- /** Get paginated orders */
46
- getPaginatedOrders: (params?: GetPaginatedOrdersParams) => Promise<GetPaginatedOrdersResponse>;
47
- /** Get a single order by ID */
48
- getOrder: (orderId: string) => Promise<GetOrderResponse>;
49
- }
File without changes
@@ -1,2 +0,0 @@
1
- import type { UseTradeReturn } from "./types";
2
- export declare const useTrade: () => UseTradeReturn;