@sodax/dapp-kit 1.5.6-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 +1594 -1532
  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 +27 -84
  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 -2562
  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,78 +1,52 @@
1
- import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';
2
- import type {
3
- ConcentratedLiquidityDecreaseLiquidityParams,
4
- HubTxHash,
5
- SpokeProvider,
6
- SpokeTxHash,
7
- } from '@sodax/sdk';
8
- import { useSodaxContext } from '../shared/useSodaxContext';
1
+ // packages/dapp-kit/src/hooks/dex/useDecreaseLiquidity.ts
2
+ import type { ClLiquidityDecreaseLiquidityAction, SpokeChainKey, TxHashPair } 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';
9
8
 
10
- export type UseDecreaseLiquidityParams = {
11
- params: ConcentratedLiquidityDecreaseLiquidityParams;
12
- spokeProvider: SpokeProvider;
13
- };
9
+ /**
10
+ * Mutation variables for {@link useDecreaseLiquidity}. Generic over `K extends SpokeChainKey`
11
+ * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow
12
+ * the `walletProvider` and `params.srcChainKey` types.
13
+ */
14
+ export type UseDecreaseLiquidityVars<K extends SpokeChainKey = SpokeChainKey> = Omit<
15
+ ClLiquidityDecreaseLiquidityAction<K, false>,
16
+ 'raw'
17
+ >;
14
18
 
15
19
  /**
16
- * React hook that provides a mutation for decreasing liquidity in a concentrated liquidity position.
17
- *
18
- * This hook returns a mutation for removing liquidity from a position using the provided
19
- * `ConcentratedLiquidityDecreaseLiquidityParams` and `SpokeProvider`. The mutation returns a tuple of
20
- * the spoke transaction hash and the hub transaction hash upon success.
21
- *
22
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams>}
23
- * React Query mutation result:
24
- * - `mutateAsync({ params, spokeProvider })`: Triggers the decrease liquidity mutation.
25
- * - On success, returns `[spokeTxHash, hubTxHash]`.
26
- * - On failure, throws an error.
27
- *
28
- * @example
29
- * ```typescript
30
- * const { mutateAsync: decreaseLiquidity, isPending, error } = useDecreaseLiquidity();
31
- *
32
- * await decreaseLiquidity({
33
- * params: {
34
- * poolKey,
35
- * tokenId: 123n,
36
- * liquidity: 100000n,
37
- * amount0Min: 0n,
38
- * amount1Min: 0n,
39
- * },
40
- * spokeProvider,
41
- * });
42
- * ```
20
+ * React hook for decreasing liquidity in an existing concentrated-liquidity position.
43
21
  *
44
- * @param {UseDecreaseLiquidityParams} variables
45
- * - `params`: Parameters for the decrease liquidity operation, matching `ConcentratedLiquidityDecreaseLiquidityParams`.
46
- * - `spokeProvider`: The provider instance for the target spoke chain.
47
- *
48
- * @remarks
49
- * - After a successful liquidity decrease, the hook will invalidate DEX pool balances and position info queries.
22
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
23
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
50
24
  */
