@sodax/dapp-kit 1.5.7-beta → 2.0.0-rc.1

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 (202) hide show
  1. package/README.md +300 -422
  2. package/ai-exported/AGENTS.md +134 -0
  3. package/ai-exported/integration/README.md +49 -0
  4. package/ai-exported/integration/ai-rules.md +79 -0
  5. package/ai-exported/integration/architecture.md +274 -0
  6. package/ai-exported/integration/features/README.md +29 -0
  7. package/ai-exported/integration/features/auxiliary-services.md +169 -0
  8. package/ai-exported/integration/features/bitcoin.md +87 -0
  9. package/ai-exported/integration/features/bridge.md +91 -0
  10. package/ai-exported/integration/features/dex.md +152 -0
  11. package/ai-exported/integration/features/migration.md +118 -0
  12. package/ai-exported/integration/features/money-market.md +116 -0
  13. package/ai-exported/integration/features/staking.md +123 -0
  14. package/ai-exported/integration/features/swap.md +101 -0
  15. package/ai-exported/integration/quickstart.md +187 -0
  16. package/ai-exported/integration/recipes/README.md +136 -0
  17. package/ai-exported/integration/recipes/backend-queries.md +157 -0
  18. package/ai-exported/integration/recipes/bitcoin.md +193 -0
  19. package/ai-exported/integration/recipes/bridge.md +174 -0
  20. package/ai-exported/integration/recipes/dex.md +204 -0
  21. package/ai-exported/integration/recipes/invalidations.md +115 -0
  22. package/ai-exported/integration/recipes/migration.md +212 -0
  23. package/ai-exported/integration/recipes/money-market.md +206 -0
  24. package/ai-exported/integration/recipes/mutation-error-handling.md +118 -0
  25. package/ai-exported/integration/recipes/observability.md +93 -0
  26. package/ai-exported/integration/recipes/setup.md +144 -0
  27. package/ai-exported/integration/recipes/staking.md +202 -0
  28. package/ai-exported/integration/recipes/swap.md +272 -0
  29. package/ai-exported/integration/recipes/wallet-connectivity.md +101 -0
  30. package/ai-exported/integration/reference/README.md +12 -0
  31. package/ai-exported/integration/reference/glossary.md +188 -0
  32. package/ai-exported/integration/reference/hooks-index.md +194 -0
  33. package/ai-exported/integration/reference/public-api.md +110 -0
  34. package/ai-exported/integration/reference/querykey-conventions.md +179 -0
  35. package/ai-exported/migration/README.md +60 -0
  36. package/ai-exported/migration/ai-rules.md +81 -0
  37. package/ai-exported/migration/breaking-changes/hook-signatures.md +233 -0
  38. package/ai-exported/migration/breaking-changes/querykey-conventions.md +108 -0
  39. package/ai-exported/migration/breaking-changes/result-handling.md +211 -0
  40. package/ai-exported/migration/breaking-changes/sdk-leakage.md +165 -0
  41. package/ai-exported/migration/checklist.md +89 -0
  42. package/ai-exported/migration/features/README.md +34 -0
  43. package/ai-exported/migration/features/auxiliary-services.md +114 -0
  44. package/ai-exported/migration/features/bitcoin.md +88 -0
  45. package/ai-exported/migration/features/bridge.md +123 -0
  46. package/ai-exported/migration/features/dex.md +101 -0
  47. package/ai-exported/migration/features/migration.md +120 -0
  48. package/ai-exported/migration/features/money-market.md +97 -0
  49. package/ai-exported/migration/features/staking.md +109 -0
  50. package/ai-exported/migration/features/swap.md +118 -0
  51. package/ai-exported/migration/recipes.md +188 -0
  52. package/ai-exported/migration/reference/README.md +15 -0
  53. package/ai-exported/migration/reference/deleted-hooks.md +110 -0
  54. package/ai-exported/migration/reference/error-shape-crosswalk.md +144 -0
  55. package/ai-exported/migration/reference/renamed-hooks.md +66 -0
  56. package/dist/index.cjs +2642 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +1550 -0
  59. package/dist/index.d.ts +1020 -2051
  60. package/dist/index.mjs +1581 -1531
  61. package/dist/index.mjs.map +1 -1
  62. package/package.json +20 -10
  63. package/src/contexts/index.ts +0 -3
  64. package/src/hooks/_mutationContract.test.ts +99 -0
  65. package/src/hooks/backend/README.md +2 -2
  66. package/src/hooks/backend/index.ts +13 -13
  67. package/src/hooks/backend/unwrapResult.ts +1 -0
  68. package/src/hooks/backend/useBackendAllMoneyMarketAssets.ts +13 -45
  69. package/src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts +29 -59
  70. package/src/hooks/backend/useBackendIntentByHash.ts +21 -47
  71. package/src/hooks/backend/useBackendIntentByTxHash.ts +23 -50
  72. package/src/hooks/backend/useBackendMoneyMarketAsset.ts +21 -54
  73. package/src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts +30 -57
  74. package/src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts +31 -58
  75. package/src/hooks/backend/useBackendMoneyMarketPosition.ts +22 -38
  76. package/src/hooks/backend/useBackendOrderbook.ts +27 -49
  77. package/src/hooks/backend/useBackendSubmitSwapTx.ts +30 -36
  78. package/src/hooks/backend/useBackendSubmitSwapTxStatus.ts +38 -58
  79. package/src/hooks/backend/useBackendUserIntents.ts +25 -63
  80. package/src/hooks/bitcoin/index.ts +9 -8
  81. package/src/hooks/bitcoin/useBitcoinBalance.ts +20 -5
  82. package/src/hooks/bitcoin/useExpiredUtxos.ts +26 -16
  83. package/src/hooks/bitcoin/useFundTradingWallet.ts +33 -30
  84. package/src/hooks/bitcoin/useRadfiAuth.ts +43 -40
  85. package/src/hooks/bitcoin/useRadfiSession.ts +53 -59
  86. package/src/hooks/bitcoin/useRadfiWithdraw.ts +35 -53
  87. package/src/hooks/bitcoin/useRenewUtxos.ts +30 -50
  88. package/src/hooks/bitcoin/useTradingWallet.ts +1 -1
  89. package/src/hooks/bitcoin/useTradingWalletBalance.ts +25 -14
  90. package/src/hooks/bridge/index.ts +5 -5
  91. package/src/hooks/bridge/useBridge.ts +29 -55
  92. package/src/hooks/bridge/useBridgeAllowance.ts +38 -38
  93. package/src/hooks/bridge/useBridgeApprove.ts +32 -57
  94. package/src/hooks/bridge/useGetBridgeableAmount.ts +23 -37
  95. package/src/hooks/bridge/useGetBridgeableTokens.ts +27 -50
  96. package/src/hooks/dex/index.ts +16 -16
  97. package/src/hooks/dex/useClaimRewards.ts +35 -54
  98. package/src/hooks/dex/useCreateDecreaseLiquidityParams.ts +7 -20
  99. package/src/hooks/dex/useCreateDepositParams.ts +7 -21
  100. package/src/hooks/dex/useCreateSupplyLiquidityParams.ts +13 -28
  101. package/src/hooks/dex/useCreateWithdrawParams.ts +7 -20
  102. package/src/hooks/dex/useDecreaseLiquidity.ts +40 -66
  103. package/src/hooks/dex/useDexAllowance.ts +29 -75
  104. package/src/hooks/dex/useDexApprove.ts +32 -43
  105. package/src/hooks/dex/useDexDeposit.ts +42 -49
  106. package/src/hooks/dex/useDexWithdraw.ts +32 -43
  107. package/src/hooks/dex/useLiquidityAmounts.ts +13 -82
  108. package/src/hooks/dex/usePoolBalances.ts +50 -72
  109. package/src/hooks/dex/usePoolData.ts +17 -43
  110. package/src/hooks/dex/usePools.ts +11 -38
  111. package/src/hooks/dex/usePositionInfo.ts +27 -62
  112. package/src/hooks/dex/useSupplyLiquidity.ts +80 -75
  113. package/src/hooks/index.ts +12 -10
  114. package/src/hooks/migrate/index.ts +13 -4
  115. package/src/hooks/migrate/useMigrateBaln.ts +42 -0
  116. package/src/hooks/migrate/useMigrateIcxToSoda.ts +44 -0
  117. package/src/hooks/migrate/useMigratebnUSD.ts +47 -0
  118. package/src/hooks/migrate/useMigrationAllowance.ts +76 -0
  119. package/src/hooks/migrate/useMigrationApprove.ts +66 -0
  120. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +39 -0
  121. package/src/hooks/mm/index.ts +14 -12
  122. package/src/hooks/mm/useAToken.ts +25 -41
  123. package/src/hooks/mm/useATokensBalances.ts +29 -60
  124. package/src/hooks/mm/useBorrow.ts +38 -56
  125. package/src/hooks/mm/useMMAllowance.ts +37 -73
  126. package/src/hooks/mm/useMMApprove.ts +36 -43
  127. package/src/hooks/mm/useRepay.ts +33 -53
  128. package/src/hooks/mm/useReservesData.ts +12 -38
  129. package/src/hooks/mm/useReservesHumanized.ts +12 -31
  130. package/src/hooks/mm/useReservesList.ts +11 -31
  131. package/src/hooks/mm/useReservesUsdFormat.ts +15 -35
  132. package/src/hooks/mm/useSupply.ts +45 -51
  133. package/src/hooks/mm/useUserFormattedSummary.ts +32 -84
  134. package/src/hooks/mm/useUserReservesData.ts +27 -77
  135. package/src/hooks/mm/useWithdraw.ts +38 -54
  136. package/src/hooks/partner/index.ts +6 -0
  137. package/src/hooks/partner/useApproveToken.ts +42 -0
  138. package/src/hooks/partner/useFeeClaimSwap.ts +38 -0
  139. package/src/hooks/partner/useFetchAssetsBalances.ts +37 -0
  140. package/src/hooks/partner/useGetAutoSwapPreferences.ts +37 -0
  141. package/src/hooks/partner/useIsTokenApproved.ts +39 -0
  142. package/src/hooks/partner/useSetSwapPreference.ts +50 -0
  143. package/src/hooks/provider/index.ts +1 -2
  144. package/src/hooks/provider/useHubProvider.ts +1 -1
  145. package/src/hooks/recovery/index.ts +2 -0
  146. package/src/hooks/recovery/useHubAssetBalances.ts +43 -0
  147. package/src/hooks/recovery/useWithdrawHubAsset.ts +48 -0
  148. package/src/hooks/shared/index.ts +10 -6
  149. package/src/hooks/shared/types.ts +77 -0
  150. package/src/hooks/shared/unwrapResult.ts +19 -0
  151. package/src/hooks/shared/useDeriveUserWalletAddress.ts +22 -40
  152. package/src/hooks/shared/useEstimateGas.ts +18 -15
  153. package/src/hooks/shared/useGetUserHubWalletAddress.ts +25 -26
  154. package/src/hooks/shared/useRequestTrustline.ts +28 -61
  155. package/src/hooks/shared/useSafeMutation.test.ts +43 -0
  156. package/src/hooks/shared/useSafeMutation.ts +68 -0
  157. package/src/hooks/shared/useSodaxContext.ts +1 -1
  158. package/src/hooks/shared/useStellarTrustlineCheck.ts +30 -64
  159. package/src/hooks/shared/useXBalances.test.ts +113 -0
  160. package/src/hooks/shared/useXBalances.ts +61 -0
  161. package/src/hooks/staking/index.ts +18 -18
  162. package/src/hooks/staking/useCancelUnstake.ts +30 -41
  163. package/src/hooks/staking/useClaim.ts +27 -36
  164. package/src/hooks/staking/useConvertedAssets.ts +24 -34
  165. package/src/hooks/staking/useInstantUnstake.ts +33 -40
  166. package/src/hooks/staking/useInstantUnstakeAllowance.ts +37 -45
  167. package/src/hooks/staking/useInstantUnstakeApprove.ts +42 -42
  168. package/src/hooks/staking/useInstantUnstakeRatio.ts +24 -41
  169. package/src/hooks/staking/useStake.ts +32 -37
  170. package/src/hooks/staking/useStakeAllowance.ts +30 -43
  171. package/src/hooks/staking/useStakeApprove.ts +40 -40
  172. package/src/hooks/staking/useStakeRatio.ts +24 -40
  173. package/src/hooks/staking/useStakingConfig.ts +14 -27
  174. package/src/hooks/staking/useStakingInfo.ts +30 -38
  175. package/src/hooks/staking/useUnstake.ts +29 -43
  176. package/src/hooks/staking/useUnstakeAllowance.ts +37 -44
  177. package/src/hooks/staking/useUnstakeApprove.ts +40 -43
  178. package/src/hooks/staking/useUnstakingInfo.ts +29 -41
  179. package/src/hooks/staking/useUnstakingInfoWithPenalty.ts +31 -47
  180. package/src/hooks/swap/index.ts +8 -8
  181. package/src/hooks/swap/useCancelLimitOrder.ts +24 -41
  182. package/src/hooks/swap/useCancelSwap.ts +24 -33
  183. package/src/hooks/swap/useCreateLimitOrder.ts +29 -62
  184. package/src/hooks/swap/useQuote.ts +17 -43
  185. package/src/hooks/swap/useStatus.ts +22 -29
  186. package/src/hooks/swap/useSwap.ts +31 -49
  187. package/src/hooks/swap/useSwapAllowance.ts +38 -35
  188. package/src/hooks/swap/useSwapApprove.ts +48 -57
  189. package/src/index.ts +5 -3
  190. package/src/providers/SodaxProvider.tsx +17 -11
  191. package/src/providers/createSodaxQueryClient.ts +96 -0
  192. package/src/providers/index.ts +2 -1
  193. package/src/utils/dex-utils.ts +27 -5
  194. package/src/utils/index.ts +1 -1
  195. package/dist/index.d.mts +0 -2581
  196. package/dist/index.js +0 -2574
  197. package/dist/index.js.map +0 -1
  198. package/src/hooks/migrate/types.ts +0 -15
  199. package/src/hooks/migrate/useMigrate.tsx +0 -110
  200. package/src/hooks/migrate/useMigrationAllowance.tsx +0 -79
  201. package/src/hooks/migrate/useMigrationApprove.tsx +0 -129
  202. package/src/hooks/provider/useSpokeProvider.ts +0 -172
