@sodax/dapp-kit 0.0.1-rc.8 → 1.0.0-beta

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -60
  3. package/dist/index.d.mts +1558 -0
  4. package/dist/index.d.ts +1558 -4
  5. package/dist/index.js +1030 -135
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +988 -134
  8. package/dist/index.mjs.map +1 -1
  9. package/package.json +7 -8
  10. package/src/contexts/index.ts +3 -2
  11. package/src/hooks/backend/README.md +135 -0
  12. package/src/hooks/backend/index.ts +23 -0
  13. package/src/hooks/backend/useBackendAllMoneyMarketAssets.ts +49 -0
  14. package/src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts +61 -0
  15. package/src/hooks/backend/useBackendIntentByHash.ts +53 -0
  16. package/src/hooks/backend/useBackendIntentByTxHash.ts +57 -0
  17. package/src/hooks/backend/useBackendMoneyMarketAsset.ts +57 -0
  18. package/src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts +67 -0
  19. package/src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts +67 -0
  20. package/src/hooks/backend/useBackendMoneyMarketPosition.ts +56 -0
  21. package/src/hooks/backend/useBackendOrderbook.ts +63 -0
  22. package/src/hooks/bridge/index.ts +5 -0
  23. package/src/hooks/bridge/useBridge.ts +57 -0
  24. package/src/hooks/bridge/useBridgeAllowance.ts +49 -0
  25. package/src/hooks/bridge/useBridgeApprove.ts +68 -0
  26. package/src/hooks/bridge/useGetBridgeableAmount.ts +50 -0
  27. package/src/hooks/bridge/useGetBridgeableTokens.ts +62 -0
  28. package/src/hooks/index.ts +4 -0
  29. package/src/hooks/migrate/index.ts +4 -0
  30. package/src/hooks/migrate/types.ts +15 -0
  31. package/src/hooks/migrate/useMigrate.tsx +110 -0
  32. package/src/hooks/migrate/useMigrationAllowance.tsx +79 -0
  33. package/src/hooks/migrate/useMigrationApprove.tsx +129 -0
  34. package/src/hooks/mm/index.ts +2 -1
  35. package/src/hooks/mm/useAToken.ts +47 -0
  36. package/src/hooks/mm/useBorrow.ts +2 -2
  37. package/src/hooks/mm/useMMAllowance.ts +2 -1
  38. package/src/hooks/mm/useMMApprove.ts +2 -1
  39. package/src/hooks/mm/useRepay.ts +2 -2
  40. package/src/hooks/mm/useReservesData.ts +1 -8
  41. package/src/hooks/mm/useReservesHumanized.ts +30 -0
  42. package/src/hooks/mm/useReservesList.ts +29 -0
  43. package/src/hooks/mm/useReservesUsdFormat.ts +38 -0
  44. package/src/hooks/mm/useSupply.ts +2 -2
  45. package/src/hooks/mm/useUserFormattedSummary.ts +54 -0
  46. package/src/hooks/mm/useUserReservesData.ts +30 -37
  47. package/src/hooks/mm/useWithdraw.ts +2 -2
  48. package/src/hooks/provider/useHubProvider.ts +3 -3
  49. package/src/hooks/provider/useSpokeProvider.ts +50 -18
  50. package/src/hooks/shared/index.ts +4 -0
  51. package/src/hooks/shared/useDeriveUserWalletAddress.ts +44 -0
  52. package/src/hooks/shared/useEstimateGas.ts +18 -0
  53. package/src/hooks/shared/useRequestTrustline.ts +103 -0
  54. package/src/hooks/shared/useStellarTrustlineCheck.ts +71 -0
  55. package/src/hooks/staking/index.ts +19 -0
  56. package/src/hooks/staking/useCancelUnstake.ts +52 -0
  57. package/src/hooks/staking/useClaim.ts +46 -0
  58. package/src/hooks/staking/useConvertedAssets.ts +47 -0
  59. package/src/hooks/staking/useInstantUnstake.ts +50 -0
  60. package/src/hooks/staking/useInstantUnstakeAllowance.ts +59 -0
  61. package/src/hooks/staking/useInstantUnstakeApprove.ts +52 -0
  62. package/src/hooks/staking/useInstantUnstakeRatio.ts +54 -0
  63. package/src/hooks/staking/useStake.ts +47 -0
  64. package/src/hooks/staking/useStakeAllowance.ts +57 -0
  65. package/src/hooks/staking/useStakeApprove.ts +50 -0
  66. package/src/hooks/staking/useStakeRatio.ts +53 -0
  67. package/src/hooks/staking/useStakingConfig.ts +40 -0
  68. package/src/hooks/staking/useStakingInfo.ts +50 -0
  69. package/src/hooks/staking/useUnstake.ts +54 -0
  70. package/src/hooks/staking/useUnstakeAllowance.ts +58 -0
  71. package/src/hooks/staking/useUnstakeApprove.ts +52 -0
  72. package/src/hooks/staking/useUnstakingInfo.ts +53 -0
  73. package/src/hooks/staking/useUnstakingInfoWithPenalty.ts +59 -0
  74. package/src/hooks/swap/index.ts +2 -1
  75. package/src/hooks/swap/useCancelSwap.ts +44 -0
  76. package/src/hooks/swap/useQuote.ts +21 -7
  77. package/src/hooks/swap/useStatus.ts +4 -4
  78. package/src/hooks/swap/{useCreateIntentOrder.ts → useSwap.ts} +19 -14
  79. package/src/hooks/swap/useSwapAllowance.ts +5 -1
  80. package/src/hooks/swap/useSwapApprove.ts +14 -14
  81. package/src/index.ts +0 -1
  82. package/src/providers/SodaxProvider.tsx +8 -20
  83. package/dist/contexts/index.d.ts +0 -8
  84. package/dist/contexts/index.d.ts.map +0 -1
  85. package/dist/core/index.d.ts +0 -4
  86. package/dist/core/index.d.ts.map +0 -1
  87. package/dist/hooks/index.d.ts +0 -5
  88. package/dist/hooks/index.d.ts.map +0 -1
  89. package/dist/hooks/mm/index.d.ts +0 -10
  90. package/dist/hooks/mm/index.d.ts.map +0 -1
  91. package/dist/hooks/mm/useBorrow.d.ts +0 -35
  92. package/dist/hooks/mm/useBorrow.d.ts.map +0 -1
  93. package/dist/hooks/mm/useHubWalletAddress.d.ts +0 -24
  94. package/dist/hooks/mm/useHubWalletAddress.d.ts.map +0 -1
  95. package/dist/hooks/mm/useMMAllowance.d.ts +0 -26
  96. package/dist/hooks/mm/useMMAllowance.d.ts.map +0 -1
  97. package/dist/hooks/mm/useMMApprove.d.ts +0 -27
  98. package/dist/hooks/mm/useMMApprove.d.ts.map +0 -1
  99. package/dist/hooks/mm/useRepay.d.ts +0 -35
  100. package/dist/hooks/mm/useRepay.d.ts.map +0 -1
  101. package/dist/hooks/mm/useReservesData.d.ts +0 -19
  102. package/dist/hooks/mm/useReservesData.d.ts.map +0 -1
  103. package/dist/hooks/mm/useSupply.d.ts +0 -34
  104. package/dist/hooks/mm/useSupply.d.ts.map +0 -1
  105. package/dist/hooks/mm/useUserReservesData.d.ts +0 -9
  106. package/dist/hooks/mm/useUserReservesData.d.ts.map +0 -1
  107. package/dist/hooks/mm/useWithdraw.d.ts +0 -33
  108. package/dist/hooks/mm/useWithdraw.d.ts.map +0 -1
  109. package/dist/hooks/provider/index.d.ts +0 -3
  110. package/dist/hooks/provider/index.d.ts.map +0 -1
  111. package/dist/hooks/provider/useHubProvider.d.ts +0 -3
  112. package/dist/hooks/provider/useHubProvider.d.ts.map +0 -1
  113. package/dist/hooks/provider/useSpokeProvider.d.ts +0 -18
  114. package/dist/hooks/provider/useSpokeProvider.d.ts.map +0 -1
  115. package/dist/hooks/shared/index.d.ts +0 -2
  116. package/dist/hooks/shared/index.d.ts.map +0 -1
  117. package/dist/hooks/shared/useSodaxContext.d.ts +0 -8
  118. package/dist/hooks/shared/useSodaxContext.d.ts.map +0 -1
  119. package/dist/hooks/swap/index.d.ts +0 -6
  120. package/dist/hooks/swap/index.d.ts.map +0 -1
  121. package/dist/hooks/swap/useCreateIntentOrder.d.ts +0 -33
  122. package/dist/hooks/swap/useCreateIntentOrder.d.ts.map +0 -1
  123. package/dist/hooks/swap/useQuote.d.ts +0 -39
  124. package/dist/hooks/swap/useQuote.d.ts.map +0 -1
  125. package/dist/hooks/swap/useStatus.d.ts +0 -31
  126. package/dist/hooks/swap/useStatus.d.ts.map +0 -1
  127. package/dist/hooks/swap/useSwapAllowance.d.ts +0 -23
  128. package/dist/hooks/swap/useSwapAllowance.d.ts.map +0 -1
  129. package/dist/hooks/swap/useSwapApprove.d.ts +0 -26
  130. package/dist/hooks/swap/useSwapApprove.d.ts.map +0 -1
  131. package/dist/index.d.ts.map +0 -1
  132. package/dist/providers/SodaxProvider.d.ts +0 -10
  133. package/dist/providers/SodaxProvider.d.ts.map +0 -1
  134. package/dist/providers/index.d.ts +0 -2
  135. package/dist/providers/index.d.ts.map +0 -1
  136. package/src/core/index.ts +0 -35
  137. package/src/hooks/mm/useHubWalletAddress.ts +0 -49