51
- export function useDecreaseLiquidity(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams> {
25
+ export function useDecreaseLiquidity<K extends SpokeChainKey = SpokeChainKey>({
26
+ mutationOptions,
27
+ }: MutationHookParams<TxHashPair, UseDecreaseLiquidityVars<K>> = {}): SafeUseMutationResult<
28
+ TxHashPair,
29
+ Error,
30
+ UseDecreaseLiquidityVars<K>
31
+ > {
52
32
  const { sodax } = useSodaxContext();
53
33
  const queryClient = useQueryClient();
54
34
 
55
- return useMutation({
56
- mutationFn: async ({ params, spokeProvider }: UseDecreaseLiquidityParams) => {
57
- if (!spokeProvider) {
58
- throw new Error('Spoke provider is required');
59
- }
60
-
61
- const decreaseResult = await sodax.dex.clService.decreaseLiquidity({
62
- params,
63
- spokeProvider,
35
+ return useSafeMutation<TxHashPair, Error, UseDecreaseLiquidityVars<K>>({
36
+ mutationKey: ['dex', 'decreaseLiquidity'],
37
+ ...mutationOptions,
38
+ mutationFn: async vars => unwrapResult(await sodax.dex.clService.decreaseLiquidity({ ...vars, raw: false })),
39
+ onSuccess: async (data, vars, ctx) => {
40
+ const { params } = vars;
41
+ // Decrease always targets a known position — scope invalidation to (tokenId, poolKey) instead
42
+ // of wiping all positions. `usePositionInfo` keys by string tokenId, so stringify the bigint
43
+ // here to keep the structural match.
44
+ queryClient.invalidateQueries({
45
+ queryKey: ['dex', 'positionInfo', params.tokenId.toString(), params.poolKey],
64
46
  });
65
-
66
- if (!decreaseResult.ok) {
67
- throw new Error(`Decrease liquidity failed: ${decreaseResult.error?.code || 'Unknown error'}`);
68
- }
69
-
70
- return decreaseResult.value;
71
- },
72
- onSuccess: () => {
73
- // Invalidate relevant queries after successful liquidity decrease
74
- queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });
75
- queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo'] });
47
+ queryClient.invalidateQueries({ queryKey: ['dex', 'poolData', params.poolKey] });
48
+ queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });
49
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
76
50
  },
77
51
  });
78
52
  }
@@ -1,87 +1,41 @@
1
- import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';
2
- import type { SpokeProvider, CreateAssetDepositParams } from '@sodax/sdk';
3
- import { useSodaxContext } from '../shared/useSodaxContext';
1
+ import type { CreateAssetDepositParams } from '@sodax/sdk';
2
+ import type { SpokeChainKey } from '@sodax/sdk';
3
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
4
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
4
6
 
5
- export type UseDexAllowanceProps = {
6
- params: CreateAssetDepositParams | undefined;
7
- spokeProvider: SpokeProvider | null;
8
- enabled?: boolean;
9
- queryOptions?: QueryObserverOptions<boolean, Error>;
10
- };
7
+ export type UseDexAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<
8
+ boolean,
9
+ {
10
+ payload: CreateAssetDepositParams<K> | undefined;
11
+ }
12
+ >;
11
13
 
12
14
  /**
13
- * Hook to check if the user has approved sufficient token allowance for DEX deposits.
14
- *
15
- * This hook automatically queries and tracks the allowance status, indicating whether
16
- * the user has granted enough allowance to allow a specific deposit to the DEX. It leverages
17
- * React Query for status, caching, and background refetching.
18
- *
19
- * @param {CreateAssetDepositParams | undefined} params
20
- * The deposit parameters: asset address, poolToken, and raw amount (BigInt), or undefined to disable.
21
- * @param {SpokeProvider | undefined} spokeProvider
22
- * The provider interface for the selected chain. When undefined, the query is disabled.
23
- * @param {boolean} [enabled]
24
- * Whether the allowance status check is enabled. Defaults to true if both params and spokeProvider are truthy.
25
- * @param {QueryObserverOptions<boolean, Error>} [queryOptions]
26
- * Optional react-query options. Any override here (e.g. staleTime, refetchInterval) will merge with defaults.
27
- *
28
- * @returns {UseQueryResult<boolean, Error>}
29
- * React Query result object: `data` is boolean (true if allowance is sufficient), plus `isLoading`, `error`, etc.
30
- *
31
- * @example
32
- * ```typescript
33
- * const { data: isAllowed, isLoading, error } = useDexAllowance({
34
- * params: { asset, amount: parseUnits('100', 18), poolToken },
35
- * spokeProvider,
36
- * });
37
- * if (isLoading) return <Spinner />;
38
- * if (error) return <div>Error: {error.message}</div>;
39
- * if (isAllowed) { ... }
40
- * ```
41
- *
42
- * @remarks
43
- * - The allowance is checked every 5 seconds as long as enabled, params, and spokeProvider are all defined.
44
- * - Returns `false` if allowance cannot be determined or any error occurs in isAllowanceValid.
45
- * - Suitable for gating UI actions that require token approval before depositing in the DEX.
15
+ * React hook to check whether the user has approved sufficient token allowance (or established a
16
+ * trustline, on Stellar) for a DEX deposit. Read-only — calls `assetService.isAllowanceValid`
17
+ * with `raw: true` so no `walletProvider` is required.
46
18
  */
47
- export function useDexAllowance({
19
+ export function useDexAllowance<K extends SpokeChainKey = SpokeChainKey>({
48
20
  params,
49
- spokeProvider,
50
- queryOptions = {
51
- queryKey: [
52
- 'dex',
53
- 'allowance',
54
- params?.asset,
55
- params?.poolToken,
56
- params?.amount.toString(),
57
- spokeProvider?.chainConfig.chain.id,
58
- ],
59
- enabled: !!params && !!spokeProvider,
60
- },
61
- }: UseDexAllowanceProps): UseQueryResult<boolean, Error> {
21
+ queryOptions,
22
+ }: UseDexAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {
62
23
  const { sodax } = useSodaxContext();
24
+ const payload = params?.payload;
63
25
 
64
- return useQuery({
65
- ...queryOptions,
26
+ return useQuery<boolean, Error>({
27
+ queryKey: ['dex', 'allowance', payload?.srcChainKey, payload?.asset, payload?.amount?.toString()],
66
28
  queryFn: async () => {
67
- if (!params || !spokeProvider) {
68
- throw new Error('Params and spoke provider are required');
69
- }
70
-
71
- const allowanceResult = await sodax.dex.assetService.isAllowanceValid({
72
- params: {
73
- asset: params.asset,
74
- amount: params.amount,
75
- poolToken: params.poolToken,
76
- },
77
- spokeProvider,
78
- });
79
-
80
- if (!allowanceResult.ok) {
81
- return false;
29
+ if (!payload) {
30
+ throw new Error('Params are required');
82
31
  }
83
-
84
- return allowanceResult.value;
32
+ const result = await sodax.dex.assetService.isAllowanceValid({ params: payload, raw: true });
33
+ if (!result.ok) throw result.error;
34
+ return result.value;
85
35
  },
36
+ enabled: !!payload,
37
+ refetchInterval: 5_000,
38
+ gcTime: 0,
39
+ ...queryOptions,
86
40
  });
87
41
  }
@@ -1,55 +1,44 @@
1
- import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';
2
- import type { SpokeProvider, CreateAssetDepositParams, SpokeTxHash } from '@sodax/sdk';
3
- import { useSodaxContext } from '../shared/useSodaxContext';
1
+ // packages/dapp-kit/src/hooks/dex/useDexApprove.ts
2
+ import type { AssetDepositAction, SpokeChainKey, TxReturnType } 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';
4
8
 
5
- export type UseDexApproveParams = {
6
- params: CreateAssetDepositParams;
7
- spokeProvider: SpokeProvider;
8
- };
9
+ /**
10
+ * Mutation variables for {@link useDexApprove}. Generic over `K extends SpokeChainKey` (defaults
11
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
12
+ * `walletProvider` and `params.srcChainKey` types.
13
+ */
14
+ export type UseDexApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;
9
15
 
10
16
  /**
11
- * React hook for performing a DEX token allowance approval transaction.
12
- *
13
- * Returns a mutation object that allows explicitly triggering a token approval
14
- * for a DEX deposit, using the specified approval parameters and spoke provider.
15
- * On successful approval, the related allowance query is invalidated and refetched
16
- * for consistent UI state.
17
- *
18
- * @returns {UseMutationResult<SpokeTxHash, Error, UseDexApproveParams>}
19
- * React Query mutation result for the approval operation. Use `mutateAsync` with
20
- * an object of shape `{ params, spokeProvider }` to initiate approval.
17
+ * React hook for approving ERC-20 token spending (or trustline establishment) for a DEX deposit.
21
18
  *
22
- * @example
23
- * ```typescript
24
- * const { mutateAsync: approve, isPending, error } = useDexApprove();
25
- * await approve({ params: { asset, amount, poolToken }, spokeProvider });
26
- * ```
27
- *
28
- * @remarks
29
- * - Throws if called without both a valid `params` and `spokeProvider`.
30
- * - On approval success, the query for ['dex', 'allowance'] is invalidated/refetched.
19
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
20
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
31
21
  */
32
- export function useDexApprove(): UseMutationResult<SpokeTxHash, Error, UseDexApproveParams> {
22
+ export function useDexApprove<K extends SpokeChainKey = SpokeChainKey>({
23
+ mutationOptions,
24
+ }: MutationHookParams<TxReturnType<K, false>, UseDexApproveVars<K>> = {}): SafeUseMutationResult<
25
+ TxReturnType<K, false>,
26
+ Error,
27
+ UseDexApproveVars<K>
28
+ > {
33
29
  const { sodax } = useSodaxContext();
34
30
  const queryClient = useQueryClient();
35
31
 
36
- return useMutation({
37
- mutationFn: async ({ params, spokeProvider }: UseDexApproveParams) => {
38
- const approveResult = await sodax.dex.assetService.approve({
39
- params,
40
- spokeProvider,
41
- raw: false,
32
+ return useSafeMutation<TxReturnType<K, false>, Error, UseDexApproveVars<K>>({
33
+ mutationKey: ['dex', 'approve'],
34
+ ...mutationOptions,
35
+ mutationFn: async vars => unwrapResult(await sodax.dex.assetService.approve({ ...vars, raw: false })),
36
+ onSuccess: async (data, vars, ctx) => {
37
+ const { params } = vars;
38
+ queryClient.invalidateQueries({
39
+ queryKey: ['dex', 'allowance', params.srcChainKey, params.asset, params.amount.toString()],
42
40
  });
43
-
44
- if (!approveResult.ok) {
45
- throw new Error('Approval failed');
46
- }
47
-
48
- return approveResult.value;
49
- },
50
- onSuccess: () => {
51
- // Invalidate allowance query to refetch the new allowance
52
- queryClient.invalidateQueries({ queryKey: ['dex', 'allowance'] });
41
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
53
42
  },
54
43
  });
55
44
  }
@@ -1,64 +1,57 @@
1
- import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';
2
- import type { SpokeProvider, CreateAssetDepositParams, SpokeTxHash, HubTxHash } from '@sodax/sdk';
3
- import { useSodaxContext } from '../shared/useSodaxContext';
4
-
5
- export type UseDexDepositParams = {
6
- params: CreateAssetDepositParams;
7
- spokeProvider: SpokeProvider;
8
- };
1
+ // packages/dapp-kit/src/hooks/dex/useDexDeposit.ts
2
+ import type { AssetDepositAction, SpokeChainKey, TxHashPair } 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';
9
8
 
10
9
  /**
10
+ * Mutation variables for {@link useDexDeposit}. Generic over `K extends SpokeChainKey` (defaults
11
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
12
+ * `walletProvider` and `params.srcChainKey` types.
13
+ */
14
+ export type UseDexDepositVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;
15
+
11
16
  /**
12
- * React hook that provides a mutation to perform a deposit into a DEX pool using the provided parameters and SpokeProvider.
17
+ * React hook for depositing an asset into a DEX pool.
13
18
  *
14
- * The hook returns a mutation object for executing the deposit (`mutateAsync`), tracking its state (`isPending`), and any resulting error (`error`).
15
- * On successful deposit, all queries matching ['dex', 'poolBalances'] are invalidated and refetched.
16
- *
17
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams>}
18
- * React Query mutation result:
19
- * - `mutateAsync({ params, spokeProvider })`: Triggers the deposit with {@link CreateDepositParams} and the target SpokeProvider.
20
- * - `isPending`: True while the deposit transaction is pending.
21
- * - `error`: Error if the mutation fails.
19
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
20
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
22
21
  *
23
22
  * @example
24
- * ```typescript
25
- * const { mutateAsync: deposit, isPending, error } = useDexDeposit();
26
- * await deposit({ params: { asset, amount, poolToken }, spokeProvider });
23
+ * ```tsx
24
+ * const walletProvider = useWalletProvider({ xChainId: chainKey });
25
+ * const { mutateAsync: deposit } = useDexDeposit();
26
+ * try {
27
+ * const { spokeTxHash, hubTxHash } = await deposit({ params, walletProvider });
28
+ * } catch (e) {
29
+ * // surfaced via mutation.error / onError
30
+ * }
27
31
  * ```
28
- *
29
- * @remarks
30
- * - Throws if called with missing `spokeProvider` or `params`.
31
- * - Upon success, automatically refetches up-to-date pool balances.
32
32
  */
33
- export function useDexDeposit(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams> {
33
+ export function useDexDeposit<K extends SpokeChainKey = SpokeChainKey>({
34
+ mutationOptions,
35
+ }: MutationHookParams<TxHashPair, UseDexDepositVars<K>> = {}): SafeUseMutationResult<
36
+ TxHashPair,
37
+ Error,
38
+ UseDexDepositVars<K>
39
+ > {
34
40
  const { sodax } = useSodaxContext();
35
41
  const queryClient = useQueryClient();
36
42
 
37
- return useMutation({
38
- mutationFn: async ({ params, spokeProvider }: UseDexDepositParams) => {
39
- if (!spokeProvider) {
40
- throw new Error('Spoke provider is required');
41
- }
42
-
43
- if (!params) {
44
- throw new Error('Deposit params are required');
45
- }
46
-
47
- // Perform the deposit operation
48
- const depositResult = await sodax.dex.assetService.deposit({
49
- params,
50
- spokeProvider,
43
+ return useSafeMutation<TxHashPair, Error, UseDexDepositVars<K>>({
44
+ mutationKey: ['dex', 'deposit'],
45
+ ...mutationOptions,
46
+ mutationFn: async vars => unwrapResult(await sodax.dex.assetService.deposit({ ...vars, raw: false })),
47
+ onSuccess: async (data, vars, ctx) => {
48
+ const { params } = vars;
49
+ queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });
50
+ queryClient.invalidateQueries({
51
+ queryKey: ['dex', 'allowance', params.srcChainKey, params.asset, params.amount.toString()],
51
52
  });
52
-
53
- if (!depositResult.ok) {
54
- throw new Error(`Deposit failed: ${depositResult.error?.code || 'Unknown error'}`);
55
- }
56
-
57
- return depositResult.value;
58
- },
59
- onSuccess: () => {
60
- // Refetch pool balances after a successful deposit
61
- queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });
53
+ queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
54
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
62
55
  },
63
56
  });
64
57
  }
@@ -1,54 +1,43 @@
1
- import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';
2
- import type { SpokeProvider, SpokeTxHash, HubTxHash, CreateAssetWithdrawParams } from '@sodax/sdk';
3
- import { useSodaxContext } from '../shared/useSodaxContext';
1
+ // packages/dapp-kit/src/hooks/dex/useDexWithdraw.ts
2
+ import type { AssetWithdrawAction, SpokeChainKey, TxHashPair } 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';
4
8
 
5
- export type UseDexWithdrawParams = {
6
- params: CreateAssetWithdrawParams;
7
- spokeProvider: SpokeProvider;
8
- };
9
+ /**
10
+ * Mutation variables for {@link useDexWithdraw}. Generic over `K extends SpokeChainKey` (defaults
11
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
12
+ * `walletProvider` and `params.srcChainKey` types.
13
+ */
14
+ export type UseDexWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetWithdrawAction<K, false>, 'raw'>;
9
15
 
10
16
  /**
11
- * React hook to provide a mutation for withdrawing assets from a DEX pool.
12
- *
13
- * This hook returns a mutation result object valid for use with React Query.
14
- * The mutation function expects an object with the withdrawal parameters and a SpokeProvider,
15
- * and triggers the withdrawal operation on the DEX. On success, it invalidates the relevant
16
- * ['dex', 'poolBalances'] query to fetch the updated balances.
17
- *
18
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams>}
19
- * Mutation result object. Use its properties to:
20
- * - Call `mutateAsync({ params, spokeProvider })` to perform the withdrawal.
21
- * - Track progress with `isPending`.
22
- * - Access any `error` encountered during the mutation.
17
+ * React hook for withdrawing an asset from a DEX pool.
23
18
  *
24
- * @example
25
- * const { mutateAsync: withdraw, isPending, error } = useDexWithdraw();
26
- * await withdraw({ params, spokeProvider });
19
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
20
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
27
21
  */
28
- export function useDexWithdraw(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams> {
22
+ export function useDexWithdraw<K extends SpokeChainKey = SpokeChainKey>({
23
+ mutationOptions,
24
+ }: MutationHookParams<TxHashPair, UseDexWithdrawVars<K>> = {}): SafeUseMutationResult<
25
+ TxHashPair,
26
+ Error,
27
+ UseDexWithdrawVars<K>
28
+ > {
29
29
  const { sodax } = useSodaxContext();
30
30
  const queryClient = useQueryClient();
31
31
 
32
- return useMutation({
33
- mutationFn: async ({ params, spokeProvider }: UseDexWithdrawParams) => {
34
- if (!spokeProvider) {
35
- throw new Error('Spoke provider is required');
36
- }
37
- // Execute withdraw
38
- const withdrawResult = await sodax.dex.assetService.withdraw({
39
- params,
40
- spokeProvider,
41
- });
42
-
43
- if (!withdrawResult.ok) {
44
- throw new Error(`Withdraw failed: ${withdrawResult.error.code}`);
45
- }
46
-
47
- return withdrawResult.value;
48
- },
49
- onSuccess: () => {
50
- // Invalidate balances query to refetch after withdraw
51
- queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });
32
+ return useSafeMutation<TxHashPair, Error, UseDexWithdrawVars<K>>({
33
+ mutationKey: ['dex', 'withdraw'],
34
+ ...mutationOptions,
35
+ mutationFn: async vars => unwrapResult(await sodax.dex.assetService.withdraw({ ...vars, raw: false })),
36
+ onSuccess: async (data, vars, ctx) => {
37
+ const { params } = vars;
38
+ queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });
39
+ queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });
40
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
52
41
  },
53
42
  });
54
43
  }