@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
package/dist/index.d.ts CHANGED
@@ -1,137 +1,160 @@
1
- import { Sodax, SpokeProvider, GetEstimateGasReturnType, TxReturnType, SpokeChainId, StellarSpokeProvider, EvmHubProvider, IWalletProvider, BitcoinSpokeProvider, RadfiWalletBalance, RadfiUtxo, MoneyMarketBorrowParams, MoneyMarketError, RelayErrorCode, MoneyMarketRepayParams, MoneyMarketSupplyParams, MoneyMarketWithdrawParams, UserReserveData, AggregatedReserveData, BaseCurrencyInfo, MoneyMarketParams, XToken, ReserveData, FormatReserveUSDResponse, FormatUserSummaryResponse, SolverIntentQuoteRequest, Result, SolverIntentQuoteResponse, SolverErrorResponse, SolverExecutionResponse, Intent, IntentDeliveryInfo, IntentError, IntentErrorCode, CreateIntentParams, Hex, SolverIntentStatusResponse, CreateLimitOrderParams, IntentResponse, Address as Address$1, UserIntentsResponse, RequestOverrideConfig, OrderbookResponse, MoneyMarketPosition, MoneyMarketAsset, MoneyMarketAssetBorrowers, MoneyMarketAssetSuppliers, MoneyMarketBorrowers, CreateBridgeIntentParams, SpokeTxHash, HubTxHash, BridgeError, BridgeErrorCode, BridgeLimit, StakeParams, UnstakeParams, ClaimParams, CancelUnstakeParams, StakingInfo, UnstakingInfo, UnstakeRequestWithPenalty, StakingConfig, InstantUnstakeParams, PoolKey, PoolData, ClPositionInfo, CreateAssetDepositParams, CreateAssetWithdrawParams, ConcentratedLiquiditySupplyParams, ConcentratedLiquidityIncreaseLiquidityParams, ConcentratedLiquidityDecreaseLiquidityParams, PoolSpokeAssets, DestinationParamsType, ConcentratedLiquidityClaimRewardsParams, ConcentratedLiquidityError, ConcentratedLiquidityErrorCode, SodaxConfig } from '@sodax/sdk';
2
- import { RpcConfig, SpokeChainId as SpokeChainId$1, SubmitSwapTxResponse, SubmitSwapTxRequest, SubmitSwapTxStatusResponse, XToken as XToken$1 } from '@sodax/types';
3
- import { UseMutationResult, UseQueryResult, UseQueryOptions, UseMutationOptions, QueryObserverOptions } from '@tanstack/react-query';
1
+ import { UseQueryOptions, UseMutationOptions, UseMutationResult, MutateOptions, UseQueryResult, QueryClientConfig, QueryClient } from '@tanstack/react-query';
2
+ import { Result, Sodax, SpokeChainKey, GetEstimateGasReturnType, EstimateGasParams, IStellarWalletProvider, StellarChainKey, IXServiceBase, XToken, EvmHubProvider, IBitcoinWalletProvider, RadfiWalletBalance, RadfiUtxo, MoneyMarketBorrowActionParams, TxHashPair, MoneyMarketRepayActionParams, MoneyMarketSupplyActionParams, MoneyMarketWithdrawActionParams, UserReserveData, AggregatedReserveData, BaseCurrencyInfo, ReservesDataHumanized, Address as Address$1, MoneyMarketParams, MoneyMarketApproveActionParams, TxReturnType, Erc20Token, ChainKey, ReserveDataHumanized, FormatReserveUSDResponse, FormatUserSummaryResponse, SolverIntentQuoteResponse, SolverErrorResponse, SolverIntentQuoteRequest, SwapActionParams, SwapResponse, SolverIntentStatusResponse, Hex, CreateIntentParams, CreateLimitOrderParams, GetWalletProviderType, Intent, LimitOrderActionParams, IntentResponse, UserIntentsResponse, SubmitSwapTxResponse, SubmitSwapTxRequest, RequestOverrideConfig, SubmitSwapTxStatusResponse, OrderbookResponse, MoneyMarketPosition, MoneyMarketAsset, MoneyMarketAssetBorrowers, MoneyMarketAssetSuppliers, MoneyMarketBorrowers, BridgeParams, CreateBridgeIntentParams, BridgeLimit, StakeAction, StakeParams, UnstakeAction, ClaimAction, CancelUnstakeAction, StakingInfo, UnstakingInfo, UnstakeRequestWithPenalty, StakingConfig, InstantUnstakeAction, UnstakeParams, InstantUnstakeParams, PartnerFeeClaimAssetBalance, AutoSwapPreferences, FeeTokenApproveParams, FeeTokenApproveAction, HubChainKey, SetSwapPreferenceAction, PartnerFeeClaimSwapAction, IntentAutoSwapResult, HubAssetBalance, WithdrawHubAssetAction, IcxMigrateAction, IcxRevertMigrationAction, UnifiedBnUSDMigrateAction, BalnMigrateAction, MigrationAction, IcxMigrateParams, IcxCreateRevertMigrationParams, UnifiedBnUSDMigrateParams, BalnMigrateParams, PoolKey, PoolData, ClPositionInfo, AssetDepositAction, AssetWithdrawAction, CreateAssetDepositParams, ClSupplyParams, ClIncreaseLiquidityParams, ClLiquidityDecreaseLiquidityAction, ClDecreaseLiquidityParams, CreateAssetWithdrawParams, PoolSpokeAssets, DestinationParamsType, ClLiquidityClaimRewardsAction, DeepPartial, SodaxConfig } from '@sodax/sdk';
3
+ export * from '@sodax/sdk';
4
4
  import { Address } from 'viem';
5
5
  import { ReactNode, ReactElement } from 'react';
6
6
 
7
- interface SodaxContextType {
8
- sodax: Sodax;
9
- testnet: boolean;
10
- rpcConfig: RpcConfig;
11
- }
12
-
13
7
  /**
14
- * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration
15
- * @throws {Error} If used outside of a SodaxProvider
16
- * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration
8
+ * Subset of `UseQueryOptions` consumers may override on dapp-kit read hooks.
9
+ *
10
+ * `queryKey`, `queryFn`, and `enabled` are owned by the hook (the latter is derived
11
+ * from required-input presence) and are intentionally stripped here.
17
12
  */
18
- declare const useSodaxContext: () => SodaxContextType;
19
-
20
- declare function useEstimateGas<T extends SpokeProvider = SpokeProvider>(spokeProvider: T | undefined): UseMutationResult<GetEstimateGasReturnType<T>, Error, TxReturnType<T, true>>;
21
-
13
+ type ReadQueryOptions<TData, TError = Error> = Omit<UseQueryOptions<TData, TError>, 'queryKey' | 'queryFn' | 'enabled'>;
22
14
  /**
23
- * Hook for deriving user wallet address for hub abstraction.
15
+ * Canonical params shape for read-only `useQuery`-backed hooks in dapp-kit.
24
16
  *
25
- * This hook derives the user's abstracted wallet address for the hub chain based on the spoke chain ID and address.
26
- * If the spoke chain is the same as the hub chain, it returns the encoded spoke address.
27
- * Otherwise, it derives and returns the abstracted wallet address for cross-chain operations.
17
+ * Two top-level keys, always:
18
+ * - `params`: SDK-feature-domain inputs (the "what" being fetched)
19
+ * - `queryOptions`: React Query behavior knobs (the "how" the query behaves)
28
20
  *
29
- * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.
30
- * This is a deterministic operation, so the result is cached and not refetched automatically.
21
+ * For hooks with no required inputs, leave `TParams` at its default and accept the
22
+ * whole params object as optional at the call site.
23
+ */
24
+ type ReadHookParams<TData, TParams = Record<string, never>, TError = Error> = {
25
+ params?: TParams;
26
+ queryOptions?: ReadQueryOptions<TData, TError>;
27
+ };
28
+ /**
29
+ * Subset of `UseMutationOptions` consumers may override on dapp-kit mutation hooks.
31
30
  *
32
- * @param spokeChainId - Optional spoke chain ID. If not provided, the query will be disabled.
33
- * @param spokeAddress - Optional user wallet address on the spoke chain. If not provided, the query will be disabled.
34
- * @returns A React Query result object containing:
35
- * - data: The derived user wallet address (Address) when available
36
- * - isLoading: Loading state indicator
37
- * - error: Any error that occurred during derivation (Error)
31
+ * `mutationFn` is owned by the hook (it's the SDK integration point) and is
32
+ * intentionally stripped here. Everything else `mutationKey`, `retry`, `gcTime`,
33
+ * `networkMode`, `onMutate`, `onSuccess`, `onError`, `onSettled`, `meta`, etc. —
34
+ * is consumer-overridable.
38
35
  *
39
- * @example
40
- * ```typescript
41
- * const { data: derivedAddress, isLoading, error } = useDeriveUserWalletAddress(spokeChainId, userAddress);
36
+ * Conventions enforced by every dapp-kit mutation hook:
42
37
  *
43
- * if (isLoading) return <div>Deriving address...</div>;
44
- * if (error) return <div>Error: {error.message}</div>;
45
- * if (derivedAddress) return <div>Derived Address: {derivedAddress}</div>;
46
- * ```
38
+ * 1. **`mutationFn` throws on SDK failure.** The SDK returns `Result<T>`; the hook
39
+ * unwraps `result.value` on `ok` and throws `result.error` on `!ok`. So `TData`
40
+ * here is the unwrapped success type, not `Result<T>`. React Query's native
41
+ * error model — `isError`, `error`, `onError`, `retry`, `throwOnError`, devtools —
42
+ * works exactly as documented.
43
+ *
44
+ * 2. **`onSuccess` is composed.** Hook-owned invalidations always run first; then
45
+ * the hook awaits `mutationOptions?.onSuccess?.(data, vars, ctx)`. Per-call
46
+ * `mutate(vars, { onSuccess })` runs after both, per TanStack Query's native
47
+ * ordering. Because invalidations now live inside `onSuccess` (not `onSettled`),
48
+ * they only fire on confirmed success — failed mutations never trigger them.
49
+ *
50
+ * 3. **A default `mutationKey` is set per hook** (e.g. `['mm', 'supply']`,
51
+ * `['swap']`) so consumers can use `useIsMutating(['mm'])` and
52
+ * `useMutationState` without guessing the key shape. The default is set
53
+ * *before* `...mutationOptions` is spread, so consumers can override it.
47
54
  */
48
- declare function useDeriveUserWalletAddress(spokeChainId?: SpokeChainId | SpokeProvider | undefined, spokeAddress?: string | undefined): UseQueryResult<Address, Error>;
49
-
55
+ type MutationHookOptions<TData, TVars, TError = Error, TContext = unknown> = Omit<UseMutationOptions<TData, TError, TVars, TContext>, 'mutationFn'>;
50
56
  /**
51
- * React hook to check if a Stellar account has a sufficient trustline for a given token and amount.
57
+ * Canonical params shape for `useMutation`-backed hooks in dapp-kit.
52
58
  *
53
- * This hook queries the Stellar network (via the provided SpokeProvider) to determine
54
- * whether the account has established a trustline for the specified token and if the trustline
55
- * is sufficient for the intended amount. It is useful for gating UI actions that require
56
- * a trustline to be present and funded.
59
+ * One top-level key:
60
+ * - `mutationOptions`: React Query behavior knobs (the "how" the mutation behaves)
57
61
  *
58
- * @template T - The type of SpokeProvider, defaults to SpokeProvider.
59
- * @param {string | undefined} token - The Stellar asset code or token address to check the trustline for.
60
- * @param {bigint | undefined} amount - The minimum amount required for the trustline.
61
- * @param {T | undefined} spokeProvider - The provider instance for interacting with the Stellar network.
62
- * @param {SpokeChainId | undefined} chainId - The chain ID to determine if the check should be performed (only on Stellar mainnet).
63
- * @returns {UseQueryResult<boolean, Error>} A React Query result object containing:
64
- * - `data`: `true` if the trustline exists and is sufficient, `false` otherwise.
65
- * - `error`: Any error encountered during the check.
66
- * - `isLoading`: Whether the query is in progress.
67
- * - Other React Query state.
62
+ * Domain inputs (params, walletProvider, etc.) are NOT here they belong in
63
+ * `TVars` and flow through `mutate(vars)` so the call site can vary them per
64
+ * invocation without re-rendering the hook.
68
65
  *
69
- * @example
70
- * ```tsx
71
- * import { useStellarTrustlineCheck } from '@sodax/dapp-kit';
72
- *
73
- * const { data: hasTrustline, isLoading, error } = useStellarTrustlineCheck(
74
- * 'USDC-G...TOKEN',
75
- * 10000000n,
76
- * stellarProvider,
77
- * 'stellar'
78
- * );
79
- *
80
- * if (isLoading) return <span>Checking trustline...</span>;
81
- * if (error) return <span>Error: {error.message}</span>;
82
- * if (!hasTrustline) return <span>Trustline not established or insufficient.</span>;
83
- * return <span>Trustline is sufficient!</span>;
84
- * ```
66
+ * Always accept the whole params object as optional at the call site:
67
+ * `useFoo({ mutationOptions } = {})`.
85
68
  */
86
- declare function useStellarTrustlineCheck<T extends SpokeProvider = SpokeProvider>(token: string | undefined, amount: bigint | undefined, spokeProvider: T | undefined, chainId: SpokeChainId | undefined): UseQueryResult<boolean, Error>;
69
+ type MutationHookParams<TData, TVars, TError = Error, TContext = unknown> = {
70
+ mutationOptions?: MutationHookOptions<TData, TVars, TError, TContext>;
71
+ };
87
72
 
88
73
  /**
89
- * React hook to request a Stellar trustline for a given token and amount.
90
- *
91
- * This hook provides a callback function for requesting a trustline on the Stellar network
92
- * using the provided SpokeProvider. It is intended for use with StellarSpokeProvider
93
- * and will throw if used with a non-Stellar provider. Upon success, it invalidates
94
- * the trustline check query to ensure UI reflects the updated trustline state.
95
- *
96
- * @template T - The type of SpokeProvider, defaults to SpokeProvider.
97
- * @param {string | undefined} token - The Stellar asset code or token address for which to request a trustline.
98
- * @returns {Object} An object containing:
99
- * - `requestTrustline`: Function to trigger the trustline request.
100
- * - `isLoading`: Whether the request is in progress.
101
- * - `isRequested`: Whether a trustline has been successfully requested.
102
- * - `error`: Any error encountered during the request.
103
- * - `data`: The transaction result if successful.
74
+ * Translates the SDK's `Result<T>` contract into the React Query contract: returns `value` on
75
+ * success, throws `error` on failure. Non-`Error` throwables are wrapped so consumers always get
76
+ * an `Error` in `mutation.error` / catch blocks.
104
77
  *
105
- * @example
106
- * ```tsx
107
- * import { useRequestTrustline } from '@sodax/dapp-kit';
108
- *
109
- * const { requestTrustline, isLoading, isRequested, error, data } = useRequestTrustline('USDC-G...TOKEN');
110
- *
111
- * // To request a trustline:
112
- * await requestTrustline({
113
- * token: 'USDC-G...TOKEN',
114
- * amount: 10000000n,
115
- * spokeProvider: stellarProvider,
116
- * });
78
+ * Used by every dapp-kit mutation hook so the React Query error model (`isError`, `error`,
79
+ * `onError`, `retry`, `throwOnError`, devtools) engages uniformly.
80
+ */
81
+ declare function unwrapResult<T>(result: Result<T>): T;
82
+
83
+ /**
84
+ * Return shape of every dapp-kit mutation hook. Extends `UseMutationResult` with one extra
85
+ * method, `mutateAsyncSafe`, that never rejects — it returns the SDK's `Result<T>` shape so
86
+ * callers can branch on `.ok` without `try/catch`.
117
87
  *
118
- * if (isLoading) return <span>Requesting trustline...</span>;
119
- * if (error) return <span>Error: {error.message}</span>;
120
- * if (isRequested) return <span>Trustline requested! Tx: {data?.txHash}</span>;
121
- * ```
88
+ * The underlying `mutationFn` still throws on SDK failure, so React Query's native error model
89
+ * (`isError`, `error`, `onError`, `retry`, `throwOnError`, devtools) keeps working as documented.
90
+ */
91
+ type SafeUseMutationResult<TData, TError, TVars, TContext = unknown> = UseMutationResult<TData, TError, TVars, TContext> & {
92
+ /**
93
+ * Like `mutateAsync` but never rejects. Returns `Result<TData>` so callers can branch
94
+ * on `.ok` without `try/catch`.
95
+ *
96
+ * Use this for imperative flows where rejection-style errors are awkward — e.g. sequential
97
+ * `if (!hasAllowance) await approve(...); await action(...)` chains where the user-reject
98
+ * case is the modal failure mode, not an exceptional one.
99
+ */
100
+ mutateAsyncSafe: (vars: TVars, options?: MutateOptions<TData, TError, TVars, TContext>) => Promise<Result<TData>>;
101
+ };
102
+ /**
103
+ * Wraps a `Promise<T>` (typically `mutateAsync(vars)`) into a `Promise<Result<T>>` that never
104
+ * rejects. Pure, side-effect-free — extracted for unit testing.
105
+ */
106
+ declare function toResult<T>(promise: Promise<T>): Promise<Result<T>>;
107
+ /**
108
+ * Drop-in replacement for `useMutation` that augments the result with `mutateAsyncSafe`. Used
109
+ * by every dapp-kit mutation hook so consumers can pick rejection-style (`mutateAsync`) or
110
+ * Result-style (`mutateAsyncSafe`) ergonomics without the hook author having to think about it.
122
111
  */
123
- declare function useRequestTrustline<T extends SpokeProvider = SpokeProvider>(token: string | undefined): {
112
+ declare function useSafeMutation<TData, TError, TVars, TContext = unknown>(options: UseMutationOptions<TData, TError, TVars, TContext>): SafeUseMutationResult<TData, TError, TVars, TContext>;
113
+
114
+ interface SodaxContextType {
115
+ sodax: Sodax;
116
+ }
117
+
118
+ /**
119
+ * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration
120
+ * @throws {Error} If used outside of a SodaxProvider
121
+ * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration
122
+ */
123
+ declare const useSodaxContext: () => SodaxContextType;
124
+
125
+ declare function useEstimateGas<C extends SpokeChainKey>({ mutationOptions, }?: MutationHookParams<GetEstimateGasReturnType<C>, EstimateGasParams<C>>): SafeUseMutationResult<GetEstimateGasReturnType<C>, Error, EstimateGasParams<C>>;
126
+
127
+ type UseDeriveUserWalletAddressParams = ReadHookParams<Address, {
128
+ spokeChainId?: SpokeChainKey;
129
+ spokeAddress?: string;
130
+ }>;
131
+ declare function useDeriveUserWalletAddress({ params, queryOptions, }?: UseDeriveUserWalletAddressParams): UseQueryResult<Address, Error>;
132
+
133
+ type UseStellarTrustlineCheckParams = ReadHookParams<boolean, {
134
+ token: string | undefined;
135
+ amount: bigint | undefined;
136
+ chainId: SpokeChainKey | undefined;
137
+ walletProvider: IStellarWalletProvider | undefined;
138
+ }>;
139
+ declare function useStellarTrustlineCheck({ params, queryOptions, }?: UseStellarTrustlineCheckParams): UseQueryResult<boolean, Error>;
140
+
141
+ declare function useRequestTrustline(token: string | undefined): {
124
142
  requestTrustline: (params: {
125
143
  token: string;
126
144
  amount: bigint;
127
- spokeProvider: T;
128
- }) => Promise<TxReturnType<StellarSpokeProvider, false>>;
145
+ srcChainKey: StellarChainKey;
146
+ walletProvider: IStellarWalletProvider;
147
+ }) => Promise<string>;
129
148
  isLoading: boolean;
130
149
  isRequested: boolean;
131
150
  error: Error | null;
132
- data: TxReturnType<StellarSpokeProvider, false> | null;
151
+ data: string | null;
133
152
  };
134
153
 
154
+ type UseGetUserHubWalletAddressParams = ReadHookParams<Address, {
155
+ spokeChainId?: SpokeChainKey;
156
+ spokeAddress?: string;
157
+ }>;
135
158
  /**
136
159
  * Hook for deriving user wallet address for hub abstraction.
137
160
  *
@@ -143,41 +166,49 @@ declare function useRequestTrustline<T extends SpokeProvider = SpokeProvider>(to
143
166
  * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.
144
167
  * This is a deterministic operation, so the result is cached and not refetched automatically.
145
168
  *
146
- * @param spokeChainId - Optional spoke chain ID. If not provided, the query will be disabled.
147
- * @param spokeAddress - Optional user wallet address on the spoke chain. If not provided, the query will be disabled.
148
- * @returns A React Query result object containing:
149
- * - data: The derived user wallet address (Address) when available
150
- * - isLoading: Loading state indicator
151
- * - error: Any error that occurred during derivation (Error)
152
- *
153
169
  * @example
154
170
  * ```typescript
155
- * const { data: derivedAddress, isLoading, error } = useDeriveUserWalletAddress(spokeChainId, userAddress);
156
- *
157
- * if (isLoading) return <div>Deriving address...</div>;
158
- * if (error) return <div>Error: {error.message}</div>;
159
- * if (derivedAddress) return <div>Derived Address: {derivedAddress}</div>;
171
+ * const { data: derivedAddress, isLoading, error } = useGetUserHubWalletAddress({
172
+ * params: { spokeChainId, spokeAddress: userAddress },
173
+ * });
160
174
  * ```
161
175
  */
162
- declare function useGetUserHubWalletAddress(spokeChainId?: SpokeChainId | SpokeProvider | undefined, spokeAddress?: string | undefined): UseQueryResult<Address, Error>;
163
-
164
- declare function useHubProvider(): EvmHubProvider;
176
+ declare function useGetUserHubWalletAddress({ params, queryOptions, }?: UseGetUserHubWalletAddressParams): UseQueryResult<Address, Error>;
165
177
 
166
178
  /**
167
- * Hook to get the appropriate spoke provider based on the chain type.
168
- * Supports EVM, SUI, ICON and INJECTIVE chains.
169
- *
170
- * @param {SpokeChainId | undefined} spokeChainId - The spoke chain ID to get the provider for
171
- * @param {IWalletProvider | undefined} walletProvider - The wallet provider to use
172
- * @returns {SpokeProvider | undefined} The appropriate spoke provider instance for the given chain ID, or undefined if invalid/unsupported
179
+ * Domain inputs for {@link useXBalances}. `xChainId` is optional so the hook can be mounted
180
+ * before a chain is selected; `enabled` gates execution on every required field being present.
181
+ */
182
+ interface XBalancesInputs {
183
+ xService: IXServiceBase | undefined;
184
+ xChainId: SpokeChainKey | undefined;
185
+ xTokens: readonly XToken[];
186
+ address: string | undefined;
187
+ }
188
+ type UseXBalancesParams = ReadHookParams<Record<string, bigint>, XBalancesInputs>;
189
+ /**
190
+ * Pure builder for {@link useXBalances} query options. Exported for unit
191
+ * tests and for advanced callers that compose their own `useQuery` wrapper.
192
+ */
193
+ declare function getXBalancesQueryOptions({ xService, xChainId, xTokens, address }: XBalancesInputs): {
194
+ queryKey: readonly ["shared", "xBalances", "0xa86a.avax" | "0xa4b1.arbitrum" | "0x2105.base" | "0x38.bsc" | "injective-1" | "sonic" | "0x1.icon" | "sui" | "0xa.optimism" | "0x89.polygon" | "solana" | "stellar" | "hyper" | "lightlink" | "near" | "ethereum" | "bitcoin" | "redbelly" | "0x2019.kaia" | "stacks" | undefined, (readonly [string, string])[], string | undefined];
195
+ queryFn: () => Promise<Record<string, bigint>>;
196
+ enabled: boolean;
197
+ refetchInterval: number;
198
+ };
199
+ /**
200
+ * Fetch token balances for multiple tokens on a specific chain. Returns an
201
+ * object mapping each token's address to its balance in smallest unit.
173
202
  *
174
203
  * @example
175
204
  * ```tsx
176
- * // Using a specific SpokeChainId and wallet provider
177
- * const spokeProvider = useSpokeProvider(spokeChainId, walletProvider);
205
+ * const xService = useXService({ xChainType: getXChainType(xChainId) });
206
+ * const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });
178
207
  * ```
179
208
  */
180
- declare function useSpokeProvider(spokeChainId: SpokeChainId$1 | undefined, walletProvider?: IWalletProvider | undefined): SpokeProvider | undefined;
209
+ declare function useXBalances({ params, queryOptions, }?: UseXBalancesParams): UseQueryResult<Record<string, bigint>>;
210
+
211
+ declare function useHubProvider(): EvmHubProvider;
181
212
 