@@ -0,0 +1,63 @@
1
+ // packages/dapp-kit/src/hooks/backend/useOrderbook.ts
2
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
+ import type { OrderbookResponse } from '@sodax/sdk';
4
+ import { useSodaxContext } from '../shared/useSodaxContext';
5
+
6
+ /**
7
+ * Hook for fetching the solver orderbook from the backend API.
8
+ *
9
+ * This hook provides access to the solver orderbook data, including intent states
10
+ * and intent data for all available intents. The data is automatically fetched
11
+ * and cached using React Query with pagination support.
12
+ *
13
+ * @param {Object} params - Pagination parameters for the orderbook
14
+ * @param {string} params.offset - The offset for pagination (number as string)
15
+ * @param {string} params.limit - The limit for pagination (number as string)
16
+ *
17
+ * @returns {UseQueryResult<OrderbookResponse | undefined>} A query result object containing:
18
+ * - data: The orderbook response data when available
19
+ * - isLoading: Boolean indicating if the request is in progress
20
+ * - error: Error object if the request failed
21
+ * - refetch: Function to manually trigger a data refresh
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const { data: orderbook, isLoading, error } = useOrderbook({
26
+ * offset: '0',
27
+ * limit: '10'
28
+ * });
29
+ *
30
+ * if (isLoading) return <div>Loading orderbook...</div>;
31
+ * if (error) return <div>Error: {error.message}</div>;
32
+ * if (orderbook) {
33
+ * console.log('Total intents:', orderbook.total);
34
+ * console.log('Intents:', orderbook.data);
35
+ * }
36
+ * ```
37
+ *
38
+ * @remarks
39
+ * - The query is disabled when params are undefined or invalid
40
+ * - Uses React Query for efficient caching and state management
41
+ * - Automatically handles error states and loading indicators
42
+ * - Stale time of 30 seconds for real-time orderbook data
43
+ * - Supports pagination through offset and limit parameters
44
+ */
45
+ export const useBackendOrderbook = (
46
+ params: { offset: string; limit: string } | undefined,
47
+ ): UseQueryResult<OrderbookResponse | undefined> => {
48
+ const { sodax } = useSodaxContext();
49
+
50
+ return useQuery({
51
+ queryKey: ['backend', 'solver', 'orderbook', params],
52
+ queryFn: async (): Promise<OrderbookResponse | undefined> => {
53
+ if (!params || !params.offset || !params.limit) {
54
+ return undefined;
55
+ }
56
+
57
+ return sodax.backendApi.getOrderbook(params);
58
+ },
59
+ enabled: !!params && !!params.offset && !!params.limit,
60
+ staleTime: 30 * 1000, // 30 seconds for real-time data
61
+ retry: 3,
62
+ });
63
+ };
@@ -0,0 +1,5 @@
1
+ export * from './useBridgeAllowance';
2
+ export * from './useBridgeApprove';
3
+ export * from './useBridge';
4
+ export * from './useGetBridgeableAmount';
5
+ export * from './useGetBridgeableTokens';
@@ -0,0 +1,57 @@
1
+ import { useSodaxContext } from '../shared/useSodaxContext';
2
+ import type { BridgeError, BridgeErrorCode, SpokeTxHash, HubTxHash, Result, CreateBridgeIntentParams } from '@sodax/sdk';
3
+ import { useMutation, type UseMutationResult } from '@tanstack/react-query';
4
+ import type { SpokeProvider } from '@sodax/sdk';
5
+
6
+ /**
7
+ * Hook for executing bridge transactions to transfer tokens between chains.
8
+ * Uses React Query's useMutation for better state management and caching.
9
+ *
10
+ * @param {SpokeProvider} spokeProvider - The spoke provider to use for the bridge
11
+ * @returns {UseMutationResult} Mutation result object containing mutation function and state
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const { mutateAsync: bridge, isPending } = useBridge(spokeProvider);
16
+ *
17
+ * const handleBridge = async () => {
18
+ * const result = await bridge({
19
+ * srcChainId: '0x2105.base',
20
+ * srcAsset: '0x...',
21
+ * amount: 1000n,
22
+ * dstChainId: '0x89.polygon',
23
+ * dstAsset: '0x...',
24
+ * recipient: '0x...'
25
+ * });
26
+ *
27
+ * console.log('Bridge transaction hashes:', {
28
+ * spokeTxHash: result.spokeTxHash,
29
+ * hubTxHash: result.hubTxHash
30
+ * });
31
+ * };
32
+ * ```
33
+ */
34
+ export function useBridge(
35
+ spokeProvider: SpokeProvider | undefined,
36
+ ): UseMutationResult<Result<[SpokeTxHash, HubTxHash], BridgeError<BridgeErrorCode>>, Error, CreateBridgeIntentParams> {
37
+ const { sodax } = useSodaxContext();
38
+
39
+ return useMutation<Result<[SpokeTxHash, HubTxHash], BridgeError<BridgeErrorCode>>, Error, CreateBridgeIntentParams>({
40
+ mutationFn: async (params: CreateBridgeIntentParams) => {
41
+ if (!spokeProvider) {
42
+ throw new Error('Spoke provider not found');
43
+ }
44
+
45
+ const result = await sodax.bridge.bridge({
46
+ params,
47
+ spokeProvider,
48
+ });
49
+
50
+ if (!result.ok) {
51
+ throw new Error(`Bridge failed: ${result.error.code}`);
52
+ }
53
+
54
+ return result;
55
+ },
56
+ });
57
+ }
@@ -0,0 +1,49 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import { useSodaxContext } from '../shared/useSodaxContext';
3
+ import type { SpokeProvider, CreateBridgeIntentParams } from '@sodax/sdk';
4
+
5
+ /**
6
+ * Hook for checking token allowance for bridge operations.
7
+ *
8
+ * This hook verifies if the user has approved enough tokens for a specific bridge action.
9
+ * It automatically queries and tracks the allowance status.
10
+ *
11
+ * @param {BridgeParams} params - The parameters for the bridge to check allowance for.
12
+ * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
13
+ *
14
+ * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
15
+ * - data: Boolean indicating if allowance is sufficient
16
+ * - isLoading: Loading state indicator
17
+ * - error: Any error that occurred during the check
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const { data: hasAllowed, isLoading } = useBridgeAllowance(params, spokeProvider);
22
+ * ```
23
+ */
24
+ export function useBridgeAllowance(
25
+ params: CreateBridgeIntentParams | undefined,
26
+ spokeProvider: SpokeProvider | undefined,
27
+ ): UseQueryResult<boolean, Error> {
28
+ const { sodax } = useSodaxContext();
29
+
30
+ return useQuery({
31
+ queryKey: ['bridge-allowance', params],
32
+ queryFn: async () => {
33
+ if (!spokeProvider || !params) {
34
+ return false;
35
+ }
36
+
37
+ const allowance = await sodax.bridge.isAllowanceValid({
38
+ params,
39
+ spokeProvider,
40
+ });
41
+
42
+ if (allowance.ok) {
43
+ return allowance.value;
44
+ }
45
+ return false;
46
+ },
47
+ enabled: !!spokeProvider && !!params,
48
+ });
49
+ }
@@ -0,0 +1,68 @@
1
+ import { useSodaxContext } from '../shared/useSodaxContext';
2
+ import type { CreateBridgeIntentParams, SpokeProvider } from '@sodax/sdk';
3
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
4
+
5
+ interface UseBridgeApproveReturn {
6
+ approve: (params: CreateBridgeIntentParams) => Promise<boolean>;
7
+ isLoading: boolean;
8
+ error: Error | null;
9
+ resetError: () => void;
10
+ }
11
+
12
+ /**
13
+ * Hook for approving token spending for bridge actions
14
+ * @param spokeProvider The spoke provider instance for the chain
15
+ * @returns Object containing approve function, loading state, error state and reset function
16
+ * @example
17
+ * ```tsx
18
+ * const { approve, isLoading, error } = useBridgeApprove(spokeProvider);
19
+ *
20
+ * // Approve tokens for bridge action
21
+ * await approve({
22
+ * srcChainId: '0x2105.base',
23
+ * srcAsset: '0x...',
24
+ * amount: 1000n,
25
+ * dstChainId: '0x89.polygon',
26
+ * dstAsset: '0x...',
27
+ * recipient: '0x...'
28
+ * });
29
+ * ```
30
+ */
31
+ export function useBridgeApprove(spokeProvider: SpokeProvider | undefined): UseBridgeApproveReturn {
32
+ const { sodax } = useSodaxContext();
33
+ const queryClient = useQueryClient();
34
+
35
+ const {
36
+ mutateAsync: approve,
37
+ isPending,
38
+ error,
39
+ reset: resetError,
40
+ } = useMutation({
41
+ mutationFn: async (params: CreateBridgeIntentParams) => {
42
+ if (!spokeProvider) {
43
+ throw new Error('Spoke provider not found');
44
+ }
45
+
46
+ const allowance = await sodax.bridge.approve({
47
+ params,
48
+ spokeProvider,
49
+ });
50
+
51
+ if (!allowance.ok) {
52
+ throw new Error('Failed to approve tokens for bridge');
53
+ }
54
+ return true;
55
+ },
56
+ onSuccess: (_, params) => {
57
+ // Invalidate allowance query to refetch the new allowance
58
+ queryClient.invalidateQueries({ queryKey: ['bridge-allowance', params] });
59
+ },
60
+ });
61
+
62
+ return {
63
+ approve,
64
+ isLoading: isPending,
65
+ error: error,
66
+ resetError,
67
+ };
68
+ }
@@ -0,0 +1,50 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import { useSodaxContext } from '../shared/useSodaxContext';
3
+ import type { XToken } from '@sodax/sdk';
4
+
5
+ /**
6
+ * Hook for getting the amount available to be bridged.
7
+ *
8
+ * This hook is used to check if a target chain has enough balance to bridge when bridging.
9
+ * It automatically queries and tracks the available amount to be bridged.
10
+ *
11
+ * @param {SpokeChainId | undefined} chainId - The chain ID to get the balance for
12
+ * @param {string | undefined} token - The token address to get the balance for
13
+ *
14
+ * @returns {UseQueryResult<bigint, Error>} A React Query result containing:
15
+ * - data: The available amount to be bridged (bigint)
16
+ * - error: Any error that occurred during the check
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const { data: balance, isLoading } = useSpokeAssetManagerTokenBalance(chainId, tokenAddress);
21
+ *
22
+ * if (balance) {
23
+ * console.log('Asset manager token balance:', balance.toString());
24
+ * }
25
+ * ```
26
+ */
27
+ export function useGetBridgeableAmount(
28
+ from: XToken | undefined,
29
+ to: XToken | undefined,
30
+ ): UseQueryResult<bigint, Error> {
31
+ const { sodax } = useSodaxContext();
32
+
33
+ return useQuery({
34
+ queryKey: ['spoke-asset-manager-token-balance', from, to],
35
+ queryFn: async () => {
36
+ if (!from || !to) {
37
+ return 0n;
38
+ }
39
+
40
+ const result = await sodax.bridge.getBridgeableAmount(from, to);
41
+ if (result.ok) {
42
+ return result.value;
43
+ }
44
+
45
+ console.error('Error getting bridgeable amount:', result.error);
46
+ return 0n;
47
+ },
48
+ enabled: !!from && !!to,
49
+ });
50
+ }
@@ -0,0 +1,62 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { XToken, SpokeChainId } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared';
4
+
5
+ /**
6
+ /**
7
+ * Hook for retrieving all bridgeable tokens from a source token on one chain to a destination chain.
8
+ *
9
+ * This hook queries and tracks the set of tokens on the destination chain that can be bridged to,
10
+ * given a source chain, destination chain, and source token address.
11
+ *
12
+ * @param {SpokeChainId | undefined} from - The source chain ID
13
+ * @param {SpokeChainId | undefined} to - The destination chain ID
14
+ * @param {string | undefined} token - The source token address
15
+ *
16
+ * @returns {UseQueryResult<XToken[], Error>} A React Query result containing:
17
+ * - data: Array of bridgeable tokens (XToken[]) on the destination chain
18
+ * - error: Any error that occurred during the query
19
+ *
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const { data: bridgeableTokens, isLoading } = useGetBridgeableTokens(
24
+ * fromChainId,
25
+ * toChainId,
26
+ * fromTokenAddress
27
+ * );
28
+ *
29
+ * if (bridgeableTokens && bridgeableTokens.length > 0) {
30
+ * bridgeableTokens.forEach(token => {
31
+ * console.log(`Bridgeable token: ${token.symbol} (${token.address}) on chain ${token.xChainId}`);
32
+ * });
33
+ * } else {
34
+ * console.log('No bridgeable tokens found for the selected route.');
35
+ * }
36
+ * ```
37
+ */
38
+ export function useGetBridgeableTokens(
39
+ from: SpokeChainId | undefined,
40
+ to: SpokeChainId | undefined,
41
+ token: string | undefined,
42
+ ): UseQueryResult<XToken[], Error> {
43
+ const { sodax } = useSodaxContext();
44
+
45
+ return useQuery({
46
+ queryKey: ['bridgeable-tokens', from, to, token],
47
+ queryFn: async () => {
48
+ if (!from || !to || !token) {
49
+ return [];
50
+ }
51
+
52
+ const result = sodax.bridge.getBridgeableTokens(from, to, token);
53
+ if (result.ok) {
54
+ return result.value;
55
+ }
56
+
57
+ console.error('Error getting bridgeable tokens:', result.error);
58
+ return [];
59
+ },
60
+ enabled: !!from && !!to && !!token,
61
+ });
62
+ }
@@ -2,3 +2,7 @@ export * from './shared';
2
2
  export * from './provider';