@@ -1,58 +1,51 @@
1
- // packages/dapp-kit/src/hooks/staking/useStakeAllowance.ts
2
- import { useSodaxContext } from '../shared/useSodaxContext';
3
- import type { UnstakeParams, SpokeProvider } from '@sodax/sdk';
1
+ import type { UnstakeParams } from '@sodax/sdk';
2
+ import type { SpokeChainKey } from '@sodax/sdk';
4
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<
8
+ boolean,
9
+ {
10
+ payload: Omit<UnstakeParams<K>, 'action'> | undefined;
11
+ }
12
+ >;
5
13
 
6
14
  /**
7
- * Hook for checking xSODA token allowance for unstaking operations.
8
- * Uses React Query for efficient caching and state management.
9
- *
10
- * @param {Omit<UnstakeParams, 'action'> | undefined} params - The unstaking parameters. If undefined, the query will be disabled.
11
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check
12
- * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state
13
- *
14
- * @example
15
- * ```typescript
16
- * const { data: hasAllowed, isLoading } = useUnstakeAllowance(
17
- * {
18
- * amount: 1000000000000000000n, // 1 xSODA
19
- * account: '0x...'
20
- * },
21
- * spokeProvider
22
- * );
23
- *
24
- * if (isLoading) return <div>Checking allowance...</div>;
25
- * if (hasAllowed) {
26
- * console.log('Sufficient allowance for unstaking');
27
- * }
28
- * ```
15
+ * React hook to check whether the user has approved sufficient xSODA spending for the unstake
16
+ * action. Read-only calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`
17
+ * is required.
29
18
  */