182
213
  type RadfiSession = {
183
214
  accessToken: string;
@@ -185,6 +216,9 @@ type RadfiSession = {
185
216
  tradingAddress: string;
186
217
  publicKey: string;
187
218
  };
219
+ type UseRadfiAuthVars = {
220
+ walletProvider: IBitcoinWalletProvider;
221
+ };
188
222
  type RadfiAuthResult = {
189
223
  accessToken: string;
190
224
  refreshToken: string;
@@ -194,10 +228,11 @@ declare function saveRadfiSession(address: string, session: RadfiSession): void;
194
228
  declare function loadRadfiSession(address: string): RadfiSession | null;
195
229
  declare function clearRadfiSession(address: string): void;
196
230
  /**
197
- * Hook to authenticate with Radfi using BIP322 message signing.
198
- * Saves session (accessToken, refreshToken, tradingAddress, publicKey) to localStorage.
231
+ * React hook for authenticating with Radfi via BIP322-signed message. Pure mutation: pass
232
+ * `{ walletProvider }` to `mutate({...})`. The hook itself takes no arguments other than the
233
+ * structural `mutationOptions` slot.
199
234
  */
200
- declare function useRadfiAuth(spokeProvider: BitcoinSpokeProvider | undefined): UseMutationResult<RadfiAuthResult, Error, void>;
235
+ declare function useRadfiAuth({ mutationOptions, }?: MutationHookParams<RadfiAuthResult, UseRadfiAuthVars>): SafeUseMutationResult<RadfiAuthResult, Error, UseRadfiAuthVars>;
201
236
 
202
237
  type UseRadfiSessionReturn = {
203
238
  walletAddress: string | undefined;
@@ -206,33 +241,23 @@ type UseRadfiSessionReturn = {
206
241
  login: () => Promise<void>;
207
242
  isLoginPending: boolean;
208
243
  };
209
- /**
210
- * Manages the full Radfi session lifecycle:
211
- * - On mount / wallet switch: refreshes token to validate session
212
- * - Single interval (~5 min): refreshes access token. If refresh fails → clears session, isAuthed=false
213
- * - ensureRadfiAccessToken (SDK layer) acts as safety net before swap/bridge
214
- * - Exposes login() and isAuthed for UI
215
- */
216
- declare function useRadfiSession(spokeProvider: BitcoinSpokeProvider | undefined): UseRadfiSessionReturn;
244
+ declare function useRadfiSession(walletProvider: IBitcoinWalletProvider | undefined): UseRadfiSessionReturn;
217
245
 
246
+ type UseFundTradingWalletVars = {
247
+ amount: bigint;
248
+ walletProvider: IBitcoinWalletProvider;
249
+ };
218
250
  /**
219
- * Hook to fund the Radfi trading wallet by sending BTC from the user's personal wallet.
220
- *
221
- * @param {BitcoinSpokeProvider | undefined} spokeProvider - The Bitcoin spoke provider with signing capability
222
- * @returns {UseMutationResult} Mutation result — input is amount in satoshis, output is transaction ID
223
- *
224
- * @example
225
- * ```tsx
226
- * const { mutateAsync: fundWallet, isPending } = useFundTradingWallet(spokeProvider);
227
- *
228
- * const handleFund = async () => {
229
- * const txId = await fundWallet(100_000n); // fund 100,000 satoshis
230
- * console.log('Funded:', txId);
231
- * };
232
- * ```
251
+ * React hook for funding the user's Radfi trading wallet from their personal Bitcoin wallet.
252
+ * Pure mutation: pass `{ amount, walletProvider }` to `mutate({...})`. Returns the broadcast tx
253
+ * id on success.
233
254
  */
234
- declare function useFundTradingWallet(spokeProvider: BitcoinSpokeProvider | undefined): UseMutationResult<string, Error, bigint>;
255
+ declare function useFundTradingWallet({ mutationOptions, }?: MutationHookParams<string, UseFundTradingWalletVars>): SafeUseMutationResult<string, Error, UseFundTradingWalletVars>;
235
256
 
257
+ type UseBitcoinBalanceParams = ReadHookParams<bigint, {
258
+ address: string | undefined;
259
+ rpcUrl?: string;
260
+ }>;
236
261
  /**
237
262
  * Hook to fetch BTC balance for any Bitcoin address.
238
263
  * Sums all UTXOs (confirmed + unconfirmed) from mempool.space API.
@@ -240,2079 +265,1060 @@ declare function useFundTradingWallet(spokeProvider: BitcoinSpokeProvider | unde
240
265
  * The UTXO set already excludes spent outputs (even from unconfirmed txs),
241
266
  * so the total is always the correct spendable balance.
242
267
  */
243
- declare function useBitcoinBalance(address: string | undefined, rpcUrl?: string): UseQueryResult<bigint, Error>;
268
+ declare function useBitcoinBalance({ params, queryOptions, }?: UseBitcoinBalanceParams): UseQueryResult<bigint, Error>;
244
269
 
270
+ type UseTradingWalletReturn = {
271
+ tradingAddress: string | undefined;
272
+ };
245
273
  /**
246
- * Hook to fetch trading wallet balance from Radfi API.
247
- * Returns confirmed + pending satoshi balances.
274
+ * Returns the Radfi trading wallet address from the persisted session.
275
+ * Trading wallet is created automatically during authentication — no API call needed.
248
276
  */
249
- declare function useTradingWalletBalance(spokeProvider: BitcoinSpokeProvider | undefined, tradingAddress: string | undefined): UseQueryResult<RadfiWalletBalance, Error>;
277
+ declare function useTradingWallet(walletAddress: string | undefined): UseTradingWalletReturn;
250
278
 
251
- /**
252
- * Hook to fetch expired UTXOs for a trading wallet address.
253
- * UTXOs that are expired or within 2 weeks of expiry are considered invalid for trading
254
- * and need to be renewed via the Radfi renew-utxo flow.
255
- */
256
- declare function useExpiredUtxos(spokeProvider: BitcoinSpokeProvider | undefined, tradingAddress: string | undefined): UseQueryResult<RadfiUtxo[], Error>;
279
+ type UseTradingWalletBalanceParams = ReadHookParams<RadfiWalletBalance, {
280
+ walletProvider: IBitcoinWalletProvider | undefined;
281
+ tradingAddress: string | undefined;
282
+ }>;
283
+ declare function useTradingWalletBalance({ params, queryOptions, }?: UseTradingWalletBalanceParams): UseQueryResult<RadfiWalletBalance, Error>;
284
+
285
+ type UseExpiredUtxosParams = ReadHookParams<RadfiUtxo[], {
286
+ walletProvider: IBitcoinWalletProvider | undefined;
287
+ tradingAddress: string | undefined;
288
+ }>;
289
+ declare function useExpiredUtxos({ params, queryOptions, }?: UseExpiredUtxosParams): UseQueryResult<RadfiUtxo[], Error>;
257
290
 
258
- type RenewUtxosParams = {
291
+ type UseRenewUtxosVars = {
259
292
  txIdVouts: string[];
293
+ walletProvider: IBitcoinWalletProvider;
260
294
  };
261
295
  /**
262
- * Hook to renew expired UTXOs in the Radfi trading wallet.
263
- *
264
- * Flow:
265
- * 1. Build renew-utxo transaction via Radfi API (returns unsigned PSBT)
266
- * 2. User signs the PSBT with their wallet
267
- * 3. Submit signed PSBT back to Radfi for co-signing and broadcasting
268
- *
269
- * @example
270
- * ```tsx
271
- * const { mutateAsync: renewUtxos, isPending } = useRenewUtxos(spokeProvider);
272
- *
273
- * const handleRenew = async (expiredUtxos: RadfiUtxo[]) => {
274
- * const txIdVouts = expiredUtxos.map(u => u.txidVout);
275
- * const txId = await renewUtxos({ txIdVouts });
276
- * console.log('Renewed:', txId);
277
- * };
278
- * ```
296
+ * React hook for renewing expired UTXOs in the user's Radfi trading wallet. Pure mutation: pass
297
+ * `{ txIdVouts, walletProvider }` to `mutate({...})`.
279
298
  */
280
- declare function useRenewUtxos(spokeProvider: BitcoinSpokeProvider | undefined): UseMutationResult<string, Error, RenewUtxosParams>;
299
+ declare function useRenewUtxos({ mutationOptions, }?: MutationHookParams<string, UseRenewUtxosVars>): SafeUseMutationResult<string, Error, UseRenewUtxosVars>;
281
300
 
282
- type WithdrawToUserParams = {
301
+ type UseRadfiWithdrawVars = {
283
302
  amount: string;
284
303
  tokenId: string;
285
304
  withdrawTo: string;
305
+ walletProvider: IBitcoinWalletProvider;
286
306
  };
287
307
  type WithdrawResult = {
288
308
  txId: string;
289
309
  fee: number;
290
310
  };
291
311
  /**
292
- * Hook to withdraw BTC from Radfi trading wallet to user's personal wallet.
293
- *
294
- * Flow:
295
- * 1. Build withdraw transaction via Radfi API (returns unsigned PSBT)
296
- * 2. User signs the PSBT with their wallet
297
- * 3. Submit signed PSBT back to Radfi for co-signing and broadcasting
298
- *
299
- * @example
300
- * ```tsx
301
- * const { mutateAsync: withdraw, isPending } = useRadfiWithdraw(spokeProvider);
302
- *
303
- * const handleWithdraw = async () => {
304
- * const result = await withdraw({
305
- * amount: '10000',
306
- * tokenId: '0:0',
307
- * withdrawTo: 'bc1q...', // user's segwit address
308
- * });
309
- * console.log('Withdrawn:', result.txId);
310
- * };
311
- * ```
312
+ * React hook for withdrawing BTC from the user's Radfi trading wallet back to their personal
313
+ * Bitcoin wallet. Pure mutation: pass all inputs (including the wallet provider) to
314
+ * `mutate({...})`.
312
315
  */
313
- declare function useRadfiWithdraw(spokeProvider: BitcoinSpokeProvider | undefined): UseMutationResult<WithdrawResult, Error, WithdrawToUserParams>;
316
+ declare function useRadfiWithdraw({ mutationOptions, }?: MutationHookParams<WithdrawResult, UseRadfiWithdrawVars>): SafeUseMutationResult<WithdrawResult, Error, UseRadfiWithdrawVars>;
314
317
 
315
- interface BorrowResponse {
316
- ok: true;
317
- value: [string, string];
318
- }
319
- type UseBorrowParams = {
320
- params: MoneyMarketBorrowParams;
321
- spokeProvider: SpokeProvider;
322
- };
323
318
  /**
324
- * React hook for borrowing tokens in the Sodax money market protocol.
325
- *
326
- * Encapsulates the async process to initiate a borrow transaction via the money market,
327
- * handling transaction creation, submission, and cross-chain logic.
328
- *
329
- * @returns {UseMutationResult<
330
- * BorrowResponse,
331
- * MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,
332
- * UseBorrowParams
333
- * >} A React Query mutation result object containing:
334
- * - mutateAsync: (params: UseBorrowParams) => Promise<BorrowResponse>
335
- * Triggers the borrow action. Expects an object with valid borrow params and a `SpokeProvider`.
336
- * - isPending: `boolean` if a borrow transaction is in progress.
337
- * - error: `MoneyMarketError` if the transaction fails, or `null`.
338
- *
339
- * @example
340
- * ```typescript
341
- * const { mutateAsync: borrow, isPending, error } = useBorrow();
342
- * await borrow({ params: borrowParams, spokeProvider });
343
- * ```
319
+ * Mutation variables for {@link useBorrow}. Generic over `K extends SpokeChainKey` (defaults to
320
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
321
+ * `walletProvider` and `params.srcChainKey` types.
322
+ */
323
+ type UseBorrowVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketBorrowActionParams<K, false>, 'raw'>;
324
+ /**
325
+ * React hook for borrowing tokens from the Sodax money market protocol.
344
326
  *
345
- * @throws {Error} When:
346
- * - `spokeProvider` is missing or invalid.
347
- * - The underlying borrow transaction fails.
327
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
328
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
348
329
  */
349
- declare function useBorrow(): UseMutationResult<BorrowResponse, MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>, UseBorrowParams>;
330
+ declare function useBorrow<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseBorrowVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseBorrowVars<K>>;
350
331
 
351
- interface RepayResponse {
352
- ok: true;
353
- value: [string, string];
354
- }
355
- type UseRepayParams = {
356
- params: MoneyMarketRepayParams;
357
- spokeProvider: SpokeProvider;
358
- };
332
+ /**
333
+ * Mutation variables for {@link useRepay}. Generic over `K extends SpokeChainKey` (defaults to
334
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
335
+ * `walletProvider` and `params.srcChainKey` types.
336
+ */
337
+ type UseRepayVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketRepayActionParams<K, false>, 'raw'>;
359
338
  /**
360
339
  * React hook for repaying a borrow in the Sodax money market protocol.
361
340
  *
362
- * This hook encapsulates the process of sending a repay transaction to the money market.
363
- * It manages the asynchronous operation for repayment, including sending the transaction
364
- * and error handling.
365
- *
366
- * @returns {UseMutationResult<RepayResponse, MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>, UseRepayParams>} React Query mutation result object containing:
367
- * - mutateAsync: (params: UseRepayParams) => Promise<RepayResponse>
368
- * Initiates a repay transaction using the given MoneyMarketRepayParams and SpokeProvider.
369
- * - isPending: boolean indicating if a transaction is in progress.
370
- * - error: MoneyMarketError if an error occurred while repaying, otherwise undefined.
371
- *
372
- * @example
373
- * ```typescript
374
- * const { mutateAsync: repay, isPending, error } = useRepay();
375
- * await repay({ params: repayParams, spokeProvider });
376
- * ```
377
- *
378
- * @throws {Error} When:
379
- * - `spokeProvider` is missing or invalid.
380
- * - The underlying repay transaction fails.
341
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
342
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
381
343
  */
382
- declare function useRepay(): UseMutationResult<RepayResponse, MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>, UseRepayParams>;
344
+ declare function useRepay<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseRepayVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseRepayVars<K>>;
383
345
 
384
- interface SupplyResponse {
385
- ok: true;
386
- value: [string, string];
387
- }
388
- type UseSupplyParams = {
389
- params: MoneyMarketSupplyParams;
390
- spokeProvider: SpokeProvider;
391
- };
346
+ /**
347
+ * Mutation variables for {@link useSupply}. Generic over `K extends SpokeChainKey` (defaults to
348
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
349
+ * `walletProvider` and `params.srcChainKey` types.
350
+ */
351
+ type UseSupplyVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketSupplyActionParams<K, false>, 'raw'>;
392
352
  /**
393
353
  * React hook for supplying tokens to the Sodax money market protocol.
394
354
  *
395
- * Provides a mutation for performing the supply operation using React Query. Useful
396
- * for UI components needing to manage the full state (pending, error, etc.) of a supply
397
- * transaction. It handles transaction creation, cross-chain logic, and errors.
398
- *
399
- * @returns {UseMutationResult<SupplyResponse, MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>, UseSupplyParams>}
400
- * Mutation result object from React Query, where:
401
- * - mutateAsync(params: UseSupplyParams): Promise<SupplyResponse>
402
- * Initiates a supply transaction using the given MoneyMarketSupplyParams and SpokeProvider.
403
- * - isPending: boolean indicating if a transaction is in progress.
404
- * - error: MoneyMarketError if an error occurred while supplying, otherwise undefined.
355
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
356
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
405
357
  *
406
358
  * @example
407
- * ```typescript
408
- * const { mutateAsync: supply, isPending, error } = useSupply();
409
- * await supply({ params: supplyParams, spokeProvider });
359
+ * ```tsx
360
+ * const walletProvider = useWalletProvider({ xChainId: chainKey });
361
+ * const { mutateAsync: supply, isError, error } = useSupply();
362
+ * if (!walletProvider) return;
363
+ * try {
364
+ * const { spokeTxHash, hubTxHash } = await supply({ params: supplyParams, walletProvider });
365
+ * } catch (e) {
366
+ * // surfaced via mutation.error / onError
367
+ * }
410
368
  * ```
411
- *
412
- * @throws {Error|MoneyMarketError<...>} When:
413
- * - `spokeProvider` is not provided or invalid.
414
- * - The underlying supply transaction fails.
415
369
  */
416
- declare function useSupply(): UseMutationResult<SupplyResponse, MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>, UseSupplyParams>;
370
+ declare function useSupply<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseSupplyVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseSupplyVars<K>>;
417
371
 
418
- type UseWithdrawParams = {
419
- params: MoneyMarketWithdrawParams;
420
- spokeProvider: SpokeProvider;
421
- };
422
- interface WithdrawResponse {
423
- ok: true;
424
- value: [string, string];
425
- }
426
372
  /**
427
- * Hook for performing withdrawals from the Sodax money market.
428
- *
429
- * This hook exposes a mutation that executes the complete withdrawal logic, including transaction
430
- * creation and handling cross-chain communication. It leverages React Query's mutation API for
431
- * easy asynchronous handling and status tracking within UI components.
432
- *
433
- * @returns {UseMutationResult<WithdrawResponse, MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>, UseWithdrawParams>}
434
- * Mutation result object, with:
435
- * - mutateAsync: (params: UseWithdrawParams) => Promise<WithdrawResponse>
436
- * Initiates the withdrawal using the provided params.
437
- * - isPending: boolean indicating if a transaction is in progress.
438
- * - error: MoneyMarketError if an error occurred while withdrawing, otherwise undefined.
439
- *
440
- * @example
441
- * ```typescript
442
- * const { mutateAsync: withdraw, isPending, error } = useWithdraw();
443
- * await withdraw({ params: withdrawParams, spokeProvider });
444
- * ```
373
+ * Mutation variables for {@link useWithdraw}. Generic over `K extends SpokeChainKey` (defaults to
374
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
375
+ * `walletProvider` and `params.srcChainKey` types.
376
+ */
377
+ type UseWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketWithdrawActionParams<K, false>, 'raw'>;
378
+ /**
379
+ * React hook for withdrawing supplied tokens from the Sodax money market protocol.
445
380
  *
446
- * @throws {Error} When:
447
- * - spokeProvider is not provided or invalid.
448
- * - Underlying withdrawal logic fails.
381
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
382
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
449
383
  */
450
- declare function useWithdraw(): UseMutationResult<WithdrawResponse, MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>, UseWithdrawParams>;
384
+ declare function useWithdraw<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseWithdrawVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseWithdrawVars<K>>;
451
385
 
452
- type BaseQueryOptions$1 = {
453
- queryOptions?: UseQueryOptions<readonly [readonly UserReserveData[], number], Error>;
454
- };
455
- type NewParams$1 = BaseQueryOptions$1 & {
456
- /** Spoke chain id (e.g. '0xa86a.avax') */
457
- spokeChainId: SpokeChainId$1 | undefined;
458
- /** User wallet address on the spoke chain */
386
+ type UseUserReservesDataParams = ReadHookParams<readonly [readonly UserReserveData[], number], {
387
+ spokeChainKey: SpokeChainKey | undefined;
459
388
  userAddress: string | undefined;
460
- };
461
- /** @deprecated Use `{ spokeChainId, userAddress }` instead */
462
- type LegacyParams$1 = BaseQueryOptions$1 & {
463
- /** @deprecated Use `spokeChainId` instead */
464
- spokeProvider: SpokeProvider | undefined;
465
- /** @deprecated Use `userAddress` instead */
466
- address: string | undefined;
467
- };
468
- type UseUserReservesDataParams = NewParams$1 | LegacyParams$1;
389
+ }>;
469
390
  /**
470
- * Hook for fetching user reserves data from the Sodax money market.
471
- *
472
- * @param params (optional) - Object including:
473
- * - spokeChainId: The spoke chain id whose reserves data will be fetched. If not provided, data fetching is disabled.
474
- * - userAddress: The user's address (string) whose reserves data will be fetched. If not provided, data fetching is disabled.
475
- * - queryOptions: (optional) Custom React Query options such as `queryKey`, `enabled`, or cache policy.
476
- *
477
- * @returns {UseQueryResult<readonly [readonly UserReserveData[], number], Error>} React Query result object containing:
478
- * - data: A tuple with array of UserReserveData and associated number, or undefined if loading
479
- * - isLoading: Boolean loading state
480
- * - isError: Boolean error state
481
- * - error: Error object, if present
482
- *
483
- * @example
484
- * const { data: userReservesData, isLoading, error } = useUserReservesData({
485
- * spokeChainId,
486
- * userAddress,
487
- * });
391
+ * React hook for fetching the raw user reserves data (positions on the hub) for a given spoke
392
+ * chain and user address.
488
393
  */
489
- declare function useUserReservesData(params?: UseUserReservesDataParams): UseQueryResult<readonly [readonly UserReserveData[], number], Error>;
394
+ declare function useUserReservesData({ params, queryOptions, }?: UseUserReservesDataParams): UseQueryResult<readonly [readonly UserReserveData[], number], Error>;
490
395
 
491
- type UseReservesDataParams = {
492
- queryOptions?: UseQueryOptions<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>;
493
- };
396
+ type UseReservesDataParams = ReadHookParams<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo]>;
494
397
  /**
495
- * React hook for fetching the latest reserves data from the Sodax money market.
496
- *
497
- * Provides the full set of aggregated reserves and base currency information.
498
- * Optionally accepts React Query options for customizing the query key, cache time, and related behaviors.
499
- *
500
- * @param params (optional) - Object including:
501
- * - queryOptions: Custom React Query options
502
- *
503
- * @returns {UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>}
504
- * React Query result object containing:
505
- * - data: [aggregated reserves[], base currency info], or undefined if not loaded
506
- * - isLoading: True if the request is loading
507
- * - isError: True if the request failed
508
- * - error: Error object, if present
509
- *
510
- * @example
511
- * const { data, isLoading, error } = useReservesData();
512
- * const { data } = useReservesData({ queryOptions: { queryKey: ['custom', 'reservesData'] } });
398
+ * React hook for fetching the latest aggregated reserves data and base-currency info from the
399
+ * Sodax money market.
513
400
  */
514
- declare function useReservesData(params?: UseReservesDataParams): UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>;
401
+ declare function useReservesData({ queryOptions, }?: UseReservesDataParams): UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>;
515
402
 
516
- type UseMMAllowanceParams = {
517
- params: MoneyMarketParams | undefined;
518
- spokeProvider: SpokeProvider | undefined;
519
- queryOptions?: UseQueryOptions<boolean, Error>;
520
- };
403
+ type UseReservesHumanizedParams = ReadHookParams<ReservesDataHumanized>;
521
404
  /**
522
- * Hook for checking token allowance for money market operations.
523
- *
524
- * This hook verifies if the user has approved enough tokens for a specific money market action
525
- * (borrow/repay). It automatically queries and tracks the allowance status.
526
- *
527
- * @param {XToken} token - The token to check allowance for. Must be an XToken with valid address and chain information.
528
- * @param {string} amount - The amount to check allowance for, as a decimal string
529
- * @param {MoneyMarketAction} action - The money market action to check allowance for ('borrow' or 'repay')
530
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
531
- *
532
- * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
533
- * - data: Boolean indicating if allowance is sufficient
534
- * - isLoading: Loading state indicator
535
- * - error: Any error that occurred during the check
536
- *
537
- * @example
538
- * ```typescript
539
- * const { data: hasAllowed, isLoading } = useMMAllowance(token, "100", "repay", provider);
540
- * ```
405
+ * React hook for fetching the human-readable (decimal-normalized, string-formatted) reserves
406
+ * snapshot from the Sodax money market.
541
407
  */
542
- declare function useMMAllowance({ params, spokeProvider, queryOptions, }: UseMMAllowanceParams): UseQueryResult<boolean, Error>;
408
+ declare function useReservesHumanized({ queryOptions, }?: UseReservesHumanizedParams): UseQueryResult<ReservesDataHumanized, Error>;
543
409
 
544
- type UseMMApproveParams = {
545
- params: MoneyMarketParams;
546
- spokeProvider: SpokeProvider | undefined;
547
- };
410
+ type UseReservesListParams = ReadHookParams<readonly Address$1[]>;
411
+ /**
412
+ * React hook for fetching the list of reserve asset addresses currently registered in the
413
+ * Sodax money market.
414
+ */
415
+ declare function useReservesList({ queryOptions, }?: UseReservesListParams): UseQueryResult<readonly Address$1[], Error>;
416
+
417
+ type UseMMAllowanceParams<K extends SpokeChainKey> = ReadHookParams<boolean, {
418
+ payload: MoneyMarketParams<K> | undefined;
419
+ }>;
548
420
  /**
549
- * Hook for approving ERC20 token spending for Sodax money market actions.
421
+ * Hook for checking token allowance / trustline sufficiency for money market operations.
550
422
  *
551
- * This hook manages the approval transaction, allowing the user
552
- * to grant the protocol permission to spend their tokens for specific money market actions
553
- * (such as supply, borrow, or repay). Upon successful approval, it also invalidates and
554
- * refetches the associated allowance status so the UI remains up-to-date.
423
+ * Skips the on-chain check entirely for `borrow` and `withdraw` actions — those don't require
424
+ * approval, and the SDK already short-circuits to `true` for them. The early `enabled: false`
425
+ * here additionally avoids a render flash with `isLoading: true`.
555
426
  *
556
- * @returns {UseMutationResult<string, Error, UseMMApproveParams>} A React Query mutation result containing:
557
- * - mutateAsync: Function to trigger the approval (see below)
558
- * - isPending: Boolean indicating if approval transaction is in progress
559
- * - error: Error object if the last approval failed, null otherwise
427
+ * The query key matches the invalidation keys emitted by `useMMApprove` and the four mutation
428
+ * hooks: `['mm', 'allowance', srcChainKey, token, action]`.
560
429
  *
561
430
  * @example
562
431
  * ```tsx
563
- * const { mutateAsync: approve, isPending, error } = useMMApprove();
564
- * await approve({ params: { token, amount: "100", action: "supply", ... }, spokeProvider });
432
+ * const { data: hasAllowance } = useMMAllowance({ params: { payload: supplyParams } });
565
433
  * ```
434
+ */
435
+ declare function useMMAllowance<K extends SpokeChainKey>({ params, queryOptions, }?: UseMMAllowanceParams<K>): UseQueryResult<boolean, Error>;
436
+
437
+ /**
438
+ * Mutation variables for {@link useMMApprove}. Generic over `K extends SpokeChainKey` (defaults
439
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
440
+ * `walletProvider` and `params.srcChainKey` types.
441
+ */
442
+ type UseMMApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketApproveActionParams<K, false>, 'raw'>;
443
+ /**
444
+ * React hook for approving ERC-20 token spending (or trustline establishment) for a Sodax money
445
+ * market action.
566
446
  *
567
- * @throws {Error} When:
568
- * - spokeProvider is undefined or invalid
569
- * - Approval transaction fails for any reason
447
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
448
+ * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates the matching
449
+ * `['mm', 'allowance', srcChainKey, token, action]` query on confirmed success.
570
450
  */
571
- declare function useMMApprove(): UseMutationResult<string, Error, UseMMApproveParams>;
451
+ declare function useMMApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseMMApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseMMApproveVars<K>>;
572
452
 
573
- type UseATokenParams = {
574
- aToken: string;
575
- queryOptions?: UseQueryOptions<XToken, Error>;
453
+ type ATokenData = Erc20Token & {
454
+ chainKey: ChainKey;
576
455
  };
456
+ type UseATokenParams = ReadHookParams<ATokenData, {
457
+ aToken: Address | string | undefined;
458
+ }>;
577
459
  /**
578
- * React hook to fetch and cache metadata for a given aToken address.
579
- *
580
- * Accepts an aToken address and React Query options to control query behavior.
581
- * Returns the aToken's ERC20-style metadata from the Sodax money market, with querying/caching
582
- * powered by React Query.
583
- *
584
- * @param {UseATokenParams} params - Required params object:
585
- * @property {Address} aToken - The aToken contract address to query.
586
- * @property {UseQueryOptions<XToken, Error>} queryOptions - React Query options to control query (e.g., staleTime, refetch, etc.).
587
- *
588
- * @returns {UseQueryResult<XToken, Error>} React Query result object:
589
- * - data: XToken metadata, if available
590
- * - isLoading: Boolean loading state
591
- * - error: Error, if API call fails
592
- *
593
- * @example
594
- * const { data: xToken, isLoading, error } = useAToken({ aToken: aTokenAddress, queryOptions: {} });
595
- * if (xToken) {
596
- * console.log(xToken.symbol);
597
- * }
460
+ * React hook to fetch ERC-20 metadata for a given aToken address on the hub chain.
461
+ * Returns `Erc20Token` (`name`, `symbol`, `decimals`, `address`) augmented with the hub
462
+ * `chainKey`. Note: the returned shape is a subset of `XToken` `hubAsset` and `vault` fields
463
+ * must be resolved separately if needed.
598
464
  */
599
- declare function useAToken({ aToken, queryOptions }: UseATokenParams): UseQueryResult<XToken, Error>;
465
+ declare function useAToken({ params, queryOptions }?: UseATokenParams): UseQueryResult<ATokenData, Error>;
600
466
 
601
- type UseATokensBalancesParams = {
467
+ type UseATokensBalancesParams = ReadHookParams<Map<Address, bigint>, {
602
468
  aTokens: readonly Address[];
603
- spokeProvider?: SpokeProvider;
604
- userAddress?: string;
605
- queryOptions?: UseQueryOptions<Map<Address, bigint>, Error>;
606
- };
469
+ spokeChainKey: SpokeChainKey | undefined;
470
+ userAddress: string | undefined;
471
+ }>;
607
472
  /**
608
- * React hook to fetch and cache aToken balances for multiple aToken addresses in a single multicall.
609
- *
610
- * Accepts an array of aToken addresses, a spoke provider, and user address. The hook derives the user's
611
- * hub wallet address and then fetches balanceOf for each aToken in a single multicall. Returns a Map
612
- * of aToken address to balance, with querying/caching powered by React Query. This hook uses viem's
613
- * multicall to batch all requests into a single RPC call for better performance.
614
- *
615
- * @param {UseATokensBalancesParams} params - Required params object:
616
- * @property {readonly Address[]} aTokens - Array of aToken contract addresses to query balances for.
617
- * @property {SpokeProvider} spokeProvider - The spoke provider to derive hub wallet address from.
618
- * @property {string} userAddress - User's wallet address on the spoke chain.
619
- * @property {UseQueryOptions<Map<Address, bigint>, Error>} queryOptions - React Query options to control query (e.g., staleTime, refetch, etc.).
620
- *
621
- * @returns {UseQueryResult<Map<Address, bigint>, Error>} React Query result object:
622
- * - data: Map of aToken address to balance, if available
623
- * - isLoading: Boolean loading state
624
- * - error: Error, if API call fails
625
- *
626
- * @example
627
- * const { data: aTokenBalances, isLoading, error } = useATokensBalances({
628
- * aTokens: [aToken1, aToken2, aToken3],
629
- * spokeProvider,
630
- * userAddress: '0x...',
631
- * queryOptions: {}
632
- * });
633
- * const aToken1Balance = aTokenBalances?.get(aToken1);
473
+ * React hook to fetch aToken balances for a list of addresses in a single multicall.
474
+ * Derives the user's hub wallet via `EvmHubProvider.getUserHubWalletAddress` from the
475
+ * spoke `chainKey` + spoke wallet `userAddress`.
634
476
  */
635
- declare function useATokensBalances({ aTokens, spokeProvider, userAddress, queryOptions, }: UseATokensBalancesParams): UseQueryResult<Map<Address, bigint>, Error>;
477
+ declare function useATokensBalances({ params, queryOptions, }?: UseATokensBalancesParams): UseQueryResult<Map<Address, bigint>, Error>;
636
478
 
637
- type UseReservesUsdFormatParams = {
638
- queryOptions?: UseQueryOptions<(ReserveData & {
639
- priceInMarketReferenceCurrency: string;
640
- } & FormatReserveUSDResponse)[], Error>;
641
- };
479
+ type ReserveUsdFormat = ReserveDataHumanized & FormatReserveUSDResponse;
480
+ type UseReservesUsdFormatParams = ReadHookParams<ReserveUsdFormat[]>;
642
481
  /**
643
- * Hook for fetching reserves data formatted with USD values in the Sodax money market.
644
- *
645
- * This hook returns an array of reserve objects, each extended with its price in the market reference
646
- * currency and formatted USD values. Data is automatically fetched and cached using React Query.
647
- *
648
- * @param params (optional) - Object including:
649
- * - queryOptions: Custom React Query options such as `queryKey`, cache behavior, or refetching policy.
650
- *
651
- * @returns {UseQueryResult<(ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[], Error>} React Query result object containing:
652
- * - data: Array of reserves with USD-formatted values, or undefined if loading
653
- * - isLoading: Boolean loading state
654
- * - isError: Boolean error state
655
- * - error: Error object, if present
656
- *
657
- * @example
658
- * const { data: reservesUSD, isLoading, error } = useReservesUsdFormat();
482
+ * React hook returning reserves with USD-formatted values for the Sodax money market.
483
+ * Chains `getReservesHumanized` → `buildReserveDataWithPrice` → `formatReservesUSD`.
659
484
  */
660
- declare function useReservesUsdFormat(params?: UseReservesUsdFormatParams): UseQueryResult<(ReserveData & {
661
- priceInMarketReferenceCurrency: string;
662
- } & FormatReserveUSDResponse)[], Error>;
485
+ declare function useReservesUsdFormat({ queryOptions, }?: UseReservesUsdFormatParams): UseQueryResult<ReserveUsdFormat[], Error>;
663
486
 
664
- type BaseQueryOptions = {
665
- queryOptions?: UseQueryOptions<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>;
666
- };
667
- type NewParams = BaseQueryOptions & {
668
- /** Spoke chain id (e.g. '0xa86a.avax') */
669
- spokeChainId: SpokeChainId$1 | undefined;
670
- /** User wallet address on the spoke chain */
487
+ type UseUserFormattedSummaryParams = ReadHookParams<FormatUserSummaryResponse<FormatReserveUSDResponse>, {
488
+ spokeChainKey: SpokeChainKey | undefined;
671
489
  userAddress: string | undefined;
672
- };
673
- /** @deprecated Use `{ spokeChainId, userAddress }` instead */
674
- type LegacyParams = BaseQueryOptions & {
675
- /** @deprecated Use `spokeChainId` instead */
676
- spokeProvider: SpokeProvider | undefined;
677
- /** @deprecated Use `userAddress` instead */
678
- address: string | undefined;
679
- };
680
- type UseUserFormattedSummaryParams = NewParams | LegacyParams;
490
+ }>;
681
491
  /**
682
- * React hook to fetch a formatted summary of a user's Sodax money market portfolio.
683
- *
684
- * @param params (optional) - Object including:
685
- * - spokeChainId: The spoke chain id whose data will be fetched. If not provided, data fetching is disabled.
686
- * - userAddress: The user's address (string) whose summary will be fetched. If not provided, data fetching is disabled.
687
- * - queryOptions: (optional) Custom React Query options such as `queryKey`, `enabled`, or cache policy.
688
- *
689
- * @returns {UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>}
690
- * A result object from React Query including:
691
- * - data: The user's formatted portfolio summary (or undefined if not loaded)
692
- * - isLoading: Boolean loading state
693
- * - isError: Boolean error state
694
- * - error: Error if thrown in fetching
492
+ * React hook returning the user's formatted money market portfolio summary (collateral, borrows,
493
+ * health factor, available borrow power, etc.) for the given spoke chain.
695
494
  *
696
- * @example
697
- * const { data, isLoading, error } = useUserFormattedSummary({ spokeChainId, userAddress });
495
+ * Internally chains `getReservesHumanized` → `formatReservesUSD` → `getUserReservesHumanized`
496
+ * `formatUserSummary`.
698
497
  */
699
- declare function useUserFormattedSummary(params?: UseUserFormattedSummaryParams): UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>;
498
+ declare function useUserFormattedSummary({ params, queryOptions, }?: UseUserFormattedSummaryParams): UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>;
700
499
 
500
+ type UseQuoteParams = ReadHookParams<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined, {
501
+ payload: SolverIntentQuoteRequest | undefined;
502
+ }>;
701
503
  /**
702
504
  * Hook for fetching a quote for an intent-based swap.
703
505
  *
704
- * This hook provides real-time quote data for an intent-based swap.
705
- *
706
- * @param {SolverIntentQuoteRequest | undefined} payload - The intent quote request parameters. If undefined, the query will be disabled.
707
- *
708
- * @returns {UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined>} A query result object containing:
709
- * - data: The quote result from the solver
710
- * - isLoading: Boolean indicating if the quote is being fetched
711
- * - error: Error object if the quote request failed
712
- * - refetch: Function to manually trigger a quote refresh
713
- *
714
506
  * @example
715
507
  * ```typescript
716
- * const { data: quote, isLoading } = useQuote({
717
- * token_src: '0x...',
718
- * token_src_blockchain_id: '1',
719
- * token_dst: '0x...',
720
- * token_dst_blockchain_id: '2',
721
- * amount: '1000000000000000000',
722
- * quote_type: 'exact_input',
723
- * });
724
- *
725
- * if (isLoading) return <div>Loading quote...</div>;
726
- * if (quote) {
727
- * console.log('Quote received:', quote);
728
- * }
508
+ * const { data: quote, isLoading } = useQuote({ params: { payload } });
729
509
  * ```
730
510
  *
731
511
  * @remarks
732
512
  * - The quote is automatically refreshed every 3 seconds
733
513
  * - The query is disabled when payload is undefined
734
- * - Uses React Query for efficient caching and state management
735
514
  */
736
- declare const useQuote: (payload: SolverIntentQuoteRequest | undefined) => UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined>;
515
+ declare const useQuote: ({ params, queryOptions, }?: UseQuoteParams) => UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined>;
737
516
 
738
- type CreateIntentResult = Result<[SolverExecutionResponse, Intent, IntentDeliveryInfo], IntentError<IntentErrorCode>>;
739
517
  /**
740
- * Hook for creating and submitting an swap intent order for cross-chain swaps.
741
- * Uses React Query's useMutation for better state management and caching.
742
- *
743
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the swap
744
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
518
+ * Mutation variables for {@link useSwap}. Generic over `K extends SpokeChainKey` (defaults to the
519
+ * full union). Sophisticated callers can lock K at the hook call site to narrow the
520
+ * `walletProvider` and `params.srcChainKey` types.
521
+ */
522
+ type UseSwapVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapActionParams<K, false>, 'raw'>;
523
+ /**
524
+ * React hook for executing an intent-based cross-chain swap.
745
525
  *
746
- * @example
747
- * ```typescript
748
- * const { mutateAsync: swap, isPending } = useSwap(spokeProvider);
749
- *
750
- * const handleSwap = async () => {
751
- * const result = await swap({
752
- * token_src: '0x...',
753
- * token_src_blockchain_id: 'arbitrum',
754
- * token_dst: '0x...',
755
- * token_dst_blockchain_id: 'polygon',
756
- * amount: '1000000000000000000',
757
- * min_output_amount: '900000000000000000'
758
- * });
759
- * };
760
- * ```
526
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
527
+ * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.
761
528
  */
762
- declare function useSwap(spokeProvider: SpokeProvider | undefined): UseMutationResult<CreateIntentResult, Error, CreateIntentParams>;
529
+ declare function useSwap<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<SwapResponse, UseSwapVars<K>>): SafeUseMutationResult<SwapResponse, Error, UseSwapVars<K>>;
763
530
 
531
+ type UseStatusParams = ReadHookParams<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined, {
532
+ intentTxHash: Hex | undefined;
533
+ }>;
764
534
  /**
765
535
  * Hook for monitoring the status of an intent-based swap.
766
536
  *
767
- * This hook provides real-time status updates for an intent-based swap transaction.
768
- *
769
- * @param {Hex} intent_tx_hash - The transaction hash of the intent order on the hub chain
770
- *
771
- * @returns {UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined>} A query result object containing:
772
- * - data: The status result from the solver
773
- * - isLoading: Boolean indicating if the status is being fetched
774
- * - error: Error object if the status request failed
775
- * - refetch: Function to manually trigger a status refresh
776
- *
777
537
  * @example
778
538
  * ```typescript
779
- * const { data: status, isLoading } = useStatus('0x...');
780
- *
781
- * if (isLoading) return <div>Loading status...</div>;
782
- * if (status?.ok) {
783
- * console.log('Status:', status.value);
784
- * }
539
+ * const { data: status, isLoading } = useStatus({ params: { intentTxHash } });
785
540
  * ```
786
- *
787
- * @remarks
788
- * - The status is automatically refreshed every 3 seconds
789
- * - Uses React Query for efficient caching and state management
790
541
  */
791
- declare const useStatus: (intent_tx_hash: Hex) => UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined>;
542
+ declare const useStatus: ({ params, queryOptions, }?: UseStatusParams) => UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined>;
543
+
544
+ type UseSwapAllowanceParams<K extends SpokeChainKey> = ReadHookParams<boolean, {
545
+ payload: CreateIntentParams | CreateLimitOrderParams | undefined;
546
+ srcChainKey: K | undefined;
547
+ walletProvider: GetWalletProviderType<K> | undefined;
548
+ }>;
549
+ declare function useSwapAllowance<K extends SpokeChainKey>({ params, queryOptions, }?: UseSwapAllowanceParams<K>): UseQueryResult<boolean, Error>;
792
550
 
793
551
  /**
794
- * Hook for checking token allowance for swap operations.
795
- *
796
- * This hook verifies if the user has approved enough tokens for a specific swap action.
797
- * It automatically queries and tracks the allowance status.
798
- *
799
- * @param {CreateIntentParams | CreateLimitOrderParams} params - The parameters for the intent to check allowance for.
800
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
801
- *
802
- * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
803
- * - data: Boolean indicating if allowance is sufficient
804
- * - isLoading: Loading state indicator
805
- * - error: Any error that occurred during the check
806
- *
807
- * @example
808
- * ```typescript
809
- * const { data: hasAllowed, isLoading } = useSwapAllowance(params, spokeProvider);
810
- * ```
552
+ * Mutation variables for {@link useSwapApprove}. Generic over `K extends SpokeChainKey` (defaults
553
+ * to the full union). Sophisticated callers can lock K at the call site to narrow the
554
+ * `walletProvider` and `params.srcChainKey` types.
811
555
  */
812
- declare function useSwapAllowance(params: CreateIntentParams | CreateLimitOrderParams | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
813
-
814
- interface UseApproveReturn$1 {
815
- approve: ({ params }: {
816
- params: CreateIntentParams | CreateLimitOrderParams;
817
- }) => Promise<boolean>;
818
- isLoading: boolean;
819
- error: Error | null;
820
- resetError: () => void;
821
- }
556
+ type UseSwapApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
557
+ params: CreateIntentParams<K> | CreateLimitOrderParams<K>;
558
+ walletProvider: GetWalletProviderType<K>;
559
+ };
822
560
  /**
823
- * Hook for approving token spending for swap actions
824
- * @param params The parameters for the intent to approve spending for
825
- * @param spokeProvider The spoke provider instance for the chain
826
- * @returns Object containing approve function, loading state, error state and reset function
827
- * @example
828
- * ```tsx
829
- * const { approve, isLoading, error } = useApprove(token, spokeProvider);
561
+ * React hook for approving ERC-20 token spending (or trustline establishment) for a swap or
562
+ * limit-order intent.
830
563
  *
831
- * // Approve tokens for supply action
832
- * await approve({ amount: "100", action: "supply" });
833
- * ```
564
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
565
+ * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates all
566
+ * `['swap', 'allowance', ...]` queries so any pending allowance check refreshes.
834
567
  */
835
- declare function useSwapApprove(params: CreateIntentParams | CreateLimitOrderParams | undefined, spokeProvider: SpokeProvider | undefined): UseApproveReturn$1;
568
+ declare function useSwapApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseSwapApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseSwapApproveVars<K>>;
836
569
 
837
- type CancelIntentParams = {
570
+ type CancelIntentParams<K extends SpokeChainKey = SpokeChainKey> = {
571
+ srcChainKey: K;
572
+ walletProvider: GetWalletProviderType<K>;
838
573
  intent: Intent;
839
- raw?: boolean;
840
574
  };
841
- type CancelIntentResult = Result<TxReturnType<SpokeProvider, boolean>>;
842
575
  /**
843
- * Hook for canceling a swap intent order.
844
- * Uses React Query's useMutation for better state management and caching.
576
+ * React hook for cancelling an in-flight swap intent.
845
577
  *
846
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for canceling the intent
847
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
848
- *
849
- * @example
850
- * ```typescript
851
- * const { mutateAsync: cancelSwap, isPending } = useCancelSwap(spokeProvider);
852
- *
853
- * const handleCancelSwap = async () => {
854
- * const result = await cancelSwap({
855
- * intent: intentObject,
856
- * raw: false // optional, defaults to false
857
- * });
858
- * };
859
- * ```
578
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
579
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
860
580
  */
861
- declare function useCancelSwap(spokeProvider: SpokeProvider | undefined): UseMutationResult<CancelIntentResult, Error, CancelIntentParams>;
581
+ declare function useCancelSwap({ mutationOptions, }?: MutationHookParams<TxHashPair, CancelIntentParams>): SafeUseMutationResult<TxHashPair, Error, CancelIntentParams>;
862
582
 
863
- type CreateLimitOrderResult = Result<[
864
- SolverExecutionResponse,
865
- Intent,
866
- IntentDeliveryInfo
867
- ], IntentError<IntentErrorCode>>;
868
583
  /**
869
- * Hook for creating a limit order intent (no deadline, must be cancelled manually by user).
870
- * Uses React Query's useMutation for better state management and caching.
871
- *
872
- * Limit orders remain active until manually cancelled by the user. Unlike swaps, limit orders
873
- * do not have a deadline (deadline is automatically set to 0n).
874
- *
875
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for creating the limit order
876
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
584
+ * Mutation variables for {@link useCreateLimitOrder}. Generic over `K extends SpokeChainKey`
585
+ * (defaults to the full union). Sophisticated callers can lock K at the call site to narrow the
586
+ * `walletProvider` and `params.srcChainKey` types.
587
+ */
588
+ type UseCreateLimitOrderVars<K extends SpokeChainKey = SpokeChainKey> = Omit<LimitOrderActionParams<K, false>, 'raw'>;
589
+ /**
590
+ * React hook for creating a limit-order intent (no deadline).
877
591
  *
878
- * @example
879
- * ```typescript
880
- * const { mutateAsync: createLimitOrder, isPending } = useCreateLimitOrder(spokeProvider);
881
- *
882
- * const handleCreateLimitOrder = async () => {
883
- * const result = await createLimitOrder({
884
- * inputToken: '0x...',
885
- * outputToken: '0x...',
886
- * inputAmount: 1000000000000000000n,
887
- * minOutputAmount: 900000000000000000n,
888
- * allowPartialFill: false,
889
- * srcChain: '0xa4b1.arbitrum',
890
- * dstChain: '0x89.polygon',
891
- * srcAddress: '0x...',
892
- * dstAddress: '0x...',
893
- * solver: '0x0000000000000000000000000000000000000000',
894
- * data: '0x'
895
- * });
896
- *
897
- * if (result.ok) {
898
- * const [solverExecutionResponse, intent, intentDeliveryInfo] = result.value;
899
- * console.log('Limit order created:', intent);
900
- * console.log('Intent hash:', solverExecutionResponse.intent_hash);
901
- * }
902
- * };
903
- * ```
592
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
593
+ * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.
904
594
  */
905
- declare function useCreateLimitOrder(spokeProvider: SpokeProvider | undefined): UseMutationResult<CreateLimitOrderResult, Error, CreateLimitOrderParams>;
595
+ declare function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<SwapResponse, UseCreateLimitOrderVars<K>>): SafeUseMutationResult<SwapResponse, Error, UseCreateLimitOrderVars<K>>;
906
596
 
907
- type CancelLimitOrderParams = {
597
+ type CancelLimitOrderParams<K extends SpokeChainKey = SpokeChainKey> = {
598
+ srcChainKey: K;
599
+ walletProvider: GetWalletProviderType<K>;
908
600
  intent: Intent;
909
- spokeProvider: SpokeProvider;
910
601
  timeout?: number;
911
602
  };
912
- type CancelLimitOrderResult = Result<[string, string], IntentError<IntentErrorCode>>;
913
603
  /**
914
- * Hook for canceling a limit order intent and submitting it to the Relayer API.
915
- * Uses React Query's useMutation for better state management and caching.
916
- *
917
- * This hook wraps cancelLimitOrder which cancels the intent on the spoke chain,
918
- * submits it to the relayer API, and waits for execution on the destination/hub chain.
604
+ * React hook for cancelling a limit-order intent.
919
605
  *
920
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
921
- *
922
- * @example
923
- * ```typescript
924
- * const { mutateAsync: cancelLimitOrder, isPending } = useCancelLimitOrder();
925
- *
926
- * const handleCancelLimitOrder = async () => {
927
- * const result = await cancelLimitOrder({
928
- * intent: intentObject,
929
- * spokeProvider,
930
- * timeout: 60000 // optional, defaults to 60 seconds
931
- * });
932
- *
933
- * if (result.ok) {
934
- * const [cancelTxHash, dstTxHash] = result.value;
935
- * console.log('Cancel transaction hash:', cancelTxHash);
936
- * console.log('Destination transaction hash:', dstTxHash);
937
- * }
938
- * };
939
- * ```
606
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
607
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
940
608
  */
941
- declare function useCancelLimitOrder(): UseMutationResult<CancelLimitOrderResult, Error, CancelLimitOrderParams>;
609
+ declare function useCancelLimitOrder({ mutationOptions, }?: MutationHookParams<TxHashPair, CancelLimitOrderParams>): SafeUseMutationResult<TxHashPair, Error, CancelLimitOrderParams>;
942
610
 
943
- type UseBackendIntentByTxHashParams = {
944
- params: {
945
- txHash: string | undefined;
946
- };
947
- queryOptions?: UseQueryOptions<IntentResponse | undefined, Error>;
948
- };
611
+ type UseBackendIntentByTxHashParams = ReadHookParams<IntentResponse | undefined, {
612
+ txHash: string | undefined;
613
+ }>;
949
614
  /**
950
615
  * React hook for fetching intent details from the backend API using a transaction hash.
951
616
  *
952
- * @param {UseBackendIntentByTxHashParams | undefined} params - Parameters for the query:
953
- * - params: { txHash: string | undefined }
954
- * - `txHash`: Transaction hash used to retrieve the associated intent; query is disabled if undefined or empty.
955
- * - queryOptions (optional): React Query options to customize request behavior (e.g., caching, retry, refetchInterval, etc.).
956
- *
957
- * @returns {UseQueryResult<IntentResponse | undefined, Error>} React Query result object, including:
958
- * - `data`: The intent response or undefined if unavailable,
959
- * - `isLoading`: Loading state,
960
- * - `error`: Error (if request failed),
961
- * - `refetch`: Function to refetch the data.
962
- *
963
617
  * @example
964
- * const { data: intent, isLoading, error } = useBackendIntentByTxHash({
965
- * params: { txHash: '0x123...' },
966
- * });
967
- *
968
- * if (isLoading) return <div>Loading intent...</div>;
969
- * if (error) return <div>Error: {error.message}</div>;
970
- * if (intent) {
971
- * console.log('Intent found:', intent.intentHash);
972
- * }
618
+ * const { data: intent } = useBackendIntentByTxHash({ params: { txHash: '0x123...' } });
973
619
  *
974
620
  * @remarks
975
621
  * - Intents are only created on the hub chain, so `txHash` must originate from there.
976
- * - Query is disabled if `params` is undefined, or if `params.params.txHash` is undefined or an empty string.
977
- * - Default refetch interval is 1 second. Uses React Query for state management, caching, and retries.
622
+ * - Default refetch interval is 1 second.
978
623
  */
979
- declare const useBackendIntentByTxHash: (params: UseBackendIntentByTxHashParams | undefined) => UseQueryResult<IntentResponse | undefined, Error>;
624
+ declare const useBackendIntentByTxHash: ({ params, queryOptions, }?: UseBackendIntentByTxHashParams) => UseQueryResult<IntentResponse | undefined, Error>;
980
625
 
981
- type UseBackendIntentByHashParams = {
982
- params: {
983
- intentHash: string | undefined;
984
- };
985
- queryOptions?: UseQueryOptions<IntentResponse | undefined, Error>;
986
- };
626
+ type UseBackendIntentByHashParams = ReadHookParams<IntentResponse | undefined, {
627
+ intentHash: string | undefined;
628
+ }>;
987
629
  /**
988
630
  * React hook to fetch intent details from the backend API using an intent hash.
989
631
  *
990
- * @param {UseBackendIntentByHashParams | undefined} params - Parameters for the query:
991
- * - params: { intentHash: string | undefined }
992
- * - `intentHash`: The hash identifying the intent to fetch (disables query if undefined or empty).
993
- * - queryOptions (optional): Options to customize React Query (e.g., staleTime, enabled).
994
- *
995
- * @returns {UseQueryResult<IntentResponse | undefined, Error>} React Query result containing intent response data, loading, error, and refetch states.
996
- *
997
632
  * @example
998
- * const { data: intent, isLoading, error } = useBackendIntentByHash({
999
- * params: { intentHash: '0xabc...' },
1000
- * });
1001
- *
1002
- * if (isLoading) return <div>Loading intent...</div>;
1003
- * if (error) return <div>Error: {error.message}</div>;
1004
- * if (intent) {
1005
- * console.log('Intent found:', intent.intentHash);
1006
- * }
1007
- *
1008
- * @remarks
1009
- * - Returns `undefined` data if no intentHash is provided or query is disabled.
1010
- * - Query is cached and managed using React Query.
1011
- * - Use `queryOptions` to customize caching, retry and fetch behavior.
633
+ * const { data: intent } = useBackendIntentByHash({ params: { intentHash: '0xabc...' } });
1012
634
  */
1013
- declare const useBackendIntentByHash: (params: UseBackendIntentByHashParams | undefined) => UseQueryResult<IntentResponse | undefined, Error>;
635
+ declare const useBackendIntentByHash: ({ params, queryOptions, }?: UseBackendIntentByHashParams) => UseQueryResult<IntentResponse | undefined, Error>;
1014
636
 
1015
- type BackendPaginationParams = {
1016
- offset: string;
1017
- limit: string;
1018
- };
1019
-
1020
- type GetUserIntentsParams = {
1021
- userAddress: Address$1;
637
+ type UseBackendUserIntentsParams = ReadHookParams<UserIntentsResponse | undefined, {
638
+ userAddress: Address$1 | undefined;
1022
639
  startDate?: number;
1023
640
  endDate?: number;
1024
- };
1025
- type UseBackendUserIntentsParams = {
1026
- params?: GetUserIntentsParams;
1027
- queryOptions?: UseQueryOptions<UserIntentsResponse | undefined, Error>;
1028
- pagination?: BackendPaginationParams;
1029
- };
641
+ }>;
1030
642
  /**
1031
- * React hook for fetching user-created intents from the backend API for a given user address,
1032
- * with optional support for a date filtering range.
1033
- *
1034
- * @param {UseBackendUserIntentsParams} args - Query configuration.
1035
- * @param {GetUserIntentsParams | undefined} args.params - User intent filter parameters.
1036
- * @param {Address} args.params.userAddress - The wallet address of the user (required).
1037
- * @param {number} [args.params.startDate] - Include intents created after this timestamp (ms).
1038
- * @param {number} [args.params.endDate] - Include intents created before this timestamp (ms).
1039
- * @param {UseQueryOptions<UserIntentsResponse | undefined, Error>} [args.queryOptions] - Optional React Query options.
1040
- * @param {BackendPaginationParams} [args.pagination] - (currently ignored) Pagination options.
1041
- *
1042
- * @returns {UseQueryResult<UserIntentsResponse | undefined, Error>} React Query result:
1043
- * - `data`: The user intent response, or undefined if unavailable.
1044
- * - `isLoading`: `true` if loading.
1045
- * - `error`: An Error instance if any occurred.
1046
- * - `refetch`: Function to refetch data.
643
+ * React hook for fetching user-created intents from the backend API for a given user address.
1047
644
  *
1048
645
  * @example
1049
- * const { data: userIntents, isLoading, error } = useBackendUserIntents({
1050
- * params: { userAddress: "0x123..." }
646
+ * const { data: userIntents } = useBackendUserIntents({
647
+ * params: { userAddress: '0x123...' },
1051
648
  * });
1052
- *
1053
- * @example
1054
- * const { data } = useBackendUserIntents({
1055
- * params: {
1056
- * userAddress: "0xabc...",
1057
- * startDate: Date.now() - 1_000_000,
1058
- * endDate: Date.now(),
1059
- * },
1060
- * });
1061
- *
1062
- * @remarks
1063
- * The query is disabled if `params` or `params.userAddress` is missing or empty. Uses React Query for
1064
- * cache/state management and auto-retries failed requests three times by default.
1065
649
  */
1066
- declare const useBackendUserIntents: ({ params, queryOptions, }: UseBackendUserIntentsParams) => UseQueryResult<UserIntentsResponse | undefined, Error>;
650
+ declare const useBackendUserIntents: ({ params, queryOptions, }?: UseBackendUserIntentsParams) => UseQueryResult<UserIntentsResponse | undefined, Error>;
1067
651
 
1068
- type UseBackendSubmitSwapTxParams = {
652
+ /**
653
+ * Mutation variables for {@link useBackendSubmitSwapTx}. The per-request `apiConfig` override
654
+ * (e.g. base URL) belongs here rather than at the hook level — different submissions in the same
655
+ * component can target different endpoints without re-rendering.
656
+ */
657
+ type UseBackendSubmitSwapTxVars = {
658
+ request: SubmitSwapTxRequest;
1069
659
  apiConfig?: RequestOverrideConfig;
1070
- mutationOptions?: UseMutationOptions<SubmitSwapTxResponse, Error, SubmitSwapTxRequest>;
1071
660
  };
1072
661
  /**
1073
- * React hook for submitting a swap transaction to be processed by the backend
1074
- * (relay, post execution to solver, etc.).
1075
- *
1076
- * @param {UseBackendSubmitSwapTxParams | undefined} params - Optional parameters:
1077
- * - `mutationOptions`: React Query mutation options to customize behavior (e.g., onSuccess, onError, retry).
662
+ * React hook for submitting a swap transaction to be processed by the backend (relay, post
663
+ * execution to solver, etc.).
1078
664
  *
1079
- * @returns {UseMutationResult<SubmitSwapTxResponse, Error, SubmitSwapTxRequest>} React Query mutation result:
1080
- * - `mutate` / `mutateAsync`: Functions to trigger the submission.
1081
- * - `data`: The submit response on success.
1082
- * - `isPending`: Loading state.
1083
- * - `error`: Error instance if the mutation failed.
665
+ * Pure mutation: pass `{ request, apiConfig? }` to `mutate({...})`. Default `retry: 3` is applied
666
+ * at the hook level consumers can override via `mutationOptions.retry`.
1084
667
  *
1085
668
  * @example
1086
669
  * const { mutateAsync: submitSwapTx, isPending, error } = useBackendSubmitSwapTx();
1087
670
  *
1088
671
  * const result = await submitSwapTx({
1089
- * txHash: '0x123...',
1090
- * srcChainId: '1',
1091
- * walletAddress: '0xabc...',
1092
- * intent: { ... },
1093
- * relayData: '0x...',
672
+ * request: { txHash: '0x123...', srcChainKey: 'sonic', walletAddress: '0xabc...', intent: { ... }, relayData: '0x...' },
673
+ * apiConfig: { baseURL: 'https://...' },
1094
674
  * });
1095
675
  */
1096
- declare const useBackendSubmitSwapTx: (params?: UseBackendSubmitSwapTxParams) => UseMutationResult<SubmitSwapTxResponse, Error, SubmitSwapTxRequest>;
676
+ declare const useBackendSubmitSwapTx: ({ mutationOptions, }?: MutationHookParams<SubmitSwapTxResponse, UseBackendSubmitSwapTxVars>) => SafeUseMutationResult<SubmitSwapTxResponse, Error, UseBackendSubmitSwapTxVars>;
1097
677
 
1098
- type UseBackendSubmitSwapTxStatusParams = {
1099
- params: {
1100
- txHash: string | undefined;
1101
- srcChainId?: string;
1102
- };
678
+ type UseBackendSubmitSwapTxStatusParams = ReadHookParams<SubmitSwapTxStatusResponse | undefined, {
679
+ txHash: string | undefined;
680
+ srcChainKey?: string;
1103
681
  apiConfig?: RequestOverrideConfig;
1104
- queryOptions?: UseQueryOptions<SubmitSwapTxStatusResponse | undefined, Error>;
1105
- };
682
+ }>;
1106
683
  /**
1107
684
  * React hook for polling the processing status of a submitted swap transaction.
1108
685
  *
1109
- * @param {UseBackendSubmitSwapTxStatusParams | undefined} params - Parameters for the query:
1110
- * - `params.txHash`: The transaction hash of the submitted swap; query is disabled if undefined or empty.
1111
- * - `params.srcChainId`: Optional source chain ID to narrow the status lookup.
1112
- * - `queryOptions`: Optional React Query options to override default behavior (e.g., refetchInterval, retry).
1113
- *
1114
- * @returns {UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error>} React Query result object:
1115
- * - `data`: The status response or undefined if unavailable.
1116
- * - `isLoading`: Loading state.
1117
- * - `error`: Error instance if the query failed.
1118
- * - `refetch`: Function to re-trigger the query.
1119
- *
1120
686
  * @example
1121
- * const { data: status, isLoading, error } = useBackendSubmitSwapTxStatus({
1122
- * params: { txHash: '0x123...', srcChainId: '1' },
687
+ * const { data: status } = useBackendSubmitSwapTxStatus({
688
+ * params: { txHash: '0x123...', srcChainKey: 'sonic' },
1123
689
  * });
1124
690
  *
1125
- * if (status?.data.status === 'executed') {
1126
- * console.log('Swap completed!', status.data.result);
1127
- * }
1128
- *
1129
691
  * @remarks
1130
- * - Query is disabled if `params` is undefined or `txHash` is undefined/empty.
1131
- * - Default refetch interval is 1 second for real-time status polling.
1132
- * - Uses React Query for state management, caching, and retries.
692
+ * - Default refetch interval is 1 second; stops on 'executed' or 'failed' status.
1133
693
  */
1134
- declare const useBackendSubmitSwapTxStatus: (params: UseBackendSubmitSwapTxStatusParams | undefined) => UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error>;
694
+ declare const useBackendSubmitSwapTxStatus: ({ params, queryOptions, }?: UseBackendSubmitSwapTxStatusParams) => UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error>;
1135
695
 
1136
- type UseBackendOrderbookParams = {
1137
- queryOptions?: UseQueryOptions<OrderbookResponse | undefined, Error>;
1138
- pagination?: BackendPaginationParams;
696
+ type BackendPaginationParams = {
697
+ offset: string;
698
+ limit: string;
1139
699
  };
700
+
701
+ type UseBackendOrderbookParams = ReadHookParams<OrderbookResponse, {
702
+ pagination: BackendPaginationParams;
703
+ }>;
1140
704
  /**
1141
705
  * Hook for fetching the solver orderbook from the backend API.
1142
706
  *
1143
- * @param {UseBackendOrderbookParams | undefined} params - Optional parameters:
1144
- * - `pagination`: Pagination configuration (see `BackendPaginationParams`), including
1145
- * `offset` and `limit` (both required for fetch to be enabled).
1146
- * - `queryOptions`: Optional React Query options to override default behavior.
1147
- *
1148
- * @returns {UseQueryResult<OrderbookResponse | undefined, Error>} React Query result object:
1149
- * - `data`: The orderbook response, or undefined if unavailable.
1150
- * - `isLoading`: Loading state.
1151
- * - `error`: Error instance if the query failed.
1152
- * - `refetch`: Function to re-trigger the query.
1153
- *
1154
707
  * @example
1155
- * const { data, isLoading, error } = useBackendOrderbook({
1156
- * pagination: { offset: '0', limit: '10' },
1157
- * queryOptions: { staleTime: 60000 },
1158
- * });
1159
- *
1160
- * @remarks
1161
- * - Query is disabled if `params?.pagination`, `offset`, or `limit` are missing/empty.
1162
- * - Caches and manages server state using React Query.
1163
- * - Default `staleTime` is 30 seconds to support near-real-time updates.
708
+ * const { data } = useBackendOrderbook({ params: { pagination: { offset: '0', limit: '10' } } });
1164
709
  */
1165
- declare const useBackendOrderbook: (params: UseBackendOrderbookParams | undefined) => UseQueryResult<OrderbookResponse | undefined>;
710
+ declare const useBackendOrderbook: ({ params, queryOptions, }?: UseBackendOrderbookParams) => UseQueryResult<OrderbookResponse>;
1166
711
 
1167
- type UseBackendMoneyMarketPositionParams = {
712
+ type UseBackendMoneyMarketPositionParams = ReadHookParams<MoneyMarketPosition | undefined, {
1168
713
  userAddress: string | undefined;
1169
- queryOptions?: UseQueryOptions<MoneyMarketPosition | undefined, Error>;
1170
- };
714
+ }>;
1171
715
  /**
1172
716
  * React hook for fetching a user's money market position from the backend API.
1173
717
  *
1174
- * @param {UseBackendMoneyMarketPositionParams | undefined} params - Parameters object:
1175
- * - userAddress: The user's wallet address to fetch positions for. If undefined or empty, the query is disabled.
1176
- * - queryOptions: (Optional) React Query options to customize behavior (e.g., staleTime, enabled).
1177
- *
1178
- * @returns {UseQueryResult<MoneyMarketPosition | undefined, Error>} - React Query result object with:
1179
- * - data: The user's money market position data, or undefined if not available.
1180
- * - isLoading: Loading state.
1181
- * - error: An Error instance if fetching failed.
1182
- * - refetch: Function to manually trigger a refetch.
1183
- *
1184
718
  * @example
1185
- * const { data, isLoading, error } = useBackendMoneyMarketPosition({
1186
- * userAddress: '0xabc...',
1187
- * queryOptions: { staleTime: 60000 },
1188
- * });
719
+ * const { data } = useBackendMoneyMarketPosition({ params: { userAddress: '0xabc...' } });
1189
720
  */
1190
- declare const useBackendMoneyMarketPosition: (params: UseBackendMoneyMarketPositionParams | undefined) => UseQueryResult<MoneyMarketPosition | undefined, Error>;
721
+ declare const useBackendMoneyMarketPosition: ({ params, queryOptions, }?: UseBackendMoneyMarketPositionParams) => UseQueryResult<MoneyMarketPosition | undefined, Error>;
1191
722
 
1192
- type UseBackendAllMoneyMarketAssetsParams = {
1193
- queryOptions?: UseQueryOptions<MoneyMarketAsset[], Error>;
1194
- };
723
+ type UseBackendAllMoneyMarketAssetsParams = ReadHookParams<MoneyMarketAsset[]>;
1195
724
  /**
1196
725
  * React hook to fetch all money market assets from the backend API.
1197
726
  *
1198
- * @param {UseBackendAllMoneyMarketAssetsParams | undefined} params - Optional parameters:
1199
- * - `queryOptions` (optional): React Query options to override default behavior (e.g., caching, retry, etc).
1200
- *
1201
- * @returns {UseQueryResult<MoneyMarketAsset[], Error>} React Query result object:
1202
- * - `data`: Array of all money market asset data when available.
1203
- * - `isLoading`: Boolean indicating if the request is in progress.
1204
- * - `error`: Error object if the request failed.
1205
- * - `refetch`: Function to manually trigger a data refresh.
1206
- *
1207
727
  * @example
1208
728
  * const { data: assets, isLoading, error } = useBackendAllMoneyMarketAssets();
1209
- *
1210
- * if (isLoading) return <div>Loading assets...</div>;
1211
- * if (error) return <div>Error: {error.message}</div>;
1212
- * if (assets) {
1213
- * console.log('Total assets:', assets.length);
1214
- * assets.forEach(asset => {
1215
- * console.log(`${asset.symbol}: ${asset.liquidityRate} liquidity rate`);
1216
- * });
1217
- * }
1218
- *
1219
- * @remarks
1220
- * - No required parameters — fetches all available money market assets from backend.
1221
- * - Uses React Query for caching, retries, and loading/error state management.
1222
- * - Supports overriding React Query config via `queryOptions`.
1223
729
  */
1224
- declare const useBackendAllMoneyMarketAssets: (params: UseBackendAllMoneyMarketAssetsParams | undefined) => UseQueryResult<MoneyMarketAsset[], Error>;
730
+ declare const useBackendAllMoneyMarketAssets: ({ queryOptions, }?: UseBackendAllMoneyMarketAssetsParams) => UseQueryResult<MoneyMarketAsset[], Error>;
1225
731
 
1226
- type UseBackendMoneyMarketAssetParams = {
1227
- params: {
1228
- reserveAddress: string | undefined;
1229
- };
1230
- queryOptions?: UseQueryOptions<MoneyMarketAsset | undefined, Error>;
1231
- };
732
+ type UseBackendMoneyMarketAssetParams = ReadHookParams<MoneyMarketAsset | undefined, {
733
+ reserveAddress: string | undefined;
734
+ }>;
1232
735
  /**
1233
736
  * React hook to fetch a specific money market asset from the backend API.
1234
737
  *
1235
- * @param params - The hook input parameter object (may be undefined):
1236
- * - `params`: An object containing:
1237
- * - `reserveAddress` (string | undefined): Reserve contract address to fetch asset details. Disables query if undefined or empty.
1238
- * - `queryOptions` (optional): React Query options for advanced configuration (e.g. caching, staleTime, retry, etc.).
1239
- *
1240
- * @returns A React Query result object: {@link UseQueryResult} for {@link MoneyMarketAsset} or `undefined` on error or if disabled,
1241
- * including:
1242
- * - `data`: The money market asset (when available) or `undefined`.
1243
- * - `isLoading`: Whether the query is running.
1244
- * - `error`: An error encountered by the query (if any).
1245
- * - `refetch`: Function to manually refetch the asset.
1246
- *
1247
738
  * @example
1248
- * const { data: asset, isLoading, error } = useBackendMoneyMarketAsset({
1249
- * params: { reserveAddress: '0xabc...' },
1250
- * });
1251
- * if (isLoading) return <div>Loading asset...</div>;
1252
- * if (error) return <div>Error: {error.message}</div>;
1253
- * if (asset) {
1254
- * console.log('Asset symbol:', asset.symbol);
1255
- * console.log('Liquidity rate:', asset.liquidityRate);
1256
- * console.log('Variable borrow rate:', asset.variableBorrowRate);
1257
- * }
1258
- *
1259
- * @remarks
1260
- * - Query is disabled if `params`, `params.params`, or `params.params.reserveAddress` is missing or empty.
1261
- * - Uses React Query for caching and background-state management.
1262
- * - Loading and error handling are managed automatically.
739
+ * const { data: asset } = useBackendMoneyMarketAsset({ params: { reserveAddress: '0xabc...' } });
1263
740
  */
1264
- declare const useBackendMoneyMarketAsset: (params: UseBackendMoneyMarketAssetParams | undefined) => UseQueryResult<MoneyMarketAsset | undefined, Error>;
741
+ declare const useBackendMoneyMarketAsset: ({ params, queryOptions, }?: UseBackendMoneyMarketAssetParams) => UseQueryResult<MoneyMarketAsset | undefined, Error>;
1265
742
 
1266
- type UseBackendMoneyMarketAssetBorrowersParams = {
1267
- params: {
1268
- reserveAddress: string | undefined;
1269
- };
743
+ type UseBackendMoneyMarketAssetBorrowersParams = ReadHookParams<MoneyMarketAssetBorrowers | undefined, {
744
+ reserveAddress: string | undefined;
1270
745
  pagination: BackendPaginationParams;
1271
- queryOptions?: UseQueryOptions<MoneyMarketAssetBorrowers | undefined, Error>;
1272
- };
746
+ }>;
1273
747
  /**
1274
748
  * React hook for fetching borrowers for a specific money market asset from the backend API with pagination.
1275
749
  *
1276
- * @param {UseBackendMoneyMarketAssetBorrowersParams | undefined} params - Query parameters:
1277
- * - `params`: Object containing:
1278
- * - `reserveAddress`: Reserve contract address for which to fetch borrowers, or `undefined` to disable query.
1279
- * - `pagination`: Pagination controls with `offset` and `limit` (both required as strings).
1280
- * - `queryOptions` (optional): React Query options to override defaults (e.g. `staleTime`, `enabled`, etc.).
1281
- *
1282
- * @returns {UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error>} React Query result object including:
1283
- * - `data`: The money market asset borrowers data, or `undefined` if not available.
1284
- * - `isLoading`: Boolean indicating whether the query is loading.
1285
- * - `error`: An Error instance if the request failed.
1286
- * - `refetch`: Function to manually trigger a data refresh.
1287
- *
1288
750
  * @example
1289
- * const { data: borrowers, isLoading, error } = useBackendMoneyMarketAssetBorrowers({
1290
- * params: { reserveAddress: '0xabc...' },
1291
- * pagination: { offset: '0', limit: '20' }
751
+ * const { data: borrowers } = useBackendMoneyMarketAssetBorrowers({
752
+ * params: { reserveAddress: '0xabc...', pagination: { offset: '0', limit: '20' } },
1292
753
  * });
1293
- *
1294
- * if (isLoading) return <div>Loading borrowers...</div>;
1295
- * if (error) return <div>Error: {error.message}</div>;
1296
- * if (borrowers) {
1297
- * console.log('Total borrowers:', borrowers.total);
1298
- * console.log('Borrowers:', borrowers.borrowers);
1299
- * }
1300
- *
1301
- * @remarks
1302
- * - The query is disabled if `reserveAddress`, `offset`, or `limit` are not provided.
1303
- * - Uses React Query for caching, retries, and auto error/loading management.
1304
- * - Pagination is handled via `pagination.offset` and `pagination.limit`.
1305
754
  */
1306
- declare const useBackendMoneyMarketAssetBorrowers: (params: UseBackendMoneyMarketAssetBorrowersParams | undefined) => UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error>;
755
+ declare const useBackendMoneyMarketAssetBorrowers: ({ params, queryOptions, }?: UseBackendMoneyMarketAssetBorrowersParams) => UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error>;
1307
756
 
1308
- type UseBackendMoneyMarketAssetSuppliersParams = {
1309
- params: {
1310
- reserveAddress: string | undefined;
1311
- };
757
+ type UseBackendMoneyMarketAssetSuppliersParams = ReadHookParams<MoneyMarketAssetSuppliers | undefined, {
758
+ reserveAddress: string | undefined;
1312
759
  pagination: BackendPaginationParams;
1313
- queryOptions?: UseQueryOptions<MoneyMarketAssetSuppliers | undefined, Error>;
1314
- };
760
+ }>;
1315
761
  /**
1316
- * React hook for fetching suppliers for a specific money market asset from the backend API, with pagination support.
1317
- *
1318
- * @param {UseBackendMoneyMarketAssetSuppliersParams | undefined} params - Hook parameters:
1319
- * - `params`: Object containing:
1320
- * - `reserveAddress`: The reserve contract address to query, or undefined to disable the query.
1321
- * - `pagination`: Backend pagination controls (`offset` and `limit` as strings).
1322
- * - `queryOptions` (optional): React Query options to override defaults.
1323
- *
1324
- * @returns {UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error>} - Query result object with:
1325
- * - `data`: The asset suppliers data when available.
1326
- * - `isLoading`: Indicates if the request is in progress.
1327
- * - `error`: Error object if the request failed.
1328
- * - `refetch`: Function to trigger a manual data refresh.
762
+ * React hook for fetching suppliers for a specific money market asset from the backend API.
1329
763
  *
1330
764
  * @example
1331
- * const { data: suppliers, isLoading, error } = useBackendMoneyMarketAssetSuppliers({
1332
- * params: { reserveAddress: '0xabc...' },
1333
- * pagination: { offset: '0', limit: '20' }
765
+ * const { data: suppliers } = useBackendMoneyMarketAssetSuppliers({
766
+ * params: { reserveAddress: '0xabc...', pagination: { offset: '0', limit: '20' } },
1334
767
  * });
1335
- *
1336
- * if (isLoading) return <div>Loading suppliers...</div>;
1337
- * if (error) return <div>Error: {error.message}</div>;
1338
- * if (suppliers) {
1339
- * console.log('Total suppliers:', suppliers.total);
1340
- * console.log('Suppliers:', suppliers.suppliers);
1341
- * }
1342
- *
1343
- * @remarks
1344
- * - The query is disabled if `reserveAddress`, `offset`, or `limit` are not provided.
1345
- * - Uses React Query for efficient caching, automatic retries, and error/loading handling.
1346
- * - Pagination is handled via `pagination.offset` and `pagination.limit`.
1347
768
  */
1348
- declare const useBackendMoneyMarketAssetSuppliers: (params: UseBackendMoneyMarketAssetSuppliersParams | undefined) => UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error>;
769
+ declare const useBackendMoneyMarketAssetSuppliers: ({ params, queryOptions, }?: UseBackendMoneyMarketAssetSuppliersParams) => UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error>;
1349
770
 
1350
- type UseBackendAllMoneyMarketBorrowersParams = {
771
+ type UseBackendAllMoneyMarketBorrowersParams = ReadHookParams<MoneyMarketBorrowers | undefined, {
1351
772
  pagination: BackendPaginationParams;
1352
- queryOptions?: UseQueryOptions<MoneyMarketBorrowers | undefined, Error>;
1353
- };
773
+ }>;
1354
774
  /**
1355
775
  * Hook for fetching all money market borrowers from the backend API.
1356
776
  *
1357
- * This hook provides access to the list of all borrowers across all money market assets,
1358
- * with pagination support. The data is automatically fetched and cached using React Query.
1359
- *
1360
- * @param {Object} params - Pagination parameters for fetching all borrowers
1361
- * @param {string} params.offset - The offset for pagination (number as string)
1362
- * @param {string} params.limit - The limit for pagination (number as string)
1363
- *
1364
- * @returns {UseQueryResult<MoneyMarketBorrowers | undefined>} A query result object containing:
1365
- * - data: The all borrowers data when available
1366
- * - isLoading: Boolean indicating if the request is in progress
1367
- * - error: Error object if the request failed
1368
- * - refetch: Function to manually trigger a data refresh
1369
- *
1370
777
  * @example
1371
778
  * ```typescript
1372
- * const { data: borrowers, isLoading, error } = useAllMoneyMarketBorrowers({
1373
- * offset: '0',
1374
- * limit: '50'
779
+ * const { data, isLoading, error } = useBackendAllMoneyMarketBorrowers({
780
+ * params: { pagination: { offset: '0', limit: '50' } },
1375
781
  * });
1376
- *
1377
- * if (isLoading) return <div>Loading borrowers...</div>;
1378
- * if (error) return <div>Error: {error.message}</div>;
1379
- * if (borrowers) {
1380
- * console.log('Total borrowers:', borrowers.total);
1381
- * console.log('Borrowers:', borrowers.borrowers);
1382
- * }
1383
782
  * ```
1384
- *
1385
- * @remarks
1386
- * - The query is disabled when params are undefined or invalid
1387
- * - Uses React Query for efficient caching and state management
1388
- * - Automatically handles error states and loading indicators
1389
- * - Supports pagination through offset and limit parameters
1390
- * - Returns borrowers across all money market assets
1391
783
  */
1392
- declare const useBackendAllMoneyMarketBorrowers: (params: UseBackendAllMoneyMarketBorrowersParams | undefined) => UseQueryResult<MoneyMarketBorrowers | undefined>;
784
+ declare const useBackendAllMoneyMarketBorrowers: ({ params, queryOptions, }?: UseBackendAllMoneyMarketBorrowersParams) => UseQueryResult<MoneyMarketBorrowers | undefined>;
1393
785
 
1394
786
  /**
1395
- * Hook for checking token allowance for bridge operations.
787
+ * Mutation variables for {@link useBridge}. Generic over `K extends SpokeChainKey` (defaults to
788
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
789
+ * `walletProvider` and `params.srcChainKey` types.
790
+ */
791
+ type UseBridgeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<BridgeParams<K, false>, 'raw'>;
792
+ /**
793
+ * React hook for executing a cross-chain bridge transfer.
1396
794
  *
1397
- * This hook verifies if the user has approved enough tokens for a specific bridge action.
1398
- * It automatically queries and tracks the allowance status.
795
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
796
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
797
+ */
798
+ declare function useBridge<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseBridgeVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseBridgeVars<K>>;
799
+
800
+ type UseBridgeAllowanceParams<K extends SpokeChainKey> = ReadHookParams<boolean, {
801
+ payload: CreateBridgeIntentParams<K> | undefined;
802
+ walletProvider: GetWalletProviderType<K> | undefined;
803
+ }>;
804
+ declare function useBridgeAllowance<K extends SpokeChainKey>({ params, queryOptions, }?: UseBridgeAllowanceParams<K>): UseQueryResult<boolean, Error>;
805
+
806
+ /**
807
+ * Mutation variables for {@link useBridgeApprove}. Generic over `K extends SpokeChainKey`
808
+ * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow
809
+ * the `walletProvider` and `params.srcChainKey` types.
810
+ */
811
+ type UseBridgeApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<BridgeParams<K, false>, 'raw'>;
812
+ /**
813
+ * React hook for approving ERC-20 token spending (or trustline establishment) for a bridge
814
+ * action.
1399
815
  *
1400
- * @param {BridgeParams} params - The parameters for the bridge to check allowance for.
1401
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
816
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
817
+ * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates all
818
+ * `['bridge', 'allowance', ...]` queries so any pending allowance check refreshes.
819
+ */
820
+ declare function useBridgeApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseBridgeApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseBridgeApproveVars<K>>;
821
+
822
+ type UseGetBridgeableAmountParams = ReadHookParams<BridgeLimit, {
823
+ from: XToken | undefined;
824
+ to: XToken | undefined;
825
+ }>;
826
+ declare function useGetBridgeableAmount({ params, queryOptions, }?: UseGetBridgeableAmountParams): UseQueryResult<BridgeLimit, Error>;
827
+
828
+ type UseGetBridgeableTokensParams = ReadHookParams<XToken[], {
829
+ from: SpokeChainKey | undefined;
830
+ to: SpokeChainKey | undefined;
831
+ token: string | undefined;
832
+ }>;
833
+ declare function useGetBridgeableTokens({ params, queryOptions, }?: UseGetBridgeableTokensParams): UseQueryResult<XToken[], Error>;
834
+
835
+ /**
836
+ * Mutation variables for {@link useStake}. Generic over `K extends SpokeChainKey` (defaults to
837
+ * the full union). Sophisticated callers can lock K at the hook call site to narrow the
838
+ * `walletProvider` and `params.srcChainKey` types.
839
+ */
840
+ type UseStakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<StakeAction<K, false>, 'raw'>;
841
+ /**
842
+ * React hook for staking SODA tokens.
1402
843
  *
1403
- * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
1404
- * - data: Boolean indicating if allowance is sufficient
1405
- * - isLoading: Loading state indicator
1406
- * - error: Any error that occurred during the check
844
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
845
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
846
+ */
847
+ declare function useStake<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseStakeVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseStakeVars<K>>;
848
+
849
+ /**
850
+ * Mutation variables for {@link useStakeApprove}. The `action` literal is injected by the hook —
851
+ * callers pass the stake-specific fields only.
852
+ */
853
+ type UseStakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
854
+ params: Omit<StakeParams<K>, 'action'>;
855
+ walletProvider: GetWalletProviderType<K>;
856
+ };
857
+ /**
858
+ * React hook for approving SODA spending on the stake action.
1407
859
  *
1408
- * @example
1409
- * ```typescript
1410
- * const { data: hasAllowed, isLoading } = useBridgeAllowance(params, spokeProvider);
1411
- * ```
860
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
861
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1412
862
  */
1413
- declare function useBridgeAllowance(params: CreateBridgeIntentParams | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
863
+ declare function useStakeApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseStakeApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseStakeApproveVars<K>>;
1414
864
 
1415
- interface UseBridgeApproveReturn {
1416
- approve: (params: CreateBridgeIntentParams) => Promise<boolean>;
1417
- isLoading: boolean;
1418
- error: Error | null;
1419
- resetError: () => void;
1420
- }
865
+ type UseStakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<boolean, {
866
+ payload: Omit<StakeParams<K>, 'action'> | undefined;
867
+ }>;
1421
868
  /**
1422
- * Hook for approving token spending for bridge actions
1423
- * @param spokeProvider The spoke provider instance for the chain
1424
- * @returns Object containing approve function, loading state, error state and reset function
1425
- * @example
1426
- * ```tsx
1427
- * const { approve, isLoading, error } = useBridgeApprove(spokeProvider);
1428
- *
1429
- * // Approve tokens for bridge action
1430
- * await approve({
1431
- * srcChainId: '0x2105.base',
1432
- * srcAsset: '0x...',
1433
- * amount: 1000n,
1434
- * dstChainId: '0x89.polygon',
1435
- * dstAsset: '0x...',
1436
- * recipient: '0x...'
1437
- * });
1438
- * ```
869
+ * React hook to check whether the user has approved sufficient SODA spending for the stake
870
+ * action. Read-only calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`
871
+ * is required.
1439
872
  */
1440
- declare function useBridgeApprove(spokeProvider: SpokeProvider | undefined): UseBridgeApproveReturn;
873
+ declare function useStakeAllowance<K extends SpokeChainKey = SpokeChainKey>({ params, queryOptions, }?: UseStakeAllowanceParams<K>): UseQueryResult<boolean, Error>;
1441
874
 
875
+ type UseUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<UnstakeAction<K, false>, 'raw'>;
1442
876
  /**
1443
- * Hook for executing bridge transactions to transfer tokens between chains.
1444
- * Uses React Query's useMutation for better state management and caching.
877
+ * React hook for initiating an SODA unstake.
1445
878
  *
1446
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the bridge
1447
- * @returns {UseMutationResult} Mutation result object containing mutation function and state
1448
- *
1449
- * @example
1450
- * ```typescript
1451
- * const { mutateAsync: bridge, isPending } = useBridge(spokeProvider);
1452
- *
1453
- * const handleBridge = async () => {
1454
- * const result = await bridge({
1455
- * srcChainId: '0x2105.base',
1456
- * srcAsset: '0x...',
1457
- * amount: 1000n,
1458
- * dstChainId: '0x89.polygon',
1459
- * dstAsset: '0x...',
1460
- * recipient: '0x...'
1461
- * });
1462
- *
1463
- * console.log('Bridge transaction hashes:', {
1464
- * spokeTxHash: result.spokeTxHash,
1465
- * hubTxHash: result.hubTxHash
1466
- * });
1467
- * };
1468
- * ```
879
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
880
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1469
881
  */
1470
- declare function useBridge(spokeProvider: SpokeProvider | undefined): UseMutationResult<Result<[SpokeTxHash, HubTxHash], BridgeError<BridgeErrorCode>>, Error, CreateBridgeIntentParams>;
882
+ declare function useUnstake<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseUnstakeVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseUnstakeVars<K>>;
1471
883
 
884
+ type UseClaimVars<K extends SpokeChainKey = SpokeChainKey> = Omit<ClaimAction<K, false>, 'raw'>;
1472
885
  /**
1473
- * Hook for getting the amount available to be bridged.
1474
- *
1475
- * This hook is used to check if a target chain has enough balance to bridge when bridging.
1476
- * It automatically queries and tracks the available amount to be bridged.
1477
- *
1478
- * @param {SpokeChainId | undefined} chainId - The chain ID to get the balance for
1479
- * @param {string | undefined} token - The token address to get the balance for
1480
- *
1481
- * @returns {UseQueryResult<BridgeLimit, Error>} A React Query result containing:
1482
- * - data: Data about available amount to be bridged
1483
- * - error: Any error that occurred during the check
886
+ * React hook for claiming an unstaked SODA request that has reached the end of its waiting period.
1484
887
  *
1485
- * @example
1486
- * ```typescript
1487
- * const { data: balance, isLoading } = useSpokeAssetManagerTokenBalance(chainId, tokenAddress);
888
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
889
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
890
+ */
891
+ declare function useClaim<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseClaimVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseClaimVars<K>>;
892
+
893
+ type UseCancelUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<CancelUnstakeAction<K, false>, 'raw'>;
894
+ /**
895
+ * React hook for cancelling a pending unstake request.
1488
896
  *
1489
- * if (balance) {
1490
- * console.log('Asset manager token balance:', balance.toString());
1491
- * }
1492
- * ```
897
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
898
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1493
899
  */
1494
- declare function useGetBridgeableAmount(from: XToken | undefined, to: XToken | undefined): UseQueryResult<BridgeLimit, Error>;
900
+ declare function useCancelUnstake<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseCancelUnstakeVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseCancelUnstakeVars<K>>;
1495
901
 
902
+ type UseStakingInfoParams = ReadHookParams<StakingInfo, {
903
+ srcAddress: `0x${string}` | undefined;
904
+ srcChainKey: SpokeChainKey | undefined;
905
+ }>;
1496
906
  /**
907
+ * React hook to fetch the user's staking info (xSODA balance, share value, underlying SODA) by
908
+ * deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok` so React
909
+ * Query lands in `error` state.
910
+ */
911
+ declare function useStakingInfo({ params, queryOptions }?: UseStakingInfoParams): UseQueryResult<StakingInfo, Error>;
912
+
913
+ type UnstakingInfoWithPenalty = UnstakingInfo & {
914
+ requestsWithPenalty: UnstakeRequestWithPenalty[];
915
+ };
916
+ type UseUnstakingInfoWithPenaltyParams = ReadHookParams<UnstakingInfoWithPenalty, {
917
+ srcAddress: `0x${string}` | undefined;
918
+ srcChainKey: SpokeChainKey | undefined;
919
+ }>;
1497
920
  /**
1498
- * Hook for retrieving all bridgeable tokens from a source token on one chain to a destination chain.
1499
- *
1500
- * This hook queries and tracks the set of tokens on the destination chain that can be bridged to,
1501
- * given a source chain, destination chain, and source token address.
1502
- *
1503
- * @param {SpokeChainId | undefined} from - The source chain ID
1504
- * @param {SpokeChainId | undefined} to - The destination chain ID
1505
- * @param {string | undefined} token - The source token address
1506
- *
1507
- * @returns {UseQueryResult<XToken[], Error>} A React Query result containing:
1508
- * - data: Array of bridgeable tokens (XToken[]) on the destination chain
1509
- * - error: Any error that occurred during the query
1510
- *
1511
- *
1512
- * @example
1513
- * ```typescript
1514
- * const { data: bridgeableTokens, isLoading } = useGetBridgeableTokens(
1515
- * fromChainId,
1516
- * toChainId,
1517
- * fromTokenAddress
1518
- * );
1519
- *
1520
- * if (bridgeableTokens && bridgeableTokens.length > 0) {
1521
- * bridgeableTokens.forEach(token => {
1522
- * console.log(`Bridgeable token: ${token.symbol} (${token.address}) on chain ${token.xChainId}`);
1523
- * });
1524
- * } else {
1525
- * console.log('No bridgeable tokens found for the selected route.');
1526
- * }
1527
- * ```
921
+ * React hook to fetch the user's pending unstake requests **with computed early-exit penalties**
922
+ * by deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
1528
923
  */
1529
- declare function useGetBridgeableTokens(from: SpokeChainId | undefined, to: SpokeChainId | undefined, token: string | undefined): UseQueryResult<XToken[], Error>;
924
+ declare function useUnstakingInfoWithPenalty({ params, queryOptions, }?: UseUnstakingInfoWithPenaltyParams): UseQueryResult<UnstakingInfoWithPenalty, Error>;
1530
925
 
926
+ type UseStakingConfigParams = ReadHookParams<StakingConfig>;
1531
927
  /**
1532
- * Hook for executing stake transactions to stake SODA tokens and receive xSODA shares.
1533
- * Uses React Query's useMutation for better state management and caching.
1534
- *
1535
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the stake
1536
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, StakeParams>} Mutation result object containing mutation function and state
1537
- *
1538
- * @example
1539
- * ```typescript
1540
- * const { mutateAsync: stake, isPending } = useStake(spokeProvider);
1541
- *
1542
- * const handleStake = async () => {
1543
- * const result = await stake({
1544
- * amount: 1000000000000000000n, // 1 SODA
1545
- * account: '0x...'
1546
- * });
1547
- *
1548
- * console.log('Stake successful:', result);
1549
- * };
1550
- * ```
928
+ * React hook to fetch the global staking config (unstaking period, min unstaking period, max
929
+ * penalty). Hub-only read; no chain context required. Throws on `!ok`.
1551
930
  */
1552
- declare function useStake(spokeProvider: SpokeProvider | undefined): UseMutationResult<[SpokeTxHash, HubTxHash], Error, StakeParams>;
931
+ declare function useStakingConfig({ queryOptions, }?: UseStakingConfigParams): UseQueryResult<StakingConfig, Error>;
1553
932
 
933
+ type UseStakeRatioParams = ReadHookParams<[
934
+ bigint,
935
+ bigint
936
+ ], {
937
+ amount: bigint | undefined;
938
+ }>;
1554
939
  /**
1555
- * Hook for approving SODA token spending for staking operations.
1556
- * Uses React Query's useMutation for better state management and caching.
1557
- *
1558
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval
1559
- * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<StakeParams, 'action'>>} Mutation result object containing mutation function and state
1560
- *
1561
- * @example
1562
- * ```typescript
1563
- * const { mutateAsync: approve, isPending } = useStakeApprove(spokeProvider);
1564
- *
1565
- * const handleApprove = async () => {
1566
- * const result = await approve({
1567
- * amount: 1000000000000000000n, // 1 SODA
1568
- * account: '0x...'
1569
- * });
1570
- *
1571
- * console.log('Approval successful:', result);
1572
- * };
1573
- * ```
940
+ * React hook to estimate the SODA xSODA stake ratio for a given amount. Hub-only read. Throws
941
+ * on `!ok`.
1574
942
  */
1575
- declare function useStakeApprove(spokeProvider: SpokeProvider | undefined): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<StakeParams, 'action'>>;
943
+ declare function useStakeRatio({ params, queryOptions, }?: UseStakeRatioParams): UseQueryResult<[bigint, bigint], Error>;
1576
944
 
945
+ type UseInstantUnstakeRatioParams = ReadHookParams<bigint, {
946
+ amount: bigint | undefined;
947
+ }>;
1577
948
  /**
1578
- * Hook for checking SODA token allowance for staking operations.
1579
- * Uses React Query for efficient caching and state management.
1580
- *
1581
- * @param {Omit<StakeParams, 'action'> | undefined} params - The staking parameters. If undefined, the query will be disabled.
1582
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check
1583
- * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state
1584
- *
1585
- * @example
1586
- * ```typescript
1587
- * const { data: hasAllowed, isLoading } = useStakeAllowance(
1588
- * {
1589
- * amount: 1000000000000000000n, // 1 SODA
1590
- * account: '0x...'
1591
- * },
1592
- * spokeProvider
1593
- * );
1594
- *
1595
- * if (isLoading) return <div>Checking allowance...</div>;
1596
- * if (hasAllowed) {
1597
- * console.log('Sufficient allowance for staking');
1598
- * }
1599
- * ```
949
+ * React hook to estimate the SODA amount received from instant-unstaking a given xSODA amount
950
+ * (after slippage). Hub-only read. Throws on `!ok`.
1600
951
  */
1601
- declare function useStakeAllowance(params: Omit<StakeParams, 'action'> | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
952
+ declare function useInstantUnstakeRatio({ params, queryOptions, }?: UseInstantUnstakeRatioParams): UseQueryResult<bigint, Error>;
1602
953
 
954
+ type UseConvertedAssetsParams = ReadHookParams<bigint, {
955
+ amount: bigint | undefined;
956
+ }>;
1603
957
  /**
1604
- * Hook for executing unstake transactions to unstake xSODA shares.
1605
- * Uses React Query's useMutation for better state management and caching.
1606
- *
1607
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the unstake
1608
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<UnstakeParams, 'action'>>} Mutation result object containing mutation function and state
1609
- *
1610
- * @example
1611
- * ```typescript
1612
- * const { mutateAsync: unstake, isPending } = useUnstake(spokeProvider);
1613
- *
1614
- * const handleUnstake = async () => {
1615
- * const result = await unstake({
1616
- * amount: 1000000000000000000n, // 1 xSODA
1617
- * account: '0x...'
1618
- * });
1619
- *
1620
- * console.log('Unstake successful:', result);
1621
- * };
1622
- * ```
958
+ * React hook to convert an xSODA share amount to its underlying SODA value via the vault's
959
+ * exchange rate. Hub-only read. Throws on `!ok`.
1623
960
  */
1624
- declare function useUnstake(spokeProvider: SpokeProvider | undefined): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<UnstakeParams, 'action'>>;
961
+ declare function useConvertedAssets({ params, queryOptions, }?: UseConvertedAssetsParams): UseQueryResult<bigint, Error>;
1625
962
 
963
+ type UseInstantUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<InstantUnstakeAction<K, false>, 'raw'>;
1626
964
  /**
1627
- * Hook for executing claim transactions to claim unstaked SODA tokens after the unstaking period.
1628
- * Uses React Query's useMutation for better state management and caching.
965
+ * React hook for instant-unstaking SODA (bypassing the waiting period at a slippage cost).
1629
966
  *
1630
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the claim
1631
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<ClaimParams, 'action'>>} Mutation result object containing mutation function and state
1632
- *
1633
- * @example
1634
- * ```typescript
1635
- * const { mutateAsync: claim, isPending } = useClaim(spokeProvider);
1636
- *
1637
- * const handleClaim = async () => {
1638
- * const result = await claim({
1639
- * requestId: 1n
1640
- * });
1641
- *
1642
- * console.log('Claim successful:', result);
1643
- * };
1644
- * ```
967
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
968
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1645
969
  */
1646
- declare function useClaim(spokeProvider: SpokeProvider | undefined): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<ClaimParams, 'action'>>;
970
+ declare function useInstantUnstake<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseInstantUnstakeVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseInstantUnstakeVars<K>>;
1647
971
 
972
+ type UseUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<boolean, {
973
+ payload: Omit<UnstakeParams<K>, 'action'> | undefined;
974
+ }>;
1648
975
  /**
1649
- * Hook for executing cancel unstake transactions to cancel pending unstake requests.
1650
- * Uses React Query's useMutation for better state management and caching.
1651
- *
1652
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the cancel unstake
1653
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<CancelUnstakeParams, 'action'>>} Mutation result object containing mutation function and state
1654
- *
1655
- * @example
1656
- * ```typescript
1657
- * const { mutateAsync: cancelUnstake, isPending } = useCancelUnstake(spokeProvider);
1658
- *
1659
- * const handleCancelUnstake = async () => {
1660
- * const result = await cancelUnstake({
1661
- * requestId: 1n
1662
- * });
1663
- *
1664
- * console.log('Cancel unstake successful:', result);
1665
- * };
1666
- * ```
976
+ * React hook to check whether the user has approved sufficient xSODA spending for the unstake
977
+ * action. Read-only calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`
978
+ * is required.
1667
979
  */
1668
- declare function useCancelUnstake(spokeProvider: SpokeProvider | undefined): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<CancelUnstakeParams, 'action'>>;
980
+ declare function useUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({ params, queryOptions, }?: UseUnstakeAllowanceParams<K>): UseQueryResult<boolean, Error>;
1669
981
 
1670
982
  /**
1671
- * Hook for fetching comprehensive staking information for a user.
1672
- * Uses React Query for efficient caching and state management.
1673
- *
1674
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the query
1675
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)
1676
- * @returns {UseQueryResult<StakingInfo, Error>} Query result object containing staking info and state
1677
- *
1678
- * @example
1679
- * ```typescript
1680
- * const { data: stakingInfo, isLoading, error } = useStakingInfo(spokeProvider);
983
+ * Mutation variables for {@link useUnstakeApprove}. The `action` literal is injected by the hook.
984
+ */
985
+ type UseUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
986
+ params: Omit<UnstakeParams<K>, 'action'>;
987
+ walletProvider: GetWalletProviderType<K>;
988
+ };
989
+ /**
990
+ * React hook for approving xSODA spending on the unstake action.
1681
991
  *
1682
- * if (isLoading) return <div>Loading staking info...</div>;
1683
- * if (stakingInfo) {
1684
- * console.log('Total staked:', stakingInfo.totalStaked);
1685
- * console.log('User staked:', stakingInfo.userStaked);
1686
- * console.log('xSODA balance:', stakingInfo.userXSodaBalance);
1687
- * }
1688
- * ```
992
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
993
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1689
994
  */
1690
- declare function useStakingInfo(spokeProvider: SpokeProvider | undefined, refetchInterval?: number): UseQueryResult<StakingInfo, Error>;
995
+ declare function useUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseUnstakeApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseUnstakeApproveVars<K>>;
1691
996
 
1692
- type UnstakingInfoWithPenalty = UnstakingInfo & {
1693
- requestsWithPenalty: UnstakeRequestWithPenalty[];
997
+ type UseUnstakingInfoParams = ReadHookParams<UnstakingInfo, {
998
+ srcAddress: `0x${string}` | undefined;
999
+ srcChainKey: SpokeChainKey | undefined;
1000
+ }>;
1001
+ /**
1002
+ * React hook to fetch the user's pending unstake requests by deriving the hub wallet from the
1003
+ * spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.
1004
+ */
1005
+ declare function useUnstakingInfo({ params, queryOptions, }?: UseUnstakingInfoParams): UseQueryResult<UnstakingInfo, Error>;
1006
+
1007
+ /**
1008
+ * Mutation variables for {@link useInstantUnstakeApprove}. The `action` literal is injected by
1009
+ * the hook.
1010
+ */
1011
+ type UseInstantUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {
1012
+ params: Omit<InstantUnstakeParams<K>, 'action'>;
1013
+ walletProvider: GetWalletProviderType<K>;
1694
1014
  };
1695
1015
  /**
1696
- * Hook for fetching unstaking information with penalty calculations from the stakedSoda contract.
1697
- * Uses React Query for efficient caching and state management.
1698
- *
1699
- * @param {string | undefined} userAddress - The user address to fetch unstaking info for
1700
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance
1701
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)
1702
- * @returns {UseQueryResult<UnstakingInfoWithPenalty, Error>} Query result object containing unstaking info with penalties and state
1016
+ * React hook for approving xSODA spending on the instant-unstake action.
1703
1017
  *
1704
- * @example
1705
- * ```typescript
1706
- * const { data: unstakingInfo, isLoading, error } = useUnstakingInfoWithPenalty(userAddress, spokeProvider);
1707
- *
1708
- * if (isLoading) return <div>Loading unstaking info...</div>;
1709
- * if (unstakingInfo) {
1710
- * console.log('Total unstaking:', unstakingInfo.totalUnstaking);
1711
- * unstakingInfo.requestsWithPenalty.forEach(request => {
1712
- * console.log('Penalty:', request.penaltyPercentage + '%');
1713
- * console.log('Claimable amount:', request.claimableAmount);
1714
- * });
1715
- * }
1716
- * ```
1018
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1019
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1717
1020
  */
1718
- declare function useUnstakingInfoWithPenalty(userAddress: string | undefined, spokeProvider: SpokeProvider | undefined, refetchInterval?: number): UseQueryResult<UnstakingInfoWithPenalty, Error>;
1021
+ declare function useInstantUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseInstantUnstakeApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseInstantUnstakeApproveVars<K>>;
1719
1022
 
1023
+ type UseInstantUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<boolean, {
1024
+ payload: Omit<InstantUnstakeParams<K>, 'action'> | undefined;
1025
+ }>;
1720
1026
  /**
1721
- * Hook for fetching staking configuration from the stakedSoda contract.
1722
- * Uses React Query for efficient caching and state management.
1723
- *
1724
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 30000)
1725
- * @returns {UseQueryResult<StakingConfig, Error>} Query result object containing staking config and state
1726
- *
1727
- * @example
1728
- * ```typescript
1729
- * const { data: stakingConfig, isLoading, error } = useStakingConfig();
1730
- *
1731
- * if (isLoading) return <div>Loading staking config...</div>;
1732
- * if (stakingConfig) {
1733
- * console.log('Unstaking period (days):', stakingConfig.unstakingPeriod / 86400n);
1734
- * console.log('Max penalty (%):', stakingConfig.maxPenalty);
1735
- * }
1736
- * ```
1027
+ * React hook to check whether the user has approved sufficient xSODA spending for the
1028
+ * instant-unstake action. Read-only calls `staking.isAllowanceValid` with `raw: true` so no
1029
+ * `walletProvider` is required.
1737
1030
  */
1738
- declare function useStakingConfig(refetchInterval?: number): UseQueryResult<StakingConfig, Error>;
1031
+ declare function useInstantUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({ params, queryOptions, }?: UseInstantUnstakeAllowanceParams<K>): UseQueryResult<boolean, Error>;
1739
1032
 
1033
+ type UseFetchAssetsBalancesParams = ReadHookParams<Map<string, PartnerFeeClaimAssetBalance>, {
1034
+ queryAddress: string | undefined;
1035
+ }>;
1740
1036
  /**
1741
- * Hook for fetching stake ratio estimates (xSoda amount and preview deposit).
1742
- * Uses React Query for efficient caching and state management.
1743
- *
1744
- * @param {bigint | undefined} amount - The amount of SODA to estimate stake for
1745
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)
1746
- * @returns {UseQueryResult<[bigint, bigint], Error>} Query result object containing stake ratio estimates and state
1747
- *
1748
- * @example
1749
- * ```typescript
1750
- * const { data: stakeRatio, isLoading, error } = useStakeRatio(1000000000000000000n); // 1 SODA
1751
- *
1752
- * if (isLoading) return <div>Loading stake ratio...</div>;
1753
- * if (stakeRatio) {
1754
- * const [xSodaAmount, previewDepositAmount] = stakeRatio;
1755
- * console.log('xSoda amount:', xSodaAmount);
1756
- * console.log('Preview deposit:', previewDepositAmount);
1757
- * }
1758
- * ```
1037
+ * React hook to fetch hub-asset balances on Sonic for a given EVM address. Disabled when
1038
+ * `queryAddress` is missing. Throws on `!ok`.
1759
1039
  */
1760
- declare function useStakeRatio(amount: bigint | undefined, refetchInterval?: number): UseQueryResult<[bigint, bigint], Error>;
1040
+ declare function useFetchAssetsBalances({ params, queryOptions, }?: UseFetchAssetsBalancesParams): UseQueryResult<Map<string, PartnerFeeClaimAssetBalance>, Error>;
1761
1041
 
1042
+ type UseGetAutoSwapPreferencesParams = ReadHookParams<AutoSwapPreferences, {
1043
+ queryAddress: string | undefined;
1044
+ }>;
1762
1045
  /**
1763
- * Hook for fetching instant unstake ratio estimates.
1764
- * Uses React Query for efficient caching and state management.
1765
- *
1766
- * @param {bigint | undefined} amount - The amount of xSoda to estimate instant unstake for
1767
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)
1768
- * @returns {UseQueryResult<bigint, Error>} Query result object containing instant unstake ratio and state
1769
- *
1770
- * @example
1771
- * ```typescript
1772
- * const { data: instantUnstakeRatio, isLoading, error } = useInstantUnstakeRatio(1000000000000000000n); // 1 xSoda
1773
- *
1774
- * if (isLoading) return <div>Loading instant unstake ratio...</div>;
1775
- * if (instantUnstakeRatio) {
1776
- * console.log('Instant unstake ratio:', instantUnstakeRatio);
1777
- * }
1778
- * ```
1046
+ * React hook to fetch the auto-swap preferences (output token, destination chain, destination
1047
+ * address) for a given EVM address. Disabled when `queryAddress` is missing. Throws on `!ok`.
1779
1048
  */
1780
- declare function useInstantUnstakeRatio(amount: bigint | undefined, refetchInterval?: number): UseQueryResult<bigint, Error>;
1049
+ declare function useGetAutoSwapPreferences({ params, queryOptions, }?: UseGetAutoSwapPreferencesParams): UseQueryResult<AutoSwapPreferences, Error>;
1781
1050
 
1051
+ type UseIsTokenApprovedParams = ReadHookParams<boolean, {
1052
+ payload: FeeTokenApproveParams | undefined;
1053
+ }>;
1782
1054
  /**
1783
- * Hook for fetching converted assets amount for xSODA shares.
1784
- * Uses React Query for efficient caching and state management.
1785
- *
1786
- * @param {bigint | undefined} amount - The amount of xSODA shares to convert
1787
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)
1788
- * @returns {UseQueryResult<bigint, Error>} Query result object containing converted assets amount and state
1789
- *
1790
- * @example
1791
- * ```typescript
1792
- * const { data: convertedAssets, isLoading, error } = useConvertedAssets(1000000000000000000n); // 1 xSODA
1793
- *
1794
- * if (isLoading) return <div>Loading converted assets...</div>;
1795
- * if (convertedAssets) {
1796
- * console.log('Converted assets:', convertedAssets);
1797
- * }
1798
- * ```
1055
+ * React hook to check whether a token is approved to the protocol-intents contract on Sonic for
1056
+ * a given owner. Read-only; throws on `!ok`.
1799
1057
  */
1800
- declare function useConvertedAssets(amount: bigint | undefined, refetchInterval?: number): UseQueryResult<bigint, Error>;
1058
+ declare function useIsTokenApproved({ params, queryOptions, }?: UseIsTokenApprovedParams): UseQueryResult<boolean, Error>;
1801
1059
 
1060
+ type UseApproveTokenVars = Omit<FeeTokenApproveAction<HubChainKey, false>, 'raw'>;
1061
+ type ApproveTokenData = TxReturnType<HubChainKey, false>;
1802
1062
  /**
1803
- * Hook for executing instant unstake operations.
1804
- * Uses React Query for efficient state management and error handling.
1805
- *
1806
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider for the transaction
1807
- * @returns {UseMutationResult<[string, string], Error, Omit<InstantUnstakeParams, 'action'>>} Mutation result object containing instant unstake state and methods
1063
+ * React hook to approve a token to the protocol-intents contract on Sonic with max allowance.
1808
1064
  *
1809
- * @example
1810
- * ```typescript
1811
- * const { mutateAsync: instantUnstake, isPending } = useInstantUnstake(spokeProvider);
1812
- *
1813
- * const handleInstantUnstake = async () => {
1814
- * const result = await instantUnstake({
1815
- * amount: 1000000000000000000n,
1816
- * minAmount: 950000000000000000n,
1817
- * account: '0x...'
1818
- * });
1819
- * console.log('Instant unstake successful:', result);
1820
- * };
1821
- * ```
1065
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1066
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1822
1067
  */
1823
- declare function useInstantUnstake(spokeProvider: SpokeProvider | undefined): UseMutationResult<[string, string], Error, Omit<InstantUnstakeParams, 'action'>>;
1068
+ declare function useApproveToken({ mutationOptions, }?: MutationHookParams<ApproveTokenData, UseApproveTokenVars>): SafeUseMutationResult<ApproveTokenData, Error, UseApproveTokenVars>;
1824
1069
 
1825
1070
  /**
1826
- * Hook for checking xSODA token allowance for unstaking operations.
1827
- * Uses React Query for efficient caching and state management.
1828
- *
1829
- * @param {Omit<UnstakeParams, 'action'> | undefined} params - The unstaking parameters. If undefined, the query will be disabled.
1830
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check
1831
- * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state
1071
+ * Mutation variables for {@link useSetSwapPreference}. Generic over `K extends SpokeChainKey`
1072
+ * for compatibility with the SDK signature; at runtime the SDK enforces hub-only
1073
+ * (`isHubChainKeyType(srcChainKey)`).
1074
+ */
1075
+ type UseSetSwapPreferenceVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SetSwapPreferenceAction<K, false>, 'raw'>;
1076
+ /**
1077
+ * React hook to set the partner's auto-swap preferences (output token + destination chain +
1078
+ * destination address) on the protocol-intents contract.
1832
1079
  *
1833
- * @example
1834
- * ```typescript
1835
- * const { data: hasAllowed, isLoading } = useUnstakeAllowance(
1836
- * {
1837
- * amount: 1000000000000000000n, // 1 xSODA
1838
- * account: '0x...'
1839
- * },
1840
- * spokeProvider
1841
- * );
1842
- *
1843
- * if (isLoading) return <div>Checking allowance...</div>;
1844
- * if (hasAllowed) {
1845
- * console.log('Sufficient allowance for unstaking');
1846
- * }
1847
- * ```
1080
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1081
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1848
1082
  */
1849
- declare function useUnstakeAllowance(params: Omit<UnstakeParams, 'action'> | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
1083
+ declare function useSetSwapPreference<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseSetSwapPreferenceVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseSetSwapPreferenceVars<K>>;
1084
+ type UseSetSwapPreferenceVarsHub = UseSetSwapPreferenceVars<HubChainKey>;
1850
1085
 
1086
+ type UseFeeClaimSwapVars = Omit<PartnerFeeClaimSwapAction<HubChainKey, false>, 'raw'>;
1851
1087
  /**
1852
- * Hook for approving xSODA token spending for unstaking operations.
1853
- * Uses React Query's useMutation for better state management and caching.
1088
+ * React hook to create a partner-fee auto-swap intent and wait for the solver execution.
1854
1089
  *
1855
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval
1856
- * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>} Mutation result object containing mutation function and state
1857
- *
1858
- * @example
1859
- * ```typescript
1860
- * const { mutateAsync: approve, isPending } = useUnstakeApprove(spokeProvider);
1861
- *
1862
- * const handleApprove = async () => {
1863
- * const result = await approve({
1864
- * amount: 1000000000000000000n, // 1 xSODA
1865
- * account: '0x...'
1866
- * });
1867
- *
1868
- * console.log('Approval successful:', result);
1869
- * };
1870
- * ```
1090
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1091
+ * `onError`, `retry`). Returns the unwrapped `IntentAutoSwapResult` on success.
1871
1092
  */
1872
- declare function useUnstakeApprove(spokeProvider: SpokeProvider | undefined): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>;
1093
+ declare function useFeeClaimSwap({ mutationOptions, }?: MutationHookParams<IntentAutoSwapResult, UseFeeClaimSwapVars>): SafeUseMutationResult<IntentAutoSwapResult, Error, UseFeeClaimSwapVars>;
1873
1094
 
1095
+ type UseHubAssetBalancesParams = ReadHookParams<HubAssetBalance[], {
1096
+ chainKey: SpokeChainKey | undefined;
1097
+ /** The user's address on the spoke chain. The SDK derives the hub wallet abstraction internally. */
1098
+ srcAddress: string | undefined;
1099
+ }>;
1874
1100
  /**
1875
- * Hook for fetching unstaking information from the stakedSoda contract.
1876
- * Uses React Query for efficient caching and state management.
1877
- *
1878
- * @param {string | undefined} userAddress - The user address to fetch unstaking info for
1879
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance
1880
- * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)
1881
- * @returns {UseQueryResult<UnstakingInfo, Error>} Query result object containing unstaking info and state
1882
- *
1883
- * @example
1884
- * ```typescript
1885
- * const { data: unstakingInfo, isLoading, error } = useUnstakingInfo(userAddress, spokeProvider);
1886
- *
1887
- * if (isLoading) return <div>Loading unstaking info...</div>;
1888
- * if (unstakingInfo) {
1889
- * console.log('Total unstaking:', unstakingInfo.totalUnstaking);
1890
- * unstakingInfo.userUnstakeSodaRequests.forEach(request => {
1891
- * console.log('Request amount:', request.request.amount);
1892
- * });
1893
- * }
1894
- * ```
1101
+ * React hook to fetch the hub-side balances of every supported token on the given spoke chain
1102
+ * for the user's hub wallet (derived internally from `srcAddress` + `chainKey`). Disabled when
1103
+ * either input is missing. Throws on `!ok`.
1895
1104
  */
1896
- declare function useUnstakingInfo(userAddress: string | undefined, spokeProvider: SpokeProvider | undefined, refetchInterval?: number): UseQueryResult<UnstakingInfo, Error>;
1105
+ declare function useHubAssetBalances({ params, queryOptions, }?: UseHubAssetBalancesParams): UseQueryResult<HubAssetBalance[], Error>;
1897
1106
 
1898
1107
  /**
1899
- * Hook for approving xSODA token spending for instant unstaking operations.
1900
- * Uses React Query's useMutation for better state management and caching.
1901
- *
1902
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval
1903
- * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<InstantUnstakeParams, 'action'>>} Mutation result object containing mutation function and state
1904
- *
1905
- * @example
1906
- * ```typescript
1907
- * const { mutateAsync: approve, isPending } = useInstantUnstakeApprove(spokeProvider);
1908
- *
1909
- * const handleApprove = async () => {
1910
- * const result = await approve({
1911
- * amount: 1000000000000000000n, // 1 xSODA
1912
- * minAmount: 950000000000000000n, // 0.95 SODA
1913
- * account: '0x...'
1914
- * });
1108
+ * Mutation variables for {@link useWithdrawHubAsset}. Generic over `K extends SpokeChainKey`
1109
+ * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow
1110
+ * the `walletProvider` and `params.srcChainKey` types.
1111
+ */
1112
+ type UseWithdrawHubAssetVars<K extends SpokeChainKey = SpokeChainKey> = Omit<WithdrawHubAssetAction<K, false>, 'raw'>;
1113
+ /**
1114
+ * React hook for withdrawing a hub-side asset back to the user's spoke chain wallet.
1915
1115
  *
1916
- * console.log('Approval successful:', result);
1917
- * };
1918
- * ```
1116
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1117
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1919
1118
  */
1920
- declare function useInstantUnstakeApprove(spokeProvider: SpokeProvider | undefined): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<InstantUnstakeParams, 'action'>>;
1119
+ declare function useWithdrawHubAsset<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseWithdrawHubAssetVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseWithdrawHubAssetVars<K>>;
1921
1120
 
1922
1121
  /**
1923
- * Hook for checking xSODA token allowance for instant unstaking operations.
1924
- * Uses React Query for efficient caching and state management.
1925
- *
1926
- * @param {Omit<InstantUnstakeParams, 'action'> | undefined} params - The instant unstaking parameters. If undefined, the query will be disabled.
1927
- * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check
1928
- * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state
1122
+ * Mutation variables for {@link useMigrateIcxToSoda}. Wraps `IcxMigrateAction<false>` with `raw`
1123
+ * stripped the hook always submits non-raw and unwraps the SDK Result.
1124
+ */
1125
+ type UseMigrateIcxToSodaVars = Omit<IcxMigrateAction<false>, 'raw'>;
1126
+ /**
1127
+ * React hook for migrating ICX/wICX SODA on the Sonic hub. Forward-only direction; for the
1128
+ * reverse (SODA → ICX) use {@link useRevertMigrateSodaToIcx}.
1929
1129
  *
1930
- * @example
1931
- * ```typescript
1932
- * const { data: hasAllowed, isLoading } = useInstantUnstakeAllowance(
1933
- * {
1934
- * amount: 1000000000000000000n, // 1 xSODA
1935
- * minAmount: 950000000000000000n, // 0.95 SODA
1936
- * account: '0x...'
1937
- * },
1938
- * spokeProvider
1939
- * );
1940
- *
1941
- * if (isLoading) return <div>Checking allowance...</div>;
1942
- * if (hasAllowed) {
1943
- * console.log('Sufficient allowance for instant unstaking');
1944
- * }
1945
- * ```
1130
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1131
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1946
1132
  */
1947
- declare function useInstantUnstakeAllowance(params: Omit<InstantUnstakeParams, 'action'> | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
1948
-
1949
- declare const MIGRATION_MODE_ICX_SODA = "icxsoda";
1950
- declare const MIGRATION_MODE_BNUSD = "bnusd";
1951
- type MigrationMode = typeof MIGRATION_MODE_ICX_SODA | typeof MIGRATION_MODE_BNUSD;
1952
- interface MigrationIntentParams {
1953
- token: XToken$1 | undefined;
1954
- amount: string | undefined;
1955
- sourceAddress: string | undefined;
1956
- migrationMode?: MigrationMode;
1957
- toToken?: XToken$1;
1958
- destinationAddress?: string;
1959
- }
1133
+ declare function useMigrateIcxToSoda({ mutationOptions, }?: MutationHookParams<TxHashPair, UseMigrateIcxToSodaVars>): SafeUseMutationResult<TxHashPair, Error, UseMigrateIcxToSodaVars>;
1960
1134
 
1135
+ type UseRevertMigrateSodaToIcxVars = Omit<IcxRevertMigrationAction<false>, 'raw'>;
1961
1136
  /**
1962
- * Hook for executing migration operations between chains.
1137
+ * React hook for reverting SODA ICX (the inverse of {@link useMigrateIcxToSoda}).
1963
1138
  *
1964
- * This hook handles ICX/SODA and bnUSD migrations by accepting a spoke provider
1965
- * and returning a mutation function that accepts migration parameters.
1966
- *
1967
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the migration
1968
- * @returns {UseMutationResult} Mutation result object containing migration function and state
1969
- *
1970
- * @example
1971
- * ```typescript
1972
- * const { mutateAsync: migrate, isPending } = useMigrate(spokeProvider);
1973
- *
1974
- * const result = await migrate({
1975
- * token: { address: "0x...", decimals: 18 },
1976
- * amount: "100",
1977
- * migrationMode: MIGRATION_MODE_ICX_SODA,
1978
- * toToken: { address: "0x...", decimals: 18 },
1979
- * destinationAddress: "0x..."
1980
- * });
1981
- * ```
1139
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1140
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1982
1141
  */
1983
- declare function useMigrate(spokeProvider: SpokeProvider | undefined): UseMutationResult<{
1984
- spokeTxHash: string;
1985
- hubTxHash: `0x${string}`;
1986
- }, Error, MigrationIntentParams>;
1142
+ declare function useRevertMigrateSodaToIcx({ mutationOptions, }?: MutationHookParams<TxHashPair, UseRevertMigrateSodaToIcxVars>): SafeUseMutationResult<TxHashPair, Error, UseRevertMigrateSodaToIcxVars>;
1987
1143
 
1988
1144
  /**
1989
- * Hook for checking token allowance for migration operations.
1990
- *
1991
- * This hook verifies if the user has approved enough tokens for migration operations.
1992
- * It handles both ICX/SODA and bnUSD migration allowance checks.
1993
- *
1994
- * @param {MigrationIntentParams} params - The parameters for the migration allowance check
1995
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
1996
- *
1997
- * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
1998
- * - data: Boolean indicating if allowance is sufficient
1999
- * - isLoading: Loading state indicator
2000
- * - error: Any error that occurred during the check
1145
+ * Mutation variables for {@link useMigratebnUSD}. Generic over `K extends SpokeChainKey` (defaults
1146
+ * to the full union). Bidirectional — handles both legacy → new and new → legacy bnUSD migration
1147
+ * via the same SDK call; the SDK detects direction from the token addresses.
1148
+ */
1149
+ type UseMigratebnUSDVars<K extends SpokeChainKey = SpokeChainKey> = Omit<UnifiedBnUSDMigrateAction<K, false>, 'raw'>;
1150
+ /**
1151
+ * React hook for migrating bnUSD between legacy and new formats across spoke chains via Sonic.
2001
1152
  *
2002
- * @example
2003
- * ```typescript
2004
- * const { data: hasAllowed, isLoading } = useMigrationAllowance(params, spokeProvider);
2005
- * ```
1153
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1154
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2006
1155
  */
2007
- declare function useMigrationAllowance(params: MigrationIntentParams | undefined, spokeProvider: SpokeProvider | undefined): UseQueryResult<boolean, Error>;
1156
+ declare function useMigratebnUSD<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseMigratebnUSDVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseMigratebnUSDVars<K>>;
2008
1157
 
2009
- interface UseApproveReturn {
2010
- approve: ({ params }: {
2011
- params: MigrationIntentParams;
2012
- }) => Promise<boolean>;
2013
- isLoading: boolean;
2014
- error: Error | null;
2015
- resetError: () => void;
2016
- isApproved: boolean;
2017
- }
1158
+ type UseMigrateBalnVars = Omit<BalnMigrateAction<false>, 'raw'>;
2018
1159
  /**
2019
- * Hook for approving token spending for migration actions
2020
- * @param params The parameters for the migration approval
2021
- * @param spokeProvider The spoke provider instance for the chain
2022
- * @returns Object containing approve function, loading state, error state and reset function
2023
- * @example
2024
- * ```tsx
2025
- * const { approve, isLoading, error } = useMigrationApprove(params, spokeProvider);
1160
+ * React hook for migrating BALN SODA on the Sonic hub. Source chain is always Icon. Supports
1161
+ * lockup periods (0–24 months) which multiply the SODA reward (0.5x–1.5x).
2026
1162
  *
2027
- * // Approve tokens for migration
2028
- * await approve({ params });
2029
- * ```
1163
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1164
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2030
1165
  */
2031
- declare function useMigrationApprove(params: MigrationIntentParams | undefined, spokeProvider: SpokeProvider | undefined): UseApproveReturn;
1166
+ declare function useMigrateBaln({ mutationOptions, }?: MutationHookParams<TxHashPair, UseMigrateBalnVars>): SafeUseMutationResult<TxHashPair, Error, UseMigrateBalnVars>;
2032
1167
 
2033
- type UsePoolsProps = {
2034
- /**
2035
- * Optional react-query QueryObserverOptions for customizing query behavior such as
2036
- * staleTime, refetchInterval, cacheTime, etc. These are merged with sensible defaults.
2037
- */
2038
- queryOptions?: QueryObserverOptions<PoolKey[], Error>;
1168
+ /**
1169
+ * Mutation variables for {@link useMigrationApprove}. The SDK's `approve` accepts a union of
1170
+ * action wrappers (Icx-revert OR bnUSD bidirectional) plus a separate `'migrate' | 'revert'`
1171
+ * discriminator. Both ride along in `TVars` here so the hook stays a pure pass-through.
1172
+ */
1173
+ type UseMigrationApproveVars<K extends SpokeChainKey = SpokeChainKey> = (Omit<IcxRevertMigrationAction<false>, 'raw'> | Omit<UnifiedBnUSDMigrateAction<K, false>, 'raw'>) & {
1174
+ action: MigrationAction;
2039
1175
  };
2040
1176
  /**
2041
- * Loads and caches the available list of pools from the DEX service's ConcentratedLiquidityService.
1177
+ * React hook for approving token spending on a migration intent. Required before:
1178
+ * - SODA → ICX revert (consumes SODA on Sonic via the user's hub router)
1179
+ * - bnUSD migrations on EVM/Stellar source chains (consumes the source bnUSD via asset manager)
2042
1180
  *
2043
- * By default, the query result is cached indefinitely (with `staleTime` set to Infinity), reflecting the
2044
- * assumption that the pools list is mostly static.
1181
+ * NOT required for ICX SODA forward migrations or BALN migrations (both originate on Icon
1182
+ * which doesn't use ERC-20 allowances).
2045
1183
  *
2046
- * @param params
2047
- * Optional configuration object:
2048
- * - queryOptions: Partial QueryObserverOptions for react-query (merged with built-in defaults).
1184
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1185
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
1186
+ */
1187
+ declare function useMigrationApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseMigrationApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseMigrationApproveVars<K>>;
1188
+
1189
+ /**
1190
+ * Domain inputs for {@link useMigrationAllowance}. `params` is the underlying migration params
1191
+ * (NOT the action wrapper — no `walletProvider`/`raw`); `action` is the `'migrate' | 'revert'`
1192
+ * discriminator the SDK uses to pick the right allowance check path.
2049
1193
  *
2050
- * @returns
2051
- * A UseQueryResult object from @tanstack/react-query containing:
2052
- * - `data`: Array of PoolKey objects or undefined if not loaded or errored.
2053
- * - Status fields: `isLoading`, `isError`, `error`, etc.
1194
+ * For ICX forward migration (`migrate`, params={IcxMigrateParams}) and BALN migration the SDK
1195
+ * always returns `true` (Icon has no ERC-20-style allowance) — but the hook still works there
1196
+ * for code-uniformity at the call site.
1197
+ */
1198
+ type UseMigrationAllowanceInputs<K extends SpokeChainKey = SpokeChainKey> = {
1199
+ params: IcxMigrateParams | IcxCreateRevertMigrationParams | UnifiedBnUSDMigrateParams<K> | BalnMigrateParams | undefined;
1200
+ action: MigrationAction | undefined;
1201
+ };
1202
+ type UseMigrationAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<boolean, UseMigrationAllowanceInputs<K>>;
1203
+ /**
1204
+ * React hook to check if migration spending is approved.
2054
1205
  *
2055
- * @example
2056
- * const { data: pools, isLoading, error } = usePools();
2057
- * if (isLoading) return <div>Loading pools...</div>;
2058
- * if (error) return <div>Error: {error.message}</div>;
2059
- * if (pools) pools.forEach((pool, idx) => console.log(pool.id, pool.fee));
1206
+ * Returns `false` when params are missing (so the call site can disable the action button).
1207
+ * Hook lifecycle (`enabled`, `queryKey`, `queryFn`) is owned internally; consumers can override
1208
+ * other React Query knobs via `queryOptions`.
2060
1209
  */
2061
- declare function usePools(params?: UsePoolsProps): UseQueryResult<PoolKey[], Error>;
1210
+ declare function useMigrationAllowance<K extends SpokeChainKey = SpokeChainKey>({ params, queryOptions, }?: UseMigrationAllowanceParams<K>): UseQueryResult<boolean, Error>;
2062
1211
 
2063
- type UsePoolDataProps = {
1212
+ type UsePoolsParams = ReadHookParams<PoolKey[]>;
1213
+ /**
1214
+ * Loads the list of concentrated-liquidity pools known to the SDK config. The SDK's `getPools()`
1215
+ * is synchronous in v2 (no network), so this hook caches indefinitely by default.
1216
+ */
1217
+ declare function usePools({ queryOptions }?: UsePoolsParams): UseQueryResult<PoolKey[], Error>;
1218
+
1219
+ type UsePoolDataParams = ReadHookParams<PoolData, {
2064
1220
  poolKey: PoolKey | null;
2065
- enabled?: boolean;
2066
- queryOptions?: QueryObserverOptions<PoolData, Error>;
2067
- };
1221
+ }>;
2068
1222
  /**
2069
- * React hook to fetch on-chain data for a given DEX pool.
2070
- *
2071
- * @param {UsePoolDataProps} props - The props object:
2072
- * - `poolKey`: PoolKey | null — The unique identifier for the pool to fetch data for. If null, disables the query.
2073
- * - `enabled`: boolean (optional) — Whether the query is enabled. Defaults to enabled if a poolKey is provided, otherwise false.
2074
- * - `queryOptions`: QueryObserverOptions<PoolData, Error> (optional) — Additional React Query options (e.g., staleTime, refetchInterval).
2075
- *
2076
- * @returns {UseQueryResult<PoolData, Error>} React Query result containing pool data (`data`), loading state (`isLoading`), error (`error`), and status fields.
2077
- *
2078
- * @example
2079
- * ```typescript
2080
- * const { data: poolData, isLoading, error } = usePoolData({ poolKey });
2081
- * if (isLoading) return <div>Loading…</div>;
2082
- * if (error) return <div>Error!</div>;
2083
- * if (poolData) {
2084
- * // poolData is available
2085
- * }
2086
- * ```
2087
- *
2088
- * @remarks
2089
- * - Refetches pool data every 30 seconds by default, and may be configured via `queryOptions`.
2090
- * - If `poolKey` is `null`, the query is disabled and no network request is performed.
2091
- * - Throws an error if `poolKey` is missing when the query is enabled.
1223
+ * React hook to fetch on-chain pool data (sqrt price, tick, fees, token info, etc.) for a given
1224
+ * pool key. Reads via the hub `publicClient`. Disabled when `poolKey` is null.
2092
1225
  */
2093
- declare function usePoolData({ poolKey, queryOptions, }: UsePoolDataProps): UseQueryResult<PoolData, Error>;
1226
+ declare function usePoolData({ params, queryOptions }?: UsePoolDataParams): UseQueryResult<PoolData, Error>;
2094
1227
 
2095
- interface UsePoolBalancesResponse {
1228
+ type UsePoolBalancesResponse = {
2096
1229
  token0Balance: bigint;
2097
1230
  token1Balance: bigint;
2098
- }
2099
- interface UsePoolBalancesProps {
1231
+ };
1232
+ type UsePoolBalancesParams = ReadHookParams<UsePoolBalancesResponse, {
2100
1233
  poolData: PoolData | null;
2101
1234
  poolKey: PoolKey | null;
2102
- spokeProvider: SpokeProvider | null;
2103
- enabled?: boolean;
2104
- queryOptions?: QueryObserverOptions<UsePoolBalancesResponse, Error>;
2105
- }
1235
+ spokeChainKey: SpokeChainKey | undefined;
1236
+ userAddress: string | undefined;
1237
+ }>;
2106
1238
  /**
2107
- * React hook to query a user's token balances for a DEX pool.
2108
- *
2109
- * Given the pool data (with token addresses), the pool's key, and a SpokeProvider,
2110
- * fetches the user's protocol balances for both token0 and token1 for the specified pool.
2111
- * Queries are auto-refreshed; advanced options can be customized via `queryOptions`.
2112
- *
2113
- * @param {UsePoolBalancesProps} props
2114
- * Object containing:
2115
- * - `poolData`: {PoolData | null} - Pool info (must include token0 and token1 addresses). Required unless disabling.
2116
- * - `poolKey`: {PoolKey | null} - Unique key for the DEX pool. Required unless disabling.
2117
- * - `spokeProvider`: {SpokeProvider | null} - Provider instance for the chain. Required unless disabling.
2118
- * - `enabled`: {boolean} (optional) - Whether to enable the query. Defaults to `true` if all other arguments are provided.
2119
- * - `queryOptions`: {QueryObserverOptions<UsePoolBalancesResponse, Error>} (optional) - Advanced react-query options.
2120
- *
2121
- * @returns {UseQueryResult<UsePoolBalancesResponse, Error>}
2122
- * React Query result object:
2123
- * - `data`: `{ token0Balance: bigint, token1Balance: bigint }` if loaded, undefined otherwise.
2124
- * - `isLoading`, `isError`, etc. for status handling.
2125
- *
2126
- * @remarks
2127
- * - Throws an error if any of `poolData`, `poolKey`, or `spokeProvider` is missing when enabled.
2128
- * - Suitable for tracking current protocol/wallet balances for both pool tokens.
2129
- * - The hook is designed for use within a React component tree that provides the Sodax context.
2130
- * - Data are automatically refreshed at the provided or default polling interval (default: refetch every 10s).
2131
- *
2132
- * @example
2133
- * ```typescript
2134
- * const { data, isLoading } = usePoolBalances({ poolData, poolKey, spokeProvider });
2135
- * if (data) {
2136
- * console.log('Balances:', data.token0Balance, data.token1Balance);
2137
- * }
2138
- * ```
1239
+ * React hook to query the user's hub-side deposit balances for both pool tokens. Derives the hub
1240
+ * wallet once and reads both pool-token balances in parallel via the hub `publicClient`.
2139
1241
  */
2140
- declare function usePoolBalances({ poolData, poolKey, spokeProvider, enabled, queryOptions, }: UsePoolBalancesProps): UseQueryResult<UsePoolBalancesResponse, Error>;
1242
+ declare function usePoolBalances({ params, queryOptions, }?: UsePoolBalancesParams): UseQueryResult<UsePoolBalancesResponse, Error>;
2141
1243
 
2142
- interface UsePositionInfoResponse {
1244
+ type UsePositionInfoResponse = {
2143
1245
  positionInfo: ClPositionInfo;
2144
1246
  isValid: boolean;
2145
- }
2146
- interface UsePositionInfoProps {
1247
+ };
1248
+ type UsePositionInfoParams = ReadHookParams<UsePositionInfoResponse, {
2147
1249
  tokenId: string | null;
2148
1250
  poolKey: PoolKey | null;
2149
- queryOptions?: QueryObserverOptions<UsePositionInfoResponse, Error>;
2150
- }
1251
+ }>;
2151
1252
  /**
2152
- * React hook to fetch and validate CL position details by position NFT token ID.
2153
- *
2154
- * Fetches position data on-chain for a given tokenId, and checks if it matches the expected PoolKey.
2155
- * This is commonly used in DEX dashboards to show or pre-validate user positions by ID.
2156
- *
2157
- * @param {string | null} tokenId
2158
- * Position NFT token ID to query, as a string. Pass `null` or empty string to disable.
2159
- * @param {PoolKey | null} poolKey
2160
- * PoolKey to match against the position's underlying pool. Pass `null` to disable.
2161
- * @param {QueryObserverOptions<UsePositionInfoResponse, Error>} [queryOptions]
2162
- * Optional react-query options for polling/refresh and config. Merged with sensible defaults.
2163
- *
2164
- * @returns {UseQueryResult<UsePositionInfoResponse, Error>}
2165
- * Standard React Query result object:
2166
- * - `data`: { positionInfo, isValid } if loaded, or undefined if not loaded/error
2167
- * - `isLoading`: boolean (query active)
2168
- * - `isError`: boolean (query failed)
2169
- * - ...other react-query helpers (refetch, status, etc)
2170
- *
2171
- * @example
2172
- * ```typescript
2173
- * const { data, isLoading, error } = usePositionInfo({ tokenId, poolKey });
2174
- * if (isLoading) return <div>Loading position...</div>;
2175
- * if (error) return <div>Error: {error.message}</div>;
2176
- * if (data) {
2177
- * console.log('Valid for pool:', data.isValid);
2178
- * console.log('Liquidity:', data.positionInfo.liquidity);
2179
- * }
2180
- * ```
2181
- *
2182
- * @remarks
2183
- * - Validates the underlying position's pool definition (currency0, currency1, fee) with the supplied PoolKey.
2184
- * - Returns `isValid: false` if any field mismatches.
2185
- * - Pass `null` as tokenId or poolKey to disable the query.
2186
- * - Defaults: 10s stale, not enabled if missing arguments. Customizable via `queryOptions`.
2187
- * - Throws error if called with invalid/null tokenId or poolKey when enabled.
1253
+ * React hook to fetch a CL position by NFT token id and validate it against an expected pool key.
1254
+ * Reads via the hub `publicClient`. Disabled when `tokenId` or `poolKey` is missing.
2188
1255
  */
2189
- declare function usePositionInfo({ tokenId, poolKey, queryOptions, }: UsePositionInfoProps): UseQueryResult<UsePositionInfoResponse, Error>;
1256
+ declare function usePositionInfo({ params, queryOptions, }?: UsePositionInfoParams): UseQueryResult<UsePositionInfoResponse, Error>;
2190
1257
 
2191
- type UseDexDepositParams = {
2192
- params: CreateAssetDepositParams;
2193
- spokeProvider: SpokeProvider;
2194
- };
2195
1258
  /**
1259
+ * Mutation variables for {@link useDexDeposit}. Generic over `K extends SpokeChainKey` (defaults
1260
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
1261
+ * `walletProvider` and `params.srcChainKey` types.
1262
+ */
1263
+ type UseDexDepositVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;
2196
1264
  /**
2197
- * React hook that provides a mutation to perform a deposit into a DEX pool using the provided parameters and SpokeProvider.
2198
- *
2199
- * The hook returns a mutation object for executing the deposit (`mutateAsync`), tracking its state (`isPending`), and any resulting error (`error`).
2200
- * On successful deposit, all queries matching ['dex', 'poolBalances'] are invalidated and refetched.
1265
+ * React hook for depositing an asset into a DEX pool.
2201
1266
  *
2202
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams>}
2203
- * React Query mutation result:
2204
- * - `mutateAsync({ params, spokeProvider })`: Triggers the deposit with {@link CreateDepositParams} and the target SpokeProvider.
2205
- * - `isPending`: True while the deposit transaction is pending.
2206
- * - `error`: Error if the mutation fails.
1267
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1268
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2207
1269
  *
2208
1270
  * @example
2209
- * ```typescript
2210
- * const { mutateAsync: deposit, isPending, error } = useDexDeposit();
2211
- * await deposit({ params: { asset, amount, poolToken }, spokeProvider });
1271
+ * ```tsx
1272
+ * const walletProvider = useWalletProvider({ xChainId: chainKey });
1273
+ * const { mutateAsync: deposit } = useDexDeposit();
1274
+ * try {
1275
+ * const { spokeTxHash, hubTxHash } = await deposit({ params, walletProvider });
1276
+ * } catch (e) {
1277
+ * // surfaced via mutation.error / onError
1278
+ * }
2212
1279
  * ```
2213
- *
2214
- * @remarks
2215
- * - Throws if called with missing `spokeProvider` or `params`.
2216
- * - Upon success, automatically refetches up-to-date pool balances.
2217
1280
  */
2218
- declare function useDexDeposit(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams>;
1281
+ declare function useDexDeposit<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseDexDepositVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseDexDepositVars<K>>;
2219
1282
 
2220
- type UseDexWithdrawParams = {
2221
- params: CreateAssetWithdrawParams;
2222
- spokeProvider: SpokeProvider;
2223
- };
2224
1283
  /**
2225
- * React hook to provide a mutation for withdrawing assets from a DEX pool.
2226
- *
2227
- * This hook returns a mutation result object valid for use with React Query.
2228
- * The mutation function expects an object with the withdrawal parameters and a SpokeProvider,
2229
- * and triggers the withdrawal operation on the DEX. On success, it invalidates the relevant
2230
- * ['dex', 'poolBalances'] query to fetch the updated balances.
2231
- *
2232
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams>}
2233
- * Mutation result object. Use its properties to:
2234
- * - Call `mutateAsync({ params, spokeProvider })` to perform the withdrawal.
2235
- * - Track progress with `isPending`.
2236
- * - Access any `error` encountered during the mutation.
1284
+ * Mutation variables for {@link useDexWithdraw}. Generic over `K extends SpokeChainKey` (defaults
1285
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
1286
+ * `walletProvider` and `params.srcChainKey` types.
1287
+ */
1288
+ type UseDexWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetWithdrawAction<K, false>, 'raw'>;
1289
+ /**
1290
+ * React hook for withdrawing an asset from a DEX pool.
2237
1291
  *
2238
- * @example
2239
- * const { mutateAsync: withdraw, isPending, error } = useDexWithdraw();
2240
- * await withdraw({ params, spokeProvider });
1292
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1293
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2241
1294
  */
2242
- declare function useDexWithdraw(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams>;
1295
+ declare function useDexWithdraw<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseDexWithdrawVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseDexWithdrawVars<K>>;
2243
1296
 
2244
- type UseDexAllowanceProps = {
2245
- params: CreateAssetDepositParams | undefined;
2246
- spokeProvider: SpokeProvider | null;
2247
- enabled?: boolean;
2248
- queryOptions?: QueryObserverOptions<boolean, Error>;
2249
- };
1297
+ type UseDexAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<boolean, {
1298
+ payload: CreateAssetDepositParams<K> | undefined;
1299
+ }>;
2250
1300
  /**
2251
- * Hook to check if the user has approved sufficient token allowance for DEX deposits.
2252
- *
2253
- * This hook automatically queries and tracks the allowance status, indicating whether
2254
- * the user has granted enough allowance to allow a specific deposit to the DEX. It leverages
2255
- * React Query for status, caching, and background refetching.
2256
- *
2257
- * @param {CreateAssetDepositParams | undefined} params
2258
- * The deposit parameters: asset address, poolToken, and raw amount (BigInt), or undefined to disable.
2259
- * @param {SpokeProvider | undefined} spokeProvider
2260
- * The provider interface for the selected chain. When undefined, the query is disabled.
2261
- * @param {boolean} [enabled]
2262
- * Whether the allowance status check is enabled. Defaults to true if both params and spokeProvider are truthy.
2263
- * @param {QueryObserverOptions<boolean, Error>} [queryOptions]
2264
- * Optional react-query options. Any override here (e.g. staleTime, refetchInterval) will merge with defaults.
2265
- *
2266
- * @returns {UseQueryResult<boolean, Error>}
2267
- * React Query result object: `data` is boolean (true if allowance is sufficient), plus `isLoading`, `error`, etc.
2268
- *
2269
- * @example
2270
- * ```typescript
2271
- * const { data: isAllowed, isLoading, error } = useDexAllowance({
2272
- * params: { asset, amount: parseUnits('100', 18), poolToken },
2273
- * spokeProvider,
2274
- * });
2275
- * if (isLoading) return <Spinner />;
2276
- * if (error) return <div>Error: {error.message}</div>;
2277
- * if (isAllowed) { ... }
2278
- * ```
2279
- *
2280
- * @remarks
2281
- * - The allowance is checked every 5 seconds as long as enabled, params, and spokeProvider are all defined.
2282
- * - Returns `false` if allowance cannot be determined or any error occurs in isAllowanceValid.
2283
- * - Suitable for gating UI actions that require token approval before depositing in the DEX.
1301
+ * React hook to check whether the user has approved sufficient token allowance (or established a
1302
+ * trustline, on Stellar) for a DEX deposit. Read-only — calls `assetService.isAllowanceValid`
1303
+ * with `raw: true` so no `walletProvider` is required.
2284
1304
  */
2285
- declare function useDexAllowance({ params, spokeProvider, queryOptions, }: UseDexAllowanceProps): UseQueryResult<boolean, Error>;
1305
+ declare function useDexAllowance<K extends SpokeChainKey = SpokeChainKey>({ params, queryOptions, }?: UseDexAllowanceParams<K>): UseQueryResult<boolean, Error>;
2286
1306
 
2287
- type UseDexApproveParams = {
2288
- params: CreateAssetDepositParams;
2289
- spokeProvider: SpokeProvider;
2290
- };
2291
1307
  /**
2292
- * React hook for performing a DEX token allowance approval transaction.
2293
- *
2294
- * Returns a mutation object that allows explicitly triggering a token approval
2295
- * for a DEX deposit, using the specified approval parameters and spoke provider.
2296
- * On successful approval, the related allowance query is invalidated and refetched
2297
- * for consistent UI state.
2298
- *
2299
- * @returns {UseMutationResult<SpokeTxHash, Error, UseDexApproveParams>}
2300
- * React Query mutation result for the approval operation. Use `mutateAsync` with
2301
- * an object of shape `{ params, spokeProvider }` to initiate approval.
2302
- *
2303
- * @example
2304
- * ```typescript
2305
- * const { mutateAsync: approve, isPending, error } = useDexApprove();
2306
- * await approve({ params: { asset, amount, poolToken }, spokeProvider });
2307
- * ```
1308
+ * Mutation variables for {@link useDexApprove}. Generic over `K extends SpokeChainKey` (defaults
1309
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
1310
+ * `walletProvider` and `params.srcChainKey` types.
1311
+ */
1312
+ type UseDexApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;
1313
+ /**
1314
+ * React hook for approving ERC-20 token spending (or trustline establishment) for a DEX deposit.
2308
1315
  *
2309
- * @remarks
2310
- * - Throws if called without both a valid `params` and `spokeProvider`.
2311
- * - On approval success, the query for ['dex', 'allowance'] is invalidated/refetched.
1316
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1317
+ * `onError`, `retry`). Returns the unwrapped tx return value on success.
2312
1318
  */
2313
- declare function useDexApprove(): UseMutationResult<SpokeTxHash, Error, UseDexApproveParams>;
1319
+ declare function useDexApprove<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxReturnType<K, false>, UseDexApproveVars<K>>): SafeUseMutationResult<TxReturnType<K, false>, Error, UseDexApproveVars<K>>;
2314
1320
 
2315
- interface UseLiquidityAmountsResult {
1321
+ type UseLiquidityAmountsResult = {
2316
1322
  liquidityToken0Amount: string;
2317
1323
  liquidityToken1Amount: string;
2318
1324
  lastEditedToken: 'token0' | 'token1' | null;
@@ -2320,33 +1326,10 @@ interface UseLiquidityAmountsResult {
2320
1326
  setLiquidityToken1Amount: (value: string) => void;
2321
1327
  handleToken0AmountChange: (value: string) => void;
2322
1328
  handleToken1AmountChange: (value: string) => void;
2323
- }
1329
+ };
2324
1330
  /**
2325
- * Hook for calculating liquidity amounts based on price range.
2326
- *
2327
- * This hook manages the state and calculations for liquidity token amounts.
2328
- * It automatically calculates the corresponding token amount when one is changed,
2329
- * based on the current price range and pool data.
2330
- *
2331
- * @param {string} minPrice - Minimum price for the liquidity range
2332
- * @param {string} maxPrice - Maximum price for the liquidity range
2333
- * @param {PoolData | null} poolData - The pool data containing token information
2334
- * @returns {UseLiquidityAmountsResult} Object containing amounts, state, and handlers
2335
- *
2336
- * @example
2337
- * ```typescript
2338
- * const {
2339
- * liquidityToken0Amount,
2340
- * liquidityToken1Amount,
2341
- * handleToken0AmountChange,
2342
- * handleToken1AmountChange,
2343
- * } = useLiquidityAmounts(minPrice, maxPrice, poolData);
2344
- *
2345
- * <Input
2346
- * value={liquidityToken0Amount}
2347
- * onChange={(e) => handleToken0AmountChange(e.target.value)}
2348
- * />
2349
- * ```
1331
+ * Hook for calculating concentrated-liquidity amounts based on the price range. Pure state +
1332
+ * math; no SDK calls beyond the static {@link ClService} helpers.
2350
1333
  */
2351
1334
  declare function useLiquidityAmounts(minPrice: string, maxPrice: string, poolData: PoolData | null): UseLiquidityAmountsResult;
2352
1335
 
@@ -2361,105 +1344,81 @@ type UseCreateSupplyLiquidityParamsProps = {
2361
1344
  positionId?: string | null;
2362
1345
  isValidPosition?: boolean;
2363
1346
  };
2364
- type UseCreateSupplyLiquidityParamsResult = ConcentratedLiquiditySupplyParams & Omit<ConcentratedLiquidityIncreaseLiquidityParams, 'tokenId'> & {
1347
+ /**
1348
+ * Subset of {@link ClSupplyParams} / {@link ClIncreaseLiquidityParams} produced by
1349
+ * {@link useCreateSupplyLiquidityParams}. Callers add `srcChainKey` + `srcAddress` at the mutation
1350
+ * call site. `tokenId` and `isValidPosition` distinguish the mint-new vs increase-existing path.
1351
+ */
1352
+ type UseCreateSupplyLiquidityParamsResult = Omit<ClSupplyParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'> & Omit<ClIncreaseLiquidityParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress' | 'tokenId'> & {
2365
1353
  tokenId?: string | bigint;
2366
1354
  positionId?: string | null;
2367
1355
  isValidPosition?: boolean;
2368
1356
  };
2369
1357
  /**
2370
- * React hook to create the supply liquidity parameters for a given pool.
2371
- *
2372
- * Purpose:
2373
- * - Provides a hook which memoizes the supply liquidity parameters for a given pool.
2374
- *
2375
- * Usage:
2376
- * - Call the function with the pool data, pool key, minimum price, maximum price, liquidity token0 amount, liquidity token1 amount, slippage tolerance, position id, and validity of the position to create the supply liquidity parameters.
2377
- *
2378
- * Params:
2379
- * @param poolData - The pool data of the pool to supply liquidity to.
2380
- * @param poolKey - The pool key of the pool to supply liquidity to.
2381
- * @param minPrice - The minimum price of the liquidity to supply.
2382
- * @param maxPrice - The maximum price of the liquidity to supply.
2383
- * @param liquidityToken0Amount - The amount of the token0 to supply.
2384
- * @param liquidityToken1Amount - The amount of the token1 to supply.
2385
- * @param slippageTolerance - The slippage tolerance to use for the supply.
2386
- * @param positionId - The position id of the position to supply liquidity to.
2387
- * @param isValidPosition - Whether the position is valid.
2388
- * @returns The supply liquidity parameters.
1358
+ * React hook to memoize concentrated-liquidity supply parameters for a given pool. Returns the
1359
+ * pool/tick/liquidity/amount fields without `srcChainKey`/`srcAddress` — callers add those at the
1360
+ * mutation call site.
2389
1361
  */
2390
1362
  declare function useCreateSupplyLiquidityParams({ poolData, poolKey, minPrice, maxPrice, liquidityToken0Amount, liquidityToken1Amount, slippageTolerance, positionId, isValidPosition, }: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult;
2391
1363
 
2392
- type UseSupplyLiquidityProps = {
2393
- params: UseCreateSupplyLiquidityParamsResult;
2394
- spokeProvider: SpokeProvider;
1364
+ /**
1365
+ * Mutation variables for {@link useSupplyLiquidity}. Generic over `K extends SpokeChainKey`
1366
+ * (defaults to the full union). The hook fans out internally to either
1367
+ * `clService.increaseLiquidity` (when `params.tokenId` + `params.isValidPosition` are present) or
1368
+ * `clService.supplyLiquidity` (mint a new position).
1369
+ */
1370
+ type UseSupplyLiquidityVars<K extends SpokeChainKey = SpokeChainKey> = {
1371
+ params: UseCreateSupplyLiquidityParamsResult & {
1372
+ srcChainKey: K;
1373
+ srcAddress: string;
1374
+ };
1375
+ walletProvider: GetWalletProviderType<K>;
1376
+ /** Optional relay timeout in ms (default 60_000) */
1377
+ timeout?: number;
2395
1378
  };
2396
1379
  /**
2397
- * Hook for supplying liquidity to a pool.
2398
- *
2399
- * This hook handles both minting new positions and increasing liquidity in existing positions.
2400
- * It applies slippage tolerance before calculating liquidity and handles the complete transaction flow.
2401
- *
2402
- * @param {SpokeProvider} spokeProvider - The spoke provider for the chain
2403
- * @returns {UseMutationResult<void, Error, SupplyLiquidityParams>} Mutation result with supply function
1380
+ * React hook for supplying liquidity to a concentrated-liquidity pool. If the input vars include a
1381
+ * valid `tokenId` for an existing position, the hook calls `increaseLiquidity`; otherwise it mints
1382
+ * a new position via `supplyLiquidity`.
2404
1383
  *
2405
- * @example
2406
- * ```typescript
2407
- * const { mutateAsync: supplyLiquidity, isPending, error } = useSupplyLiquidity(spokeProvider);
2408
- *
2409
- * await supplyLiquidity({
2410
- * poolData,
2411
- * poolKey,
2412
- * minPrice: '100',
2413
- * maxPrice: '200',
2414
- * liquidityToken0Amount: '10',
2415
- * liquidityToken1Amount: '20',
2416
- * slippageTolerance: '0.5',
2417
- * });
2418
- * ```
1384
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1385
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2419
1386
  */
2420
- declare function useSupplyLiquidity(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseSupplyLiquidityProps>;
1387
+ declare function useSupplyLiquidity<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseSupplyLiquidityVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseSupplyLiquidityVars<K>>;
2421
1388
 
2422
- type UseDecreaseLiquidityParams = {
2423
- params: ConcentratedLiquidityDecreaseLiquidityParams;
2424
- spokeProvider: SpokeProvider;
2425
- };
2426
1389
  /**
2427
- * React hook that provides a mutation for decreasing liquidity in a concentrated liquidity position.
2428
- *
2429
- * This hook returns a mutation for removing liquidity from a position using the provided
2430
- * `ConcentratedLiquidityDecreaseLiquidityParams` and `SpokeProvider`. The mutation returns a tuple of
2431
- * the spoke transaction hash and the hub transaction hash upon success.
2432
- *
2433
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams>}
2434
- * React Query mutation result:
2435
- * - `mutateAsync({ params, spokeProvider })`: Triggers the decrease liquidity mutation.
2436
- * - On success, returns `[spokeTxHash, hubTxHash]`.
2437
- * - On failure, throws an error.
2438
- *
2439
- * @example
2440
- * ```typescript
2441
- * const { mutateAsync: decreaseLiquidity, isPending, error } = useDecreaseLiquidity();
2442
- *
2443
- * await decreaseLiquidity({
2444
- * params: {
2445
- * poolKey,
2446
- * tokenId: 123n,
2447
- * liquidity: 100000n,
2448
- * amount0Min: 0n,
2449
- * amount1Min: 0n,
2450
- * },
2451
- * spokeProvider,
2452
- * });
2453
- * ```
2454
- *
2455
- * @param {UseDecreaseLiquidityParams} variables
2456
- * - `params`: Parameters for the decrease liquidity operation, matching `ConcentratedLiquidityDecreaseLiquidityParams`.
2457
- * - `spokeProvider`: The provider instance for the target spoke chain.
1390
+ * Mutation variables for {@link useDecreaseLiquidity}. Generic over `K extends SpokeChainKey`
1391
+ * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow
1392
+ * the `walletProvider` and `params.srcChainKey` types.
1393
+ */
1394
+ type UseDecreaseLiquidityVars<K extends SpokeChainKey = SpokeChainKey> = Omit<ClLiquidityDecreaseLiquidityAction<K, false>, 'raw'>;
1395
+ /**
1396
+ * React hook for decreasing liquidity in an existing concentrated-liquidity position.
2458
1397
  *
2459
- * @remarks
2460
- * - After a successful liquidity decrease, the hook will invalidate DEX pool balances and position info queries.
1398
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1399
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
1400
+ */
1401
+ declare function useDecreaseLiquidity<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseDecreaseLiquidityVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseDecreaseLiquidityVars<K>>;
1402
+
1403
+ /**
1404
+ * Subset of {@link CreateAssetDepositParams} produced by {@link createDepositParamsProps}.
1405
+ * Callers add `srcChainKey` + `srcAddress` at the mutation call site.
1406
+ */
1407
+ type DepositParamsCore = Omit<CreateAssetDepositParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;
1408
+ /**
1409
+ * Subset of {@link CreateAssetWithdrawParams} produced by {@link createWithdrawParamsProps}.
1410
+ * Callers add `srcChainKey` + `srcAddress` at the mutation call site.
2461
1411
  */
2462
- declare function useDecreaseLiquidity(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams>;
1412
+ type WithdrawParamsCore = Omit<CreateAssetWithdrawParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;
1413
+ /**
1414
+ * Subset of {@link ClDecreaseLiquidityParams} produced by {@link createDecreaseLiquidityParamsProps}.
1415
+ * Callers add `srcChainKey` + `srcAddress` at the mutation call site.
1416
+ */
1417
+ type DecreaseLiquidityParamsCore = Omit<ClDecreaseLiquidityParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;
1418
+ declare function createDecreaseLiquidityParamsProps({ poolKey, tokenId, percentage, positionInfo, slippageTolerance, }: UseCreateDecreaseLiquidityParamsProps): DecreaseLiquidityParamsCore;
1419
+ declare function createDepositParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, }: UseCreateDepositParamsProps): DepositParamsCore;
1420
+ declare function createSupplyLiquidityParamsProps({ poolData, poolKey, minPrice, maxPrice, liquidityToken0Amount, liquidityToken1Amount, slippageTolerance, positionId, isValidPosition, }: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult;
1421
+ declare function createWithdrawParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, dst, }: UseCreateWithdrawParamsProps): WithdrawParamsCore;
2463
1422
 
2464
1423
  type UseCreateDepositParamsProps = {
2465
1424
  tokenIndex: 0 | 1;
@@ -2468,23 +1427,11 @@ type UseCreateDepositParamsProps = {
2468
1427
  poolSpokeAssets: PoolSpokeAssets;
2469
1428
  };
2470
1429
  /**
2471
- * React hook to create the deposit parameters for a given pool and token.
2472
- *
2473
- * Purpose:
2474
- * - Provides a hook which memoizes the deposit parameters for a given pool and token.
2475
- *
2476
- * Usage:
2477
- * - Call the function with the token index, amount, pool data, pool key, and spoke provider to create the deposit parameters.
2478
- *
2479
- * Params:
2480
- * @param tokenIndex - The index of the token to deposit.
2481
- * @param amount - The amount of the token to deposit.
2482
- * @param poolData - The pool data of the pool to deposit to.
2483
- * @param poolKey - The pool key of the pool to deposit to.
2484
- * @param spokeProvider - The spoke provider to use for the deposit.
2485
- * @returns The deposit parameters or undefined if the pool key, spoke provider, or amount is not set.
1430
+ * React hook to memoize the deposit-specific subset of {@link CreateAssetDepositParams}
1431
+ * (`{ asset, amount, poolToken, dst? }`). Callers add `srcChainKey` + `srcAddress` at the mutation
1432
+ * call site.
2486
1433
  */
2487
- declare function useCreateDepositParams({ tokenIndex, amount, poolData, poolSpokeAssets, }: UseCreateDepositParamsProps): CreateAssetDepositParams | undefined;
1434
+ declare function useCreateDepositParams({ tokenIndex, amount, poolData, poolSpokeAssets, }: UseCreateDepositParamsProps): DepositParamsCore | undefined;
2488
1435
 
2489
1436
  type UseCreateDecreaseLiquidityParamsProps = {
2490
1437
  poolKey: PoolKey;
@@ -2494,23 +1441,11 @@ type UseCreateDecreaseLiquidityParamsProps = {
2494
1441
  slippageTolerance: string | number;
2495
1442
  };
2496
1443
  /**
2497
- * React hook to create the decrease liquidity parameters for a given pool and position.
2498
- *
2499
- * Purpose:
2500
- * - Provides a hook which memoizes the decrease liquidity parameters for a given pool and position.
2501
- *
2502
- * Usage:
2503
- * - Call the function with the pool key, token ID, percentage, position info, and slippage tolerance to create the decrease liquidity parameters.
2504
- *
2505
- * Params:
2506
- * @param poolKey - The pool key of the pool to decrease the liquidity from.
2507
- * @param tokenId - The token ID of the position to decrease the liquidity from.
2508
- * @param percentage - The percentage of liquidity to decrease.
2509
- * @param positionInfo - The position info of the position to decrease the liquidity from.
2510
- * @param slippageTolerance - The slippage tolerance to use for the decrease.
2511
- * @returns The decrease liquidity parameters.
1444
+ * React hook to memoize the decrease-liquidity-specific subset of {@link ClDecreaseLiquidityParams}
1445
+ * (`{ poolKey, tokenId, liquidity, amount0Min, amount1Min }`). Callers add `srcChainKey` +
1446
+ * `srcAddress` at the mutation call site.
2512
1447
  */
2513
- declare function useCreateDecreaseLiquidityParams({ poolKey, tokenId, percentage, positionInfo, slippageTolerance, }: UseCreateDecreaseLiquidityParamsProps): ConcentratedLiquidityDecreaseLiquidityParams;
1448
+ declare function useCreateDecreaseLiquidityParams({ poolKey, tokenId, percentage, positionInfo, slippageTolerance, }: UseCreateDecreaseLiquidityParamsProps): DecreaseLiquidityParamsCore;
2514
1449
 
2515
1450
  type UseCreateWithdrawParamsProps = {
2516
1451
  tokenIndex: 0 | 1;
@@ -2520,62 +1455,96 @@ type UseCreateWithdrawParamsProps = {
2520
1455
  dst?: DestinationParamsType;
2521
1456
  };
2522
1457
  /**
2523
- * React hook to create the withdrawal parameters for a given pool and token.
2524
- *
2525
- * Purpose:
2526
- * - Provides a hook which memoizes the withdrawal parameters for a given pool and token.
2527
- *
2528
- * Usage:
2529
- * - Call the function with the token index, amount, pool data, pool spoke assets, and destination parameters to create the withdrawal parameters.
2530
- *
2531
- * Params:
2532
- * @param tokenIndex - The index of the token to withdraw.
2533
- * @param amount - The amount of the token to withdraw.
2534
- * @param poolData - The pool data of the pool to withdraw from.
2535
- * @param poolSpokeAssets - The pool spoke assets of the pool to withdraw from.
2536
- * @param dst - The destination parameters for the withdrawal.
2537
- * @returns The withdrawal parameters or undefined if the amount is not set.
1458
+ * React hook to memoize the withdraw-specific subset of {@link CreateAssetWithdrawParams}
1459
+ * (`{ asset, amount, poolToken, dst? }`). Callers add `srcChainKey` + `srcAddress` at the mutation
1460
+ * call site.
2538
1461
  */
2539
- declare function useCreateWithdrawParams({ tokenIndex, amount, poolData, poolSpokeAssets, dst, }: UseCreateWithdrawParamsProps): CreateAssetWithdrawParams | undefined;
1462
+ declare function useCreateWithdrawParams({ tokenIndex, amount, poolData, poolSpokeAssets, dst, }: UseCreateWithdrawParamsProps): WithdrawParamsCore | undefined;
2540
1463
 
2541
- type UseClaimRewardsParams = {
2542
- params: ConcentratedLiquidityClaimRewardsParams;
2543
- spokeProvider: SpokeProvider;
2544
- };
2545
1464
  /**
2546
- * React hook for creating a mutation to claim DEX rewards for a concentrated liquidity position.
2547
- *
2548
- * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>, UseClaimRewardsParams>}
2549
- * Returns a react-query mutation result object:
2550
- * - On success: resolves to a tuple `[SpokeTxHash, HubTxHash]`.
2551
- * - On error: the error is of type `ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>`.
2552
- * - The mutation function expects an argument of type {@link UseClaimRewardsParams}
2553
- * containing `params` (the claim parameters) and `spokeProvider` (the target provider).
2554
- * - On mutation success, invalidates the queries `'dex/poolBalances'` and `'dex/positionInfo'`.
1465
+ * Mutation variables for {@link useClaimRewards}. Generic over `K extends SpokeChainKey` (defaults
1466
+ * to the full union). Sophisticated callers can lock K at the hook call site to narrow the
1467
+ * `walletProvider` and `params.srcChainKey` types.
1468
+ */
1469
+ type UseClaimRewardsVars<K extends SpokeChainKey = SpokeChainKey> = Omit<ClLiquidityClaimRewardsAction<K, false>, 'raw'>;
1470
+ /**
1471
+ * React hook for claiming accrued fees on a concentrated-liquidity position.
2555
1472
  *
2556
- * @example
2557
- * const claimRewardsMutation = useClaimRewards();
2558
- * claimRewardsMutation.mutateAsync({
2559
- * params: { poolKey, tokenId, tickLower, tickUpper },
2560
- * spokeProvider,
2561
- * });
1473
+ * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,
1474
+ * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.
2562
1475
  */
2563
- declare function useClaimRewards(): UseMutationResult<[
2564
- SpokeTxHash,
2565
- HubTxHash
2566
- ], ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>, UseClaimRewardsParams>;
1476
+ declare function useClaimRewards<K extends SpokeChainKey = SpokeChainKey>({ mutationOptions, }?: MutationHookParams<TxHashPair, UseClaimRewardsVars<K>>): SafeUseMutationResult<TxHashPair, Error, UseClaimRewardsVars<K>>;
2567
1477
 
2568
1478
  interface SodaxProviderProps {
2569
1479
  children: ReactNode;
2570
- testnet?: boolean;
2571
- config?: SodaxConfig;
2572
- rpcConfig: RpcConfig;
1480
+ /**
1481
+ * Sodax config (overrides defaults including rpcUrls). **Read-once at mount** —
1482
+ * changes after first render are ignored to prevent re-instantiating the SDK
1483
+ * from unstable parent references. To switch config (e.g. testnet ↔ mainnet),
1484
+ * unmount/remount the provider.
1485
+ */
1486
+ config?: DeepPartial<SodaxConfig>;
2573
1487
  }
2574
- declare const SodaxProvider: ({ children, testnet, config, rpcConfig }: SodaxProviderProps) => ReactElement;
1488
+ declare const SodaxProvider: ({ children, config }: SodaxProviderProps) => ReactElement;
2575
1489
 
2576
- declare function createDecreaseLiquidityParamsProps({ poolKey, tokenId, percentage, positionInfo, slippageTolerance, }: UseCreateDecreaseLiquidityParamsProps): ConcentratedLiquidityDecreaseLiquidityParams;
2577
- declare function createDepositParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, }: UseCreateDepositParamsProps): CreateAssetDepositParams;
2578
- declare function createSupplyLiquidityParamsProps({ poolData, poolKey, minPrice, maxPrice, liquidityToken0Amount, liquidityToken1Amount, slippageTolerance, positionId, isValidPosition, }: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult;
2579
- declare function createWithdrawParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, dst, }: UseCreateWithdrawParamsProps): CreateAssetWithdrawParams;
1490
+ type CreateSodaxQueryClientOptions = {
1491
+ /**
1492
+ * Called for every mutation failure (i.e. every time `mutationFn` throws) that does NOT opt out
1493
+ * via `meta: { silent: true }` on the mutation. Defaults to `console.error`.
1494
+ *
1495
+ * This is **global observability** — it runs alongside any per-hook `onError` handler the
1496
+ * consumer set, NOT instead of them. In particular, it fires:
1497
+ * - whether or not `mutateAsync` was awaited inside `try/catch`
1498
+ * - whether or not `mutateAsyncSafe` was used (the wrapper packs into `Result<T>` AFTER React
1499
+ * Query has already entered the error state and dispatched its callbacks)
1500
+ * - whether or not the consumer's `mutationOptions.onError` already toasted/logged
1501
+ *
1502
+ * It is NOT a "did this rejection escape to the global handler?" detector — accurate
1503
+ * unhandled-rejection detection lives at `window.onunhandledrejection`, not here.
1504
+ *
1505
+ * To silence the default for a specific mutation that the consumer is handling locally, set
1506
+ * `meta: { silent: true }`:
1507
+ *
1508
+ * ```ts
1509
+ * useSwap({ mutationOptions: { meta: { silent: true }, onError: (e) => toast(e.message) } });
1510
+ * ```
1511
+ *
1512
+ * To disable the default globally (e.g. wire your own error boundary), pass a no-op:
1513
+ *
1514
+ * ```ts
1515
+ * createSodaxQueryClient({ onMutationError: () => {} });
1516
+ * ```
1517
+ */
1518
+ onMutationError?: (error: unknown) => void;
1519
+ /** Pass-through for any other QueryClient config (default queries options, etc.) */
1520
+ config?: QueryClientConfig;
1521
+ };
1522
+ /**
1523
+ * Creates a `QueryClient` pre-wired with a mutation-error observability hook that gives dapp-kit
1524
+ * consumers a single seam for every mutation failure across the app — wire to Sentry/Datadog/console
1525
+ * as you like. Optional opt-in: consumers who construct their own `QueryClient` are unaffected.
1526
+ *
1527
+ * **Composition with a custom `MutationCache`.** If you pass `config.mutationCache`, we keep your
1528
+ * cache instance (preserving its own `onError` / `onSuccess` / etc.) and *additionally* subscribe
1529
+ * to its event stream to dispatch `onMutationError`. Both your handler and the dapp-kit handler
1530
+ * fire — neither replaces the other. If you don't pass one, we install our own.
1531
+ *
1532
+ * @example default — logs to console
1533
+ * const queryClient = createSodaxQueryClient();
1534
+ *
1535
+ * @example custom — Sentry
1536
+ * const queryClient = createSodaxQueryClient({
1537
+ * onMutationError: (e) => Sentry.captureException(e),
1538
+ * });
1539
+ *
1540
+ * @example silent — disable the default
1541
+ * const queryClient = createSodaxQueryClient({ onMutationError: () => {} });
1542
+ *
1543
+ * @example bring-your-own MutationCache
1544
+ * const myCache = new MutationCache({ onError: myOwnErrorHandler });
1545
+ * const queryClient = createSodaxQueryClient({ config: { mutationCache: myCache } });
1546
+ * // myOwnErrorHandler still runs; onMutationError ALSO runs (unless meta.silent).
1547
+ */
1548
+ declare function createSodaxQueryClient({ onMutationError, config, }?: CreateSodaxQueryClientOptions): QueryClient;
2580
1549
 
2581
- export { type BackendPaginationParams, MIGRATION_MODE_BNUSD, MIGRATION_MODE_ICX_SODA, type MigrationIntentParams, type MigrationMode, type RadfiSession, SodaxProvider, type UseATokenParams, type UseATokensBalancesParams, type UseBorrowParams, type UseClaimRewardsParams, type UseCreateDecreaseLiquidityParamsProps, type UseCreateDepositParamsProps, type UseCreateSupplyLiquidityParamsProps, type UseCreateSupplyLiquidityParamsResult, type UseCreateWithdrawParamsProps, type UseDecreaseLiquidityParams, type UseDexAllowanceProps, type UseDexApproveParams, type UseDexDepositParams, type UseDexWithdrawParams, type UseMMAllowanceParams, type UseMMApproveParams, type UsePoolBalancesProps, type UsePoolBalancesResponse, type UsePoolDataProps, type UsePoolsProps, type UsePositionInfoProps, type UsePositionInfoResponse, type UseRadfiSessionReturn, type UseRepayParams, type UseReservesDataParams, type UseReservesUsdFormatParams, type UseSupplyLiquidityProps, type UseSupplyParams, type UseUserFormattedSummaryParams, type UseUserReservesDataParams, type UseWithdrawParams, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSupplyLiquidityParamsProps, createWithdrawParamsProps, loadRadfiSession, saveRadfiSession, useAToken, useATokensBalances, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendSubmitSwapTx, useBackendSubmitSwapTxStatus, useBackendUserIntents, useBitcoinBalance, useBorrow, useBridge, useBridgeAllowance, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEstimateGas, useExpiredUtxos, useFundTradingWallet, useGetBridgeableAmount, useGetBridgeableTokens, useGetUserHubWalletAddress, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrate, useMigrationAllowance, useMigrationApprove, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesUsdFormat, useSodaxContext, useSpokeProvider, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarTrustlineCheck, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw };
1550
+ export { type ATokenData, type BackendPaginationParams, type CreateSodaxQueryClientOptions, type DecreaseLiquidityParamsCore, type DepositParamsCore, type MutationHookOptions, type MutationHookParams, type RadfiSession, type ReadHookParams, type ReadQueryOptions, type ReserveUsdFormat, type SafeUseMutationResult, SodaxProvider, type UseATokenParams, type UseATokensBalancesParams, type UseApproveTokenVars, type UseBitcoinBalanceParams, type UseBorrowVars, type UseBridgeAllowanceParams, type UseBridgeApproveVars, type UseBridgeVars, type UseClaimRewardsVars, type UseCreateDecreaseLiquidityParamsProps, type UseCreateDepositParamsProps, type UseCreateLimitOrderVars, type UseCreateSupplyLiquidityParamsProps, type UseCreateSupplyLiquidityParamsResult, type UseCreateWithdrawParamsProps, type UseDecreaseLiquidityVars, type UseDeriveUserWalletAddressParams, type UseDexAllowanceParams, type UseDexApproveVars, type UseDexDepositVars, type UseDexWithdrawVars, type UseExpiredUtxosParams, type UseFeeClaimSwapVars, type UseFetchAssetsBalancesParams, type UseFundTradingWalletVars, type UseGetAutoSwapPreferencesParams, type UseGetBridgeableAmountParams, type UseGetBridgeableTokensParams, type UseGetUserHubWalletAddressParams, type UseHubAssetBalancesParams, type UseIsTokenApprovedParams, type UseLiquidityAmountsResult, type UseMMAllowanceParams, type UseMMApproveVars, type UseMigrateBalnVars, type UseMigrateIcxToSodaVars, type UseMigratebnUSDVars, type UseMigrationAllowanceInputs, type UseMigrationAllowanceParams, type UseMigrationApproveVars, type UsePoolBalancesParams, type UsePoolBalancesResponse, type UsePoolDataParams, type UsePoolsParams, type UsePositionInfoParams, type UsePositionInfoResponse, type UseQuoteParams, type UseRadfiAuthVars, type UseRadfiSessionReturn, type UseRadfiWithdrawVars, type UseRenewUtxosVars, type UseRepayVars, type UseReservesDataParams, type UseReservesHumanizedParams, type UseReservesListParams, type UseReservesUsdFormatParams, type UseRevertMigrateSodaToIcxVars, type UseSetSwapPreferenceVars, type UseSetSwapPreferenceVarsHub, type UseStatusParams, type UseStellarTrustlineCheckParams, type UseSupplyLiquidityVars, type UseSupplyVars, type UseSwapAllowanceParams, type UseSwapApproveVars, type UseSwapVars, type UseTradingWalletBalanceParams, type UseUserFormattedSummaryParams, type UseUserReservesDataParams, type UseWithdrawHubAssetVars, type UseWithdrawVars, type UseXBalancesParams, type WithdrawParamsCore, type XBalancesInputs, clearRadfiSession, createDecreaseLiquidityParamsProps, createDepositParamsProps, createSodaxQueryClient, createSupplyLiquidityParamsProps, createWithdrawParamsProps, getXBalancesQueryOptions, loadRadfiSession, saveRadfiSession, toResult, unwrapResult, useAToken, useATokensBalances, useApproveToken, useBackendAllMoneyMarketAssets, useBackendAllMoneyMarketBorrowers, useBackendIntentByHash, useBackendIntentByTxHash, useBackendMoneyMarketAsset, useBackendMoneyMarketAssetBorrowers, useBackendMoneyMarketAssetSuppliers, useBackendMoneyMarketPosition, useBackendOrderbook, useBackendSubmitSwapTx, useBackendSubmitSwapTxStatus, useBackendUserIntents, useBitcoinBalance, useBorrow, useBridge, useBridgeAllowance, useBridgeApprove, useCancelLimitOrder, useCancelSwap, useCancelUnstake, useClaim, useClaimRewards, useConvertedAssets, useCreateDecreaseLiquidityParams, useCreateDepositParams, useCreateLimitOrder, useCreateSupplyLiquidityParams, useCreateWithdrawParams, useDecreaseLiquidity, useDeriveUserWalletAddress, useDexAllowance, useDexApprove, useDexDeposit, useDexWithdraw, useEstimateGas, useExpiredUtxos, useFeeClaimSwap, useFetchAssetsBalances, useFundTradingWallet, useGetAutoSwapPreferences, useGetBridgeableAmount, useGetBridgeableTokens, useGetUserHubWalletAddress, useHubAssetBalances, useHubProvider, useInstantUnstake, useInstantUnstakeAllowance, useInstantUnstakeApprove, useInstantUnstakeRatio, useIsTokenApproved, useLiquidityAmounts, useMMAllowance, useMMApprove, useMigrateBaln, useMigrateIcxToSoda, useMigratebnUSD, useMigrationAllowance, useMigrationApprove, usePoolBalances, usePoolData, usePools, usePositionInfo, useQuote, useRadfiAuth, useRadfiSession, useRadfiWithdraw, useRenewUtxos, useRepay, useRequestTrustline, useReservesData, useReservesHumanized, useReservesList, useReservesUsdFormat, useRevertMigrateSodaToIcx, useSafeMutation, useSetSwapPreference, useSodaxContext, useStake, useStakeAllowance, useStakeApprove, useStakeRatio, useStakingConfig, useStakingInfo, useStatus, useStellarTrustlineCheck, useSupply, useSupplyLiquidity, useSwap, useSwapAllowance, useSwapApprove, useTradingWallet, useTradingWalletBalance, useUnstake, useUnstakeAllowance, useUnstakeApprove, useUnstakingInfo, useUnstakingInfoWithPenalty, useUserFormattedSummary, useUserReservesData, useWithdraw, useWithdrawHubAsset, useXBalances };