3
3
  export * from './mm';
4
4
  export * from './swap';
5
+ export * from './backend';
6
+ export * from './bridge';
7
+ export * from './staking';
8
+ export * from './migrate';
@@ -0,0 +1,4 @@
1
+ export { useMigrate } from './useMigrate';
2
+ export { useMigrationAllowance } from './useMigrationAllowance';
3
+ export { useMigrationApprove } from './useMigrationApprove';
4
+ export * from './types';
@@ -0,0 +1,15 @@
1
+ import type { XToken } from '@sodax/types';
2
+
3
+ export const MIGRATION_MODE_ICX_SODA = 'icxsoda';
4
+ export const MIGRATION_MODE_BNUSD = 'bnusd';
5
+
6
+ export type MigrationMode = typeof MIGRATION_MODE_ICX_SODA | typeof MIGRATION_MODE_BNUSD;
7
+
8
+ export interface MigrationIntentParams {
9
+ token: XToken | undefined;
10
+ amount: string | undefined;
11
+ sourceAddress: string | undefined;
12
+ migrationMode?: MigrationMode;
13
+ toToken?: XToken;
14
+ destinationAddress?: string;
15
+ }
@@ -0,0 +1,110 @@
1
+ import { parseUnits } from 'viem';
2
+ import {
3
+ spokeChainConfig,
4
+ type UnifiedBnUSDMigrateParams,
5
+ type IconSpokeProvider,
6
+ type SonicSpokeProvider,
7
+ isLegacybnUSDToken,
8
+ type SpokeProvider,
9
+ } from '@sodax/sdk';
10
+ import { type ChainId, ICON_MAINNET_CHAIN_ID } from '@sodax/types';
11
+ import { useSodaxContext } from '../shared/useSodaxContext';
12
+ import { useMutation, type UseMutationResult } from '@tanstack/react-query';
13
+ import { MIGRATION_MODE_BNUSD, MIGRATION_MODE_ICX_SODA, type MigrationIntentParams } from './types';
14
+
15
+ /**
16
+ * Hook for executing migration operations between chains.
17
+ *
18
+ * This hook handles ICX/SODA and bnUSD migrations by accepting a spoke provider
19
+ * and returning a mutation function that accepts migration parameters.
20
+ *
21
+ * @param {SpokeProvider} spokeProvider - The spoke provider to use for the migration
22
+ * @returns {UseMutationResult} Mutation result object containing migration function and state
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const { mutateAsync: migrate, isPending } = useMigrate(spokeProvider);
27
+ *
28
+ * const result = await migrate({
29
+ * token: { address: "0x...", decimals: 18 },
30
+ * amount: "100",
31
+ * migrationMode: MIGRATION_MODE_ICX_SODA,
32
+ * toToken: { address: "0x...", decimals: 18 },
33
+ * destinationAddress: "0x..."
34
+ * });
35
+ * ```
36
+ */
37
+ export function useMigrate(
38
+ spokeProvider: SpokeProvider | undefined,
39
+ ): UseMutationResult<{ spokeTxHash: string; hubTxHash: `0x${string}` }, Error, MigrationIntentParams> {
40
+ const { sodax } = useSodaxContext();
41
+
42
+ return useMutation({
43
+ mutationFn: async (params: MigrationIntentParams) => {
44
+ const { token, amount, migrationMode = MIGRATION_MODE_ICX_SODA, toToken, destinationAddress } = params;
45
+ const amountToMigrate = parseUnits(amount ?? '0', token?.decimals ?? 0);
46
+
47
+ if (!spokeProvider) {
48
+ throw new Error('Spoke provider not found');
49
+ }
50
+
51
+ if (migrationMode === MIGRATION_MODE_ICX_SODA) {
52
+ // ICX->SODA migration logic
53
+ if (token?.xChainId === ICON_MAINNET_CHAIN_ID) {
54
+ const params = {
55
+ address: spokeChainConfig[ICON_MAINNET_CHAIN_ID].nativeToken,
56
+ amount: amountToMigrate,
57
+ to: destinationAddress as `0x${string}`,
58
+ };
59
+ const result = await sodax.migration.migrateIcxToSoda(params, spokeProvider as IconSpokeProvider, 30000);
60
+ if (result.ok) {
61
+ const [spokeTxHash, hubTxHash] = result.value;
62
+ return { spokeTxHash, hubTxHash };
63
+ }
64
+ throw new Error('ICX to SODA migration failed. Please try again.');
65
+ }
66
+
67
+ // SODA->ICX migration
68
+ const revertParams = {
69
+ amount: amountToMigrate,
70
+ to: destinationAddress as `hx${string}`,
71
+ };
72
+ const result = await sodax.migration.revertMigrateSodaToIcx(
73
+ revertParams,
74
+ spokeProvider as SonicSpokeProvider,
75
+ 30000,
76
+ );
77
+ if (result.ok) {
78
+ const [hubTxHash, spokeTxHash] = result.value;
79
+ return { spokeTxHash, hubTxHash };
80
+ }
81
+ throw new Error('SODA to ICX migration failed. Please try again.');
82
+ }
83
+
84
+ if (migrationMode === MIGRATION_MODE_BNUSD) {
85
+ // bnUSD migration logic - handle dynamic source/destination chains
86
+ const params = {
87
+ srcChainId: token?.xChainId as ChainId,
88
+ dstChainId: toToken?.xChainId as ChainId,
89
+ srcbnUSD: token?.address as string,
90
+ dstbnUSD: toToken?.address as string,
91
+ amount: amountToMigrate,
92
+ to: destinationAddress as `hx${string}` | `0x${string}`,
93
+ } satisfies UnifiedBnUSDMigrateParams;
94
+
95
+ const result = await sodax.migration.migratebnUSD(params, spokeProvider, 30000);
96
+ if (result.ok) {
97
+ const [spokeTxHash, hubTxHash] = result.value;
98
+ return { spokeTxHash, hubTxHash };
99
+ }
100
+
101
+ const errorMessage = isLegacybnUSDToken(token?.address as string)
102
+ ? 'bnUSD migration failed. Please try again.'
103
+ : 'bnUSD reverse migration failed. Please try again.';
104
+ throw new Error(errorMessage);
105
+ }
106
+
107
+ throw new Error('Invalid migration mode');
108
+ },
109
+ });
110
+ }
@@ -0,0 +1,79 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { ChainId } from '@sodax/types';
3
+ import { useSodaxContext } from '../shared/useSodaxContext';
4
+ import { parseUnits } from 'viem';
5
+ import type { IcxCreateRevertMigrationParams, UnifiedBnUSDMigrateParams, SpokeProvider } from '@sodax/sdk';
6
+ import { ICON_MAINNET_CHAIN_ID } from '@sodax/types';
7
+ import { MIGRATION_MODE_ICX_SODA, type MigrationIntentParams } from './types';
8
+
9
+ /**
10
+ * Hook for checking token allowance for migration operations.
11
+ *
12
+ * This hook verifies if the user has approved enough tokens for migration operations.
13
+ * It handles both ICX/SODA and bnUSD migration allowance checks.
14
+ *
15
+ * @param {MigrationIntentParams} params - The parameters for the migration allowance check
16
+ * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
17
+ *
18
+ * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
19
+ * - data: Boolean indicating if allowance is sufficient
20
+ * - isLoading: Loading state indicator
21
+ * - error: Any error that occurred during the check
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const { data: hasAllowed, isLoading } = useMigrationAllowance(params, spokeProvider);
26
+ * ```
27
+ */
28
+ export function useMigrationAllowance(
29
+ params: MigrationIntentParams | undefined,
30
+ spokeProvider: SpokeProvider | undefined,
31
+ ): UseQueryResult<boolean, Error> {
32
+ const { sodax } = useSodaxContext();
33
+
34
+ return useQuery({
35
+ queryKey: ['migration-allowance', params],
36
+ queryFn: async () => {
37
+ if (!spokeProvider || !params) {
38
+ return false;
39
+ }
40
+
41
+ const { token, amount, migrationMode = MIGRATION_MODE_ICX_SODA, toToken, destinationAddress } = params;
42
+
43
+ // For ICON chain, no allowance is required (forward migrations)
44
+ if (token?.xChainId === ICON_MAINNET_CHAIN_ID) {
45
+ return true;
46
+ }
47
+
48
+ if (!spokeProvider) throw new Error('Spoke provider is required');
49
+ const amountToMigrate = parseUnits(amount ?? '0', token?.decimals ?? 0);
50
+
51
+ let migrationParams: IcxCreateRevertMigrationParams | UnifiedBnUSDMigrateParams;
52
+ if (migrationMode === MIGRATION_MODE_ICX_SODA) {
53
+ migrationParams = {
54
+ amount: amountToMigrate,
55
+ to: destinationAddress as `hx${string}`,
56
+ } satisfies IcxCreateRevertMigrationParams;
57
+ } else {
58
+ if (!toToken) throw new Error('Destination token is required for bnUSD migration');
59
+
60
+ migrationParams = {
61
+ srcChainId: token?.xChainId as ChainId,
62
+ dstChainId: toToken?.xChainId as ChainId,
63
+ srcbnUSD: token?.address as string,
64
+ dstbnUSD: toToken?.address as string,
65
+ amount: amountToMigrate,
66
+ to: destinationAddress as `hx${string}` | `0x${string}`,
67
+ } satisfies UnifiedBnUSDMigrateParams;
68
+ }
69
+
70
+ const allowance = await sodax.migration.isAllowanceValid(migrationParams, 'revert', spokeProvider);
71
+ if (allowance.ok) {
72
+ return allowance.value;
73
+ }
74
+ return false;
75
+ },
76
+ enabled: !!spokeProvider && !!params,
77
+ refetchInterval: 2000,
78
+ });
79
+ }