30
- export function useUnstakeAllowance(
31
- params: Omit<UnstakeParams, 'action'> | undefined,
32
- spokeProvider: SpokeProvider | undefined,
33
- ): UseQueryResult<boolean, Error> {
19
+ export function useUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({
20
+ params,
21
+ queryOptions,
22
+ }: UseUnstakeAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {
34
23
  const { sodax } = useSodaxContext();
24
+ const payload = params?.payload;
35
25
 
36
- return useQuery({
37
- queryKey: ['soda', 'unstakeAllowance', params, spokeProvider?.chainConfig.chain.id],
26
+ return useQuery<boolean, Error>({
27
+ queryKey: [
28
+ 'staking',
29
+ 'allowance',
30
+ payload?.srcChainKey,
31
+ 'unstake',
32
+ payload?.srcAddress,
33
+ payload?.amount?.toString(),
34
+ ],
38
35
  queryFn: async () => {
39
- if (!params || !spokeProvider) {
40
- return false;
36
+ if (!payload) {
37
+ throw new Error('Params are required');
41
38
  }
42
-
43
39
  const result = await sodax.staking.isAllowanceValid({
44
- params: { ...params, action: 'unstake' },
45
- spokeProvider,
40
+ params: { ...payload, action: 'unstake' },
41
+ raw: true,
46
42
  });
47
-
48
- if (!result.ok) {
49
- console.error(`Unstake allowance check failed: ${result.error.code}, error: ${result.error.error}`);
50
- throw new Error(`Unstake allowance check failed: ${result.error.code}`);
51
- }
52
-
43
+ if (!result.ok) throw result.error;
53
44
  return result.value;
54
45
  },
55
- enabled: !!params && !!spokeProvider,
56
- refetchInterval: 5000, // Refetch every 5 seconds
46
+ enabled: !!payload,
47
+ refetchInterval: 5_000,
48
+ gcTime: 0,
49
+ ...queryOptions,
57
50
  });
58
51
  }
@@ -1,52 +1,49 @@
1
- // packages/dapp-kit/src/hooks/staking/useStakeApprove.ts
2
- import { useSodaxContext } from '../shared/useSodaxContext';
3
- import type { TxReturnType, UnstakeParams } from '@sodax/sdk';
4
- import { useMutation, type UseMutationResult } from '@tanstack/react-query';
5
- import type { SpokeProvider } from '@sodax/sdk';
1
+ // packages/dapp-kit/src/hooks/staking/useUnstakeApprove.ts
2
+ import type { GetWalletProviderType, SpokeChainKey, TxReturnType, UnstakeParams } from '@sodax/sdk';
3
+ import { useQueryClient } from '@tanstack/react-query';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import type { MutationHookParams } from '../shared/types.js';
6
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
7
+ import { unwrapResult } from '../shared/unwrapResult.js';
6
8
 
7
9
  /**
8
- * Hook for approving xSODA token spending for unstaking operations.
9
- * Uses React Query's useMutation for better state management and caching.
10
- *
11
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval
12
- * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>} Mutation result object containing mutation function and state
13
- *
14
- * @example
15
- * ```typescript
16
- * const { mutateAsync: approve, isPending } = useUnstakeApprove(spokeProvider);
17
- *
18
- * const handleApprove = async () => {
19
- * const result = await approve({
20
- * amount: 1000000000000000000n, // 1 xSODA
21
- * account: '0x...'
22
- * });
10
+ * Mutation variables for {@link useUnstakeApprove}. The `action` literal is injected by the hook.
11
+ */
12
+ export type UseUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
13
+ params: Omit<UnstakeParams<K>, 'action'>;
14
+ walletProvider: GetWalletProviderType<K>;
15
+ };
16
+
17
+ /**
18
+ * React hook for approving xSODA spending on the unstake action.
23
19
  *
24
- * console.log('Approval successful:', result);
25
- * };
26
- * ```
20
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
21
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
27
22
  */
28
- export function useUnstakeApprove(
29
- spokeProvider: SpokeProvider | undefined,
30
- ): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>> {
23
+ export function useUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({
24
+ mutationOptions,
25
+ }: MutationHookParams<TxReturnType<K, false>, UseUnstakeApproveVars<K>> = {}): SafeUseMutationResult<
26
+ TxReturnType<K, false>,
27
+ Error,
28
+ UseUnstakeApproveVars<K>
29
+ > {
31
30
  const { sodax } = useSodaxContext();
31
+ const queryClient = useQueryClient();
32
32
 
33
- return useMutation<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>({
34
- mutationFn: async (params: Omit<UnstakeParams, 'action'>) => {
35
- console.log('useUnstakeApprove called with params:', params);
36
- if (!spokeProvider) {
37
- throw new Error('Spoke provider not found');
38
- }
39
-
40
- const result = await sodax.staking.approve({
41
- params: { ...params, action: 'unstake' },
42
- spokeProvider,
43
- });
44
-
45
- if (!result.ok) {
46
- throw new Error(`Unstake approval failed: ${result.error.code}`);
47
- }
48
-
49
- return result.value;
33
+ return useSafeMutation<TxReturnType<K, false>, Error, UseUnstakeApproveVars<K>>({
34
+ mutationKey: ['staking', 'approve', 'unstake'],
35
+ ...mutationOptions,
36
+ mutationFn: async ({ params, walletProvider }) =>
37
+ unwrapResult(
38
+ await sodax.staking.approve({
39
+ params: { ...params, action: 'unstake' },
40
+ raw: false,
41
+ walletProvider,
42
+ }),
43
+ ),
44
+ onSuccess: async (data, vars, ctx) => {
45
+ queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', vars.params.srcChainKey, 'unstake'] });
46
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
50
47
  },
51
48
  });
52
49
  }
@@ -1,53 +1,41 @@
1
- // packages/dapp-kit/src/hooks/staking/useUnstakingInfoWithPenalty.ts
2
- import { useSodaxContext } from '../shared/useSodaxContext';
3
- import type { UnstakingInfo, SpokeProvider } from '@sodax/sdk';
1
+ import type { UnstakingInfo } from '@sodax/sdk';
2
+ import type { SpokeChainKey } from '@sodax/sdk';
4
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseUnstakingInfoParams = ReadHookParams<
8
+ UnstakingInfo,
9
+ {
10
+ srcAddress: `0x${string}` | undefined;
11
+ srcChainKey: SpokeChainKey | undefined;
12
+ }
13
+ >;
5
14
 
6
15
  /**
7
- * Hook for fetching unstaking information from the stakedSoda contract.
8
- * Uses React Query for efficient caching and state management.
9
- *
10
- * @param {string | undefined} userAddress - The user address to fetch unstaking info for
11
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance
12
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)
13
- * @returns {UseQueryResult<UnstakingInfo, Error>} Query result object containing unstaking info and state
14
- *
15
- * @example
16
- * ```typescript
17
- * const { data: unstakingInfo, isLoading, error } = useUnstakingInfo(userAddress, spokeProvider);
18
- *
19
- * if (isLoading) return <div>Loading unstaking info...</div>;
20
- * if (unstakingInfo) {
21
- * console.log('Total unstaking:', unstakingInfo.totalUnstaking);
22
- * unstakingInfo.userUnstakeSodaRequests.forEach(request => {
23
- * console.log('Request amount:', request.request.amount);
24
- * });
25
- * }
26
- * ```
16
+ * React hook to fetch the user's pending unstake requests by deriving the hub wallet from the
17
+ * spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
27
18
  */
28
- export function useUnstakingInfo(
29
- userAddress: string | undefined,
30
- spokeProvider: SpokeProvider | undefined,
31
- refetchInterval = 5000,
32
- ): UseQueryResult<UnstakingInfo, Error> {
19
+ export function useUnstakingInfo({
20
+ params,
21
+ queryOptions,
22
+ }: UseUnstakingInfoParams = {}): UseQueryResult<UnstakingInfo, Error> {
33
23
  const { sodax } = useSodaxContext();
24
+ const srcAddress = params?.srcAddress;
25
+ const srcChainKey = params?.srcChainKey;
34
26
 
35
- return useQuery({
36
- queryKey: ['soda', 'unstakingInfoWithPenalty', spokeProvider?.chainConfig.chain.id, userAddress],
27
+ return useQuery<UnstakingInfo, Error>({
28
+ queryKey: ['staking', 'unstakingInfo', srcChainKey, srcAddress],
37
29
  queryFn: async () => {
38
- if (!spokeProvider || !userAddress) {
39
- throw new Error('Spoke provider or user address not found');
30
+ if (!srcAddress || !srcChainKey) {
31
+ throw new Error('srcAddress and srcChainKey are required');
40
32
  }
41
-
42
- const result = await sodax.staking.getUnstakingInfo(spokeProvider);
43
-
44
- if (!result.ok) {
45
- throw new Error(`Failed to fetch unstaking info: ${result.error.code}`);
46
- }
47
-
33
+ const result = await sodax.staking.getUnstakingInfo(srcAddress, srcChainKey);
34
+ if (!result.ok) throw result.error;
48
35
  return result.value;
49
36
  },
50
- enabled: !!spokeProvider && !!userAddress,
51
- refetchInterval,
37
+ enabled: !!srcAddress && !!srcChainKey,
38
+ refetchInterval: 5_000,
39
+ ...queryOptions,
52
40
  });
53
41
  }
@@ -1,59 +1,43 @@
1
- // packages/dapp-kit/src/hooks/staking/useUnstakingInfoWithPenalty.ts
2
- import { useSodaxContext } from '../shared/useSodaxContext';
3
- import type { UnstakingInfo, UnstakeRequestWithPenalty, SpokeProvider } from '@sodax/sdk';
1
+ import type { UnstakeRequestWithPenalty, UnstakingInfo } from '@sodax/sdk';
2
+ import type { SpokeChainKey } from '@sodax/sdk';
4
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
5
6
 
6
- export type UnstakingInfoWithPenalty = UnstakingInfo & {
7
- requestsWithPenalty: UnstakeRequestWithPenalty[];
8
- };
7
+ export type UnstakingInfoWithPenalty = UnstakingInfo & { requestsWithPenalty: UnstakeRequestWithPenalty[] };
8
+
9
+ export type UseUnstakingInfoWithPenaltyParams = ReadHookParams<
10
+ UnstakingInfoWithPenalty,
11
+ {
12
+ srcAddress: `0x${string}` | undefined;
13
+ srcChainKey: SpokeChainKey | undefined;
14
+ }
15
+ >;
9
16
 
10
17
  /**
11
- * Hook for fetching unstaking information with penalty calculations from the stakedSoda contract.
12
- * Uses React Query for efficient caching and state management.
13
- *
14
- * @param {string | undefined} userAddress - The user address to fetch unstaking info for
15
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance
16
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)
17
- * @returns {UseQueryResult<UnstakingInfoWithPenalty, Error>} Query result object containing unstaking info with penalties and state
18
- *
19
- * @example
20
- * ```typescript
21
- * const { data: unstakingInfo, isLoading, error } = useUnstakingInfoWithPenalty(userAddress, spokeProvider);
22
- *
23
- * if (isLoading) return <div>Loading unstaking info...</div>;
24
- * if (unstakingInfo) {
25
- * console.log('Total unstaking:', unstakingInfo.totalUnstaking);
26
- * unstakingInfo.requestsWithPenalty.forEach(request => {
27
- * console.log('Penalty:', request.penaltyPercentage + '%');
28
- * console.log('Claimable amount:', request.claimableAmount);
29
- * });
30
- * }
31
- * ```
18
+ * React hook to fetch the user's pending unstake requests **with computed early-exit penalties**
19
+ * by deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
32
20
  */
33
- export function useUnstakingInfoWithPenalty(
34
- userAddress: string | undefined,
35
- spokeProvider: SpokeProvider | undefined,
36
- refetchInterval = 5000,
37
- ): UseQueryResult<UnstakingInfoWithPenalty, Error> {
21
+ export function useUnstakingInfoWithPenalty({
22
+ params,
23
+ queryOptions,
24
+ }: UseUnstakingInfoWithPenaltyParams = {}): UseQueryResult<UnstakingInfoWithPenalty, Error> {
38
25
  const { sodax } = useSodaxContext();
26
+ const srcAddress = params?.srcAddress;
27
+ const srcChainKey = params?.srcChainKey;
39
28
 
40
- return useQuery({
41
- queryKey: ['soda', 'unstakingInfoWithPenalty', spokeProvider?.chainConfig.chain.id, userAddress],
29
+ return useQuery<UnstakingInfoWithPenalty, Error>({
30
+ queryKey: ['staking', 'unstakingInfoWithPenalty', srcChainKey, srcAddress],
42
31
  queryFn: async () => {
43
- if (!spokeProvider) {
44
- throw new Error('Spoke provider not found');
32
+ if (!srcAddress || !srcChainKey) {
33
+ throw new Error('srcAddress and srcChainKey are required');
45
34
  }
46
-
47
- // Get unstaking info with penalty calculations
48
- const penaltyResult = await sodax.staking.getUnstakingInfoWithPenalty(spokeProvider);
49
-
50
- if (!penaltyResult.ok) {
51
- throw new Error(`Failed to fetch unstaking info with penalty: ${penaltyResult.error.code}`);
52
- }
53
-
54
- return penaltyResult.value;
35
+ const result = await sodax.staking.getUnstakingInfoWithPenalty(srcAddress, srcChainKey);
36
+ if (!result.ok) throw result.error;
37
+ return result.value;
55
38
  },
56
- enabled: !!spokeProvider && !!userAddress,
57
- refetchInterval,
39
+ enabled: !!srcAddress && !!srcChainKey,
40
+ refetchInterval: 5_000,
41
+ ...queryOptions,
58
42
  });
59
43
  }
@@ -1,8 +1,8 @@
1
- export * from './useQuote';
2
- export * from './useSwap';
3
- export * from './useStatus';
4
- export * from './useSwapAllowance';
5
- export * from './useSwapApprove';
6
- export * from './useCancelSwap';
7
- export * from './useCreateLimitOrder';
8
- export * from './useCancelLimitOrder';
1
+ export * from './useQuote.js';
2
+ export * from './useSwap.js';
3
+ export * from './useStatus.js';
4
+ export * from './useSwapAllowance.js';
5
+ export * from './useSwapApprove.js';
6
+ export * from './useCancelSwap.js';
7
+ export * from './useCreateLimitOrder.js';
8
+ export * from './useCancelLimitOrder.js';
@@ -1,53 +1,36 @@
1
- import { useSodaxContext } from '../shared/useSodaxContext';
2
- import type { Intent, IntentError, IntentErrorCode, Result, SpokeProvider } from '@sodax/sdk';
3
- import { useMutation, type UseMutationResult } from '@tanstack/react-query';
1
+ // packages/dapp-kit/src/hooks/swap/useCancelLimitOrder.ts
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
7
 
5
- type CancelLimitOrderParams = {
8
+ type CancelLimitOrderParams<K extends SpokeChainKey = SpokeChainKey> = {
9
+ srcChainKey: K;
10
+ walletProvider: GetWalletProviderType<K>;
6
11
  intent: Intent;
7
- spokeProvider: SpokeProvider;
8
12
  timeout?: number;
9
13
  };
10
14
 
11
- type CancelLimitOrderResult = Result<[string, string], IntentError<IntentErrorCode>>;
12
-
13
15
  /**
14
- * Hook for canceling a limit order intent and submitting it to the Relayer API.
15
- * Uses React Query's useMutation for better state management and caching.
16
- *
17
- * This hook wraps cancelLimitOrder which cancels the intent on the spoke chain,
18
- * submits it to the relayer API, and waits for execution on the destination/hub chain.
19
- *
20
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
21
- *
22
- * @example
23
- * ```typescript
24
- * const { mutateAsync: cancelLimitOrder, isPending } = useCancelLimitOrder();
25
- *
26
- * const handleCancelLimitOrder = async () => {
27
- * const result = await cancelLimitOrder({
28
- * intent: intentObject,
29
- * spokeProvider,
30
- * timeout: 60000 // optional, defaults to 60 seconds
31
- * });
16
+ * React hook for cancelling a limit-order intent.
32
17
  *
33
- * if (result.ok) {
34
- * const [cancelTxHash, dstTxHash] = result.value;
35
- * console.log('Cancel transaction hash:', cancelTxHash);
36
- * console.log('Destination transaction hash:', dstTxHash);
37
- * }
38
- * };
39
- * ```
18
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
19
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
40
20
  */
41
- export function useCancelLimitOrder(): UseMutationResult<CancelLimitOrderResult, Error, CancelLimitOrderParams> {
21
+ export function useCancelLimitOrder({
22
+ mutationOptions,
23
+ }: MutationHookParams<TxHashPair, CancelLimitOrderParams> = {}): SafeUseMutationResult<
24
+ TxHashPair,
25
+ Error,
26
+ CancelLimitOrderParams
27
+ > {
42
28
  const { sodax } = useSodaxContext();
43
29
 
44
- return useMutation<CancelLimitOrderResult, Error, CancelLimitOrderParams>({
45
- mutationFn: async ({ intent, spokeProvider, timeout }: CancelLimitOrderParams): Promise<CancelLimitOrderResult> => {
46
- return sodax.swaps.cancelLimitOrder({
47
- intent,
48
- spokeProvider,
49
- timeout,
50
- });
51
- },
30
+ return useSafeMutation<TxHashPair, Error, CancelLimitOrderParams>({
31
+ mutationKey: ['swap', 'limitOrder', 'cancel'],
32
+ ...mutationOptions,
33
+ mutationFn: async ({ srcChainKey, walletProvider, intent, timeout }) =>
34
+ unwrapResult(await sodax.swaps.cancelLimitOrder({ params: { srcChainKey, intent }, walletProvider, timeout })),
52
35
  });
53
36
  }
@@ -1,44 +1,35 @@
1
- import { useSodaxContext } from '../shared/useSodaxContext';
2
- import type { Intent, Result, SpokeProvider, TxReturnType } from '@sodax/sdk';
3
- import { useMutation, type UseMutationResult } from '@tanstack/react-query';
1
+ // packages/dapp-kit/src/hooks/swap/useCancelSwap.ts
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
7
 
5
- type CancelIntentParams = {
8
+ type CancelIntentParams<K extends SpokeChainKey = SpokeChainKey> = {
9
+ srcChainKey: K;
10
+ walletProvider: GetWalletProviderType<K>;
6
11
  intent: Intent;
7
- raw?: boolean;
8
12
  };
9
13
 
10
- type CancelIntentResult = Result<TxReturnType<SpokeProvider, boolean>>;
11
-
12
14
  /**
13
- * Hook for canceling a swap intent order.
14
- * Uses React Query's useMutation for better state management and caching.
15
- *
16
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for canceling the intent
17
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
18
- *
19
- * @example
20
- * ```typescript
21
- * const { mutateAsync: cancelSwap, isPending } = useCancelSwap(spokeProvider);
15
+ * React hook for cancelling an in-flight swap intent.
22
16
  *
23
- * const handleCancelSwap = async () => {
24
- * const result = await cancelSwap({
25
- * intent: intentObject,
26
- * raw: false // optional, defaults to false
27
- * });
28
- * };
29
- * ```
17
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
18
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
30
19
  */
31
- export function useCancelSwap(
32
- spokeProvider: SpokeProvider | undefined,
33
- ): UseMutationResult<CancelIntentResult, Error, CancelIntentParams> {
20
+ export function useCancelSwap({
21
+ mutationOptions,
22
+ }: MutationHookParams<TxHashPair, CancelIntentParams> = {}): SafeUseMutationResult<
23
+ TxHashPair,
24
+ Error,
25
+ CancelIntentParams
26
+ > {
34
27
  const { sodax } = useSodaxContext();
35
28
 
36
- return useMutation<CancelIntentResult, Error, CancelIntentParams>({
37
- mutationFn: async ({ intent, raw = false }: CancelIntentParams) => {
38
- if (!spokeProvider) {
39
- throw new Error('Spoke provider not found');
40
- }
41
- return sodax.swaps.cancelIntent(intent, spokeProvider, raw);
42
- },
29
+ return useSafeMutation<TxHashPair, Error, CancelIntentParams>({
30
+ mutationKey: ['swap', 'cancel'],
31
+ ...mutationOptions,
32
+ mutationFn: async ({ srcChainKey, walletProvider, intent }) =>
33
+ unwrapResult(await sodax.swaps.cancelIntent({ params: { srcChainKey, intent }, walletProvider })),
43
34
  });
44
35
  }
@@ -1,72 +1,39 @@
1
- import { useSodaxContext } from '../shared/useSodaxContext';
2
- import { useMutation, type UseMutationResult } from '@tanstack/react-query';
3
- import type {
4
- CreateLimitOrderParams,
5
- SolverExecutionResponse,
6
- Intent,
7
- IntentError,
8
- IntentErrorCode,
9
- IntentDeliveryInfo,
10
- Result,
11
- SpokeProvider,
12
- } from '@sodax/sdk';
1
+ // packages/dapp-kit/src/hooks/swap/useCreateLimitOrder.ts
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import type { LimitOrderActionParams, SpokeChainKey, SwapResponse } from '@sodax/sdk';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+ import { unwrapResult } from '../shared/unwrapResult.js';
13
7
 
14
- type CreateLimitOrderResult = Result<
15
- [SolverExecutionResponse, Intent, IntentDeliveryInfo],
16
- IntentError<IntentErrorCode>
8
+ /**
9
+ * Mutation variables for {@link useCreateLimitOrder}. Generic over `K extends SpokeChainKey`
10
+ * (defaults to the full union). Sophisticated callers can lock K at the call site to narrow the
11
+ * `walletProvider` and `params.srcChainKey` types.
12
+ */
13
+ export type UseCreateLimitOrderVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
14
+ LimitOrderActionParams<K, false>,
15
+ 'raw'
17
16
  >;
18
17
 
19
18
  /**
20
- * Hook for creating a limit order intent (no deadline, must be cancelled manually by user).
21
- * Uses React Query's useMutation for better state management and caching.
22
- *
23
- * Limit orders remain active until manually cancelled by the user. Unlike swaps, limit orders
24
- * do not have a deadline (deadline is automatically set to 0n).
25
- *
26
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for creating the limit order
27
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
28
- *
29
- * @example
30
- * ```typescript
31
- * const { mutateAsync: createLimitOrder, isPending } = useCreateLimitOrder(spokeProvider);
32
- *
33
- * const handleCreateLimitOrder = async () => {
34
- * const result = await createLimitOrder({
35
- * inputToken: '0x...',
36
- * outputToken: '0x...',
37
- * inputAmount: 1000000000000000000n,
38
- * minOutputAmount: 900000000000000000n,
39
- * allowPartialFill: false,
40
- * srcChain: '0xa4b1.arbitrum',
41
- * dstChain: '0x89.polygon',
42
- * srcAddress: '0x...',
43
- * dstAddress: '0x...',
44
- * solver: '0x0000000000000000000000000000000000000000',
45
- * data: '0x'
46
- * });
19
+ * React hook for creating a limit-order intent (no deadline).
47
20
  *
48
- * if (result.ok) {
49
- * const [solverExecutionResponse, intent, intentDeliveryInfo] = result.value;
50
- * console.log('Limit order created:', intent);
51
- * console.log('Intent hash:', solverExecutionResponse.intent_hash);
52
- * }
53
- * };
54
- * ```
21
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
22
+ * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.
55
23
  */
56
- export function useCreateLimitOrder(
57
- spokeProvider: SpokeProvider | undefined,
58
- ): UseMutationResult<CreateLimitOrderResult, Error, CreateLimitOrderParams> {
24
+ export function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({
25
+ mutationOptions,
26
+ }: MutationHookParams<SwapResponse, UseCreateLimitOrderVars<K>> = {}): SafeUseMutationResult<
27
+ SwapResponse,
28
+ Error,
29
+ UseCreateLimitOrderVars<K>
30
+ > {
59
31
  const { sodax } = useSodaxContext();
60
32
 
61
- return useMutation<CreateLimitOrderResult, Error, CreateLimitOrderParams>({
62
- mutationFn: async (params: CreateLimitOrderParams) => {
63
- if (!spokeProvider) {
64
- throw new Error('Spoke provider not found');
65
- }
66
- return sodax.swaps.createLimitOrder({
67
- intentParams: params,
68
- spokeProvider,
69
- });
70
- },
33
+ return useSafeMutation<SwapResponse, Error, UseCreateLimitOrderVars<K>>({
34
+ mutationKey: ['swap', 'limitOrder', 'create'],
35
+ ...mutationOptions,
36
+ mutationFn: async vars =>
37
+ unwrapResult(await sodax.swaps.createLimitOrder({ ...vars, raw: false })),
71
38
  });
72
39
  }