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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +300 -422
  2. package/ai-exported/AGENTS.md +134 -0
  3. package/ai-exported/integration/README.md +49 -0
  4. package/ai-exported/integration/ai-rules.md +79 -0
  5. package/ai-exported/integration/architecture.md +274 -0
  6. package/ai-exported/integration/features/README.md +29 -0
  7. package/ai-exported/integration/features/auxiliary-services.md +169 -0
  8. package/ai-exported/integration/features/bitcoin.md +87 -0
  9. package/ai-exported/integration/features/bridge.md +91 -0
  10. package/ai-exported/integration/features/dex.md +152 -0
  11. package/ai-exported/integration/features/migration.md +118 -0
  12. package/ai-exported/integration/features/money-market.md +116 -0
  13. package/ai-exported/integration/features/staking.md +123 -0
  14. package/ai-exported/integration/features/swap.md +101 -0
  15. package/ai-exported/integration/quickstart.md +187 -0
  16. package/ai-exported/integration/recipes/README.md +136 -0
  17. package/ai-exported/integration/recipes/backend-queries.md +157 -0
  18. package/ai-exported/integration/recipes/bitcoin.md +193 -0
  19. package/ai-exported/integration/recipes/bridge.md +174 -0
  20. package/ai-exported/integration/recipes/dex.md +204 -0
  21. package/ai-exported/integration/recipes/invalidations.md +115 -0
  22. package/ai-exported/integration/recipes/migration.md +212 -0
  23. package/ai-exported/integration/recipes/money-market.md +206 -0
  24. package/ai-exported/integration/recipes/mutation-error-handling.md +118 -0
  25. package/ai-exported/integration/recipes/observability.md +93 -0
  26. package/ai-exported/integration/recipes/setup.md +144 -0
  27. package/ai-exported/integration/recipes/staking.md +202 -0
  28. package/ai-exported/integration/recipes/swap.md +272 -0
  29. package/ai-exported/integration/recipes/wallet-connectivity.md +101 -0
  30. package/ai-exported/integration/reference/README.md +12 -0
  31. package/ai-exported/integration/reference/glossary.md +188 -0
  32. package/ai-exported/integration/reference/hooks-index.md +194 -0
  33. package/ai-exported/integration/reference/public-api.md +110 -0
  34. package/ai-exported/integration/reference/querykey-conventions.md +179 -0
  35. package/ai-exported/migration/README.md +60 -0
  36. package/ai-exported/migration/ai-rules.md +81 -0
  37. package/ai-exported/migration/breaking-changes/hook-signatures.md +233 -0
  38. package/ai-exported/migration/breaking-changes/querykey-conventions.md +108 -0
  39. package/ai-exported/migration/breaking-changes/result-handling.md +211 -0
  40. package/ai-exported/migration/breaking-changes/sdk-leakage.md +165 -0
  41. package/ai-exported/migration/checklist.md +89 -0
  42. package/ai-exported/migration/features/README.md +34 -0
  43. package/ai-exported/migration/features/auxiliary-services.md +114 -0
  44. package/ai-exported/migration/features/bitcoin.md +88 -0
  45. package/ai-exported/migration/features/bridge.md +123 -0
  46. package/ai-exported/migration/features/dex.md +101 -0
  47. package/ai-exported/migration/features/migration.md +120 -0
  48. package/ai-exported/migration/features/money-market.md +97 -0
  49. package/ai-exported/migration/features/staking.md +109 -0
  50. package/ai-exported/migration/features/swap.md +118 -0
  51. package/ai-exported/migration/recipes.md +188 -0
  52. package/ai-exported/migration/reference/README.md +15 -0
  53. package/ai-exported/migration/reference/deleted-hooks.md +110 -0
  54. package/ai-exported/migration/reference/error-shape-crosswalk.md +144 -0
  55. package/ai-exported/migration/reference/renamed-hooks.md +66 -0
  56. package/dist/index.cjs +2642 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +1550 -0
  59. package/dist/index.d.ts +1020 -2051
  60. package/dist/index.mjs +1581 -1531
  61. package/dist/index.mjs.map +1 -1
  62. package/package.json +20 -10
  63. package/src/contexts/index.ts +0 -3
  64. package/src/hooks/_mutationContract.test.ts +99 -0
  65. package/src/hooks/backend/README.md +2 -2
  66. package/src/hooks/backend/index.ts +13 -13
  67. package/src/hooks/backend/unwrapResult.ts +1 -0
  68. package/src/hooks/backend/useBackendAllMoneyMarketAssets.ts +13 -45
  69. package/src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts +29 -59
  70. package/src/hooks/backend/useBackendIntentByHash.ts +21 -47
  71. package/src/hooks/backend/useBackendIntentByTxHash.ts +23 -50
  72. package/src/hooks/backend/useBackendMoneyMarketAsset.ts +21 -54
  73. package/src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts +30 -57
  74. package/src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts +31 -58
  75. package/src/hooks/backend/useBackendMoneyMarketPosition.ts +22 -38
  76. package/src/hooks/backend/useBackendOrderbook.ts +27 -49
  77. package/src/hooks/backend/useBackendSubmitSwapTx.ts +30 -36
  78. package/src/hooks/backend/useBackendSubmitSwapTxStatus.ts +38 -58
  79. package/src/hooks/backend/useBackendUserIntents.ts +25 -63
  80. package/src/hooks/bitcoin/index.ts +9 -8
  81. package/src/hooks/bitcoin/useBitcoinBalance.ts +20 -5
  82. package/src/hooks/bitcoin/useExpiredUtxos.ts +26 -16
  83. package/src/hooks/bitcoin/useFundTradingWallet.ts +33 -30
  84. package/src/hooks/bitcoin/useRadfiAuth.ts +43 -40
  85. package/src/hooks/bitcoin/useRadfiSession.ts +53 -59
  86. package/src/hooks/bitcoin/useRadfiWithdraw.ts +35 -53
  87. package/src/hooks/bitcoin/useRenewUtxos.ts +30 -50
  88. package/src/hooks/bitcoin/useTradingWallet.ts +1 -1
  89. package/src/hooks/bitcoin/useTradingWalletBalance.ts +25 -14
  90. package/src/hooks/bridge/index.ts +5 -5
  91. package/src/hooks/bridge/useBridge.ts +29 -55
  92. package/src/hooks/bridge/useBridgeAllowance.ts +38 -38
  93. package/src/hooks/bridge/useBridgeApprove.ts +32 -57
  94. package/src/hooks/bridge/useGetBridgeableAmount.ts +23 -37
  95. package/src/hooks/bridge/useGetBridgeableTokens.ts +27 -50
  96. package/src/hooks/dex/index.ts +16 -16
  97. package/src/hooks/dex/useClaimRewards.ts +35 -54
  98. package/src/hooks/dex/useCreateDecreaseLiquidityParams.ts +7 -20
  99. package/src/hooks/dex/useCreateDepositParams.ts +7 -21
  100. package/src/hooks/dex/useCreateSupplyLiquidityParams.ts +13 -28
  101. package/src/hooks/dex/useCreateWithdrawParams.ts +7 -20
  102. package/src/hooks/dex/useDecreaseLiquidity.ts +40 -66
  103. package/src/hooks/dex/useDexAllowance.ts +29 -75
  104. package/src/hooks/dex/useDexApprove.ts +32 -43
  105. package/src/hooks/dex/useDexDeposit.ts +42 -49
  106. package/src/hooks/dex/useDexWithdraw.ts +32 -43
  107. package/src/hooks/dex/useLiquidityAmounts.ts +13 -82
  108. package/src/hooks/dex/usePoolBalances.ts +50 -72
  109. package/src/hooks/dex/usePoolData.ts +17 -43
  110. package/src/hooks/dex/usePools.ts +11 -38
  111. package/src/hooks/dex/usePositionInfo.ts +27 -62
  112. package/src/hooks/dex/useSupplyLiquidity.ts +80 -75
  113. package/src/hooks/index.ts +12 -10
  114. package/src/hooks/migrate/index.ts +13 -4
  115. package/src/hooks/migrate/useMigrateBaln.ts +42 -0
  116. package/src/hooks/migrate/useMigrateIcxToSoda.ts +44 -0
  117. package/src/hooks/migrate/useMigratebnUSD.ts +47 -0
  118. package/src/hooks/migrate/useMigrationAllowance.ts +76 -0
  119. package/src/hooks/migrate/useMigrationApprove.ts +66 -0
  120. package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +39 -0
  121. package/src/hooks/mm/index.ts +14 -12
  122. package/src/hooks/mm/useAToken.ts +25 -41
  123. package/src/hooks/mm/useATokensBalances.ts +29 -60
  124. package/src/hooks/mm/useBorrow.ts +38 -56
  125. package/src/hooks/mm/useMMAllowance.ts +37 -73
  126. package/src/hooks/mm/useMMApprove.ts +36 -43
  127. package/src/hooks/mm/useRepay.ts +33 -53
  128. package/src/hooks/mm/useReservesData.ts +12 -38
  129. package/src/hooks/mm/useReservesHumanized.ts +12 -31
  130. package/src/hooks/mm/useReservesList.ts +11 -31
  131. package/src/hooks/mm/useReservesUsdFormat.ts +15 -35
  132. package/src/hooks/mm/useSupply.ts +45 -51
  133. package/src/hooks/mm/useUserFormattedSummary.ts +32 -84
  134. package/src/hooks/mm/useUserReservesData.ts +27 -77
  135. package/src/hooks/mm/useWithdraw.ts +38 -54
  136. package/src/hooks/partner/index.ts +6 -0
  137. package/src/hooks/partner/useApproveToken.ts +42 -0
  138. package/src/hooks/partner/useFeeClaimSwap.ts +38 -0
  139. package/src/hooks/partner/useFetchAssetsBalances.ts +37 -0
  140. package/src/hooks/partner/useGetAutoSwapPreferences.ts +37 -0
  141. package/src/hooks/partner/useIsTokenApproved.ts +39 -0
  142. package/src/hooks/partner/useSetSwapPreference.ts +50 -0
  143. package/src/hooks/provider/index.ts +1 -2
  144. package/src/hooks/provider/useHubProvider.ts +1 -1
  145. package/src/hooks/recovery/index.ts +2 -0
  146. package/src/hooks/recovery/useHubAssetBalances.ts +43 -0
  147. package/src/hooks/recovery/useWithdrawHubAsset.ts +48 -0
  148. package/src/hooks/shared/index.ts +10 -6
  149. package/src/hooks/shared/types.ts +77 -0
  150. package/src/hooks/shared/unwrapResult.ts +19 -0
  151. package/src/hooks/shared/useDeriveUserWalletAddress.ts +22 -40
  152. package/src/hooks/shared/useEstimateGas.ts +18 -15
  153. package/src/hooks/shared/useGetUserHubWalletAddress.ts +25 -26
  154. package/src/hooks/shared/useRequestTrustline.ts +28 -61
  155. package/src/hooks/shared/useSafeMutation.test.ts +43 -0
  156. package/src/hooks/shared/useSafeMutation.ts +68 -0
  157. package/src/hooks/shared/useSodaxContext.ts +1 -1
  158. package/src/hooks/shared/useStellarTrustlineCheck.ts +30 -64
  159. package/src/hooks/shared/useXBalances.test.ts +113 -0
  160. package/src/hooks/shared/useXBalances.ts +61 -0
  161. package/src/hooks/staking/index.ts +18 -18
  162. package/src/hooks/staking/useCancelUnstake.ts +30 -41
  163. package/src/hooks/staking/useClaim.ts +27 -36
  164. package/src/hooks/staking/useConvertedAssets.ts +24 -34
  165. package/src/hooks/staking/useInstantUnstake.ts +33 -40
  166. package/src/hooks/staking/useInstantUnstakeAllowance.ts +37 -45
  167. package/src/hooks/staking/useInstantUnstakeApprove.ts +42 -42
  168. package/src/hooks/staking/useInstantUnstakeRatio.ts +24 -41
  169. package/src/hooks/staking/useStake.ts +32 -37
  170. package/src/hooks/staking/useStakeAllowance.ts +30 -43
  171. package/src/hooks/staking/useStakeApprove.ts +40 -40
  172. package/src/hooks/staking/useStakeRatio.ts +24 -40
  173. package/src/hooks/staking/useStakingConfig.ts +14 -27
  174. package/src/hooks/staking/useStakingInfo.ts +30 -38
  175. package/src/hooks/staking/useUnstake.ts +29 -43
  176. package/src/hooks/staking/useUnstakeAllowance.ts +37 -44
  177. package/src/hooks/staking/useUnstakeApprove.ts +40 -43
  178. package/src/hooks/staking/useUnstakingInfo.ts +29 -41
  179. package/src/hooks/staking/useUnstakingInfoWithPenalty.ts +31 -47
  180. package/src/hooks/swap/index.ts +8 -8
  181. package/src/hooks/swap/useCancelLimitOrder.ts +24 -41
  182. package/src/hooks/swap/useCancelSwap.ts +24 -33
  183. package/src/hooks/swap/useCreateLimitOrder.ts +29 -62
  184. package/src/hooks/swap/useQuote.ts +17 -43
  185. package/src/hooks/swap/useStatus.ts +22 -29
  186. package/src/hooks/swap/useSwap.ts +31 -49
  187. package/src/hooks/swap/useSwapAllowance.ts +38 -35
  188. package/src/hooks/swap/useSwapApprove.ts +48 -57
  189. package/src/index.ts +5 -3
  190. package/src/providers/SodaxProvider.tsx +17 -11
  191. package/src/providers/createSodaxQueryClient.ts +96 -0
  192. package/src/providers/index.ts +2 -1
  193. package/src/utils/dex-utils.ts +27 -5
  194. package/src/utils/index.ts +1 -1
  195. package/dist/index.d.mts +0 -2581
  196. package/dist/index.js +0 -2574
  197. package/dist/index.js.map +0 -1
  198. package/src/hooks/migrate/types.ts +0 -15
  199. package/src/hooks/migrate/useMigrate.tsx +0 -110
  200. package/src/hooks/migrate/useMigrationAllowance.tsx +0 -79
  201. package/src/hooks/migrate/useMigrationApprove.tsx +0 -129
  202. package/src/hooks/provider/useSpokeProvider.ts +0 -172
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contexts/index.ts","../src/hooks/shared/useSodaxContext.ts","../src/hooks/shared/useEstimateGas.ts","../src/hooks/shared/useDeriveUserWalletAddress.ts","../src/hooks/shared/useStellarTrustlineCheck.ts","../src/hooks/shared/useRequestTrustline.ts","../src/hooks/shared/useGetUserHubWalletAddress.ts","../src/hooks/provider/useHubProvider.ts","../src/hooks/provider/useSpokeProvider.ts","../src/hooks/bitcoin/useRadfiAuth.ts","../src/hooks/bitcoin/useRadfiSession.ts","../src/hooks/bitcoin/useFundTradingWallet.ts","../src/hooks/bitcoin/useBitcoinBalance.ts","../src/hooks/bitcoin/useTradingWalletBalance.ts","../src/hooks/bitcoin/useExpiredUtxos.ts","../src/hooks/bitcoin/useRenewUtxos.ts","../src/hooks/bitcoin/useRadfiWithdraw.ts","../src/hooks/mm/useBorrow.ts","../src/hooks/mm/useRepay.ts","../src/hooks/mm/useSupply.ts","../src/hooks/mm/useWithdraw.ts","../src/hooks/mm/useUserReservesData.ts","../src/hooks/mm/useReservesData.ts","../src/hooks/mm/useMMAllowance.ts","../src/hooks/mm/useMMApprove.ts","../src/hooks/mm/useAToken.ts","../src/hooks/mm/useATokensBalances.ts","../src/hooks/mm/useReservesUsdFormat.ts","../src/hooks/mm/useUserFormattedSummary.ts","../src/hooks/swap/useQuote.ts","../src/hooks/swap/useSwap.ts","../src/hooks/swap/useStatus.ts","../src/hooks/swap/useSwapAllowance.ts","../src/hooks/swap/useSwapApprove.ts","../src/hooks/swap/useCancelSwap.ts","../src/hooks/swap/useCreateLimitOrder.ts","../src/hooks/swap/useCancelLimitOrder.ts","../src/hooks/backend/useBackendIntentByTxHash.ts","../src/hooks/backend/useBackendIntentByHash.ts","../src/hooks/backend/useBackendUserIntents.ts","../src/hooks/backend/useBackendSubmitSwapTx.ts","../src/hooks/backend/useBackendSubmitSwapTxStatus.ts","../src/hooks/backend/useBackendOrderbook.ts","../src/hooks/backend/useBackendMoneyMarketPosition.ts","../src/hooks/backend/useBackendAllMoneyMarketAssets.ts","../src/hooks/backend/useBackendMoneyMarketAsset.ts","../src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts","../src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts","../src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts","../src/hooks/bridge/useBridgeAllowance.ts","../src/hooks/bridge/useBridgeApprove.ts","../src/hooks/bridge/useBridge.ts","../src/hooks/bridge/useGetBridgeableAmount.ts","../src/hooks/bridge/useGetBridgeableTokens.ts","../src/hooks/staking/useStake.ts","../src/hooks/staking/useStakeApprove.ts","../src/hooks/staking/useStakeAllowance.ts","../src/hooks/staking/useUnstake.ts","../src/hooks/staking/useClaim.ts","../src/hooks/staking/useCancelUnstake.ts","../src/hooks/staking/useStakingInfo.ts","../src/hooks/staking/useUnstakingInfoWithPenalty.ts","../src/hooks/staking/useStakingConfig.ts","../src/hooks/staking/useStakeRatio.ts","../src/hooks/staking/useInstantUnstakeRatio.ts","../src/hooks/staking/useConvertedAssets.ts","../src/hooks/staking/useInstantUnstake.ts","../src/hooks/staking/useUnstakeAllowance.ts","../src/hooks/staking/useUnstakeApprove.ts","../src/hooks/staking/useUnstakingInfo.ts","../src/hooks/staking/useInstantUnstakeApprove.ts","../src/hooks/staking/useInstantUnstakeAllowance.ts","../src/hooks/migrate/types.ts","../src/hooks/migrate/useMigrate.tsx","../src/hooks/migrate/useMigrationAllowance.tsx","../src/hooks/migrate/useMigrationApprove.tsx","../src/hooks/dex/usePools.ts","../src/hooks/dex/usePoolData.ts","../src/hooks/dex/usePoolBalances.ts","../src/hooks/dex/usePositionInfo.ts","../src/hooks/dex/useDexDeposit.ts","../src/hooks/dex/useDexWithdraw.ts","../src/hooks/dex/useDexAllowance.ts","../src/hooks/dex/useDexApprove.ts","../src/hooks/dex/useLiquidityAmounts.ts","../src/hooks/dex/useSupplyLiquidity.ts","../src/hooks/dex/useDecreaseLiquidity.ts","../src/utils/dex-utils.ts","../src/hooks/dex/useCreateDepositParams.ts","../src/hooks/dex/useCreateSupplyLiquidityParams.ts","../src/hooks/dex/useCreateDecreaseLiquidityParams.ts","../src/hooks/dex/useCreateWithdrawParams.ts","../src/hooks/dex/useClaimRewards.ts","../src/providers/SodaxProvider.tsx"],"names":["useQuery","token","StellarSpokeProvider","error","StellarSpokeService","useMutation","useState","useCallback","useQueryClient","normalizePsbtToBase64","isAddress","HubService","isLegacyParams","resolveParams","useMemo","params","spokeChainConfig","result","ICON_MAINNET_CHAIN_ID","parseUnits","useRef","useEffect","ClService"],"mappings":";;;;;;;AAUO,IAAM,YAAA,GAAe,cAAuC,IAAI,CAAA;ACDhE,IAAM,kBAAkB,MAAwB;AACrD,EAAA,MAAM,OAAA,GAAU,WAAW,YAAY,CAAA;AACvC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,MAAM,qDAAqD,CAAA;AAAA,EACvE;AACA,EAAA,OAAO,OAAA;AACT;ACZO,SAAS,eACd,aAAA,EAC8E;AAC9E,EAAA,OAAO,WAAA,CAAuE;AAAA,IAC5E,UAAA,EAAY,OAAO,KAAA,KAAiC;AAClD,MAAA,IAAI,CAAC,aAAA,EAAe;AAClB,QAAA,MAAM,IAAI,MAAM,4BAA4B,CAAA;AAAA,MAC9C;AAEA,MAAA,MAAM,QAAA,GAAW,MAAM,YAAA,CAAa,WAAA,CAAY,OAAO,aAAa,CAAA;AAEpE,MAAA,OAAO,QAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;ACcO,SAAS,0BAAA,CACd,cACA,YAAA,EACgC;AAChC,EAAA,MAAM,EAAE,KAAA,EAAM,GAAI,eAAA,EAAgB;AAElC,EAAA,OAAO,QAAA,CAAS;AAAA,IACd,QAAA,EAAU,CAAC,yBAAA,EAA2B,YAAA,EAAc,YAAY,CAAA;AAAA,IAChE,SAAS,YAA8B;AACrC,MAAA,IAAI,CAAC,YAAA,IAAgB,CAAC,YAAA,EAAc;AAClC,QAAA,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,MAC3D;AAGA,MAAA,YAAA,GAAe,OAAO,YAAA,KAAiB,QAAA,GAAW,YAA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MAAA,WAAA,CAAY,iBAAA,CAAkB,EAAE,QAAA,EAAU,CAAC,KAAA,EAAO,cAAA,EAAgB,MAAA,CAAO,OAAA,EAAS,MAAA,CAAO,OAAO,CAAA,EAAG,CAAA;AACnG,MAAA,WAAA,CAAY,iBAAA,CAAkB,EAAE,QAAA,EAAU,CAAC,OAAO,UAAA,EAAY,MAAA,CAAO,OAAO,CAAA,EAAG,CAAA;AAAA,IACjF;AAAA,GACD,CAAA;AACH;ACrDO,IAAM,aAAA,GAAgB,CAAC,EAAE,QAAA,EAAU,UAAU,KAAA,EAAO,MAAA,EAAQ,WAAU,KAAwC;AACnH,EAAA,MAAM,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAM,CAAA;AAE9B,EAAA,uBAAO,KAAA,CAAA,aAAA,CAAC,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,EAAE,KAAA,EAAO,OAAA,EAAS,SAAA,EAAU,EAAA,EAAI,QAAS,CAAA;AAChF","file":"index.mjs","sourcesContent":["import { createContext } from 'react';\nimport type { Sodax } from '@sodax/sdk';\nimport type { RpcConfig } from '@sodax/types';\n\nexport interface SodaxContextType {\n sodax: Sodax;\n testnet: boolean;\n rpcConfig: RpcConfig;\n}\n\nexport const SodaxContext = createContext<SodaxContextType | null>(null);\n","import { SodaxContext, type SodaxContextType } from '@/contexts';\nimport { useContext } from 'react';\n\n/**\n * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration\n * @throws {Error} If used outside of a SodaxProvider\n * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration\n */\n\nexport const useSodaxContext = (): SodaxContextType => {\n const context = useContext(SodaxContext);\n if (!context) {\n throw new Error('useSodaxContext must be used within a SodaxProvider');\n }\n return context;\n};\n","import { type GetEstimateGasReturnType, type SpokeProvider, SpokeService, type TxReturnType } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\nexport function useEstimateGas<T extends SpokeProvider = SpokeProvider>(\n spokeProvider: T | undefined,\n): UseMutationResult<GetEstimateGasReturnType<T>, Error, TxReturnType<T, true>> {\n return useMutation<GetEstimateGasReturnType<T>, Error, TxReturnType<T, true>>({\n mutationFn: async (rawTx: TxReturnType<T, true>) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await SpokeService.estimateGas(rawTx, spokeProvider);\n\n return response;\n },\n });\n}\n","import { deriveUserWalletAddress, type SpokeProvider, type SpokeChainId } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from './useSodaxContext';\nimport type { Address } from 'viem';\n\n/**\n * Hook for deriving user wallet address for hub abstraction.\n *\n * This hook derives the user's abstracted wallet address for the hub chain based on the spoke chain ID and address.\n * If the spoke chain is the same as the hub chain, it returns the encoded spoke address.\n * Otherwise, it derives and returns the abstracted wallet address for cross-chain operations.\n *\n * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.\n * This is a deterministic operation, so the result is cached and not refetched automatically.\n *\n * @param spokeChainId - Optional spoke chain ID. If not provided, the query will be disabled.\n * @param spokeAddress - Optional user wallet address on the spoke chain. If not provided, the query will be disabled.\n * @returns A React Query result object containing:\n * - data: The derived user wallet address (Address) when available\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during derivation (Error)\n *\n * @example\n * ```typescript\n * const { data: derivedAddress, isLoading, error } = useDeriveUserWalletAddress(spokeChainId, userAddress);\n *\n * if (isLoading) return <div>Deriving address...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (derivedAddress) return <div>Derived Address: {derivedAddress}</div>;\n * ```\n */\nexport function useDeriveUserWalletAddress(\n spokeChainId?: SpokeChainId | SpokeProvider | undefined,\n spokeAddress?: string | undefined,\n): UseQueryResult<Address, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['deriveUserWalletAddress', spokeChainId, spokeAddress],\n queryFn: async (): Promise<Address> => {\n if (!spokeChainId || !spokeAddress) {\n throw new Error('Spoke chain id and address are required');\n }\n\n // Determine if spokeChainId is a SpokeProvider object or SpokeChainId value\n spokeChainId = typeof spokeChainId === 'object' ? spokeChainId.chainConfig.chain.id : spokeChainId;\n\n return await deriveUserWalletAddress(sodax.hubProvider, spokeChainId, spokeAddress);\n },\n enabled: !!spokeChainId && !!spokeAddress,\n refetchInterval: false, // This is a deterministic operation, no need to refetch\n });\n}\n","import { STELLAR_MAINNET_CHAIN_ID, StellarSpokeProvider, StellarSpokeService } from '@sodax/sdk';\nimport type { SpokeChainId, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * React hook to check if a Stellar account has a sufficient trustline for a given token and amount.\n *\n * This hook queries the Stellar network (via the provided SpokeProvider) to determine\n * whether the account has established a trustline for the specified token and if the trustline\n * is sufficient for the intended amount. It is useful for gating UI actions that require\n * a trustline to be present and funded.\n *\n * @template T - The type of SpokeProvider, defaults to SpokeProvider.\n * @param {string | undefined} token - The Stellar asset code or token address to check the trustline for.\n * @param {bigint | undefined} amount - The minimum amount required for the trustline.\n * @param {T | undefined} spokeProvider - The provider instance for interacting with the Stellar network.\n * @param {SpokeChainId | undefined} chainId - The chain ID to determine if the check should be performed (only on Stellar mainnet).\n * @returns {UseQueryResult<boolean, Error>} A React Query result object containing:\n * - `data`: `true` if the trustline exists and is sufficient, `false` otherwise.\n * - `error`: Any error encountered during the check.\n * - `isLoading`: Whether the query is in progress.\n * - Other React Query state.\n *\n * @example\n * ```tsx\n * import { useStellarTrustlineCheck } from '@sodax/dapp-kit';\n *\n * const { data: hasTrustline, isLoading, error } = useStellarTrustlineCheck(\n * 'USDC-G...TOKEN',\n * 10000000n,\n * stellarProvider,\n * 'stellar'\n * );\n *\n * if (isLoading) return <span>Checking trustline...</span>;\n * if (error) return <span>Error: {error.message}</span>;\n * if (!hasTrustline) return <span>Trustline not established or insufficient.</span>;\n * return <span>Trustline is sufficient!</span>;\n * ```\n */\n\nexport function useStellarTrustlineCheck<T extends SpokeProvider = SpokeProvider>(\n token: string | undefined,\n amount: bigint | undefined,\n spokeProvider: T | undefined,\n chainId: SpokeChainId | undefined,\n): UseQueryResult<boolean, Error> {\n return useQuery({\n queryKey: ['stellar-trustline-check', token],\n queryFn: async () => {\n if (chainId !== STELLAR_MAINNET_CHAIN_ID) {\n return true;\n }\n if (!spokeProvider || !token || !amount || !(spokeProvider instanceof StellarSpokeProvider)) {\n console.error(\n 'Spoke provider, token or amount not found. Details: spokeProvider:',\n spokeProvider,\n 'token:',\n token,\n 'amount:',\n amount,\n );\n return false;\n }\n const response = await StellarSpokeService.hasSufficientTrustline(token, amount, spokeProvider);\n\n return response;\n },\n enabled: !!spokeProvider && !!token && !!amount,\n });\n}\n","import { type SpokeProvider, StellarSpokeProvider, StellarSpokeService, type TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useState } from 'react';\n\n/**\n * React hook to request a Stellar trustline for a given token and amount.\n *\n * This hook provides a callback function for requesting a trustline on the Stellar network\n * using the provided SpokeProvider. It is intended for use with StellarSpokeProvider\n * and will throw if used with a non-Stellar provider. Upon success, it invalidates\n * the trustline check query to ensure UI reflects the updated trustline state.\n *\n * @template T - The type of SpokeProvider, defaults to SpokeProvider.\n * @param {string | undefined} token - The Stellar asset code or token address for which to request a trustline.\n * @returns {Object} An object containing:\n * - `requestTrustline`: Function to trigger the trustline request.\n * - `isLoading`: Whether the request is in progress.\n * - `isRequested`: Whether a trustline has been successfully requested.\n * - `error`: Any error encountered during the request.\n * - `data`: The transaction result if successful.\n *\n * @example\n * ```tsx\n * import { useRequestTrustline } from '@sodax/dapp-kit';\n *\n * const { requestTrustline, isLoading, isRequested, error, data } = useRequestTrustline('USDC-G...TOKEN');\n *\n * // To request a trustline:\n * await requestTrustline({\n * token: 'USDC-G...TOKEN',\n * amount: 10000000n,\n * spokeProvider: stellarProvider,\n * });\n *\n * if (isLoading) return <span>Requesting trustline...</span>;\n * if (error) return <span>Error: {error.message}</span>;\n * if (isRequested) return <span>Trustline requested! Tx: {data?.txHash}</span>;\n * ```\n */\n\nexport function useRequestTrustline<T extends SpokeProvider = SpokeProvider>(\n token: string | undefined,\n): {\n requestTrustline: (params: {\n token: string;\n amount: bigint;\n spokeProvider: T;\n }) => Promise<TxReturnType<StellarSpokeProvider, false>>;\n isLoading: boolean;\n isRequested: boolean;\n error: Error | null;\n data: TxReturnType<StellarSpokeProvider, false> | null;\n} {\n const queryClient = useQueryClient();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isRequested, setIsRequested] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n const [data, setData] = useState<TxReturnType<StellarSpokeProvider, false> | null>(null);\n\n const requestTrustline = useCallback(\n async ({\n token,\n amount,\n spokeProvider,\n }: {\n token: string;\n amount: bigint;\n spokeProvider: T;\n }): Promise<TxReturnType<StellarSpokeProvider, false>> => {\n if (!spokeProvider || !token || !amount || !(spokeProvider instanceof StellarSpokeProvider)) {\n const error = new Error('Spoke provider, token or amount not found');\n setError(error);\n throw error;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result = await StellarSpokeService.requestTrustline(token, amount, spokeProvider);\n setData(result);\n setIsRequested(true);\n queryClient.invalidateQueries({ queryKey: ['stellar-trustline-check', token] });\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Unknown error occurred');\n setError(error);\n throw error;\n } finally {\n setIsLoading(false);\n }\n },\n [queryClient],\n );\n\n return {\n requestTrustline,\n isLoading,\n isRequested,\n error,\n data,\n };\n}\n","import { type SpokeProvider, type SpokeChainId, HubService } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from './useSodaxContext';\nimport type { Address } from 'viem';\n\n/**\n * Hook for deriving user wallet address for hub abstraction.\n *\n * This hook derives the user's abstracted wallet address for the hub chain based on the spoke chain ID and address.\n * If the spoke chain is the same as the hub chain, it returns the encoded spoke address.\n * Otherwise, it derives and returns the abstracted wallet address for cross-chain operations.\n * NOTE: This hook is different from useDeriveUserWalletAddress because it uses wallet router address instead of CREATE3 address for Sonic (hub).\n *\n * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.\n * This is a deterministic operation, so the result is cached and not refetched automatically.\n *\n * @param spokeChainId - Optional spoke chain ID. If not provided, the query will be disabled.\n * @param spokeAddress - Optional user wallet address on the spoke chain. If not provided, the query will be disabled.\n * @returns A React Query result object containing:\n * - data: The derived user wallet address (Address) when available\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during derivation (Error)\n *\n * @example\n * ```typescript\n * const { data: derivedAddress, isLoading, error } = useDeriveUserWalletAddress(spokeChainId, userAddress);\n *\n * if (isLoading) return <div>Deriving address...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (derivedAddress) return <div>Derived Address: {derivedAddress}</div>;\n * ```\n */\nexport function useGetUserHubWalletAddress(\n spokeChainId?: SpokeChainId | SpokeProvider | undefined,\n spokeAddress?: string | undefined,\n): UseQueryResult<Address, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['getUserHubWalletAddress', spokeChainId, spokeAddress],\n queryFn: async (): Promise<Address> => {\n if (!spokeChainId || !spokeAddress) {\n throw new Error('Spoke chain id and address are required');\n }\n\n // Determine if spokeChainId is a SpokeProvider object or SpokeChainId value\n spokeChainId = typeof spokeChainId === 'object' ? spokeChainId.chainConfig.chain.id : spokeChainId;\n\n return await HubService.getUserHubWalletAddress(spokeAddress, spokeChainId, sodax.hubProvider);\n },\n enabled: !!spokeChainId && !!spokeAddress,\n refetchInterval: false, // This is a deterministic operation, no need to refetch\n });\n}\n","import type { EvmHubProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport function useHubProvider(): EvmHubProvider {\n const { sodax } = useSodaxContext();\n\n return sodax.hubProvider;\n}\n","import { useSodaxContext } from '@/index';\nimport {\n BitcoinSpokeProvider,\n EvmSpokeProvider,\n spokeChainConfig,\n type SuiSpokeChainConfig,\n SuiSpokeProvider,\n type EvmSpokeChainConfig,\n IconSpokeProvider,\n type IconSpokeChainConfig,\n InjectiveSpokeProvider,\n type InjectiveSpokeChainConfig,\n StellarSpokeProvider,\n type StellarSpokeChainConfig,\n type SpokeProvider,\n type IWalletProvider,\n SolanaSpokeProvider,\n type SolanaChainConfig,\n SONIC_MAINNET_CHAIN_ID,\n SonicSpokeProvider,\n type SonicSpokeChainConfig,\n NearSpokeProvider,\n type NearSpokeChainConfig,\n StacksSpokeProvider,\n type StacksSpokeChainConfig,\n} from '@sodax/sdk';\nimport type {\n BitcoinSpokeChainConfig,\n BitcoinRpcConfig,\n IBitcoinWalletProvider,\n IEvmWalletProvider,\n IIconWalletProvider,\n ISuiWalletProvider,\n SpokeChainId,\n IInjectiveWalletProvider,\n IStellarWalletProvider,\n ISolanaWalletProvider,\n INearWalletProvider,\n IStacksWalletProvider,\n} from '@sodax/types';\nimport { useMemo } from 'react';\n\n/**\n * Hook to get the appropriate spoke provider based on the chain type.\n * Supports EVM, SUI, ICON and INJECTIVE chains.\n *\n * @param {SpokeChainId | undefined} spokeChainId - The spoke chain ID to get the provider for\n * @param {IWalletProvider | undefined} walletProvider - The wallet provider to use\n * @returns {SpokeProvider | undefined} The appropriate spoke provider instance for the given chain ID, or undefined if invalid/unsupported\n *\n * @example\n * ```tsx\n * // Using a specific SpokeChainId and wallet provider\n * const spokeProvider = useSpokeProvider(spokeChainId, walletProvider);\n * ```\n */\nexport function useSpokeProvider(\n spokeChainId: SpokeChainId | undefined,\n walletProvider?: IWalletProvider | undefined,\n): SpokeProvider | undefined {\n const { rpcConfig } = useSodaxContext();\n const xChainType = spokeChainId ? spokeChainConfig[spokeChainId]?.chain.type : undefined;\n\n const spokeProvider = useMemo(() => {\n if (!walletProvider) return undefined;\n if (!spokeChainId) return undefined;\n if (!xChainType) return undefined;\n if (!rpcConfig) return undefined;\n\n if (xChainType === 'BITCOIN') {\n const bitcoinConfig = spokeChainConfig[spokeChainId] as BitcoinSpokeChainConfig;\n const btcRpcOverride = rpcConfig[spokeChainId] as BitcoinRpcConfig | undefined;\n return new BitcoinSpokeProvider(\n walletProvider as IBitcoinWalletProvider,\n bitcoinConfig,\n {\n url: btcRpcOverride?.radfiApiUrl || bitcoinConfig.radfiApiUrl,\n apiKey: bitcoinConfig.radfiApiKey,\n umsUrl: btcRpcOverride?.radfiUmsUrl || bitcoinConfig.radfiUmsUrl,\n },\n 'TRADING',\n btcRpcOverride?.rpcUrl || bitcoinConfig.rpcUrl,\n );\n }\n\n if (xChainType === 'EVM') {\n if (spokeChainId === SONIC_MAINNET_CHAIN_ID) {\n return new SonicSpokeProvider(\n walletProvider as IEvmWalletProvider,\n spokeChainConfig[spokeChainId] as SonicSpokeChainConfig,\n );\n }\n // EVM RPC: flat RpcConfig keyed by chain id (same shape as app's rpcConfig)\n const evmRpcUrl = rpcConfig[spokeChainId];\n return new EvmSpokeProvider(\n walletProvider as IEvmWalletProvider,\n spokeChainConfig[spokeChainId] as EvmSpokeChainConfig,\n typeof evmRpcUrl === 'string' ? evmRpcUrl : undefined,\n );\n }\n\n if (xChainType === 'SUI') {\n return new SuiSpokeProvider(\n spokeChainConfig[spokeChainId] as SuiSpokeChainConfig,\n walletProvider as ISuiWalletProvider,\n );\n }\n\n if (xChainType === 'ICON') {\n return new IconSpokeProvider(\n walletProvider as IIconWalletProvider,\n spokeChainConfig[spokeChainId] as IconSpokeChainConfig,\n );\n }\n\n if (xChainType === 'INJECTIVE') {\n return new InjectiveSpokeProvider(\n spokeChainConfig[spokeChainId] as InjectiveSpokeChainConfig,\n walletProvider as IInjectiveWalletProvider,\n );\n }\n\n if (xChainType === 'STELLAR') {\n const stellarConfig = spokeChainConfig[spokeChainId] as StellarSpokeChainConfig;\n return new StellarSpokeProvider(\n walletProvider as IStellarWalletProvider,\n stellarConfig,\n rpcConfig.stellar\n ? rpcConfig.stellar\n : {\n horizonRpcUrl: stellarConfig.horizonRpcUrl,\n sorobanRpcUrl: stellarConfig.sorobanRpcUrl,\n },\n );\n }\n\n if (xChainType === 'SOLANA') {\n return new SolanaSpokeProvider(\n walletProvider as ISolanaWalletProvider,\n rpcConfig.solana\n ? ({\n ...spokeChainConfig[spokeChainId],\n rpcUrl: rpcConfig.solana,\n } as SolanaChainConfig)\n : (spokeChainConfig[spokeChainId] as SolanaChainConfig),\n );\n }\n\n if (xChainType === 'NEAR') {\n return new NearSpokeProvider(\n walletProvider as INearWalletProvider,\n spokeChainConfig[spokeChainId] as NearSpokeChainConfig,\n );\n }\n\n if (xChainType === 'STACKS') {\n return new StacksSpokeProvider(\n rpcConfig[spokeChainId]\n ? ({\n ...spokeChainConfig[spokeChainId],\n rpcUrl: rpcConfig[spokeChainId],\n } as StacksSpokeChainConfig)\n : (spokeChainConfig[spokeChainId] as StacksSpokeChainConfig),\n walletProvider as IStacksWalletProvider,\n );\n }\n\n return undefined;\n }, [spokeChainId, xChainType, walletProvider, rpcConfig]);\n\n return spokeProvider;\n}\n","import type { BitcoinSpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\nexport type RadfiSession = {\n accessToken: string;\n refreshToken: string;\n tradingAddress: string;\n publicKey: string;\n};\n\ntype RadfiAuthResult = {\n accessToken: string;\n refreshToken: string;\n tradingAddress: string;\n};\n\nconst SESSION_KEY = (address: string) => `radfi_session_${address}`;\n\nexport function saveRadfiSession(address: string, session: RadfiSession): void {\n try {\n // Radfi tokens are only used for API rate-limiting / anti-spam, not for accessing user assets.\n localStorage.setItem(SESSION_KEY(address), JSON.stringify(session));\n } catch {}\n}\n\nexport function loadRadfiSession(address: string): RadfiSession | null {\n try {\n const raw = localStorage.getItem(SESSION_KEY(address));\n return raw ? (JSON.parse(raw) as RadfiSession) : null;\n } catch {\n return null;\n }\n}\n\nexport function clearRadfiSession(address: string): void {\n try {\n localStorage.removeItem(SESSION_KEY(address));\n } catch {}\n}\n\n/**\n * Hook to authenticate with Radfi using BIP322 message signing.\n * Saves session (accessToken, refreshToken, tradingAddress, publicKey) to localStorage.\n */\nexport function useRadfiAuth(\n spokeProvider: BitcoinSpokeProvider | undefined,\n): UseMutationResult<RadfiAuthResult, Error, void> {\n return useMutation<RadfiAuthResult, Error, void>({\n mutationFn: async () => {\n if (!spokeProvider) {\n throw new Error('Bitcoin spoke provider not found');\n }\n\n const walletAddress = await spokeProvider.walletProvider.getWalletAddress();\n const existingSession = loadRadfiSession(walletAddress);\n const cachedPublicKey = existingSession?.publicKey;\n\n try {\n const { accessToken, refreshToken, tradingAddress, publicKey } = await spokeProvider.authenticateWithWallet(cachedPublicKey);\n\n const session: RadfiSession = {\n accessToken,\n refreshToken,\n tradingAddress,\n publicKey,\n };\n\n saveRadfiSession(walletAddress, session);\n\n return { accessToken, refreshToken, tradingAddress };\n } catch (err: unknown) {\n // Error 4008: wallet already registered — authenticate is register+login combined.\n // Try to refresh with existing session if available.\n const isAlreadyRegistered =\n err instanceof Error &&\n (err.message.includes('duplicatedPubKey') || err.message.includes('4008'));\n\n if (isAlreadyRegistered && existingSession?.refreshToken) {\n try {\n const refreshed = await spokeProvider.radfi.refreshAccessToken(existingSession.refreshToken);\n const session: RadfiSession = {\n ...existingSession,\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n };\n spokeProvider.setRadfiAccessToken(refreshed.accessToken, refreshed.refreshToken);\n saveRadfiSession(walletAddress, session);\n return { accessToken: refreshed.accessToken, refreshToken: refreshed.refreshToken, tradingAddress: existingSession.tradingAddress };\n } catch {\n // Refresh also failed — clear stale session and guide user\n clearRadfiSession(walletAddress);\n }\n\n throw new Error(\n 'This wallet is already registered with Radfi from another session. ' +\n 'Please clear your browser storage for this site and try again, ' +\n 'or wait for the previous session to expire.',\n );\n }\n\n throw err;\n }\n },\n });\n}\n","import { useState, useEffect, useRef, useCallback } from 'react';\nimport type { BitcoinSpokeProvider } from '@sodax/sdk';\nimport {\n useRadfiAuth,\n loadRadfiSession,\n saveRadfiSession,\n clearRadfiSession,\n type RadfiSession,\n} from './useRadfiAuth';\n\nconst REFRESH_INTERVAL = 5 * 60 * 1000; // 5 min — refresh before access token expires (10 min TTL)\n\nexport type UseRadfiSessionReturn = {\n walletAddress: string | undefined;\n isAuthed: boolean;\n tradingAddress: string | undefined;\n login: () => Promise<void>;\n isLoginPending: boolean;\n};\n\n/**\n * Manages the full Radfi session lifecycle:\n * - On mount / wallet switch: refreshes token to validate session\n * - Single interval (~5 min): refreshes access token. If refresh fails → clears session, isAuthed=false\n * - ensureRadfiAccessToken (SDK layer) acts as safety net before swap/bridge\n * - Exposes login() and isAuthed for UI\n */\nexport function useRadfiSession(\n spokeProvider: BitcoinSpokeProvider | undefined,\n): UseRadfiSessionReturn {\n const [walletAddress, setWalletAddress] = useState<string | undefined>();\n const [isAuthed, setIsAuthed] = useState(false);\n const [tradingAddress, setTradingAddress] = useState<string | undefined>();\n const isRefreshingRef = useRef(false);\n\n // ── Silent refresh helper ────────────────────────────────────────────────\n const silentRefresh = useCallback(async (address: string) => {\n if (!spokeProvider || isRefreshingRef.current) return;\n isRefreshingRef.current = true;\n\n try {\n const session = loadRadfiSession(address);\n if (!session?.refreshToken) {\n setIsAuthed(false);\n return;\n }\n\n const { accessToken, refreshToken } = await spokeProvider.radfi.refreshAccessToken(session.refreshToken);\n const updated: RadfiSession = {\n ...session,\n accessToken,\n refreshToken,\n };\n\n saveRadfiSession(address, updated);\n spokeProvider.setRadfiAccessToken(accessToken, refreshToken);\n setIsAuthed(true);\n setTradingAddress(updated.tradingAddress || undefined);\n } catch {\n clearRadfiSession(address);\n spokeProvider.setRadfiAccessToken('', '');\n setIsAuthed(false);\n setTradingAddress(undefined);\n } finally {\n isRefreshingRef.current = false;\n }\n }, [spokeProvider]);\n\n // ── On mount / wallet switch: reset state + refresh to validate session ──\n useEffect(() => {\n if (!spokeProvider) return;\n\n // Reset state immediately to avoid stale data from previous wallet\n setIsAuthed(false);\n setTradingAddress(undefined);\n setWalletAddress(undefined);\n\n spokeProvider.walletProvider.getWalletAddress()\n .then((addr) => {\n setWalletAddress(addr);\n const session = loadRadfiSession(addr);\n if (!session?.refreshToken) return;\n\n // Always refresh on mount to validate the session is actually valid\n silentRefresh(addr);\n })\n .catch(() => {});\n }, [spokeProvider, silentRefresh]);\n\n // ── Interval: refresh token every 5 min to keep access token fresh ──────\n useEffect(() => {\n if (!walletAddress || !spokeProvider) return;\n\n const id = setInterval(() => {\n silentRefresh(walletAddress);\n }, REFRESH_INTERVAL);\n\n return () => clearInterval(id);\n }, [walletAddress, spokeProvider, silentRefresh]);\n\n // ── Login ────────────────────────────────────────────────────────────────\n const { mutateAsync: loginMutate, isPending: isLoginPending } = useRadfiAuth(spokeProvider);\n\n const login = useCallback(async () => {\n const result = await loginMutate();\n setIsAuthed(true);\n setTradingAddress(result.tradingAddress || undefined);\n }, [loginMutate]);\n\n return { walletAddress, isAuthed, tradingAddress, login, isLoginPending };\n}\n","import { BitcoinSpokeService, type BitcoinSpokeProvider } from '@sodax/sdk';\nimport { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook to fund the Radfi trading wallet by sending BTC from the user's personal wallet.\n *\n * @param {BitcoinSpokeProvider | undefined} spokeProvider - The Bitcoin spoke provider with signing capability\n * @returns {UseMutationResult} Mutation result — input is amount in satoshis, output is transaction ID\n *\n * @example\n * ```tsx\n * const { mutateAsync: fundWallet, isPending } = useFundTradingWallet(spokeProvider);\n *\n * const handleFund = async () => {\n * const txId = await fundWallet(100_000n); // fund 100,000 satoshis\n * console.log('Funded:', txId);\n * };\n * ```\n */\nexport function useFundTradingWallet(\n spokeProvider: BitcoinSpokeProvider | undefined,\n): UseMutationResult<string, Error, bigint> {\n const queryClient = useQueryClient();\n\n return useMutation<string, Error, bigint>({\n mutationFn: async (amount: bigint) => {\n if (!spokeProvider) {\n throw new Error('Bitcoin spoke provider not found');\n }\n\n return BitcoinSpokeService.fundTradingWallet(amount, spokeProvider);\n },\n onSuccess: () => {\n // Invalidate balance queries to reflect the fund transfer\n queryClient.invalidateQueries({ queryKey: ['btc-balance'] });\n queryClient.invalidateQueries({ queryKey: ['xBalances'] });\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook to fetch BTC balance for any Bitcoin address.\n * Sums all UTXOs (confirmed + unconfirmed) from mempool.space API.\n *\n * The UTXO set already excludes spent outputs (even from unconfirmed txs),\n * so the total is always the correct spendable balance.\n */\nexport function useBitcoinBalance(\n address: string | undefined,\n rpcUrl = 'https://mempool.space/api',\n): UseQueryResult<bigint, Error> {\n return useQuery<bigint, Error>({\n queryKey: ['btc-balance', address],\n queryFn: async () => {\n if (!address) return 0n;\n\n const response = await fetch(`${rpcUrl}/address/${address}/utxo`);\n if (!response.ok) return 0n;\n\n const utxos: Array<{ value: number }> = await response.json();\n return BigInt(utxos.reduce((sum, utxo) => sum + utxo.value, 0));\n },\n enabled: !!address,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { BitcoinSpokeProvider, RadfiWalletBalance } from '@sodax/sdk';\n\n/**\n * Hook to fetch trading wallet balance from Radfi API.\n * Returns confirmed + pending satoshi balances.\n */\nexport function useTradingWalletBalance(\n spokeProvider: BitcoinSpokeProvider | undefined,\n tradingAddress: string | undefined,\n): UseQueryResult<RadfiWalletBalance, Error> {\n return useQuery<RadfiWalletBalance, Error>({\n queryKey: ['trading-wallet-balance', tradingAddress],\n queryFn: () => {\n if (!spokeProvider || !tradingAddress) {\n throw new Error('spokeProvider and tradingAddress are required');\n }\n return spokeProvider.radfi.getBalance(tradingAddress);\n },\n enabled: !!spokeProvider && !!tradingAddress,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { BitcoinSpokeProvider, RadfiUtxo } from '@sodax/sdk';\n\n/**\n * Hook to fetch expired UTXOs for a trading wallet address.\n * UTXOs that are expired or within 2 weeks of expiry are considered invalid for trading\n * and need to be renewed via the Radfi renew-utxo flow.\n */\nexport function useExpiredUtxos(\n spokeProvider: BitcoinSpokeProvider | undefined,\n tradingAddress: string | undefined,\n): UseQueryResult<RadfiUtxo[], Error> {\n return useQuery<RadfiUtxo[], Error>({\n queryKey: ['expired-utxos', tradingAddress],\n queryFn: async () => {\n if (!spokeProvider || !tradingAddress) {\n throw new Error('spokeProvider and tradingAddress are required');\n }\n const result = await spokeProvider.radfi.getExpiredUtxos(tradingAddress);\n return result.data;\n },\n enabled: !!spokeProvider && !!tradingAddress,\n refetchInterval: 60_000, // refetch every minute\n });\n}\n","import { normalizePsbtToBase64, type BitcoinSpokeProvider } from '@sodax/sdk';\nimport { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport { loadRadfiSession } from './useRadfiAuth';\n\ntype RenewUtxosParams = {\n txIdVouts: string[];\n};\n\n/**\n * Hook to renew expired UTXOs in the Radfi trading wallet.\n *\n * Flow:\n * 1. Build renew-utxo transaction via Radfi API (returns unsigned PSBT)\n * 2. User signs the PSBT with their wallet\n * 3. Submit signed PSBT back to Radfi for co-signing and broadcasting\n *\n * @example\n * ```tsx\n * const { mutateAsync: renewUtxos, isPending } = useRenewUtxos(spokeProvider);\n *\n * const handleRenew = async (expiredUtxos: RadfiUtxo[]) => {\n * const txIdVouts = expiredUtxos.map(u => u.txidVout);\n * const txId = await renewUtxos({ txIdVouts });\n * console.log('Renewed:', txId);\n * };\n * ```\n */\nexport function useRenewUtxos(\n spokeProvider: BitcoinSpokeProvider | undefined,\n): UseMutationResult<string, Error, RenewUtxosParams> {\n const queryClient = useQueryClient();\n\n return useMutation<string, Error, RenewUtxosParams>({\n mutationFn: async ({ txIdVouts }: RenewUtxosParams) => {\n if (!spokeProvider) {\n throw new Error('Bitcoin spoke provider not found');\n }\n\n const userAddress = await spokeProvider.walletProvider.getWalletAddress();\n const session = loadRadfiSession(userAddress);\n const accessToken = session?.accessToken || spokeProvider.radfiAccessToken;\n\n if (!accessToken) {\n throw new Error('Radfi authentication required. Please login first.');\n }\n\n // Step 1: Build the renew-utxo transaction\n const buildResult = await spokeProvider.radfi.buildRenewUtxoTransaction(\n { userAddress, txIdVouts },\n accessToken,\n );\n\n // Step 2: Sign the PSBT with user's wallet\n const signedTx = await spokeProvider.walletProvider.signTransaction(\n buildResult.base64Psbt,\n false,\n );\n\n const signedBase64Tx = normalizePsbtToBase64(signedTx);\n\n // Step 3: Submit to Radfi for co-signing and broadcasting\n return spokeProvider.radfi.signAndBroadcastRenewUtxo(\n { userAddress, signedBase64Tx },\n accessToken,\n );\n },\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: ['expired-utxos'] });\n queryClient.invalidateQueries({ queryKey: ['trading-wallet-balance'] });\n },\n });\n}\n","import { normalizePsbtToBase64, type BitcoinSpokeProvider } from '@sodax/sdk';\nimport { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport { loadRadfiSession } from './useRadfiAuth';\n\ntype WithdrawToUserParams = {\n amount: string;\n tokenId: string;\n withdrawTo: string;\n};\n\ntype WithdrawResult = {\n txId: string;\n fee: number;\n};\n\n/**\n * Hook to withdraw BTC from Radfi trading wallet to user's personal wallet.\n *\n * Flow:\n * 1. Build withdraw transaction via Radfi API (returns unsigned PSBT)\n * 2. User signs the PSBT with their wallet\n * 3. Submit signed PSBT back to Radfi for co-signing and broadcasting\n *\n * @example\n * ```tsx\n * const { mutateAsync: withdraw, isPending } = useRadfiWithdraw(spokeProvider);\n *\n * const handleWithdraw = async () => {\n * const result = await withdraw({\n * amount: '10000',\n * tokenId: '0:0',\n * withdrawTo: 'bc1q...', // user's segwit address\n * });\n * console.log('Withdrawn:', result.txId);\n * };\n * ```\n */\nexport function useRadfiWithdraw(\n spokeProvider: BitcoinSpokeProvider | undefined,\n): UseMutationResult<WithdrawResult, Error, WithdrawToUserParams> {\n const queryClient = useQueryClient();\n\n return useMutation<WithdrawResult, Error, WithdrawToUserParams>({\n mutationFn: async ({ amount, tokenId, withdrawTo }: WithdrawToUserParams) => {\n if (!spokeProvider) {\n throw new Error('Bitcoin spoke provider not found');\n }\n\n const userAddress = await spokeProvider.walletProvider.getWalletAddress();\n const session = loadRadfiSession(userAddress);\n const accessToken = session?.accessToken || spokeProvider.radfiAccessToken;\n\n if (!accessToken) {\n throw new Error('Radfi authentication required. Please login first.');\n }\n\n // Step 1: Build the withdraw transaction\n const buildResult = await spokeProvider.radfi.withdrawToUser(\n { userAddress, amount, tokenId, withdrawTo },\n accessToken,\n );\n\n // Step 2: Sign the PSBT with user's wallet\n const signedTx = await spokeProvider.walletProvider.signTransaction(\n buildResult.base64Psbt,\n false,\n );\n\n const signedBase64Tx = normalizePsbtToBase64(signedTx);\n\n // Step 3: Submit to Radfi for co-signing and broadcasting\n const txId = await spokeProvider.radfi.signAndBroadcastWithdraw(\n { userAddress, signedBase64Tx },\n accessToken,\n );\n\n return { txId, fee: buildResult.fee.totalFee };\n },\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: ['trading-wallet-balance'] });\n queryClient.invalidateQueries({ queryKey: ['btc-balance'] });\n queryClient.invalidateQueries({ queryKey: ['xBalances'] });\n },\n });\n}\n","import { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { MoneyMarketBorrowParams, MoneyMarketError, RelayErrorCode, SpokeProvider } from '@sodax/sdk';\n\ninterface BorrowResponse {\n ok: true;\n value: [string, string];\n}\n\nexport type UseBorrowParams = {\n params: MoneyMarketBorrowParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook for borrowing tokens in the Sodax money market protocol.\n *\n * Encapsulates the async process to initiate a borrow transaction via the money market,\n * handling transaction creation, submission, and cross-chain logic.\n *\n * @returns {UseMutationResult<\n * BorrowResponse,\n * MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,\n * UseBorrowParams\n * >} A React Query mutation result object containing:\n * - mutateAsync: (params: UseBorrowParams) => Promise<BorrowResponse>\n * Triggers the borrow action. Expects an object with valid borrow params and a `SpokeProvider`.\n * - isPending: `boolean` if a borrow transaction is in progress.\n * - error: `MoneyMarketError` if the transaction fails, or `null`.\n *\n * @example\n * ```typescript\n * const { mutateAsync: borrow, isPending, error } = useBorrow();\n * await borrow({ params: borrowParams, spokeProvider });\n * ```\n *\n * @throws {Error} When:\n * - `spokeProvider` is missing or invalid.\n * - The underlying borrow transaction fails.\n */\nexport function useBorrow(): UseMutationResult<\n BorrowResponse,\n MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,\n UseBorrowParams\n> {\n const { sodax } = useSodaxContext();\n\n return useMutation<\n BorrowResponse,\n MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,\n UseBorrowParams\n >({\n mutationFn: async ({ params, spokeProvider }: UseBorrowParams) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.borrow(params, spokeProvider);\n\n if (!response.ok) {\n throw response.error;\n }\n\n return response;\n },\n });\n}\n","import type { MoneyMarketError, MoneyMarketRepayParams, RelayErrorCode, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ninterface RepayResponse {\n ok: true;\n value: [string, string];\n}\n\nexport type UseRepayParams = {\n params: MoneyMarketRepayParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook for repaying a borrow in the Sodax money market protocol.\n *\n * This hook encapsulates the process of sending a repay transaction to the money market.\n * It manages the asynchronous operation for repayment, including sending the transaction\n * and error handling.\n *\n * @returns {UseMutationResult<RepayResponse, MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>, UseRepayParams>} React Query mutation result object containing:\n * - mutateAsync: (params: UseRepayParams) => Promise<RepayResponse>\n * Initiates a repay transaction using the given MoneyMarketRepayParams and SpokeProvider.\n * - isPending: boolean indicating if a transaction is in progress.\n * - error: MoneyMarketError if an error occurred while repaying, otherwise undefined.\n *\n * @example\n * ```typescript\n * const { mutateAsync: repay, isPending, error } = useRepay();\n * await repay({ params: repayParams, spokeProvider });\n * ```\n *\n * @throws {Error} When:\n * - `spokeProvider` is missing or invalid.\n * - The underlying repay transaction fails.\n */\nexport function useRepay(): UseMutationResult<\n RepayResponse,\n MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>,\n UseRepayParams\n> {\n const { sodax } = useSodaxContext();\n\n return useMutation<\n RepayResponse,\n MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>,\n UseRepayParams\n >({\n mutationFn: async ({ params, spokeProvider }: UseRepayParams) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.repay(params, spokeProvider);\n\n if (!response.ok) {\n throw response.error;\n }\n\n return response;\n },\n });\n}\n","import type { MoneyMarketError, MoneyMarketSupplyParams, RelayErrorCode, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ninterface SupplyResponse {\n ok: true;\n value: [string, string];\n}\n\nexport type UseSupplyParams = {\n params: MoneyMarketSupplyParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook for supplying tokens to the Sodax money market protocol.\n *\n * Provides a mutation for performing the supply operation using React Query. Useful\n * for UI components needing to manage the full state (pending, error, etc.) of a supply\n * transaction. It handles transaction creation, cross-chain logic, and errors.\n *\n * @returns {UseMutationResult<SupplyResponse, MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>, UseSupplyParams>}\n * Mutation result object from React Query, where:\n * - mutateAsync(params: UseSupplyParams): Promise<SupplyResponse>\n * Initiates a supply transaction using the given MoneyMarketSupplyParams and SpokeProvider.\n * - isPending: boolean indicating if a transaction is in progress.\n * - error: MoneyMarketError if an error occurred while supplying, otherwise undefined.\n *\n * @example\n * ```typescript\n * const { mutateAsync: supply, isPending, error } = useSupply();\n * await supply({ params: supplyParams, spokeProvider });\n * ```\n *\n * @throws {Error|MoneyMarketError<...>} When:\n * - `spokeProvider` is not provided or invalid.\n * - The underlying supply transaction fails.\n */\nexport function useSupply(): UseMutationResult<\n SupplyResponse,\n MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>,\n UseSupplyParams\n> {\n const { sodax } = useSodaxContext();\n\n return useMutation<\n SupplyResponse,\n MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>,\n UseSupplyParams\n >({\n mutationFn: async ({ params, spokeProvider }: UseSupplyParams) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.supply(params, spokeProvider);\n\n if (!response.ok) {\n throw response.error;\n }\n\n return response;\n },\n });\n}\n","import type { MoneyMarketError, MoneyMarketWithdrawParams, RelayErrorCode, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseWithdrawParams = {\n params: MoneyMarketWithdrawParams;\n spokeProvider: SpokeProvider;\n};\n\ninterface WithdrawResponse {\n ok: true;\n value: [string, string];\n}\n\n/**\n * Hook for performing withdrawals from the Sodax money market.\n *\n * This hook exposes a mutation that executes the complete withdrawal logic, including transaction\n * creation and handling cross-chain communication. It leverages React Query's mutation API for\n * easy asynchronous handling and status tracking within UI components.\n *\n * @returns {UseMutationResult<WithdrawResponse, MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>, UseWithdrawParams>}\n * Mutation result object, with:\n * - mutateAsync: (params: UseWithdrawParams) => Promise<WithdrawResponse>\n * Initiates the withdrawal using the provided params.\n * - isPending: boolean indicating if a transaction is in progress.\n * - error: MoneyMarketError if an error occurred while withdrawing, otherwise undefined.\n *\n * @example\n * ```typescript\n * const { mutateAsync: withdraw, isPending, error } = useWithdraw();\n * await withdraw({ params: withdrawParams, spokeProvider });\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is not provided or invalid.\n * - Underlying withdrawal logic fails.\n */\nexport function useWithdraw(): UseMutationResult<\n WithdrawResponse,\n MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>,\n UseWithdrawParams\n> {\n const { sodax } = useSodaxContext();\n\n return useMutation<\n WithdrawResponse,\n MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>,\n UseWithdrawParams\n >({\n mutationFn: async ({ params, spokeProvider }) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const response = await sodax.moneyMarket.withdraw(params, spokeProvider);\n\n if (!response.ok) {\n throw response.error;\n }\n\n return response;\n },\n });\n}\n","import type { SpokeChainId } from '@sodax/types';\nimport type { SpokeProvider, UserReserveData } from '@sodax/sdk';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ntype BaseQueryOptions = {\n queryOptions?: UseQueryOptions<readonly [readonly UserReserveData[], number], Error>;\n};\n\ntype NewParams = BaseQueryOptions & {\n /** Spoke chain id (e.g. '0xa86a.avax') */\n spokeChainId: SpokeChainId | undefined;\n /** User wallet address on the spoke chain */\n userAddress: string | undefined;\n};\n\n/** @deprecated Use `{ spokeChainId, userAddress }` instead */\ntype LegacyParams = BaseQueryOptions & {\n /** @deprecated Use `spokeChainId` instead */\n spokeProvider: SpokeProvider | undefined;\n /** @deprecated Use `userAddress` instead */\n address: string | undefined;\n};\n\nexport type UseUserReservesDataParams = NewParams | LegacyParams;\n\nfunction isLegacyParams(params: UseUserReservesDataParams): params is LegacyParams {\n return 'spokeProvider' in params || 'address' in params;\n}\n\nfunction resolveParams(params: UseUserReservesDataParams): {\n spokeChainId: SpokeChainId | undefined;\n userAddress: string | undefined;\n} {\n if (isLegacyParams(params)) {\n return {\n spokeChainId: params.spokeProvider?.chainConfig.chain.id as SpokeChainId | undefined,\n userAddress: params.address,\n };\n }\n return { spokeChainId: params.spokeChainId, userAddress: params.userAddress };\n}\n\n/**\n * Hook for fetching user reserves data from the Sodax money market.\n *\n * @param params (optional) - Object including:\n * - spokeChainId: The spoke chain id whose reserves data will be fetched. If not provided, data fetching is disabled.\n * - userAddress: The user's address (string) whose reserves data will be fetched. If not provided, data fetching is disabled.\n * - queryOptions: (optional) Custom React Query options such as `queryKey`, `enabled`, or cache policy.\n *\n * @returns {UseQueryResult<readonly [readonly UserReserveData[], number], Error>} React Query result object containing:\n * - data: A tuple with array of UserReserveData and associated number, or undefined if loading\n * - isLoading: Boolean loading state\n * - isError: Boolean error state\n * - error: Error object, if present\n *\n * @example\n * const { data: userReservesData, isLoading, error } = useUserReservesData({\n * spokeChainId,\n * userAddress,\n * });\n */\nexport function useUserReservesData(\n params?: UseUserReservesDataParams,\n): UseQueryResult<readonly [readonly UserReserveData[], number], Error> {\n const { sodax } = useSodaxContext();\n const resolved = params ? resolveParams(params) : { spokeChainId: undefined, userAddress: undefined };\n const defaultQueryOptions = {\n queryKey: ['mm', 'userReservesData', resolved.spokeChainId, resolved.userAddress],\n enabled: !!resolved.spokeChainId && !!resolved.userAddress,\n refetchInterval: 5000,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!resolved.spokeChainId || !resolved.userAddress) {\n throw new Error('spokeChainId or userAddress is not defined');\n }\n\n return await sodax.moneyMarket.data.getUserReservesData(resolved.spokeChainId, resolved.userAddress);\n },\n });\n}\n","import { useQuery, type UseQueryResult, type UseQueryOptions } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { AggregatedReserveData, BaseCurrencyInfo } from '@sodax/sdk';\n\nexport type UseReservesDataParams = {\n queryOptions?: UseQueryOptions<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>;\n};\n\n/**\n * React hook for fetching the latest reserves data from the Sodax money market.\n *\n * Provides the full set of aggregated reserves and base currency information.\n * Optionally accepts React Query options for customizing the query key, cache time, and related behaviors.\n *\n * @param params (optional) - Object including:\n * - queryOptions: Custom React Query options\n *\n * @returns {UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>}\n * React Query result object containing:\n * - data: [aggregated reserves[], base currency info], or undefined if not loaded\n * - isLoading: True if the request is loading\n * - isError: True if the request failed\n * - error: Error object, if present\n *\n * @example\n * const { data, isLoading, error } = useReservesData();\n * const { data } = useReservesData({ queryOptions: { queryKey: ['custom', 'reservesData'] } });\n */\nexport function useReservesData(\n params?: UseReservesDataParams,\n): UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error> {\n const defaultQueryOptions = {\n queryKey: ['mm', 'reservesData'],\n refetchInterval: 5000,\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions, // override default query options if provided\n }\n const { sodax } = useSodaxContext();\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo]> => {\n return await sodax.moneyMarket.data.getReservesData();\n },\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { MoneyMarketParams, SpokeProvider } from '@sodax/sdk';\n\nexport type UseMMAllowanceParams = {\n params: MoneyMarketParams | undefined;\n spokeProvider: SpokeProvider | undefined;\n queryOptions?: UseQueryOptions<boolean, Error>;\n};\n\n/**\n * Hook for checking token allowance for money market operations.\n *\n * This hook verifies if the user has approved enough tokens for a specific money market action\n * (borrow/repay). It automatically queries and tracks the allowance status.\n *\n * @param {XToken} token - The token to check allowance for. Must be an XToken with valid address and chain information.\n * @param {string} amount - The amount to check allowance for, as a decimal string\n * @param {MoneyMarketAction} action - The money market action to check allowance for ('borrow' or 'repay')\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks\n *\n * @returns {UseQueryResult<boolean, Error>} A React Query result containing:\n * - data: Boolean indicating if allowance is sufficient\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during the check\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useMMAllowance(token, \"100\", \"repay\", provider);\n * ```\n */\nexport function useMMAllowance({\n params,\n spokeProvider,\n queryOptions,\n}: UseMMAllowanceParams): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['mm', 'allowance', params?.token, params?.action],\n /**\n * IMPORTANT: Skip allowance checks for 'borrow' and 'withdraw' actions.\n *\n * Reason: According to the SDK's MoneyMarketService.isAllowanceValid() implementation,\n * borrow and withdraw actions do NOT require ERC-20 token approval. The SDK's\n * isAllowanceValid() method always returns `true` for these actions without making\n * any on-chain allowance checks.\n *\n * This optimization prevents unnecessary RPC calls and avoids showing confusing states for actions that don't actually need approval.\n *\n * Only 'supply' and 'repay' actions require token approval and should trigger allowance checks.\n */\n enabled: !!spokeProvider && !!params && params.action !== 'borrow' && params.action !== 'withdraw',\n refetchInterval: 5000,\n gcTime: 0, // Don't cache failed queries\n };\n\n queryOptions = {\n ...defaultQueryOptions,\n ...queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!spokeProvider) throw new Error('Spoke provider is required');\n if (!params) throw new Error('Params are required');\n\n /**\n * Early return for borrow/withdraw actions: these actions do NOT require ERC-20 token approval.\n *\n * The SDK's MoneyMarketService.isAllowanceValid() always returns `true` for borrow/withdraw\n * without checking on-chain allowance. This is because:\n * - Borrow: User receives tokens (no approval needed)\n * - Withdraw: User withdraws their own supplied tokens (no approval needed)\n *\n * By returning `true` here, we avoid unnecessary RPC calls and ensure consistent behavior\n * with the SDK's implementation.\n */\n if (params.action === 'borrow' || params.action === 'withdraw') {\n return true;\n }\n\n const allowance = await sodax.moneyMarket.isAllowanceValid(params, spokeProvider);\n\n if (!allowance.ok) {\n throw allowance.error;\n }\n\n return allowance.value;\n },\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, type UseMutationResult, useQueryClient } from '@tanstack/react-query';\nimport type { MoneyMarketParams, SpokeProvider } from '@sodax/sdk';\n\nexport type UseMMApproveParams = {\n params: MoneyMarketParams;\n spokeProvider: SpokeProvider | undefined;\n};\n\n/**\n * Hook for approving ERC20 token spending for Sodax money market actions.\n *\n * This hook manages the approval transaction, allowing the user\n * to grant the protocol permission to spend their tokens for specific money market actions\n * (such as supply, borrow, or repay). Upon successful approval, it also invalidates and\n * refetches the associated allowance status so the UI remains up-to-date.\n *\n * @returns {UseMutationResult<string, Error, UseMMApproveParams>} A React Query mutation result containing:\n * - mutateAsync: Function to trigger the approval (see below)\n * - isPending: Boolean indicating if approval transaction is in progress\n * - error: Error object if the last approval failed, null otherwise\n *\n * @example\n * ```tsx\n * const { mutateAsync: approve, isPending, error } = useMMApprove();\n * await approve({ params: { token, amount: \"100\", action: \"supply\", ... }, spokeProvider });\n * ```\n *\n * @throws {Error} When:\n * - spokeProvider is undefined or invalid\n * - Approval transaction fails for any reason\n */\nexport function useMMApprove(): UseMutationResult<string, Error, UseMMApproveParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseMMApproveParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n const allowance = await sodax.moneyMarket.approve(params, spokeProvider, false);\n if (!allowance.ok) {\n throw allowance.error;\n }\n\n return allowance.value;\n },\n onSuccess: (_, { params, spokeProvider }: UseMMApproveParams) => {\n // Invalidate allowance query to refetch updated approval status\n queryClient.invalidateQueries({\n queryKey: ['mm', 'allowance', spokeProvider?.chainConfig.chain.id, params.token, params.action],\n });\n },\n });\n}\n","import { isAddress } from 'viem';\nimport type { XToken } from '@sodax/sdk';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseATokenParams = {\n aToken: string;\n queryOptions?: UseQueryOptions<XToken, Error>;\n};\n\n/**\n * React hook to fetch and cache metadata for a given aToken address.\n *\n * Accepts an aToken address and React Query options to control query behavior.\n * Returns the aToken's ERC20-style metadata from the Sodax money market, with querying/caching\n * powered by React Query.\n *\n * @param {UseATokenParams} params - Required params object:\n * @property {Address} aToken - The aToken contract address to query.\n * @property {UseQueryOptions<XToken, Error>} queryOptions - React Query options to control query (e.g., staleTime, refetch, etc.).\n *\n * @returns {UseQueryResult<XToken, Error>} React Query result object:\n * - data: XToken metadata, if available\n * - isLoading: Boolean loading state\n * - error: Error, if API call fails\n *\n * @example\n * const { data: xToken, isLoading, error } = useAToken({ aToken: aTokenAddress, queryOptions: {} });\n * if (xToken) {\n * console.log(xToken.symbol);\n * }\n */\nexport function useAToken({ aToken, queryOptions }: UseATokenParams): UseQueryResult<XToken, Error> {\n const { sodax } = useSodaxContext();\n const defaultQueryOptions = {\n queryKey: ['mm', 'aToken', aToken],\n enabled: !!aToken,\n };\n queryOptions = {\n ...defaultQueryOptions,\n ...queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!aToken) {\n throw new Error('aToken address or hub provider is not defined');\n }\n\n if (!isAddress(aToken)) {\n throw new Error('aToken address is not a valid address');\n }\n\n const aTokenData = await sodax.moneyMarket.data.getATokenData(aToken);\n return {\n ...aTokenData,\n xChainId: sodax.hubProvider.chainConfig.chain.id,\n };\n },\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useATokens.ts\nimport { isAddress, type Address } from 'viem';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { SpokeProvider } from '@sodax/sdk';\nimport { HubService } from '@sodax/sdk';\n\nexport type UseATokensBalancesParams = {\n aTokens: readonly Address[];\n spokeProvider?: SpokeProvider;\n userAddress?: string;\n queryOptions?: UseQueryOptions<Map<Address, bigint>, Error>;\n};\n\n/**\n * React hook to fetch and cache aToken balances for multiple aToken addresses in a single multicall.\n *\n * Accepts an array of aToken addresses, a spoke provider, and user address. The hook derives the user's\n * hub wallet address and then fetches balanceOf for each aToken in a single multicall. Returns a Map\n * of aToken address to balance, with querying/caching powered by React Query. This hook uses viem's\n * multicall to batch all requests into a single RPC call for better performance.\n *\n * @param {UseATokensBalancesParams} params - Required params object:\n * @property {readonly Address[]} aTokens - Array of aToken contract addresses to query balances for.\n * @property {SpokeProvider} spokeProvider - The spoke provider to derive hub wallet address from.\n * @property {string} userAddress - User's wallet address on the spoke chain.\n * @property {UseQueryOptions<Map<Address, bigint>, Error>} queryOptions - React Query options to control query (e.g., staleTime, refetch, etc.).\n *\n * @returns {UseQueryResult<Map<Address, bigint>, Error>} React Query result object:\n * - data: Map of aToken address to balance, if available\n * - isLoading: Boolean loading state\n * - error: Error, if API call fails\n *\n * @example\n * const { data: aTokenBalances, isLoading, error } = useATokensBalances({\n * aTokens: [aToken1, aToken2, aToken3],\n * spokeProvider,\n * userAddress: '0x...',\n * queryOptions: {}\n * });\n * const aToken1Balance = aTokenBalances?.get(aToken1);\n */\nexport function useATokensBalances({\n aTokens,\n spokeProvider,\n userAddress,\n queryOptions,\n}: UseATokensBalancesParams): UseQueryResult<Map<Address, bigint>, Error> {\n const { sodax } = useSodaxContext();\n const defaultQueryOptions = {\n queryKey: ['mm', 'aTokensBalances', aTokens, spokeProvider?.chainConfig.chain.id, userAddress],\n enabled: aTokens.length > 0 && aTokens.every(token => isAddress(token)) && !!spokeProvider && !!userAddress,\n };\n queryOptions = {\n ...defaultQueryOptions,\n ...queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (aTokens.length === 0) {\n return new Map();\n }\n\n if (!spokeProvider || !userAddress) {\n throw new Error('Spoke provider and user address are required');\n }\n\n // Validate all addresses\n for (const aToken of aTokens) {\n if (!isAddress(aToken)) {\n throw new Error(`Invalid aToken address: ${aToken}`);\n }\n }\n\n const hubWalletAddress = await HubService.getUserHubWalletAddress(userAddress, spokeProvider.chainConfig.chain.id, sodax.hubProvider);\n\n return await sodax.moneyMarket.data.getATokensBalances(aTokens, hubWalletAddress);\n },\n });\n}\n","import type { FormatReserveUSDResponse, ReserveData } from '@sodax/sdk';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseReservesUsdFormatParams = {\n queryOptions?: UseQueryOptions<\n (ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[],\n Error\n >;\n};\n\n/**\n * Hook for fetching reserves data formatted with USD values in the Sodax money market.\n *\n * This hook returns an array of reserve objects, each extended with its price in the market reference\n * currency and formatted USD values. Data is automatically fetched and cached using React Query.\n *\n * @param params (optional) - Object including:\n * - queryOptions: Custom React Query options such as `queryKey`, cache behavior, or refetching policy.\n *\n * @returns {UseQueryResult<(ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[], Error>} React Query result object containing:\n * - data: Array of reserves with USD-formatted values, or undefined if loading\n * - isLoading: Boolean loading state\n * - isError: Boolean error state\n * - error: Error object, if present\n *\n * @example\n * const { data: reservesUSD, isLoading, error } = useReservesUsdFormat();\n */\nexport function useReservesUsdFormat(\n params?: UseReservesUsdFormatParams,\n): UseQueryResult<(ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[], Error> {\n const { sodax } = useSodaxContext();\n const defaultQueryOptions = { queryKey: ['mm', 'reservesUsdFormat'] };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n const reserves = await sodax.moneyMarket.data.getReservesHumanized();\n return sodax.moneyMarket.data.formatReservesUSD(sodax.moneyMarket.data.buildReserveDataWithPrice(reserves));\n },\n });\n}\n","import type { SpokeChainId } from '@sodax/types';\nimport type { FormatUserSummaryResponse, FormatReserveUSDResponse, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\ntype BaseQueryOptions = {\n queryOptions?: UseQueryOptions<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>;\n};\n\ntype NewParams = BaseQueryOptions & {\n /** Spoke chain id (e.g. '0xa86a.avax') */\n spokeChainId: SpokeChainId | undefined;\n /** User wallet address on the spoke chain */\n userAddress: string | undefined;\n};\n\n/** @deprecated Use `{ spokeChainId, userAddress }` instead */\ntype LegacyParams = BaseQueryOptions & {\n /** @deprecated Use `spokeChainId` instead */\n spokeProvider: SpokeProvider | undefined;\n /** @deprecated Use `userAddress` instead */\n address: string | undefined;\n};\n\nexport type UseUserFormattedSummaryParams = NewParams | LegacyParams;\n\nfunction isLegacyParams(params: UseUserFormattedSummaryParams): params is LegacyParams {\n return 'spokeProvider' in params || 'address' in params;\n}\n\nfunction resolveParams(params: UseUserFormattedSummaryParams): {\n spokeChainId: SpokeChainId | undefined;\n userAddress: string | undefined;\n} {\n if (isLegacyParams(params)) {\n return {\n spokeChainId: params.spokeProvider?.chainConfig.chain.id as SpokeChainId | undefined,\n userAddress: params.address,\n };\n }\n return { spokeChainId: params.spokeChainId, userAddress: params.userAddress };\n}\n\n/**\n * React hook to fetch a formatted summary of a user's Sodax money market portfolio.\n *\n * @param params (optional) - Object including:\n * - spokeChainId: The spoke chain id whose data will be fetched. If not provided, data fetching is disabled.\n * - userAddress: The user's address (string) whose summary will be fetched. If not provided, data fetching is disabled.\n * - queryOptions: (optional) Custom React Query options such as `queryKey`, `enabled`, or cache policy.\n *\n * @returns {UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>}\n * A result object from React Query including:\n * - data: The user's formatted portfolio summary (or undefined if not loaded)\n * - isLoading: Boolean loading state\n * - isError: Boolean error state\n * - error: Error if thrown in fetching\n *\n * @example\n * const { data, isLoading, error } = useUserFormattedSummary({ spokeChainId, userAddress });\n */\nexport function useUserFormattedSummary(\n params?: UseUserFormattedSummaryParams,\n): UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error> {\n const { sodax } = useSodaxContext();\n const resolved = params ? resolveParams(params) : { spokeChainId: undefined, userAddress: undefined };\n const defaultQueryOptions = {\n queryKey: ['mm', 'userFormattedSummary', resolved.spokeChainId, resolved.userAddress],\n enabled: !!resolved.spokeChainId && !!resolved.userAddress,\n refetchInterval: 5000,\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!resolved.spokeChainId || !resolved.userAddress) {\n throw new Error('spokeChainId or userAddress is not defined');\n }\n\n // fetch reserves and hub wallet address\n const reserves = await sodax.moneyMarket.data.getReservesHumanized();\n\n // format reserves\n const formattedReserves = sodax.moneyMarket.data.formatReservesUSD(\n sodax.moneyMarket.data.buildReserveDataWithPrice(reserves),\n );\n\n // fetch user reserves\n const userReserves = await sodax.moneyMarket.data.getUserReservesHumanized(\n resolved.spokeChainId,\n resolved.userAddress,\n );\n\n // format user summary\n return sodax.moneyMarket.data.formatUserSummary(\n sodax.moneyMarket.data.buildUserSummaryRequest(reserves, formattedReserves, userReserves),\n );\n },\n });\n}\n","import type { SolverErrorResponse, SolverIntentQuoteRequest, SolverIntentQuoteResponse, Result } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useMemo } from 'react';\n\n/**\n * Hook for fetching a quote for an intent-based swap.\n *\n * This hook provides real-time quote data for an intent-based swap.\n *\n * @param {SolverIntentQuoteRequest | undefined} payload - The intent quote request parameters. If undefined, the query will be disabled.\n *\n * @returns {UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined>} A query result object containing:\n * - data: The quote result from the solver\n * - isLoading: Boolean indicating if the quote is being fetched\n * - error: Error object if the quote request failed\n * - refetch: Function to manually trigger a quote refresh\n *\n * @example\n * ```typescript\n * const { data: quote, isLoading } = useQuote({\n * token_src: '0x...',\n * token_src_blockchain_id: '1',\n * token_dst: '0x...',\n * token_dst_blockchain_id: '2',\n * amount: '1000000000000000000',\n * quote_type: 'exact_input',\n * });\n *\n * if (isLoading) return <div>Loading quote...</div>;\n * if (quote) {\n * console.log('Quote received:', quote);\n * }\n * ```\n *\n * @remarks\n * - The quote is automatically refreshed every 3 seconds\n * - The query is disabled when payload is undefined\n * - Uses React Query for efficient caching and state management\n */\nexport const useQuote = (\n payload: SolverIntentQuoteRequest | undefined,\n): UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n\n // Create a serializable query key by converting BigInt to string\n const queryKey = useMemo(() => {\n if (!payload) return ['quote', undefined];\n return [\n 'quote',\n {\n ...payload,\n amount: payload.amount.toString(),\n },\n ];\n }, [payload]);\n\n return useQuery({\n queryKey,\n queryFn: async () => {\n if (!payload) {\n return undefined;\n }\n return sodax.swaps.getQuote(payload);\n },\n enabled: !!payload,\n refetchInterval: 3000,\n });\n};\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type {\n CreateIntentParams,\n SolverExecutionResponse,\n Result,\n IntentErrorCode,\n Intent,\n IntentError,\n SpokeProvider,\n IntentDeliveryInfo,\n} from '@sodax/sdk';\nimport { useMutation, type UseMutationResult, useQueryClient } from '@tanstack/react-query';\n\ntype CreateIntentResult = Result<[SolverExecutionResponse, Intent, IntentDeliveryInfo], IntentError<IntentErrorCode>>;\n\n/**\n * Hook for creating and submitting an swap intent order for cross-chain swaps.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for the swap\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: swap, isPending } = useSwap(spokeProvider);\n *\n * const handleSwap = async () => {\n * const result = await swap({\n * token_src: '0x...',\n * token_src_blockchain_id: 'arbitrum',\n * token_dst: '0x...',\n * token_dst_blockchain_id: 'polygon',\n * amount: '1000000000000000000',\n * min_output_amount: '900000000000000000'\n * });\n * };\n * ```\n */\nexport function useSwap(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<CreateIntentResult, Error, CreateIntentParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation<CreateIntentResult, Error, CreateIntentParams>({\n mutationFn: async (params: CreateIntentParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n return sodax.swaps.swap({\n intentParams: params,\n spokeProvider,\n });\n },\n onSuccess: () => {\n // Invalidate balance queries to refresh both source and destination token balances\n queryClient.invalidateQueries({ queryKey: ['xBalances'] });\n },\n });\n}\n","import type { Hex, SolverErrorResponse, SolverIntentStatusResponse, Result } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\n/**\n * Hook for monitoring the status of an intent-based swap.\n *\n * This hook provides real-time status updates for an intent-based swap transaction.\n *\n * @param {Hex} intent_tx_hash - The transaction hash of the intent order on the hub chain\n *\n * @returns {UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined>} A query result object containing:\n * - data: The status result from the solver\n * - isLoading: Boolean indicating if the status is being fetched\n * - error: Error object if the status request failed\n * - refetch: Function to manually trigger a status refresh\n *\n * @example\n * ```typescript\n * const { data: status, isLoading } = useStatus('0x...');\n *\n * if (isLoading) return <div>Loading status...</div>;\n * if (status?.ok) {\n * console.log('Status:', status.value);\n * }\n * ```\n *\n * @remarks\n * - The status is automatically refreshed every 3 seconds\n * - Uses React Query for efficient caching and state management\n */\n\nexport const useStatus = (\n intent_tx_hash: Hex,\n): UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n return useQuery({\n queryKey: [intent_tx_hash],\n queryFn: async () => {\n return sodax.swaps.getStatus({ intent_tx_hash });\n },\n refetchInterval: 3000, // 3s\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { CreateIntentParams, CreateLimitOrderParams, SpokeProvider } from '@sodax/sdk';\n\n/**\n * Hook for checking token allowance for swap operations.\n *\n * This hook verifies if the user has approved enough tokens for a specific swap action.\n * It automatically queries and tracks the allowance status.\n *\n * @param {CreateIntentParams | CreateLimitOrderParams} params - The parameters for the intent to check allowance for.\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks\n *\n * @returns {UseQueryResult<boolean, Error>} A React Query result containing:\n * - data: Boolean indicating if allowance is sufficient\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during the check\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useSwapAllowance(params, spokeProvider);\n * ```\n */\nexport function useSwapAllowance(\n params: CreateIntentParams | CreateLimitOrderParams | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['allowance', params],\n queryFn: async () => {\n if (!spokeProvider || !params) {\n return false;\n }\n const allowance = await sodax.swaps.isAllowanceValid({\n intentParams: params,\n spokeProvider,\n });\n if (allowance.ok) {\n return allowance.value;\n }\n return false;\n },\n enabled: !!spokeProvider && !!params,\n refetchInterval: 2000,\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport type { CreateIntentParams, CreateLimitOrderParams, SpokeProvider } from '@sodax/sdk';\n\ninterface UseApproveReturn {\n approve: ({ params }: { params: CreateIntentParams | CreateLimitOrderParams }) => Promise<boolean>;\n isLoading: boolean;\n error: Error | null;\n resetError: () => void;\n}\n\n/**\n * Hook for approving token spending for swap actions\n * @param params The parameters for the intent to approve spending for\n * @param spokeProvider The spoke provider instance for the chain\n * @returns Object containing approve function, loading state, error state and reset function\n * @example\n * ```tsx\n * const { approve, isLoading, error } = useApprove(token, spokeProvider);\n *\n * // Approve tokens for supply action\n * await approve({ amount: \"100\", action: \"supply\" });\n * ```\n */\n\nexport function useSwapApprove(\n params: CreateIntentParams | CreateLimitOrderParams | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseApproveReturn {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n const {\n mutateAsync: approve,\n isPending,\n error,\n reset: resetError,\n } = useMutation({\n mutationFn: async ({ params }: { params: CreateIntentParams | CreateLimitOrderParams | undefined }) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n if (!params) {\n throw new Error('Swap Params not found');\n }\n\n const allowance = await sodax.swaps.approve({\n intentParams: params,\n spokeProvider,\n });\n if (!allowance.ok) {\n throw new Error('Failed to approve input token');\n }\n return allowance.ok;\n },\n onSuccess: () => {\n // Invalidate allowance query to refetch the new allowance\n queryClient.invalidateQueries({ queryKey: ['allowance', params] });\n },\n });\n\n return {\n approve,\n isLoading: isPending,\n error: error,\n resetError,\n };\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type { Intent, Result, SpokeProvider, TxReturnType } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\ntype CancelIntentParams = {\n intent: Intent;\n raw?: boolean;\n};\n\ntype CancelIntentResult = Result<TxReturnType<SpokeProvider, boolean>>;\n\n/**\n * Hook for canceling a swap intent order.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for canceling the intent\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: cancelSwap, isPending } = useCancelSwap(spokeProvider);\n *\n * const handleCancelSwap = async () => {\n * const result = await cancelSwap({\n * intent: intentObject,\n * raw: false // optional, defaults to false\n * });\n * };\n * ```\n */\nexport function useCancelSwap(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<CancelIntentResult, Error, CancelIntentParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation<CancelIntentResult, Error, CancelIntentParams>({\n mutationFn: async ({ intent, raw = false }: CancelIntentParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n return sodax.swaps.cancelIntent(intent, spokeProvider, raw);\n },\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport type {\n CreateLimitOrderParams,\n SolverExecutionResponse,\n Intent,\n IntentError,\n IntentErrorCode,\n IntentDeliveryInfo,\n Result,\n SpokeProvider,\n} from '@sodax/sdk';\n\ntype CreateLimitOrderResult = Result<\n [SolverExecutionResponse, Intent, IntentDeliveryInfo],\n IntentError<IntentErrorCode>\n>;\n\n/**\n * Hook for creating a limit order intent (no deadline, must be cancelled manually by user).\n * Uses React Query's useMutation for better state management and caching.\n *\n * Limit orders remain active until manually cancelled by the user. Unlike swaps, limit orders\n * do not have a deadline (deadline is automatically set to 0n).\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for creating the limit order\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: createLimitOrder, isPending } = useCreateLimitOrder(spokeProvider);\n *\n * const handleCreateLimitOrder = async () => {\n * const result = await createLimitOrder({\n * inputToken: '0x...',\n * outputToken: '0x...',\n * inputAmount: 1000000000000000000n,\n * minOutputAmount: 900000000000000000n,\n * allowPartialFill: false,\n * srcChain: '0xa4b1.arbitrum',\n * dstChain: '0x89.polygon',\n * srcAddress: '0x...',\n * dstAddress: '0x...',\n * solver: '0x0000000000000000000000000000000000000000',\n * data: '0x'\n * });\n *\n * if (result.ok) {\n * const [solverExecutionResponse, intent, intentDeliveryInfo] = result.value;\n * console.log('Limit order created:', intent);\n * console.log('Intent hash:', solverExecutionResponse.intent_hash);\n * }\n * };\n * ```\n */\nexport function useCreateLimitOrder(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<CreateLimitOrderResult, Error, CreateLimitOrderParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation<CreateLimitOrderResult, Error, CreateLimitOrderParams>({\n mutationFn: async (params: CreateLimitOrderParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n return sodax.swaps.createLimitOrder({\n intentParams: params,\n spokeProvider,\n });\n },\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type { Intent, IntentError, IntentErrorCode, Result, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\ntype CancelLimitOrderParams = {\n intent: Intent;\n spokeProvider: SpokeProvider;\n timeout?: number;\n};\n\ntype CancelLimitOrderResult = Result<[string, string], IntentError<IntentErrorCode>>;\n\n/**\n * Hook for canceling a limit order intent and submitting it to the Relayer API.\n * Uses React Query's useMutation for better state management and caching.\n *\n * This hook wraps cancelLimitOrder which cancels the intent on the spoke chain,\n * submits it to the relayer API, and waits for execution on the destination/hub chain.\n *\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: cancelLimitOrder, isPending } = useCancelLimitOrder();\n *\n * const handleCancelLimitOrder = async () => {\n * const result = await cancelLimitOrder({\n * intent: intentObject,\n * spokeProvider,\n * timeout: 60000 // optional, defaults to 60 seconds\n * });\n *\n * if (result.ok) {\n * const [cancelTxHash, dstTxHash] = result.value;\n * console.log('Cancel transaction hash:', cancelTxHash);\n * console.log('Destination transaction hash:', dstTxHash);\n * }\n * };\n * ```\n */\nexport function useCancelLimitOrder(): UseMutationResult<CancelLimitOrderResult, Error, CancelLimitOrderParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation<CancelLimitOrderResult, Error, CancelLimitOrderParams>({\n mutationFn: async ({ intent, spokeProvider, timeout }: CancelLimitOrderParams): Promise<CancelLimitOrderResult> => {\n return sodax.swaps.cancelLimitOrder({\n intent,\n spokeProvider,\n timeout,\n });\n },\n });\n}\n","// packages/dapp-kit/src/hooks/backend/useIntentByTxHash.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { IntentResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendIntentByTxHashParams = {\n params: {\n txHash: string | undefined;\n };\n queryOptions?: UseQueryOptions<IntentResponse | undefined, Error>;\n};\n\n/**\n * React hook for fetching intent details from the backend API using a transaction hash.\n *\n * @param {UseBackendIntentByTxHashParams | undefined} params - Parameters for the query:\n * - params: { txHash: string | undefined }\n * - `txHash`: Transaction hash used to retrieve the associated intent; query is disabled if undefined or empty.\n * - queryOptions (optional): React Query options to customize request behavior (e.g., caching, retry, refetchInterval, etc.).\n *\n * @returns {UseQueryResult<IntentResponse | undefined, Error>} React Query result object, including:\n * - `data`: The intent response or undefined if unavailable,\n * - `isLoading`: Loading state,\n * - `error`: Error (if request failed),\n * - `refetch`: Function to refetch the data.\n *\n * @example\n * const { data: intent, isLoading, error } = useBackendIntentByTxHash({\n * params: { txHash: '0x123...' },\n * });\n *\n * if (isLoading) return <div>Loading intent...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (intent) {\n * console.log('Intent found:', intent.intentHash);\n * }\n *\n * @remarks\n * - Intents are only created on the hub chain, so `txHash` must originate from there.\n * - Query is disabled if `params` is undefined, or if `params.params.txHash` is undefined or an empty string.\n * - Default refetch interval is 1 second. Uses React Query for state management, caching, and retries.\n */\nexport const useBackendIntentByTxHash = (\n params: UseBackendIntentByTxHashParams | undefined,\n): UseQueryResult<IntentResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'intent', 'txHash', params?.params?.txHash],\n enabled: !!params?.params?.txHash && params?.params?.txHash.length > 0,\n retry: 3,\n refetchInterval: 1000,\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<IntentResponse | undefined> => {\n if (!params?.params?.txHash) {\n return undefined;\n }\n return sodax.backendApi.getIntentByTxHash(params.params.txHash);\n },\n });\n};\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { IntentResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendIntentByHashParams = {\n params: {\n intentHash: string | undefined;\n };\n queryOptions?: UseQueryOptions<IntentResponse | undefined, Error>;\n};\n\n/**\n * React hook to fetch intent details from the backend API using an intent hash.\n *\n * @param {UseBackendIntentByHashParams | undefined} params - Parameters for the query:\n * - params: { intentHash: string | undefined }\n * - `intentHash`: The hash identifying the intent to fetch (disables query if undefined or empty).\n * - queryOptions (optional): Options to customize React Query (e.g., staleTime, enabled).\n *\n * @returns {UseQueryResult<IntentResponse | undefined, Error>} React Query result containing intent response data, loading, error, and refetch states.\n *\n * @example\n * const { data: intent, isLoading, error } = useBackendIntentByHash({\n * params: { intentHash: '0xabc...' },\n * });\n *\n * if (isLoading) return <div>Loading intent...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (intent) {\n * console.log('Intent found:', intent.intentHash);\n * }\n *\n * @remarks\n * - Returns `undefined` data if no intentHash is provided or query is disabled.\n * - Query is cached and managed using React Query.\n * - Use `queryOptions` to customize caching, retry and fetch behavior.\n */\nexport const useBackendIntentByHash = (\n params: UseBackendIntentByHashParams | undefined,\n): UseQueryResult<IntentResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'intent', 'hash', params?.params?.intentHash],\n enabled: !!params?.params?.intentHash && params?.params?.intentHash.length > 0,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<IntentResponse | undefined> => {\n if (!params?.params?.intentHash) {\n return undefined;\n }\n\n return sodax.backendApi.getIntentByHash(params.params.intentHash);\n },\n });\n};\n","import type { UserIntentsResponse, Address } from '@sodax/sdk';\n// packages/dapp-kit/src/hooks/backend/useBackendUserIntents.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BackendPaginationParams } from './types';\n\nexport type GetUserIntentsParams = {\n userAddress: Address;\n startDate?: number;\n endDate?: number;\n};\n\nexport type UseBackendUserIntentsParams = {\n params?: GetUserIntentsParams;\n queryOptions?: UseQueryOptions<UserIntentsResponse | undefined, Error>;\n pagination?: BackendPaginationParams;\n};\n\n/**\n * React hook for fetching user-created intents from the backend API for a given user address,\n * with optional support for a date filtering range.\n *\n * @param {UseBackendUserIntentsParams} args - Query configuration.\n * @param {GetUserIntentsParams | undefined} args.params - User intent filter parameters.\n * @param {Address} args.params.userAddress - The wallet address of the user (required).\n * @param {number} [args.params.startDate] - Include intents created after this timestamp (ms).\n * @param {number} [args.params.endDate] - Include intents created before this timestamp (ms).\n * @param {UseQueryOptions<UserIntentsResponse | undefined, Error>} [args.queryOptions] - Optional React Query options.\n * @param {BackendPaginationParams} [args.pagination] - (currently ignored) Pagination options.\n *\n * @returns {UseQueryResult<UserIntentsResponse | undefined, Error>} React Query result:\n * - `data`: The user intent response, or undefined if unavailable.\n * - `isLoading`: `true` if loading.\n * - `error`: An Error instance if any occurred.\n * - `refetch`: Function to refetch data.\n *\n * @example\n * const { data: userIntents, isLoading, error } = useBackendUserIntents({\n * params: { userAddress: \"0x123...\" }\n * });\n *\n * @example\n * const { data } = useBackendUserIntents({\n * params: {\n * userAddress: \"0xabc...\",\n * startDate: Date.now() - 1_000_000,\n * endDate: Date.now(),\n * },\n * });\n *\n * @remarks\n * The query is disabled if `params` or `params.userAddress` is missing or empty. Uses React Query for\n * cache/state management and auto-retries failed requests three times by default.\n */\nexport const useBackendUserIntents = ({\n params,\n queryOptions,\n}: UseBackendUserIntentsParams): UseQueryResult<UserIntentsResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const defaultQueryOptions = {\n queryKey: ['api', 'intent', 'user', params],\n enabled: !!params && !!params.userAddress && params.userAddress.length > 0,\n retry: 3,\n };\n\n queryOptions = {\n ...defaultQueryOptions,\n ...queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<UserIntentsResponse | undefined> => {\n if (!params?.userAddress) {\n return undefined;\n }\n\n return sodax.backendApi.getUserIntents(params);\n },\n });\n};\n","import { useMutation, type UseMutationOptions, type UseMutationResult } from '@tanstack/react-query';\nimport type { SubmitSwapTxRequest, SubmitSwapTxResponse } from '@sodax/types';\nimport type { RequestOverrideConfig } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendSubmitSwapTxParams = {\n apiConfig?: RequestOverrideConfig;\n mutationOptions?: UseMutationOptions<SubmitSwapTxResponse, Error, SubmitSwapTxRequest>;\n};\n\n/**\n * React hook for submitting a swap transaction to be processed by the backend\n * (relay, post execution to solver, etc.).\n *\n * @param {UseBackendSubmitSwapTxParams | undefined} params - Optional parameters:\n * - `mutationOptions`: React Query mutation options to customize behavior (e.g., onSuccess, onError, retry).\n *\n * @returns {UseMutationResult<SubmitSwapTxResponse, Error, SubmitSwapTxRequest>} React Query mutation result:\n * - `mutate` / `mutateAsync`: Functions to trigger the submission.\n * - `data`: The submit response on success.\n * - `isPending`: Loading state.\n * - `error`: Error instance if the mutation failed.\n *\n * @example\n * const { mutateAsync: submitSwapTx, isPending, error } = useBackendSubmitSwapTx();\n *\n * const result = await submitSwapTx({\n * txHash: '0x123...',\n * srcChainId: '1',\n * walletAddress: '0xabc...',\n * intent: { ... },\n * relayData: '0x...',\n * });\n */\nexport const useBackendSubmitSwapTx = (\n params?: UseBackendSubmitSwapTxParams,\n): UseMutationResult<SubmitSwapTxResponse, Error, SubmitSwapTxRequest> => {\n const { sodax } = useSodaxContext();\n\n const defaultMutationOptions = {\n retry: 3,\n };\n\n const mutationOptions = {\n ...defaultMutationOptions,\n ...params?.mutationOptions,\n };\n\n return useMutation({\n ...mutationOptions,\n mutationFn: async (request: SubmitSwapTxRequest): Promise<SubmitSwapTxResponse> => {\n return sodax.backendApi.submitSwapTx(request, params?.apiConfig);\n },\n });\n};\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { SubmitSwapTxStatusResponse } from '@sodax/types';\nimport type { RequestOverrideConfig } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendSubmitSwapTxStatusParams = {\n params: {\n txHash: string | undefined;\n srcChainId?: string;\n };\n apiConfig?: RequestOverrideConfig;\n queryOptions?: UseQueryOptions<SubmitSwapTxStatusResponse | undefined, Error>;\n};\n\n/**\n * React hook for polling the processing status of a submitted swap transaction.\n *\n * @param {UseBackendSubmitSwapTxStatusParams | undefined} params - Parameters for the query:\n * - `params.txHash`: The transaction hash of the submitted swap; query is disabled if undefined or empty.\n * - `params.srcChainId`: Optional source chain ID to narrow the status lookup.\n * - `queryOptions`: Optional React Query options to override default behavior (e.g., refetchInterval, retry).\n *\n * @returns {UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error>} React Query result object:\n * - `data`: The status response or undefined if unavailable.\n * - `isLoading`: Loading state.\n * - `error`: Error instance if the query failed.\n * - `refetch`: Function to re-trigger the query.\n *\n * @example\n * const { data: status, isLoading, error } = useBackendSubmitSwapTxStatus({\n * params: { txHash: '0x123...', srcChainId: '1' },\n * });\n *\n * if (status?.data.status === 'executed') {\n * console.log('Swap completed!', status.data.result);\n * }\n *\n * @remarks\n * - Query is disabled if `params` is undefined or `txHash` is undefined/empty.\n * - Default refetch interval is 1 second for real-time status polling.\n * - Uses React Query for state management, caching, and retries.\n */\nexport const useBackendSubmitSwapTxStatus = (\n params: UseBackendSubmitSwapTxStatusParams | undefined,\n): UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'swaps', 'submit-tx', 'status', params?.params?.txHash, params?.params?.srcChainId],\n enabled: !!params?.params?.txHash && params.params.txHash.length > 0,\n retry: 3,\n refetchInterval: (query: { state: { data: SubmitSwapTxStatusResponse | undefined } }) => {\n const status = query.state.data?.data?.status;\n if (status === 'executed' || status === 'failed') return false;\n return 1000;\n },\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<SubmitSwapTxStatusResponse | undefined> => {\n if (!params?.params?.txHash) {\n return undefined;\n }\n return sodax.backendApi.getSubmitSwapTxStatus(\n {\n txHash: params.params.txHash,\n srcChainId: params.params.srcChainId,\n },\n params.apiConfig,\n );\n },\n });\n};\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { OrderbookResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BackendPaginationParams } from './types';\n\nexport type UseBackendOrderbookParams = {\n queryOptions?: UseQueryOptions<OrderbookResponse | undefined, Error>;\n pagination?: BackendPaginationParams;\n};\n\n/**\n * Hook for fetching the solver orderbook from the backend API.\n *\n * @param {UseBackendOrderbookParams | undefined} params - Optional parameters:\n * - `pagination`: Pagination configuration (see `BackendPaginationParams`), including\n * `offset` and `limit` (both required for fetch to be enabled).\n * - `queryOptions`: Optional React Query options to override default behavior.\n *\n * @returns {UseQueryResult<OrderbookResponse | undefined, Error>} React Query result object:\n * - `data`: The orderbook response, or undefined if unavailable.\n * - `isLoading`: Loading state.\n * - `error`: Error instance if the query failed.\n * - `refetch`: Function to re-trigger the query.\n *\n * @example\n * const { data, isLoading, error } = useBackendOrderbook({\n * pagination: { offset: '0', limit: '10' },\n * queryOptions: { staleTime: 60000 },\n * });\n *\n * @remarks\n * - Query is disabled if `params?.pagination`, `offset`, or `limit` are missing/empty.\n * - Caches and manages server state using React Query.\n * - Default `staleTime` is 30 seconds to support near-real-time updates.\n */\nexport const useBackendOrderbook = (\n params: UseBackendOrderbookParams | undefined,\n): UseQueryResult<OrderbookResponse | undefined> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'solver', 'orderbook', params?.pagination?.offset, params?.pagination?.limit],\n enabled: !!params?.pagination && !!params?.pagination.offset && !!params?.pagination.limit,\n staleTime: 30 * 1000, // 30 seconds for real-time data\n retry: 3,\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions, // override default query options if provided\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<OrderbookResponse | undefined> => {\n if (!params?.pagination || !params?.pagination.offset || !params?.pagination.limit) {\n return undefined;\n }\n\n return sodax.backendApi.getOrderbook(params.pagination);\n },\n });\n};\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketPosition } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendMoneyMarketPositionParams = {\n userAddress: string | undefined;\n queryOptions?: UseQueryOptions<MoneyMarketPosition | undefined, Error>;\n};\n\n/**\n * React hook for fetching a user's money market position from the backend API.\n *\n * @param {UseBackendMoneyMarketPositionParams | undefined} params - Parameters object:\n * - userAddress: The user's wallet address to fetch positions for. If undefined or empty, the query is disabled.\n * - queryOptions: (Optional) React Query options to customize behavior (e.g., staleTime, enabled).\n *\n * @returns {UseQueryResult<MoneyMarketPosition | undefined, Error>} - React Query result object with:\n * - data: The user's money market position data, or undefined if not available.\n * - isLoading: Loading state.\n * - error: An Error instance if fetching failed.\n * - refetch: Function to manually trigger a refetch.\n *\n * @example\n * const { data, isLoading, error } = useBackendMoneyMarketPosition({\n * userAddress: '0xabc...',\n * queryOptions: { staleTime: 60000 },\n * });\n */\nexport const useBackendMoneyMarketPosition = (\n params: UseBackendMoneyMarketPositionParams | undefined,\n): UseQueryResult<MoneyMarketPosition | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'position', params?.userAddress],\n enabled: !!params?.userAddress && params?.userAddress.length > 0,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketPosition | undefined> => {\n if (!params?.userAddress) {\n return undefined;\n }\n return sodax.backendApi.getMoneyMarketPosition(params.userAddress);\n },\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useAllMoneyMarketAssets.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAsset } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendAllMoneyMarketAssetsParams = {\n queryOptions?: UseQueryOptions<MoneyMarketAsset[], Error>;\n};\n\n/**\n * React hook to fetch all money market assets from the backend API.\n *\n * @param {UseBackendAllMoneyMarketAssetsParams | undefined} params - Optional parameters:\n * - `queryOptions` (optional): React Query options to override default behavior (e.g., caching, retry, etc).\n *\n * @returns {UseQueryResult<MoneyMarketAsset[], Error>} React Query result object:\n * - `data`: Array of all money market asset data when available.\n * - `isLoading`: Boolean indicating if the request is in progress.\n * - `error`: Error object if the request failed.\n * - `refetch`: Function to manually trigger a data refresh.\n *\n * @example\n * const { data: assets, isLoading, error } = useBackendAllMoneyMarketAssets();\n *\n * if (isLoading) return <div>Loading assets...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (assets) {\n * console.log('Total assets:', assets.length);\n * assets.forEach(asset => {\n * console.log(`${asset.symbol}: ${asset.liquidityRate} liquidity rate`);\n * });\n * }\n *\n * @remarks\n * - No required parameters — fetches all available money market assets from backend.\n * - Uses React Query for caching, retries, and loading/error state management.\n * - Supports overriding React Query config via `queryOptions`.\n */\nexport const useBackendAllMoneyMarketAssets = (\n params: UseBackendAllMoneyMarketAssetsParams | undefined,\n): UseQueryResult<MoneyMarketAsset[], Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'assets', 'all'],\n enabled: true,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketAsset[]> => {\n return sodax.backendApi.getAllMoneyMarketAssets();\n },\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useMoneyMarketAsset.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAsset } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseBackendMoneyMarketAssetParams = {\n params: {\n reserveAddress: string | undefined;\n };\n queryOptions?: UseQueryOptions<MoneyMarketAsset | undefined, Error>;\n};\n\n/**\n * React hook to fetch a specific money market asset from the backend API.\n *\n * @param params - The hook input parameter object (may be undefined):\n * - `params`: An object containing:\n * - `reserveAddress` (string | undefined): Reserve contract address to fetch asset details. Disables query if undefined or empty.\n * - `queryOptions` (optional): React Query options for advanced configuration (e.g. caching, staleTime, retry, etc.).\n *\n * @returns A React Query result object: {@link UseQueryResult} for {@link MoneyMarketAsset} or `undefined` on error or if disabled,\n * including:\n * - `data`: The money market asset (when available) or `undefined`.\n * - `isLoading`: Whether the query is running.\n * - `error`: An error encountered by the query (if any).\n * - `refetch`: Function to manually refetch the asset.\n *\n * @example\n * const { data: asset, isLoading, error } = useBackendMoneyMarketAsset({\n * params: { reserveAddress: '0xabc...' },\n * });\n * if (isLoading) return <div>Loading asset...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (asset) {\n * console.log('Asset symbol:', asset.symbol);\n * console.log('Liquidity rate:', asset.liquidityRate);\n * console.log('Variable borrow rate:', asset.variableBorrowRate);\n * }\n *\n * @remarks\n * - Query is disabled if `params`, `params.params`, or `params.params.reserveAddress` is missing or empty.\n * - Uses React Query for caching and background-state management.\n * - Loading and error handling are managed automatically.\n */\nexport const useBackendMoneyMarketAsset = (\n params: UseBackendMoneyMarketAssetParams | undefined,\n): UseQueryResult<MoneyMarketAsset | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'asset', params?.params?.reserveAddress],\n enabled: !!params?.params?.reserveAddress && params?.params?.reserveAddress.length > 0,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketAsset | undefined> => {\n if (!params?.params?.reserveAddress) {\n return undefined;\n }\n\n return sodax.backendApi.getMoneyMarketAsset(params.params.reserveAddress);\n },\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useMoneyMarketAssetBorrowers.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAssetBorrowers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BackendPaginationParams } from './types';\n\nexport type UseBackendMoneyMarketAssetBorrowersParams = {\n params: {\n reserveAddress: string | undefined;\n };\n pagination: BackendPaginationParams;\n queryOptions?: UseQueryOptions<MoneyMarketAssetBorrowers | undefined, Error>;\n};\n\n/**\n * React hook for fetching borrowers for a specific money market asset from the backend API with pagination.\n *\n * @param {UseBackendMoneyMarketAssetBorrowersParams | undefined} params - Query parameters:\n * - `params`: Object containing:\n * - `reserveAddress`: Reserve contract address for which to fetch borrowers, or `undefined` to disable query.\n * - `pagination`: Pagination controls with `offset` and `limit` (both required as strings).\n * - `queryOptions` (optional): React Query options to override defaults (e.g. `staleTime`, `enabled`, etc.).\n *\n * @returns {UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error>} React Query result object including:\n * - `data`: The money market asset borrowers data, or `undefined` if not available.\n * - `isLoading`: Boolean indicating whether the query is loading.\n * - `error`: An Error instance if the request failed.\n * - `refetch`: Function to manually trigger a data refresh.\n *\n * @example\n * const { data: borrowers, isLoading, error } = useBackendMoneyMarketAssetBorrowers({\n * params: { reserveAddress: '0xabc...' },\n * pagination: { offset: '0', limit: '20' }\n * });\n *\n * if (isLoading) return <div>Loading borrowers...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (borrowers) {\n * console.log('Total borrowers:', borrowers.total);\n * console.log('Borrowers:', borrowers.borrowers);\n * }\n *\n * @remarks\n * - The query is disabled if `reserveAddress`, `offset`, or `limit` are not provided.\n * - Uses React Query for caching, retries, and auto error/loading management.\n * - Pagination is handled via `pagination.offset` and `pagination.limit`.\n */\nexport const useBackendMoneyMarketAssetBorrowers = (\n params: UseBackendMoneyMarketAssetBorrowersParams | undefined,\n): UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'asset', 'borrowers', params],\n enabled: !!params?.params?.reserveAddress && !!params.pagination.offset && !!params.pagination.limit,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketAssetBorrowers | undefined> => {\n if (!params?.params?.reserveAddress || !params.pagination.offset || !params.pagination.limit) {\n return undefined;\n }\n\n return sodax.backendApi.getMoneyMarketAssetBorrowers(params.params.reserveAddress, {\n offset: params.pagination.offset,\n limit: params.pagination.limit,\n });\n },\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useMoneyMarketAssetSuppliers.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAssetSuppliers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BackendPaginationParams } from './types';\n\nexport type UseBackendMoneyMarketAssetSuppliersParams = {\n params: {\n reserveAddress: string | undefined;\n };\n pagination: BackendPaginationParams;\n queryOptions?: UseQueryOptions<MoneyMarketAssetSuppliers | undefined, Error>;\n};\n\n/**\n * React hook for fetching suppliers for a specific money market asset from the backend API, with pagination support.\n *\n * @param {UseBackendMoneyMarketAssetSuppliersParams | undefined} params - Hook parameters:\n * - `params`: Object containing:\n * - `reserveAddress`: The reserve contract address to query, or undefined to disable the query.\n * - `pagination`: Backend pagination controls (`offset` and `limit` as strings).\n * - `queryOptions` (optional): React Query options to override defaults.\n *\n * @returns {UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error>} - Query result object with:\n * - `data`: The asset suppliers data when available.\n * - `isLoading`: Indicates if the request is in progress.\n * - `error`: Error object if the request failed.\n * - `refetch`: Function to trigger a manual data refresh.\n *\n * @example\n * const { data: suppliers, isLoading, error } = useBackendMoneyMarketAssetSuppliers({\n * params: { reserveAddress: '0xabc...' },\n * pagination: { offset: '0', limit: '20' }\n * });\n *\n * if (isLoading) return <div>Loading suppliers...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (suppliers) {\n * console.log('Total suppliers:', suppliers.total);\n * console.log('Suppliers:', suppliers.suppliers);\n * }\n *\n * @remarks\n * - The query is disabled if `reserveAddress`, `offset`, or `limit` are not provided.\n * - Uses React Query for efficient caching, automatic retries, and error/loading handling.\n * - Pagination is handled via `pagination.offset` and `pagination.limit`.\n */\nexport const useBackendMoneyMarketAssetSuppliers = (\n params: UseBackendMoneyMarketAssetSuppliersParams | undefined,\n): UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'asset', 'suppliers', params],\n enabled: !!params?.params?.reserveAddress && !!params.pagination.offset && !!params.pagination.limit,\n retry: 3,\n };\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketAssetSuppliers | undefined> => {\n if (!params?.params?.reserveAddress || !params.pagination.offset || !params.pagination.limit) {\n return undefined;\n }\n\n return sodax.backendApi.getMoneyMarketAssetSuppliers(params.params.reserveAddress, {\n offset: params.pagination.offset,\n limit: params.pagination.limit,\n });\n },\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useAllMoneyMarketBorrowers.ts\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketBorrowers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BackendPaginationParams } from './types';\n\nexport type UseBackendAllMoneyMarketBorrowersParams = {\n pagination: BackendPaginationParams;\n queryOptions?: UseQueryOptions<MoneyMarketBorrowers | undefined, Error>;\n};\n\n/**\n * Hook for fetching all money market borrowers from the backend API.\n *\n * This hook provides access to the list of all borrowers across all money market assets,\n * with pagination support. The data is automatically fetched and cached using React Query.\n *\n * @param {Object} params - Pagination parameters for fetching all borrowers\n * @param {string} params.offset - The offset for pagination (number as string)\n * @param {string} params.limit - The limit for pagination (number as string)\n *\n * @returns {UseQueryResult<MoneyMarketBorrowers | undefined>} A query result object containing:\n * - data: The all borrowers data when available\n * - isLoading: Boolean indicating if the request is in progress\n * - error: Error object if the request failed\n * - refetch: Function to manually trigger a data refresh\n *\n * @example\n * ```typescript\n * const { data: borrowers, isLoading, error } = useAllMoneyMarketBorrowers({\n * offset: '0',\n * limit: '50'\n * });\n *\n * if (isLoading) return <div>Loading borrowers...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (borrowers) {\n * console.log('Total borrowers:', borrowers.total);\n * console.log('Borrowers:', borrowers.borrowers);\n * }\n * ```\n *\n * @remarks\n * - The query is disabled when params are undefined or invalid\n * - Uses React Query for efficient caching and state management\n * - Automatically handles error states and loading indicators\n * - Supports pagination through offset and limit parameters\n * - Returns borrowers across all money market assets\n */\nexport const useBackendAllMoneyMarketBorrowers = (\n params: UseBackendAllMoneyMarketBorrowersParams | undefined,\n): UseQueryResult<MoneyMarketBorrowers | undefined> => {\n const { sodax } = useSodaxContext();\n\n const defaultQueryOptions = {\n queryKey: ['api', 'mm', 'borrowers', 'all', params],\n enabled: !!params && !!params.pagination.offset && !!params.pagination.limit,\n retry: 3,\n };\n\n const queryOptions = {\n ...defaultQueryOptions,\n ...params?.queryOptions,\n };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<MoneyMarketBorrowers | undefined> => {\n if (!params || !params.pagination.offset || !params.pagination.limit) {\n return undefined;\n }\n\n return sodax.backendApi.getAllMoneyMarketBorrowers({\n offset: params.pagination.offset,\n limit: params.pagination.limit,\n });\n },\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { SpokeProvider, CreateBridgeIntentParams } from '@sodax/sdk';\n\n/**\n * Hook for checking token allowance for bridge operations.\n *\n * This hook verifies if the user has approved enough tokens for a specific bridge action.\n * It automatically queries and tracks the allowance status.\n *\n * @param {BridgeParams} params - The parameters for the bridge to check allowance for.\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks\n *\n * @returns {UseQueryResult<boolean, Error>} A React Query result containing:\n * - data: Boolean indicating if allowance is sufficient\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during the check\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useBridgeAllowance(params, spokeProvider);\n * ```\n */\nexport function useBridgeAllowance(\n params: CreateBridgeIntentParams | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['bridge-allowance', params],\n queryFn: async () => {\n if (!spokeProvider || !params) {\n return false;\n }\n\n const allowance = await sodax.bridge.isAllowanceValid({\n params,\n spokeProvider,\n });\n\n if (allowance.ok) {\n return allowance.value;\n }\n return false;\n },\n enabled: !!spokeProvider && !!params,\n });\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type { CreateBridgeIntentParams, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\n\ninterface UseBridgeApproveReturn {\n approve: (params: CreateBridgeIntentParams) => Promise<boolean>;\n isLoading: boolean;\n error: Error | null;\n resetError: () => void;\n}\n\n/**\n * Hook for approving token spending for bridge actions\n * @param spokeProvider The spoke provider instance for the chain\n * @returns Object containing approve function, loading state, error state and reset function\n * @example\n * ```tsx\n * const { approve, isLoading, error } = useBridgeApprove(spokeProvider);\n *\n * // Approve tokens for bridge action\n * await approve({\n * srcChainId: '0x2105.base',\n * srcAsset: '0x...',\n * amount: 1000n,\n * dstChainId: '0x89.polygon',\n * dstAsset: '0x...',\n * recipient: '0x...'\n * });\n * ```\n */\nexport function useBridgeApprove(spokeProvider: SpokeProvider | undefined): UseBridgeApproveReturn {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n const {\n mutateAsync: approve,\n isPending,\n error,\n reset: resetError,\n } = useMutation({\n mutationFn: async (params: CreateBridgeIntentParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const allowance = await sodax.bridge.approve({\n params,\n spokeProvider,\n });\n\n if (!allowance.ok) {\n throw new Error('Failed to approve tokens for bridge');\n }\n return true;\n },\n onSuccess: (_, params) => {\n // Invalidate allowance query to refetch the new allowance\n queryClient.invalidateQueries({ queryKey: ['bridge-allowance', params] });\n },\n });\n\n return {\n approve,\n isLoading: isPending,\n error: error,\n resetError,\n };\n}\n","import { useSodaxContext } from '../shared/useSodaxContext';\nimport type {\n BridgeError,\n BridgeErrorCode,\n SpokeTxHash,\n HubTxHash,\n Result,\n CreateBridgeIntentParams,\n} from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider } from '@sodax/sdk';\n\n/**\n * Hook for executing bridge transactions to transfer tokens between chains.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for the bridge\n * @returns {UseMutationResult} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: bridge, isPending } = useBridge(spokeProvider);\n *\n * const handleBridge = async () => {\n * const result = await bridge({\n * srcChainId: '0x2105.base',\n * srcAsset: '0x...',\n * amount: 1000n,\n * dstChainId: '0x89.polygon',\n * dstAsset: '0x...',\n * recipient: '0x...'\n * });\n *\n * console.log('Bridge transaction hashes:', {\n * spokeTxHash: result.spokeTxHash,\n * hubTxHash: result.hubTxHash\n * });\n * };\n * ```\n */\nexport function useBridge(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<Result<[SpokeTxHash, HubTxHash], BridgeError<BridgeErrorCode>>, Error, CreateBridgeIntentParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation<Result<[SpokeTxHash, HubTxHash], BridgeError<BridgeErrorCode>>, Error, CreateBridgeIntentParams>({\n mutationFn: async (params: CreateBridgeIntentParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.bridge.bridge({\n params,\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Bridge failed: ${result.error.code}`);\n }\n\n return result;\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { BridgeLimit, XToken } from '@sodax/sdk';\n\n/**\n * Hook for getting the amount available to be bridged.\n *\n * This hook is used to check if a target chain has enough balance to bridge when bridging.\n * It automatically queries and tracks the available amount to be bridged.\n *\n * @param {SpokeChainId | undefined} chainId - The chain ID to get the balance for\n * @param {string | undefined} token - The token address to get the balance for\n *\n * @returns {UseQueryResult<BridgeLimit, Error>} A React Query result containing:\n * - data: Data about available amount to be bridged\n * - error: Any error that occurred during the check\n *\n * @example\n * ```typescript\n * const { data: balance, isLoading } = useSpokeAssetManagerTokenBalance(chainId, tokenAddress);\n *\n * if (balance) {\n * console.log('Asset manager token balance:', balance.toString());\n * }\n * ```\n */\nexport function useGetBridgeableAmount(\n from: XToken | undefined,\n to: XToken | undefined,\n): UseQueryResult<BridgeLimit, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['spoke-asset-manager-token-balance', from, to],\n queryFn: async () => {\n if (!from || !to) {\n return { amount: 0n, decimals: 0, type: 'DEPOSIT_LIMIT' } as const;\n }\n\n const result = await sodax.bridge.getBridgeableAmount(from, to);\n\n if (result.ok) {\n return result.value;\n }\n\n console.error('Error getting bridgeable amount:', result.error);\n return { amount: 0n, decimals: 0, type: 'DEPOSIT_LIMIT' } as const;\n },\n enabled: !!from && !!to,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { XToken, SpokeChainId } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared';\n\n/**\n/**\n * Hook for retrieving all bridgeable tokens from a source token on one chain to a destination chain.\n *\n * This hook queries and tracks the set of tokens on the destination chain that can be bridged to,\n * given a source chain, destination chain, and source token address.\n *\n * @param {SpokeChainId | undefined} from - The source chain ID\n * @param {SpokeChainId | undefined} to - The destination chain ID\n * @param {string | undefined} token - The source token address\n *\n * @returns {UseQueryResult<XToken[], Error>} A React Query result containing:\n * - data: Array of bridgeable tokens (XToken[]) on the destination chain\n * - error: Any error that occurred during the query\n *\n *\n * @example\n * ```typescript\n * const { data: bridgeableTokens, isLoading } = useGetBridgeableTokens(\n * fromChainId,\n * toChainId,\n * fromTokenAddress\n * );\n *\n * if (bridgeableTokens && bridgeableTokens.length > 0) {\n * bridgeableTokens.forEach(token => {\n * console.log(`Bridgeable token: ${token.symbol} (${token.address}) on chain ${token.xChainId}`);\n * });\n * } else {\n * console.log('No bridgeable tokens found for the selected route.');\n * }\n * ```\n */\nexport function useGetBridgeableTokens(\n from: SpokeChainId | undefined,\n to: SpokeChainId | undefined,\n token: string | undefined,\n): UseQueryResult<XToken[], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['bridgeable-tokens', from, to, token],\n queryFn: async () => {\n if (!from || !to || !token) {\n return [];\n }\n\n const result = sodax.bridge.getBridgeableTokens(from, to, token);\n if (result.ok) {\n return result.value;\n }\n\n console.error('Error getting bridgeable tokens:', result.error);\n return [];\n },\n enabled: !!from && !!to && !!token,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStake.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { StakeParams, SpokeTxHash, HubTxHash, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook for executing stake transactions to stake SODA tokens and receive xSODA shares.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the stake\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, StakeParams>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: stake, isPending } = useStake(spokeProvider);\n *\n * const handleStake = async () => {\n * const result = await stake({\n * amount: 1000000000000000000n, // 1 SODA\n * account: '0x...'\n * });\n *\n * console.log('Stake successful:', result);\n * };\n * ```\n */\nexport function useStake(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<[SpokeTxHash, HubTxHash], Error, StakeParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation<[SpokeTxHash, HubTxHash], Error, StakeParams>({\n mutationFn: async (params: StakeParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.stake(params, spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Stake failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeApprove.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { StakeParams, TxReturnType, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook for approving SODA token spending for staking operations.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval\n * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<StakeParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: approve, isPending } = useStakeApprove(spokeProvider);\n *\n * const handleApprove = async () => {\n * const result = await approve({\n * amount: 1000000000000000000n, // 1 SODA\n * account: '0x...'\n * });\n *\n * console.log('Approval successful:', result);\n * };\n * ```\n */\nexport function useStakeApprove(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<StakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n\n return useMutation<TxReturnType<SpokeProvider, false>, Error, Omit<StakeParams, 'action'>>({\n mutationFn: async (params: Omit<StakeParams, 'action'>) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.approve({\n params: { ...params, action: 'stake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Stake approval failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeAllowance.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { StakeParams, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for checking SODA token allowance for staking operations.\n * Uses React Query for efficient caching and state management.\n *\n * @param {Omit<StakeParams, 'action'> | undefined} params - The staking parameters. If undefined, the query will be disabled.\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check\n * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useStakeAllowance(\n * {\n * amount: 1000000000000000000n, // 1 SODA\n * account: '0x...'\n * },\n * spokeProvider\n * );\n *\n * if (isLoading) return <div>Checking allowance...</div>;\n * if (hasAllowed) {\n * console.log('Sufficient allowance for staking');\n * }\n * ```\n */\nexport function useStakeAllowance(\n params: Omit<StakeParams, 'action'> | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'stakeAllowance', params, spokeProvider?.chainConfig.chain.id],\n queryFn: async () => {\n if (!params || !spokeProvider) {\n return false;\n }\n\n const result = await sodax.staking.isAllowanceValid({\n params: { ...params, action: 'stake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Allowance check failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!params && !!spokeProvider,\n refetchInterval: 5000, // Refetch every 5 seconds\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useUnstake.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { UnstakeParams, SpokeTxHash, HubTxHash, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook for executing unstake transactions to unstake xSODA shares.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the unstake\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<UnstakeParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: unstake, isPending } = useUnstake(spokeProvider);\n *\n * const handleUnstake = async () => {\n * const result = await unstake({\n * amount: 1000000000000000000n, // 1 xSODA\n * account: '0x...'\n * });\n *\n * console.log('Unstake successful:', result);\n * };\n * ```\n */\nexport function useUnstake(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<UnstakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation<[SpokeTxHash, HubTxHash], Error, Omit<UnstakeParams, 'action'>>({\n mutationFn: async (params: Omit<UnstakeParams, 'action'>) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.unstake({ ...params, action: 'unstake' }, spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Unstake failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n onSuccess: () => {\n // Invalidate relevant queries to refresh data\n queryClient.invalidateQueries({ queryKey: ['stakingInfo'] });\n queryClient.invalidateQueries({ queryKey: ['unstakingInfo'] });\n queryClient.invalidateQueries({ queryKey: ['unstakingInfoWithPenalty'] });\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useClaim.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { ClaimParams, SpokeTxHash, HubTxHash, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook for executing claim transactions to claim unstaked SODA tokens after the unstaking period.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the claim\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<ClaimParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: claim, isPending } = useClaim(spokeProvider);\n *\n * const handleClaim = async () => {\n * const result = await claim({\n * requestId: 1n\n * });\n *\n * console.log('Claim successful:', result);\n * };\n * ```\n */\nexport function useClaim(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<ClaimParams, 'action'>> {\n const { sodax } = useSodaxContext();\n\n return useMutation<[SpokeTxHash, HubTxHash], Error, Omit<ClaimParams, 'action'>>({\n mutationFn: async (params: Omit<ClaimParams, 'action'>) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.claim({ ...params, action: 'claim' }, spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Claim failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useCancelUnstake.ts\nimport { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { CancelUnstakeParams, SpokeProvider, SpokeTxHash, HubTxHash } from '@sodax/sdk';\n\n/**\n * Hook for executing cancel unstake transactions to cancel pending unstake requests.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the cancel unstake\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<CancelUnstakeParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: cancelUnstake, isPending } = useCancelUnstake(spokeProvider);\n *\n * const handleCancelUnstake = async () => {\n * const result = await cancelUnstake({\n * requestId: 1n\n * });\n *\n * console.log('Cancel unstake successful:', result);\n * };\n * ```\n */\nexport function useCancelUnstake(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<[SpokeTxHash, HubTxHash], Error, Omit<CancelUnstakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async (params: Omit<CancelUnstakeParams, 'action'>) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not available');\n }\n\n const result = await sodax.staking.cancelUnstake({ ...params, action: 'cancelUnstake' }, spokeProvider);\n if (!result.ok) {\n throw new Error(`Cancel unstake failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n onSuccess: () => {\n // Invalidate relevant queries to refresh data\n queryClient.invalidateQueries({ queryKey: ['stakingInfo'] });\n queryClient.invalidateQueries({ queryKey: ['unstakingInfo'] });\n queryClient.invalidateQueries({ queryKey: ['unstakingInfoWithPenalty'] });\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakingInfo.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { StakingInfo, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching comprehensive staking information for a user.\n * Uses React Query for efficient caching and state management.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the query\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)\n * @returns {UseQueryResult<StakingInfo, Error>} Query result object containing staking info and state\n *\n * @example\n * ```typescript\n * const { data: stakingInfo, isLoading, error } = useStakingInfo(spokeProvider);\n *\n * if (isLoading) return <div>Loading staking info...</div>;\n * if (stakingInfo) {\n * console.log('Total staked:', stakingInfo.totalStaked);\n * console.log('User staked:', stakingInfo.userStaked);\n * console.log('xSODA balance:', stakingInfo.userXSodaBalance);\n * }\n * ```\n */\nexport function useStakingInfo(\n spokeProvider: SpokeProvider | undefined,\n refetchInterval = 5000,\n): UseQueryResult<StakingInfo, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'stakingInfo', spokeProvider?.chainConfig.chain.id],\n queryFn: async () => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.getStakingInfoFromSpoke(spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Failed to fetch staking info: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!spokeProvider,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useUnstakingInfoWithPenalty.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { UnstakingInfo, UnstakeRequestWithPenalty, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\nexport type UnstakingInfoWithPenalty = UnstakingInfo & {\n requestsWithPenalty: UnstakeRequestWithPenalty[];\n};\n\n/**\n * Hook for fetching unstaking information with penalty calculations from the stakedSoda contract.\n * Uses React Query for efficient caching and state management.\n *\n * @param {string | undefined} userAddress - The user address to fetch unstaking info for\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)\n * @returns {UseQueryResult<UnstakingInfoWithPenalty, Error>} Query result object containing unstaking info with penalties and state\n *\n * @example\n * ```typescript\n * const { data: unstakingInfo, isLoading, error } = useUnstakingInfoWithPenalty(userAddress, spokeProvider);\n *\n * if (isLoading) return <div>Loading unstaking info...</div>;\n * if (unstakingInfo) {\n * console.log('Total unstaking:', unstakingInfo.totalUnstaking);\n * unstakingInfo.requestsWithPenalty.forEach(request => {\n * console.log('Penalty:', request.penaltyPercentage + '%');\n * console.log('Claimable amount:', request.claimableAmount);\n * });\n * }\n * ```\n */\nexport function useUnstakingInfoWithPenalty(\n userAddress: string | undefined,\n spokeProvider: SpokeProvider | undefined,\n refetchInterval = 5000,\n): UseQueryResult<UnstakingInfoWithPenalty, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'unstakingInfoWithPenalty', spokeProvider?.chainConfig.chain.id, userAddress],\n queryFn: async () => {\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n // Get unstaking info with penalty calculations\n const penaltyResult = await sodax.staking.getUnstakingInfoWithPenalty(spokeProvider);\n\n if (!penaltyResult.ok) {\n throw new Error(`Failed to fetch unstaking info with penalty: ${penaltyResult.error.code}`);\n }\n\n return penaltyResult.value;\n },\n enabled: !!spokeProvider && !!userAddress,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakingConfig.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { StakingConfig } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching staking configuration from the stakedSoda contract.\n * Uses React Query for efficient caching and state management.\n *\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 30000)\n * @returns {UseQueryResult<StakingConfig, Error>} Query result object containing staking config and state\n *\n * @example\n * ```typescript\n * const { data: stakingConfig, isLoading, error } = useStakingConfig();\n *\n * if (isLoading) return <div>Loading staking config...</div>;\n * if (stakingConfig) {\n * console.log('Unstaking period (days):', stakingConfig.unstakingPeriod / 86400n);\n * console.log('Max penalty (%):', stakingConfig.maxPenalty);\n * }\n * ```\n */\nexport function useStakingConfig(refetchInterval = 30000): UseQueryResult<StakingConfig, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'stakingConfig'],\n queryFn: async () => {\n const result = await sodax.staking.getStakingConfig();\n\n if (!result.ok) {\n throw new Error(`Failed to fetch staking config: ${result.error.code}`);\n }\n\n return result.value;\n },\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeRatio.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching stake ratio estimates (xSoda amount and preview deposit).\n * Uses React Query for efficient caching and state management.\n *\n * @param {bigint | undefined} amount - The amount of SODA to estimate stake for\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)\n * @returns {UseQueryResult<[bigint, bigint], Error>} Query result object containing stake ratio estimates and state\n *\n * @example\n * ```typescript\n * const { data: stakeRatio, isLoading, error } = useStakeRatio(1000000000000000000n); // 1 SODA\n *\n * if (isLoading) return <div>Loading stake ratio...</div>;\n * if (stakeRatio) {\n * const [xSodaAmount, previewDepositAmount] = stakeRatio;\n * console.log('xSoda amount:', xSodaAmount);\n * console.log('Preview deposit:', previewDepositAmount);\n * }\n * ```\n */\nexport function useStakeRatio(\n amount: bigint | undefined,\n refetchInterval = 10000,\n): UseQueryResult<[bigint, bigint], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'stakeRatio', amount?.toString()],\n queryFn: async () => {\n if (!amount || amount <= 0n) {\n throw new Error('Amount must be greater than 0');\n }\n\n if (!sodax?.staking) {\n throw new Error('Staking service not available');\n }\n\n const result = await sodax.staking.getStakeRatio(amount);\n\n if (!result.ok) {\n throw new Error(`Failed to fetch stake ratio: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!amount && amount > 0n && !!sodax?.staking,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useInstantUnstakeRatio.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching instant unstake ratio estimates.\n * Uses React Query for efficient caching and state management.\n *\n * @param {bigint | undefined} amount - The amount of xSoda to estimate instant unstake for\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)\n * @returns {UseQueryResult<bigint, Error>} Query result object containing instant unstake ratio and state\n *\n * @example\n * ```typescript\n * const { data: instantUnstakeRatio, isLoading, error } = useInstantUnstakeRatio(1000000000000000000n); // 1 xSoda\n *\n * if (isLoading) return <div>Loading instant unstake ratio...</div>;\n * if (instantUnstakeRatio) {\n * console.log('Instant unstake ratio:', instantUnstakeRatio);\n * }\n * ```\n */\nexport function useInstantUnstakeRatio(\n amount: bigint | undefined,\n refetchInterval = 10000,\n): UseQueryResult<bigint, Error> {\n const { sodax } = useSodaxContext();\n\n console.log('useInstantUnstakeRatio hook called with:', { amount: amount?.toString(), sodax: !!sodax });\n\n return useQuery({\n queryKey: ['soda', 'instantUnstakeRatio', amount?.toString()],\n queryFn: async () => {\n console.log('useInstantUnstakeRatio queryFn called with amount:', amount?.toString());\n if (!amount || amount <= 0n) {\n throw new Error('Amount must be greater than 0');\n }\n\n if (!sodax?.staking) {\n throw new Error('Staking service not available');\n }\n\n const result = await sodax.staking.getInstantUnstakeRatio(amount);\n\n if (!result.ok) {\n throw new Error(`Failed to fetch instant unstake ratio: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!amount && amount > 0n && !!sodax?.staking,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useConvertedAssets.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching converted assets amount for xSODA shares.\n * Uses React Query for efficient caching and state management.\n *\n * @param {bigint | undefined} amount - The amount of xSODA shares to convert\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 10000)\n * @returns {UseQueryResult<bigint, Error>} Query result object containing converted assets amount and state\n *\n * @example\n * ```typescript\n * const { data: convertedAssets, isLoading, error } = useConvertedAssets(1000000000000000000n); // 1 xSODA\n *\n * if (isLoading) return <div>Loading converted assets...</div>;\n * if (convertedAssets) {\n * console.log('Converted assets:', convertedAssets);\n * }\n * ```\n */\nexport function useConvertedAssets(amount: bigint | undefined, refetchInterval = 10000): UseQueryResult<bigint, Error> {\n const { sodax } = useSodaxContext();\n\n // console.log('useConvertedAssets hook called with:', { amount: amount?.toString(), sodax: !!sodax });\n\n return useQuery({\n queryKey: ['soda', 'convertedAssets', amount?.toString()],\n queryFn: async () => {\n // console.log('useConvertedAssets queryFn called with amount:', amount?.toString());\n if (!amount || amount <= 0n) {\n throw new Error('Amount must be greater than 0');\n }\n\n const result = await sodax.staking.getConvertedAssets(amount);\n\n if (!result.ok) {\n throw new Error(`Failed to fetch converted assets: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!amount && amount > 0n && !!sodax?.staking,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useInstantUnstake.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider, InstantUnstakeParams } from '@sodax/sdk';\n\n/**\n * Hook for executing instant unstake operations.\n * Uses React Query for efficient state management and error handling.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider for the transaction\n * @returns {UseMutationResult<[string, string], Error, Omit<InstantUnstakeParams, 'action'>>} Mutation result object containing instant unstake state and methods\n *\n * @example\n * ```typescript\n * const { mutateAsync: instantUnstake, isPending } = useInstantUnstake(spokeProvider);\n *\n * const handleInstantUnstake = async () => {\n * const result = await instantUnstake({\n * amount: 1000000000000000000n,\n * minAmount: 950000000000000000n,\n * account: '0x...'\n * });\n * console.log('Instant unstake successful:', result);\n * };\n * ```\n */\nexport function useInstantUnstake(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<[string, string], Error, Omit<InstantUnstakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n\n return useMutation({\n mutationFn: async (params: Omit<InstantUnstakeParams, 'action'>) => {\n if (!spokeProvider) {\n throw new Error('spokeProvider is not found');\n }\n\n const result = await sodax.staking.instantUnstake({ ...params, action: 'instantUnstake' }, spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Instant unstake failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n onError: error => {\n console.error('Instant unstake error:', error);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeAllowance.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { UnstakeParams, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for checking xSODA token allowance for unstaking operations.\n * Uses React Query for efficient caching and state management.\n *\n * @param {Omit<UnstakeParams, 'action'> | undefined} params - The unstaking parameters. If undefined, the query will be disabled.\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check\n * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useUnstakeAllowance(\n * {\n * amount: 1000000000000000000n, // 1 xSODA\n * account: '0x...'\n * },\n * spokeProvider\n * );\n *\n * if (isLoading) return <div>Checking allowance...</div>;\n * if (hasAllowed) {\n * console.log('Sufficient allowance for unstaking');\n * }\n * ```\n */\nexport function useUnstakeAllowance(\n params: Omit<UnstakeParams, 'action'> | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'unstakeAllowance', params, spokeProvider?.chainConfig.chain.id],\n queryFn: async () => {\n if (!params || !spokeProvider) {\n return false;\n }\n\n const result = await sodax.staking.isAllowanceValid({\n params: { ...params, action: 'unstake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n console.error(`Unstake allowance check failed: ${result.error.code}, error: ${result.error.error}`);\n throw new Error(`Unstake allowance check failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!params && !!spokeProvider,\n refetchInterval: 5000, // Refetch every 5 seconds\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeApprove.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { TxReturnType, UnstakeParams } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider } from '@sodax/sdk';\n\n/**\n * Hook for approving xSODA token spending for unstaking operations.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval\n * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: approve, isPending } = useUnstakeApprove(spokeProvider);\n *\n * const handleApprove = async () => {\n * const result = await approve({\n * amount: 1000000000000000000n, // 1 xSODA\n * account: '0x...'\n * });\n *\n * console.log('Approval successful:', result);\n * };\n * ```\n */\nexport function useUnstakeApprove(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n\n return useMutation<TxReturnType<SpokeProvider, false>, Error, Omit<UnstakeParams, 'action'>>({\n mutationFn: async (params: Omit<UnstakeParams, 'action'>) => {\n console.log('useUnstakeApprove called with params:', params);\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.approve({\n params: { ...params, action: 'unstake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Unstake approval failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useUnstakingInfoWithPenalty.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { UnstakingInfo, SpokeProvider } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for fetching unstaking information from the stakedSoda contract.\n * Uses React Query for efficient caching and state management.\n *\n * @param {string | undefined} userAddress - The user address to fetch unstaking info for\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider instance\n * @param {number} refetchInterval - The interval in milliseconds to refetch data (default: 5000)\n * @returns {UseQueryResult<UnstakingInfo, Error>} Query result object containing unstaking info and state\n *\n * @example\n * ```typescript\n * const { data: unstakingInfo, isLoading, error } = useUnstakingInfo(userAddress, spokeProvider);\n *\n * if (isLoading) return <div>Loading unstaking info...</div>;\n * if (unstakingInfo) {\n * console.log('Total unstaking:', unstakingInfo.totalUnstaking);\n * unstakingInfo.userUnstakeSodaRequests.forEach(request => {\n * console.log('Request amount:', request.request.amount);\n * });\n * }\n * ```\n */\nexport function useUnstakingInfo(\n userAddress: string | undefined,\n spokeProvider: SpokeProvider | undefined,\n refetchInterval = 5000,\n): UseQueryResult<UnstakingInfo, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'unstakingInfoWithPenalty', spokeProvider?.chainConfig.chain.id, userAddress],\n queryFn: async () => {\n if (!spokeProvider || !userAddress) {\n throw new Error('Spoke provider or user address not found');\n }\n\n const result = await sodax.staking.getUnstakingInfo(spokeProvider);\n\n if (!result.ok) {\n throw new Error(`Failed to fetch unstaking info: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!spokeProvider && !!userAddress,\n refetchInterval,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeApprove.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { InstantUnstakeParams, TxReturnType, SpokeProvider } from '@sodax/sdk';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\n\n/**\n * Hook for approving xSODA token spending for instant unstaking operations.\n * Uses React Query's useMutation for better state management and caching.\n *\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the approval\n * @returns {UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<InstantUnstakeParams, 'action'>>} Mutation result object containing mutation function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: approve, isPending } = useInstantUnstakeApprove(spokeProvider);\n *\n * const handleApprove = async () => {\n * const result = await approve({\n * amount: 1000000000000000000n, // 1 xSODA\n * minAmount: 950000000000000000n, // 0.95 SODA\n * account: '0x...'\n * });\n *\n * console.log('Approval successful:', result);\n * };\n * ```\n */\nexport function useInstantUnstakeApprove(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<TxReturnType<SpokeProvider, false>, Error, Omit<InstantUnstakeParams, 'action'>> {\n const { sodax } = useSodaxContext();\n\n return useMutation<TxReturnType<SpokeProvider, false>, Error, Omit<InstantUnstakeParams, 'action'>>({\n mutationFn: async (params: Omit<InstantUnstakeParams, 'action'>) => {\n console.log('useInstantUnstakeApprove called with params:', params);\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n const result = await sodax.staking.approve({\n params: { ...params, action: 'instantUnstake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Instant unstake approval failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeAllowance.ts\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { SpokeProvider, InstantUnstakeParams } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\n/**\n * Hook for checking xSODA token allowance for instant unstaking operations.\n * Uses React Query for efficient caching and state management.\n *\n * @param {Omit<InstantUnstakeParams, 'action'> | undefined} params - The instant unstaking parameters. If undefined, the query will be disabled.\n * @param {SpokeProvider | undefined} spokeProvider - The spoke provider to use for the allowance check\n * @returns {UseQueryResult<boolean, Error>} Query result object containing allowance data and state\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useInstantUnstakeAllowance(\n * {\n * amount: 1000000000000000000n, // 1 xSODA\n * minAmount: 950000000000000000n, // 0.95 SODA\n * account: '0x...'\n * },\n * spokeProvider\n * );\n *\n * if (isLoading) return <div>Checking allowance...</div>;\n * if (hasAllowed) {\n * console.log('Sufficient allowance for instant unstaking');\n * }\n * ```\n */\nexport function useInstantUnstakeAllowance(\n params: Omit<InstantUnstakeParams, 'action'> | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['soda', 'instantUnstakeAllowance', params, spokeProvider?.chainConfig.chain.id],\n queryFn: async () => {\n if (!params || !spokeProvider) {\n return false;\n }\n\n const result = await sodax.staking.isAllowanceValid({\n params: { ...params, action: 'instantUnstake' },\n spokeProvider,\n });\n\n if (!result.ok) {\n console.error(`Unstake allowance check failed: ${result.error.code}, error: ${result.error.error}`);\n throw new Error(`Unstake allowance check failed: ${result.error.code}`);\n }\n\n return result.value;\n },\n enabled: !!params && !!spokeProvider,\n refetchInterval: 5000, // Refetch every 5 seconds\n });\n}\n","import type { XToken } from '@sodax/types';\n\nexport const MIGRATION_MODE_ICX_SODA = 'icxsoda';\nexport const MIGRATION_MODE_BNUSD = 'bnusd';\n\nexport type MigrationMode = typeof MIGRATION_MODE_ICX_SODA | typeof MIGRATION_MODE_BNUSD;\n\nexport interface MigrationIntentParams {\n token: XToken | undefined;\n amount: string | undefined;\n sourceAddress: string | undefined;\n migrationMode?: MigrationMode;\n toToken?: XToken;\n destinationAddress?: string;\n}\n","import { parseUnits } from 'viem';\nimport {\n spokeChainConfig,\n type UnifiedBnUSDMigrateParams,\n type IconSpokeProvider,\n type SonicSpokeProvider,\n isLegacybnUSDToken,\n type SpokeProvider,\n} from '@sodax/sdk';\nimport { type ChainId, ICON_MAINNET_CHAIN_ID } from '@sodax/types';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, type UseMutationResult } from '@tanstack/react-query';\nimport { MIGRATION_MODE_BNUSD, MIGRATION_MODE_ICX_SODA, type MigrationIntentParams } from './types';\n\n/**\n * Hook for executing migration operations between chains.\n *\n * This hook handles ICX/SODA and bnUSD migrations by accepting a spoke provider\n * and returning a mutation function that accepts migration parameters.\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for the migration\n * @returns {UseMutationResult} Mutation result object containing migration function and state\n *\n * @example\n * ```typescript\n * const { mutateAsync: migrate, isPending } = useMigrate(spokeProvider);\n *\n * const result = await migrate({\n * token: { address: \"0x...\", decimals: 18 },\n * amount: \"100\",\n * migrationMode: MIGRATION_MODE_ICX_SODA,\n * toToken: { address: \"0x...\", decimals: 18 },\n * destinationAddress: \"0x...\"\n * });\n * ```\n */\nexport function useMigrate(\n spokeProvider: SpokeProvider | undefined,\n): UseMutationResult<{ spokeTxHash: string; hubTxHash: `0x${string}` }, Error, MigrationIntentParams> {\n const { sodax } = useSodaxContext();\n\n return useMutation({\n mutationFn: async (params: MigrationIntentParams) => {\n const { token, amount, migrationMode = MIGRATION_MODE_ICX_SODA, toToken, destinationAddress } = params;\n const amountToMigrate = parseUnits(amount ?? '0', token?.decimals ?? 0);\n\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n\n if (migrationMode === MIGRATION_MODE_ICX_SODA) {\n // ICX->SODA migration logic\n if (token?.xChainId === ICON_MAINNET_CHAIN_ID) {\n const params = {\n address: spokeChainConfig[ICON_MAINNET_CHAIN_ID].nativeToken,\n amount: amountToMigrate,\n to: destinationAddress as `0x${string}`,\n };\n const result = await sodax.migration.migrateIcxToSoda(params, spokeProvider as IconSpokeProvider, 30000);\n if (result.ok) {\n const [spokeTxHash, hubTxHash] = result.value;\n return { spokeTxHash, hubTxHash };\n }\n throw new Error('ICX to SODA migration failed. Please try again.');\n }\n\n // SODA->ICX migration\n const revertParams = {\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}`,\n };\n const result = await sodax.migration.revertMigrateSodaToIcx(\n revertParams,\n spokeProvider as SonicSpokeProvider,\n 30000,\n );\n if (result.ok) {\n const [hubTxHash, spokeTxHash] = result.value;\n return { spokeTxHash, hubTxHash };\n }\n throw new Error('SODA to ICX migration failed. Please try again.');\n }\n\n if (migrationMode === MIGRATION_MODE_BNUSD) {\n // bnUSD migration logic - handle dynamic source/destination chains\n const params = {\n srcChainId: token?.xChainId as ChainId,\n dstChainId: toToken?.xChainId as ChainId,\n srcbnUSD: token?.address as string,\n dstbnUSD: toToken?.address as string,\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}` | `0x${string}`,\n } satisfies UnifiedBnUSDMigrateParams;\n\n const result = await sodax.migration.migratebnUSD(params, spokeProvider, 30000);\n if (result.ok) {\n const [spokeTxHash, hubTxHash] = result.value;\n return { spokeTxHash, hubTxHash };\n }\n\n const errorMessage = isLegacybnUSDToken(token?.address as string)\n ? 'bnUSD migration failed. Please try again.'\n : 'bnUSD reverse migration failed. Please try again.';\n throw new Error(errorMessage);\n }\n\n throw new Error('Invalid migration mode');\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { ChainId } from '@sodax/types';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { parseUnits } from 'viem';\nimport type { IcxCreateRevertMigrationParams, UnifiedBnUSDMigrateParams, SpokeProvider } from '@sodax/sdk';\nimport { ICON_MAINNET_CHAIN_ID } from '@sodax/types';\nimport { MIGRATION_MODE_ICX_SODA, type MigrationIntentParams } from './types';\n\n/**\n * Hook for checking token allowance for migration operations.\n *\n * This hook verifies if the user has approved enough tokens for migration operations.\n * It handles both ICX/SODA and bnUSD migration allowance checks.\n *\n * @param {MigrationIntentParams} params - The parameters for the migration allowance check\n * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks\n *\n * @returns {UseQueryResult<boolean, Error>} A React Query result containing:\n * - data: Boolean indicating if allowance is sufficient\n * - isLoading: Loading state indicator\n * - error: Any error that occurred during the check\n *\n * @example\n * ```typescript\n * const { data: hasAllowed, isLoading } = useMigrationAllowance(params, spokeProvider);\n * ```\n */\nexport function useMigrationAllowance(\n params: MigrationIntentParams | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['migration-allowance', params],\n queryFn: async () => {\n if (!spokeProvider || !params) {\n return false;\n }\n\n const { token, amount, migrationMode = MIGRATION_MODE_ICX_SODA, toToken, destinationAddress } = params;\n\n // For ICON chain, no allowance is required (forward migrations)\n if (token?.xChainId === ICON_MAINNET_CHAIN_ID) {\n return true;\n }\n\n if (!spokeProvider) throw new Error('Spoke provider is required');\n const amountToMigrate = parseUnits(amount ?? '0', token?.decimals ?? 0);\n\n let migrationParams: IcxCreateRevertMigrationParams | UnifiedBnUSDMigrateParams;\n if (migrationMode === MIGRATION_MODE_ICX_SODA) {\n migrationParams = {\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}`,\n } satisfies IcxCreateRevertMigrationParams;\n } else {\n if (!toToken) throw new Error('Destination token is required for bnUSD migration');\n\n migrationParams = {\n srcChainId: token?.xChainId as ChainId,\n dstChainId: toToken?.xChainId as ChainId,\n srcbnUSD: token?.address as string,\n dstbnUSD: toToken?.address as string,\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}` | `0x${string}`,\n } satisfies UnifiedBnUSDMigrateParams;\n }\n\n const allowance = await sodax.migration.isAllowanceValid(migrationParams, 'revert', spokeProvider);\n if (allowance.ok) {\n return allowance.value;\n }\n return false;\n },\n enabled: !!spokeProvider && !!params,\n refetchInterval: 2000,\n });\n}\n","import { parseUnits } from 'viem';\nimport { useCallback, useState, useRef, useEffect } from 'react';\nimport type {\n IcxCreateRevertMigrationParams,\n UnifiedBnUSDMigrateParams,\n SpokeProvider,\n Result,\n ChainId,\n} from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { MIGRATION_MODE_BNUSD, MIGRATION_MODE_ICX_SODA, type MigrationIntentParams } from './types';\nimport { useQueryClient } from '@tanstack/react-query';\n\ninterface UseApproveReturn {\n approve: ({ params }: { params: MigrationIntentParams }) => Promise<boolean>;\n isLoading: boolean;\n error: Error | null;\n resetError: () => void;\n isApproved: boolean;\n}\n\n/**\n * Hook for approving token spending for migration actions\n * @param params The parameters for the migration approval\n * @param spokeProvider The spoke provider instance for the chain\n * @returns Object containing approve function, loading state, error state and reset function\n * @example\n * ```tsx\n * const { approve, isLoading, error } = useMigrationApprove(params, spokeProvider);\n *\n * // Approve tokens for migration\n * await approve({ params });\n * ```\n */\n\nexport function useMigrationApprove(\n params: MigrationIntentParams | undefined,\n spokeProvider: SpokeProvider | undefined,\n): UseApproveReturn {\n const { sodax } = useSodaxContext();\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [isApproved, setIsApproved] = useState(false);\n const queryClient = useQueryClient();\n\n // Track previous values to reset approval state when needed\n const prevTokenAddress = useRef<string | undefined>(undefined);\n const prevAmount = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n if (prevTokenAddress.current !== params?.token?.address || prevAmount.current !== params?.amount) {\n setIsApproved(false);\n prevTokenAddress.current = params?.token?.address;\n prevAmount.current = params?.amount;\n }\n }, [params?.token?.address, params?.amount]);\n\n const approve = useCallback(\n async ({ params: approveParams }: { params: MigrationIntentParams }) => {\n try {\n setIsLoading(true);\n setError(null);\n\n if (!spokeProvider) {\n throw new Error('Spoke provider not found');\n }\n if (!approveParams) {\n throw new Error('Migration intent not found');\n }\n\n const { token, amount, migrationMode = MIGRATION_MODE_ICX_SODA, toToken, destinationAddress } = approveParams;\n const amountToMigrate = parseUnits(amount ?? '0', token?.decimals ?? 0);\n\n let result: Result<string, unknown>;\n if (migrationMode === MIGRATION_MODE_ICX_SODA) {\n // ICX/SODA migration approval\n const revertParams = {\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}`,\n } satisfies IcxCreateRevertMigrationParams;\n\n result = await sodax.migration.approve(revertParams, 'revert', spokeProvider, false);\n } else if (migrationMode === MIGRATION_MODE_BNUSD) {\n // bnUSD migration approval\n if (!toToken) throw new Error('Destination token is required for bnUSD migration');\n\n const migrationParams = {\n srcChainId: token?.xChainId as ChainId,\n dstChainId: toToken?.xChainId as ChainId,\n srcbnUSD: token?.address as string,\n dstbnUSD: toToken?.address as string,\n amount: amountToMigrate,\n to: destinationAddress as `hx${string}` | `0x${string}`,\n } satisfies UnifiedBnUSDMigrateParams;\n\n result = await sodax.migration.approve(migrationParams, 'revert', spokeProvider, false);\n } else {\n throw new Error('Invalid migration mode');\n }\n if (!result.ok) {\n throw new Error('Failed to approve tokens');\n }\n\n setIsApproved(true);\n queryClient.invalidateQueries({ queryKey: ['migration-allowance', params] });\n return result.ok;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('An unknown error occurred');\n setError(error);\n throw error;\n } finally {\n setIsLoading(false);\n }\n },\n [spokeProvider, sodax, queryClient, params],\n );\n\n const resetError = useCallback(() => {\n setError(null);\n }, []);\n\n return {\n approve,\n isLoading,\n error,\n resetError,\n isApproved,\n };\n}\n","import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { PoolKey } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UsePoolsProps = {\n /**\n * Optional react-query QueryObserverOptions for customizing query behavior such as\n * staleTime, refetchInterval, cacheTime, etc. These are merged with sensible defaults.\n */\n queryOptions?: QueryObserverOptions<PoolKey[], Error>;\n};\n\n/**\n * Loads and caches the available list of pools from the DEX service's ConcentratedLiquidityService.\n *\n * By default, the query result is cached indefinitely (with `staleTime` set to Infinity), reflecting the\n * assumption that the pools list is mostly static.\n *\n * @param params\n * Optional configuration object:\n * - queryOptions: Partial QueryObserverOptions for react-query (merged with built-in defaults).\n *\n * @returns\n * A UseQueryResult object from @tanstack/react-query containing:\n * - `data`: Array of PoolKey objects or undefined if not loaded or errored.\n * - Status fields: `isLoading`, `isError`, `error`, etc.\n *\n * @example\n * const { data: pools, isLoading, error } = usePools();\n * if (isLoading) return <div>Loading pools...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (pools) pools.forEach((pool, idx) => console.log(pool.id, pool.fee));\n */\nexport function usePools(params?: UsePoolsProps): UseQueryResult<PoolKey[], Error> {\n const { sodax } = useSodaxContext();\n const defaultQueryOptions = {\n queryKey: ['dex', 'pools'],\n staleTime: Number.POSITIVE_INFINITY, // Pools list is static, cache indefinitely\n };\n const queryOptions = { ...defaultQueryOptions, ...params?.queryOptions };\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<PoolKey[]> => {\n return sodax.dex.clService.getPools();\n },\n });\n}\n","import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { PoolData, PoolKey } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UsePoolDataProps = {\n poolKey: PoolKey | null;\n enabled?: boolean;\n queryOptions?: QueryObserverOptions<PoolData, Error>;\n};\n\n/**\n * React hook to fetch on-chain data for a given DEX pool.\n *\n * @param {UsePoolDataProps} props - The props object:\n * - `poolKey`: PoolKey | null — The unique identifier for the pool to fetch data for. If null, disables the query.\n * - `enabled`: boolean (optional) — Whether the query is enabled. Defaults to enabled if a poolKey is provided, otherwise false.\n * - `queryOptions`: QueryObserverOptions<PoolData, Error> (optional) — Additional React Query options (e.g., staleTime, refetchInterval).\n *\n * @returns {UseQueryResult<PoolData, Error>} React Query result containing pool data (`data`), loading state (`isLoading`), error (`error`), and status fields.\n *\n * @example\n * ```typescript\n * const { data: poolData, isLoading, error } = usePoolData({ poolKey });\n * if (isLoading) return <div>Loading…</div>;\n * if (error) return <div>Error!</div>;\n * if (poolData) {\n * // poolData is available\n * }\n * ```\n *\n * @remarks\n * - Refetches pool data every 30 seconds by default, and may be configured via `queryOptions`.\n * - If `poolKey` is `null`, the query is disabled and no network request is performed.\n * - Throws an error if `poolKey` is missing when the query is enabled.\n */\nexport function usePoolData({\n poolKey,\n queryOptions = {\n queryKey: ['dex', 'poolData', poolKey],\n enabled: poolKey !== null,\n staleTime: 10000,\n refetchInterval: 30000,\n },\n}: UsePoolDataProps): UseQueryResult<PoolData, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n ...queryOptions,\n queryFn: async (): Promise<PoolData> => {\n if (!poolKey) {\n throw new Error('Pool key is required');\n }\n return await sodax.dex.clService.getPoolData(poolKey, sodax.hubProvider.publicClient);\n },\n enabled: poolKey !== null,\n });\n}\n","import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { PoolData, PoolKey, SpokeProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport interface UsePoolBalancesResponse {\n token0Balance: bigint;\n token1Balance: bigint;\n}\n\nexport interface UsePoolBalancesProps {\n poolData: PoolData | null;\n poolKey: PoolKey | null;\n spokeProvider: SpokeProvider | null;\n enabled?: boolean;\n queryOptions?: QueryObserverOptions<UsePoolBalancesResponse, Error>;\n}\n\n/**\n * React hook to query a user's token balances for a DEX pool.\n *\n * Given the pool data (with token addresses), the pool's key, and a SpokeProvider,\n * fetches the user's protocol balances for both token0 and token1 for the specified pool.\n * Queries are auto-refreshed; advanced options can be customized via `queryOptions`.\n *\n * @param {UsePoolBalancesProps} props\n * Object containing:\n * - `poolData`: {PoolData | null} - Pool info (must include token0 and token1 addresses). Required unless disabling.\n * - `poolKey`: {PoolKey | null} - Unique key for the DEX pool. Required unless disabling.\n * - `spokeProvider`: {SpokeProvider | null} - Provider instance for the chain. Required unless disabling.\n * - `enabled`: {boolean} (optional) - Whether to enable the query. Defaults to `true` if all other arguments are provided.\n * - `queryOptions`: {QueryObserverOptions<UsePoolBalancesResponse, Error>} (optional) - Advanced react-query options.\n *\n * @returns {UseQueryResult<UsePoolBalancesResponse, Error>}\n * React Query result object:\n * - `data`: `{ token0Balance: bigint, token1Balance: bigint }` if loaded, undefined otherwise.\n * - `isLoading`, `isError`, etc. for status handling.\n *\n * @remarks\n * - Throws an error if any of `poolData`, `poolKey`, or `spokeProvider` is missing when enabled.\n * - Suitable for tracking current protocol/wallet balances for both pool tokens.\n * - The hook is designed for use within a React component tree that provides the Sodax context.\n * - Data are automatically refreshed at the provided or default polling interval (default: refetch every 10s).\n *\n * @example\n * ```typescript\n * const { data, isLoading } = usePoolBalances({ poolData, poolKey, spokeProvider });\n * if (data) {\n * console.log('Balances:', data.token0Balance, data.token1Balance);\n * }\n * ```\n */\nexport function usePoolBalances({\n poolData,\n poolKey,\n spokeProvider,\n enabled = true,\n queryOptions = {\n queryKey: [\n 'dex',\n 'poolBalances',\n poolData?.poolKey,\n spokeProvider?.chainConfig.chain.id,\n ],\n enabled: enabled && poolData !== null && poolKey !== null && spokeProvider !== null,\n staleTime: 5000, // Consider data stale after 5 seconds\n refetchInterval: 10000, // Refetch every 10 seconds\n },\n}: UsePoolBalancesProps): UseQueryResult<UsePoolBalancesResponse, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!poolData || !spokeProvider || !poolKey) {\n throw new Error('Pool data, pool key, and spoke provider are required');\n }\n\n // Get balances from AssetService\n const [balance0, balance1] = await Promise.all([\n sodax.dex.assetService.getDeposit(poolData.token0.address, spokeProvider),\n sodax.dex.assetService.getDeposit(poolData.token1.address, spokeProvider),\n ]);\n\n return {\n token0Balance: balance0,\n token1Balance: balance1,\n };\n },\n });\n}\n","import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { ClPositionInfo, PoolKey } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport interface UsePositionInfoResponse {\n positionInfo: ClPositionInfo;\n isValid: boolean;\n}\n\nexport interface UsePositionInfoProps {\n tokenId: string | null;\n poolKey: PoolKey | null;\n queryOptions?: QueryObserverOptions<UsePositionInfoResponse, Error>;\n}\n\n/**\n * React hook to fetch and validate CL position details by position NFT token ID.\n *\n * Fetches position data on-chain for a given tokenId, and checks if it matches the expected PoolKey.\n * This is commonly used in DEX dashboards to show or pre-validate user positions by ID.\n *\n * @param {string | null} tokenId\n * Position NFT token ID to query, as a string. Pass `null` or empty string to disable.\n * @param {PoolKey | null} poolKey\n * PoolKey to match against the position's underlying pool. Pass `null` to disable.\n * @param {QueryObserverOptions<UsePositionInfoResponse, Error>} [queryOptions]\n * Optional react-query options for polling/refresh and config. Merged with sensible defaults.\n *\n * @returns {UseQueryResult<UsePositionInfoResponse, Error>}\n * Standard React Query result object:\n * - `data`: { positionInfo, isValid } if loaded, or undefined if not loaded/error\n * - `isLoading`: boolean (query active)\n * - `isError`: boolean (query failed)\n * - ...other react-query helpers (refetch, status, etc)\n *\n * @example\n * ```typescript\n * const { data, isLoading, error } = usePositionInfo({ tokenId, poolKey });\n * if (isLoading) return <div>Loading position...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * if (data) {\n * console.log('Valid for pool:', data.isValid);\n * console.log('Liquidity:', data.positionInfo.liquidity);\n * }\n * ```\n *\n * @remarks\n * - Validates the underlying position's pool definition (currency0, currency1, fee) with the supplied PoolKey.\n * - Returns `isValid: false` if any field mismatches.\n * - Pass `null` as tokenId or poolKey to disable the query.\n * - Defaults: 10s stale, not enabled if missing arguments. Customizable via `queryOptions`.\n * - Throws error if called with invalid/null tokenId or poolKey when enabled.\n */\nexport function usePositionInfo({\n tokenId,\n poolKey,\n queryOptions = {\n queryKey: ['dex', 'positionInfo', tokenId, poolKey],\n enabled: tokenId !== null && poolKey !== null && tokenId !== '',\n staleTime: 10000, // Consider data stale after 10 seconds\n },\n}: UsePositionInfoProps): UseQueryResult<UsePositionInfoResponse, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryFn: async () => {\n if (!tokenId || !poolKey) {\n throw new Error('Token ID and pool key are required');\n }\n\n const tokenIdBigInt = BigInt(tokenId);\n const publicClient = sodax.hubProvider.publicClient;\n const info = await sodax.dex.clService.getPositionInfo(tokenIdBigInt, publicClient);\n\n // Validate that position belongs to current pool\n const isValid =\n info.poolKey.currency0.toLowerCase() === poolKey.currency0.toLowerCase() &&\n info.poolKey.currency1.toLowerCase() === poolKey.currency1.toLowerCase() &&\n info.poolKey.fee === poolKey.fee;\n\n return {\n positionInfo: info,\n isValid,\n };\n },\n ...queryOptions,\n });\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider, CreateAssetDepositParams, SpokeTxHash, HubTxHash } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseDexDepositParams = {\n params: CreateAssetDepositParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n/**\n * React hook that provides a mutation to perform a deposit into a DEX pool using the provided parameters and SpokeProvider.\n *\n * The hook returns a mutation object for executing the deposit (`mutateAsync`), tracking its state (`isPending`), and any resulting error (`error`).\n * On successful deposit, all queries matching ['dex', 'poolBalances'] are invalidated and refetched.\n *\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams>}\n * React Query mutation result:\n * - `mutateAsync({ params, spokeProvider })`: Triggers the deposit with {@link CreateDepositParams} and the target SpokeProvider.\n * - `isPending`: True while the deposit transaction is pending.\n * - `error`: Error if the mutation fails.\n *\n * @example\n * ```typescript\n * const { mutateAsync: deposit, isPending, error } = useDexDeposit();\n * await deposit({ params: { asset, amount, poolToken }, spokeProvider });\n * ```\n *\n * @remarks\n * - Throws if called with missing `spokeProvider` or `params`.\n * - Upon success, automatically refetches up-to-date pool balances.\n */\nexport function useDexDeposit(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexDepositParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseDexDepositParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider is required');\n }\n\n if (!params) {\n throw new Error('Deposit params are required');\n }\n\n // Perform the deposit operation\n const depositResult = await sodax.dex.assetService.deposit({\n params,\n spokeProvider,\n });\n\n if (!depositResult.ok) {\n throw new Error(`Deposit failed: ${depositResult.error?.code || 'Unknown error'}`);\n }\n\n return depositResult.value;\n },\n onSuccess: () => {\n // Refetch pool balances after a successful deposit\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });\n },\n });\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider, SpokeTxHash, HubTxHash, CreateAssetWithdrawParams } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseDexWithdrawParams = {\n params: CreateAssetWithdrawParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook to provide a mutation for withdrawing assets from a DEX pool.\n *\n * This hook returns a mutation result object valid for use with React Query.\n * The mutation function expects an object with the withdrawal parameters and a SpokeProvider,\n * and triggers the withdrawal operation on the DEX. On success, it invalidates the relevant\n * ['dex', 'poolBalances'] query to fetch the updated balances.\n *\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams>}\n * Mutation result object. Use its properties to:\n * - Call `mutateAsync({ params, spokeProvider })` to perform the withdrawal.\n * - Track progress with `isPending`.\n * - Access any `error` encountered during the mutation.\n *\n * @example\n * const { mutateAsync: withdraw, isPending, error } = useDexWithdraw();\n * await withdraw({ params, spokeProvider });\n */\nexport function useDexWithdraw(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDexWithdrawParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseDexWithdrawParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider is required');\n }\n // Execute withdraw\n const withdrawResult = await sodax.dex.assetService.withdraw({\n params,\n spokeProvider,\n });\n\n if (!withdrawResult.ok) {\n throw new Error(`Withdraw failed: ${withdrawResult.error.code}`);\n }\n\n return withdrawResult.value;\n },\n onSuccess: () => {\n // Invalidate balances query to refetch after withdraw\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });\n },\n });\n}\n","import { type QueryObserverOptions, useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { SpokeProvider, CreateAssetDepositParams } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseDexAllowanceProps = {\n params: CreateAssetDepositParams | undefined;\n spokeProvider: SpokeProvider | null;\n enabled?: boolean;\n queryOptions?: QueryObserverOptions<boolean, Error>;\n};\n\n/**\n * Hook to check if the user has approved sufficient token allowance for DEX deposits.\n *\n * This hook automatically queries and tracks the allowance status, indicating whether\n * the user has granted enough allowance to allow a specific deposit to the DEX. It leverages\n * React Query for status, caching, and background refetching.\n *\n * @param {CreateAssetDepositParams | undefined} params\n * The deposit parameters: asset address, poolToken, and raw amount (BigInt), or undefined to disable.\n * @param {SpokeProvider | undefined} spokeProvider\n * The provider interface for the selected chain. When undefined, the query is disabled.\n * @param {boolean} [enabled]\n * Whether the allowance status check is enabled. Defaults to true if both params and spokeProvider are truthy.\n * @param {QueryObserverOptions<boolean, Error>} [queryOptions]\n * Optional react-query options. Any override here (e.g. staleTime, refetchInterval) will merge with defaults.\n *\n * @returns {UseQueryResult<boolean, Error>}\n * React Query result object: `data` is boolean (true if allowance is sufficient), plus `isLoading`, `error`, etc.\n *\n * @example\n * ```typescript\n * const { data: isAllowed, isLoading, error } = useDexAllowance({\n * params: { asset, amount: parseUnits('100', 18), poolToken },\n * spokeProvider,\n * });\n * if (isLoading) return <Spinner />;\n * if (error) return <div>Error: {error.message}</div>;\n * if (isAllowed) { ... }\n * ```\n *\n * @remarks\n * - The allowance is checked every 5 seconds as long as enabled, params, and spokeProvider are all defined.\n * - Returns `false` if allowance cannot be determined or any error occurs in isAllowanceValid.\n * - Suitable for gating UI actions that require token approval before depositing in the DEX.\n */\nexport function useDexAllowance({\n params,\n spokeProvider,\n queryOptions = {\n queryKey: [\n 'dex',\n 'allowance',\n params?.asset,\n params?.poolToken,\n params?.amount.toString(),\n spokeProvider?.chainConfig.chain.id,\n ],\n enabled: !!params && !!spokeProvider,\n },\n}: UseDexAllowanceProps): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n ...queryOptions,\n queryFn: async () => {\n if (!params || !spokeProvider) {\n throw new Error('Params and spoke provider are required');\n }\n\n const allowanceResult = await sodax.dex.assetService.isAllowanceValid({\n params: {\n asset: params.asset,\n amount: params.amount,\n poolToken: params.poolToken,\n },\n spokeProvider,\n });\n\n if (!allowanceResult.ok) {\n return false;\n }\n\n return allowanceResult.value;\n },\n });\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport type { SpokeProvider, CreateAssetDepositParams, SpokeTxHash } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseDexApproveParams = {\n params: CreateAssetDepositParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook for performing a DEX token allowance approval transaction.\n *\n * Returns a mutation object that allows explicitly triggering a token approval\n * for a DEX deposit, using the specified approval parameters and spoke provider.\n * On successful approval, the related allowance query is invalidated and refetched\n * for consistent UI state.\n *\n * @returns {UseMutationResult<SpokeTxHash, Error, UseDexApproveParams>}\n * React Query mutation result for the approval operation. Use `mutateAsync` with\n * an object of shape `{ params, spokeProvider }` to initiate approval.\n *\n * @example\n * ```typescript\n * const { mutateAsync: approve, isPending, error } = useDexApprove();\n * await approve({ params: { asset, amount, poolToken }, spokeProvider });\n * ```\n *\n * @remarks\n * - Throws if called without both a valid `params` and `spokeProvider`.\n * - On approval success, the query for ['dex', 'allowance'] is invalidated/refetched.\n */\nexport function useDexApprove(): UseMutationResult<SpokeTxHash, Error, UseDexApproveParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseDexApproveParams) => {\n const approveResult = await sodax.dex.assetService.approve({\n params,\n spokeProvider,\n raw: false,\n });\n\n if (!approveResult.ok) {\n throw new Error('Approval failed');\n }\n\n return approveResult.value;\n },\n onSuccess: () => {\n // Invalidate allowance query to refetch the new allowance\n queryClient.invalidateQueries({ queryKey: ['dex', 'allowance'] });\n },\n });\n}\n","import { useState, useEffect, useCallback, useMemo } from 'react';\nimport { ClService, type PoolData } from '@sodax/sdk';\n\ninterface UseLiquidityAmountsResult {\n liquidityToken0Amount: string;\n liquidityToken1Amount: string;\n lastEditedToken: 'token0' | 'token1' | null;\n setLiquidityToken0Amount: (value: string) => void;\n setLiquidityToken1Amount: (value: string) => void;\n handleToken0AmountChange: (value: string) => void;\n handleToken1AmountChange: (value: string) => void;\n}\n\n/**\n * Hook for calculating liquidity amounts based on price range.\n *\n * This hook manages the state and calculations for liquidity token amounts.\n * It automatically calculates the corresponding token amount when one is changed,\n * based on the current price range and pool data.\n *\n * @param {string} minPrice - Minimum price for the liquidity range\n * @param {string} maxPrice - Maximum price for the liquidity range\n * @param {PoolData | null} poolData - The pool data containing token information\n * @returns {UseLiquidityAmountsResult} Object containing amounts, state, and handlers\n *\n * @example\n * ```typescript\n * const {\n * liquidityToken0Amount,\n * liquidityToken1Amount,\n * handleToken0AmountChange,\n * handleToken1AmountChange,\n * } = useLiquidityAmounts(minPrice, maxPrice, poolData);\n *\n * <Input\n * value={liquidityToken0Amount}\n * onChange={(e) => handleToken0AmountChange(e.target.value)}\n * />\n * ```\n */\nexport function useLiquidityAmounts(\n minPrice: string,\n maxPrice: string,\n poolData: PoolData | null,\n): UseLiquidityAmountsResult {\n const [liquidityToken0Amount, setLiquidityToken0Amount] = useState<string>('');\n const [liquidityToken1Amount, setLiquidityToken1Amount] = useState<string>('');\n const [lastEditedToken, setLastEditedToken] = useState<'token0' | 'token1' | null>(null);\n\n // Memoize parsed price values to avoid repeated parsing\n const { minPriceNum, maxPriceNum, isValidPriceRange } = useMemo(() => {\n const parsedMin = Number.parseFloat(minPrice);\n const parsedMax = Number.parseFloat(maxPrice);\n const isValid = parsedMin > 0 && parsedMax > 0 && parsedMin < parsedMax;\n\n return {\n minPriceNum: parsedMin,\n maxPriceNum: parsedMax,\n isValidPriceRange: isValid,\n };\n }, [minPrice, maxPrice]);\n\n // Memoize tick calculations - these only depend on prices and pool data\n const { tickLower, tickUpper, currentTick } = useMemo(() => {\n if (!poolData || !isValidPriceRange) {\n return {\n tickLower: null,\n tickUpper: null,\n currentTick: null,\n };\n }\n\n try {\n const lower = ClService.priceToTick(minPriceNum, poolData.token0, poolData.token1, poolData.tickSpacing);\n const upper = ClService.priceToTick(maxPriceNum, poolData.token0, poolData.token1, poolData.tickSpacing);\n\n return {\n tickLower: lower,\n tickUpper: upper,\n currentTick: BigInt(poolData.currentTick),\n };\n } catch (err) {\n console.error('Failed to calculate ticks:', err);\n return {\n tickLower: null,\n tickUpper: null,\n currentTick: null,\n };\n }\n }, [minPriceNum, maxPriceNum, poolData, isValidPriceRange]);\n\n // Auto-calculate token1 amount when token0 amount changes\n const handleToken0AmountChange = useCallback(\n (value: string): void => {\n setLiquidityToken0Amount(value);\n setLastEditedToken('token0');\n\n // Only calculate if we have all required values\n if (!value || !poolData || !tickLower || !tickUpper || !currentTick) {\n return;\n }\n\n const amount0 = Number.parseFloat(value);\n\n if (amount0 <= 0 || !isValidPriceRange) {\n return;\n }\n\n try {\n const amount0BigInt = BigInt(Math.floor(amount0 * 10 ** poolData.token0.decimals));\n\n const amount1BigInt = ClService.calculateAmount1FromAmount0(\n amount0BigInt,\n tickLower,\n tickUpper,\n currentTick,\n poolData.sqrtPriceX96,\n );\n\n const amount1 = Number(amount1BigInt) / 10 ** poolData.token1.decimals;\n setLiquidityToken1Amount(amount1.toFixed(6));\n } catch (err) {\n console.error('Failed to calculate token1 amount:', err);\n }\n },\n [poolData, tickLower, tickUpper, currentTick, isValidPriceRange],\n );\n\n // Auto-calculate token0 amount when token1 amount changes\n const handleToken1AmountChange = useCallback(\n (value: string): void => {\n setLiquidityToken1Amount(value);\n setLastEditedToken('token1');\n\n // Only calculate if we have all required values\n if (!value || !poolData || !tickLower || !tickUpper || !currentTick) {\n return;\n }\n\n const amount1 = Number.parseFloat(value);\n\n if (amount1 <= 0 || !isValidPriceRange) {\n return;\n }\n\n try {\n const amount1BigInt = BigInt(Math.floor(amount1 * 10 ** poolData.token1.decimals));\n\n const amount0BigInt = ClService.calculateAmount0FromAmount1(\n amount1BigInt,\n tickLower,\n tickUpper,\n currentTick,\n poolData.sqrtPriceX96,\n );\n\n const amount0 = Number(amount0BigInt) / 10 ** poolData.token0.decimals;\n setLiquidityToken0Amount(amount0.toFixed(6));\n } catch (err) {\n console.error('Failed to calculate token0 amount:', err);\n }\n },\n [poolData, tickLower, tickUpper, currentTick, isValidPriceRange],\n );\n\n // Recalculate amounts when price range changes\n useEffect(() => {\n if (!poolData || !tickLower || !tickUpper || !lastEditedToken || !isValidPriceRange) {\n return;\n }\n\n // Recalculate based on which token was last edited\n if (lastEditedToken === 'token0' && liquidityToken0Amount) {\n handleToken0AmountChange(liquidityToken0Amount);\n } else if (lastEditedToken === 'token1' && liquidityToken1Amount) {\n handleToken1AmountChange(liquidityToken1Amount);\n }\n }, [\n poolData,\n lastEditedToken,\n liquidityToken0Amount,\n liquidityToken1Amount,\n handleToken0AmountChange,\n handleToken1AmountChange,\n tickLower,\n tickUpper,\n isValidPriceRange,\n ]);\n\n return {\n liquidityToken0Amount,\n liquidityToken1Amount,\n lastEditedToken,\n setLiquidityToken0Amount,\n setLiquidityToken1Amount,\n handleToken0AmountChange,\n handleToken1AmountChange,\n };\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport type { HubTxHash, SpokeTxHash, SpokeProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport type { UseCreateSupplyLiquidityParamsResult } from './useCreateSupplyLiquidityParams';\n\nexport type UseSupplyLiquidityProps = {\n params: UseCreateSupplyLiquidityParamsResult;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * Hook for supplying liquidity to a pool.\n *\n * This hook handles both minting new positions and increasing liquidity in existing positions.\n * It applies slippage tolerance before calculating liquidity and handles the complete transaction flow.\n *\n * @param {SpokeProvider} spokeProvider - The spoke provider for the chain\n * @returns {UseMutationResult<void, Error, SupplyLiquidityParams>} Mutation result with supply function\n *\n * @example\n * ```typescript\n * const { mutateAsync: supplyLiquidity, isPending, error } = useSupplyLiquidity(spokeProvider);\n *\n * await supplyLiquidity({\n * poolData,\n * poolKey,\n * minPrice: '100',\n * maxPrice: '200',\n * liquidityToken0Amount: '10',\n * liquidityToken1Amount: '20',\n * slippageTolerance: '0.5',\n * });\n * ```\n */\nexport function useSupplyLiquidity(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseSupplyLiquidityProps> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseSupplyLiquidityProps) => {\n // Check if we're increasing an existing position or minting a new one\n if (params.tokenId && params.isValidPosition) {\n // Increase liquidity in existing position\n const increaseResult = await sodax.dex.clService.increaseLiquidity({\n params: {\n poolKey: params.poolKey,\n tokenId: BigInt(params.tokenId),\n tickLower: params.tickLower,\n tickUpper: params.tickUpper,\n liquidity: params.liquidity,\n amount0Max: params.amount0Max,\n amount1Max: params.amount1Max,\n sqrtPriceX96: params.sqrtPriceX96,\n },\n spokeProvider,\n });\n\n if (!increaseResult.ok) {\n throw new Error(`Increase liquidity failed: ${increaseResult.error?.code || 'Unknown error'}`);\n }\n\n return increaseResult.value;\n }\n\n // Mint new position\n const supplyResult = await sodax.dex.clService.supplyLiquidity({\n params: {\n poolKey: params.poolKey,\n tickLower: params.tickLower,\n tickUpper: params.tickUpper,\n liquidity: params.liquidity,\n amount0Max: params.amount0Max,\n amount1Max: params.amount1Max,\n sqrtPriceX96: params.sqrtPriceX96,\n },\n spokeProvider,\n });\n\n if (!supplyResult.ok) {\n throw new Error(`Supply liquidity failed: ${supplyResult.error?.code || 'Unknown error'}`);\n }\n\n return supplyResult.value;\n },\n onSuccess: () => {\n // Invalidate relevant queries\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });\n queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo'] });\n },\n });\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from '@tanstack/react-query';\nimport type {\n ConcentratedLiquidityDecreaseLiquidityParams,\n HubTxHash,\n SpokeProvider,\n SpokeTxHash,\n} from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\n\nexport type UseDecreaseLiquidityParams = {\n params: ConcentratedLiquidityDecreaseLiquidityParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook that provides a mutation for decreasing liquidity in a concentrated liquidity position.\n *\n * This hook returns a mutation for removing liquidity from a position using the provided\n * `ConcentratedLiquidityDecreaseLiquidityParams` and `SpokeProvider`. The mutation returns a tuple of\n * the spoke transaction hash and the hub transaction hash upon success.\n *\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams>}\n * React Query mutation result:\n * - `mutateAsync({ params, spokeProvider })`: Triggers the decrease liquidity mutation.\n * - On success, returns `[spokeTxHash, hubTxHash]`.\n * - On failure, throws an error.\n *\n * @example\n * ```typescript\n * const { mutateAsync: decreaseLiquidity, isPending, error } = useDecreaseLiquidity();\n *\n * await decreaseLiquidity({\n * params: {\n * poolKey,\n * tokenId: 123n,\n * liquidity: 100000n,\n * amount0Min: 0n,\n * amount1Min: 0n,\n * },\n * spokeProvider,\n * });\n * ```\n *\n * @param {UseDecreaseLiquidityParams} variables\n * - `params`: Parameters for the decrease liquidity operation, matching `ConcentratedLiquidityDecreaseLiquidityParams`.\n * - `spokeProvider`: The provider instance for the target spoke chain.\n *\n * @remarks\n * - After a successful liquidity decrease, the hook will invalidate DEX pool balances and position info queries.\n */\nexport function useDecreaseLiquidity(): UseMutationResult<[SpokeTxHash, HubTxHash], Error, UseDecreaseLiquidityParams> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseDecreaseLiquidityParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider is required');\n }\n\n const decreaseResult = await sodax.dex.clService.decreaseLiquidity({\n params,\n spokeProvider,\n });\n\n if (!decreaseResult.ok) {\n throw new Error(`Decrease liquidity failed: ${decreaseResult.error?.code || 'Unknown error'}`);\n }\n\n return decreaseResult.value;\n },\n onSuccess: () => {\n // Invalidate relevant queries after successful liquidity decrease\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances'] });\n queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo'] });\n },\n });\n}\n","import type {\n UseCreateDecreaseLiquidityParamsProps,\n UseCreateDepositParamsProps,\n UseCreateSupplyLiquidityParamsProps,\n UseCreateSupplyLiquidityParamsResult,\n UseCreateWithdrawParamsProps,\n} from '@/hooks/dex';\nimport {\n ClService,\n type CreateAssetWithdrawParams,\n type ConcentratedLiquidityDecreaseLiquidityParams,\n type CreateAssetDepositParams,\n} from '@sodax/sdk';\nimport { parseUnits } from 'viem';\n\nexport function createDecreaseLiquidityParamsProps({\n poolKey,\n tokenId,\n percentage,\n positionInfo,\n slippageTolerance,\n}: UseCreateDecreaseLiquidityParamsProps): ConcentratedLiquidityDecreaseLiquidityParams {\n const percentageNum = Number.parseFloat(String(percentage));\n const slippage = Number.parseFloat(String(slippageTolerance));\n\n if (percentageNum <= 0 || percentageNum > 100) {\n throw new Error('Percentage must be between 0 and 100');\n }\n\n if (slippage <= 0 || slippage > 100) {\n throw new Error('Slippage must be between 0 and 100');\n }\n\n // Calculate liquidity to remove based on percentage\n const liquidityToRemove =\n percentageNum === 100\n ? positionInfo.liquidity\n : (positionInfo.liquidity * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n\n // Calculate expected token amounts from this liquidity\n const expectedAmount0 =\n percentageNum === 100\n ? positionInfo.amount0\n : (positionInfo.amount0 * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n const expectedAmount1 =\n percentageNum === 100\n ? positionInfo.amount1\n : (positionInfo.amount1 * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n\n // Apply slippage to minimum amounts\n const slippageMultiplier = BigInt(Math.floor((100 - slippage) * 100));\n const amount0Min = (expectedAmount0 * slippageMultiplier) / 10000n;\n const amount1Min = (expectedAmount1 * slippageMultiplier) / 10000n;\n\n return {\n poolKey,\n tokenId: BigInt(tokenId),\n liquidity: liquidityToRemove,\n amount0Min,\n amount1Min,\n };\n}\n\nexport function createDepositParamsProps({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n}: UseCreateDepositParamsProps): CreateAssetDepositParams {\n const amountNum = Number.parseFloat(String(amount));\n\n if (!amount || amountNum <= 0) {\n throw new Error('Amount must be greater than 0');\n }\n\n const token = tokenIndex === 0 ? poolData.token0 : poolData.token1;\n const originalAsset = tokenIndex === 0 ? poolSpokeAssets.token0 : poolSpokeAssets.token1;\n\n return {\n asset: originalAsset.address,\n // Use deposit token decimals (original asset) for correct unit parsing\n amount: parseUnits(String(amount), originalAsset.decimals),\n poolToken: token.address,\n };\n}\n\nexport function createSupplyLiquidityParamsProps({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n}: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult {\n const slippage = Number.parseFloat(String(slippageTolerance));\n if (slippage <= 0 || slippage > 100) {\n throw new Error('Slippage must be between 0 and 100');\n }\n\n const minPriceNum = Number.parseFloat(minPrice);\n const maxPriceNum = Number.parseFloat(maxPrice);\n const amount0 = Number.parseFloat(liquidityToken0Amount);\n const amount1 = Number.parseFloat(liquidityToken1Amount);\n\n if (minPriceNum <= 0 || maxPriceNum <= 0 || amount0 <= 0 || amount1 <= 0) {\n throw new Error('All values must be greater than 0');\n }\n\n if (minPriceNum >= maxPriceNum) {\n throw new Error('Min price must be less than max price');\n }\n\n const amount0BigInt = parseUnits(liquidityToken0Amount, poolData.token0.decimals);\n const amount1BigInt = parseUnits(liquidityToken1Amount, poolData.token1.decimals);\n\n // Convert prices to ticks\n const token0 = poolData.token0;\n const token1 = poolData.token1;\n const tickSpacing = poolData.tickSpacing;\n\n const tickLower = ClService.priceToTick(minPriceNum, token0, token1, tickSpacing);\n const tickUpper = ClService.priceToTick(maxPriceNum, token0, token1, tickSpacing);\n\n // Calculate liquidity from full amounts (the desired deposit)\n const liquidity = ClService.calculateLiquidityFromAmounts(\n amount0BigInt,\n amount1BigInt,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n );\n\n // Apply slippage to get max amounts — the ceiling the contract is allowed to pull.\n // If price moves unfavorably, the contract may need slightly more tokens than expected.\n const { amount0Max, amount1Max } = ClService.calculateMaxAmountsForSlippage(\n liquidity,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n poolData.sqrtPriceX96,\n slippage,\n );\n\n const tokenId = positionId ? BigInt(positionId) : undefined;\n\n return {\n poolKey,\n tickLower,\n tickUpper,\n liquidity,\n amount0Max,\n amount1Max,\n sqrtPriceX96: poolData.sqrtPriceX96,\n positionId,\n isValidPosition,\n tokenId,\n };\n}\n\nexport function createWithdrawParamsProps({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n dst,\n}: UseCreateWithdrawParamsProps): CreateAssetWithdrawParams {\n const amountNum = Number.parseFloat(String(amount));\n if (!amount || amountNum <= 0) {\n throw new Error('Please enter a valid amount');\n }\n\n const token = tokenIndex === 0 ? poolData.token0 : poolData.token1;\n const originalAsset = tokenIndex === 0 ? poolSpokeAssets.token0 : poolSpokeAssets.token1;\n\n return {\n asset: originalAsset.address,\n amount: parseUnits(String(amount), token.decimals),\n poolToken: token.address,\n dst,\n };\n}\n","import { useMemo } from 'react';\nimport type { CreateAssetDepositParams, PoolData, PoolSpokeAssets } from '@sodax/sdk';\nimport { createDepositParamsProps } from '@/utils/dex-utils';\n\nexport type UseCreateDepositParamsProps = {\n tokenIndex: 0 | 1;\n amount: string | number;\n poolData: PoolData;\n poolSpokeAssets: PoolSpokeAssets;\n};\n\n\n/**\n * React hook to create the deposit parameters for a given pool and token.\n *\n * Purpose:\n * - Provides a hook which memoizes the deposit parameters for a given pool and token.\n *\n * Usage:\n * - Call the function with the token index, amount, pool data, pool key, and spoke provider to create the deposit parameters.\n *\n * Params:\n * @param tokenIndex - The index of the token to deposit.\n * @param amount - The amount of the token to deposit.\n * @param poolData - The pool data of the pool to deposit to.\n * @param poolKey - The pool key of the pool to deposit to.\n * @param spokeProvider - The spoke provider to use for the deposit.\n * @returns The deposit parameters or undefined if the pool key, spoke provider, or amount is not set.\n */\nexport function useCreateDepositParams({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n}: UseCreateDepositParamsProps): CreateAssetDepositParams | undefined {\n return useMemo<CreateAssetDepositParams | undefined>(() => {\n if (!amount || Number.parseFloat(String(amount)) <= 0) {\n return undefined;\n }\n\n return createDepositParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets });\n }, [tokenIndex, amount, poolData, poolSpokeAssets]);\n}\n","import { createSupplyLiquidityParamsProps } from '@/utils/dex-utils';\nimport type {\n ConcentratedLiquiditySupplyParams,\n ConcentratedLiquidityIncreaseLiquidityParams,\n PoolData,\n PoolKey,\n} from '@sodax/sdk';\nimport { useMemo } from 'react';\n\nexport type UseCreateSupplyLiquidityParamsProps = {\n poolData: PoolData;\n poolKey: PoolKey;\n minPrice: string;\n maxPrice: string;\n liquidityToken0Amount: string;\n liquidityToken1Amount: string;\n slippageTolerance: string | number;\n positionId?: string | null;\n isValidPosition?: boolean;\n};\n\nexport type UseCreateSupplyLiquidityParamsResult = ConcentratedLiquiditySupplyParams &\n Omit<ConcentratedLiquidityIncreaseLiquidityParams, 'tokenId'> & {\n tokenId?: string | bigint;\n positionId?: string | null;\n isValidPosition?: boolean;\n };\n\n/**\n * React hook to create the supply liquidity parameters for a given pool.\n *\n * Purpose:\n * - Provides a hook which memoizes the supply liquidity parameters for a given pool.\n *\n * Usage:\n * - 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.\n *\n * Params:\n * @param poolData - The pool data of the pool to supply liquidity to.\n * @param poolKey - The pool key of the pool to supply liquidity to.\n * @param minPrice - The minimum price of the liquidity to supply.\n * @param maxPrice - The maximum price of the liquidity to supply.\n * @param liquidityToken0Amount - The amount of the token0 to supply.\n * @param liquidityToken1Amount - The amount of the token1 to supply.\n * @param slippageTolerance - The slippage tolerance to use for the supply.\n * @param positionId - The position id of the position to supply liquidity to.\n * @param isValidPosition - Whether the position is valid.\n * @returns The supply liquidity parameters.\n */\nexport function useCreateSupplyLiquidityParams({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n}: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult {\n return useMemo<UseCreateSupplyLiquidityParamsResult>(() => {\n return createSupplyLiquidityParamsProps({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n });\n }, [\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n poolData,\n poolKey,\n positionId,\n isValidPosition,\n ]);\n}\n","import { createDecreaseLiquidityParamsProps } from '@/utils/dex-utils';\nimport type { ClPositionInfo, ConcentratedLiquidityDecreaseLiquidityParams, PoolKey } from '@sodax/sdk';\nimport { useMemo } from 'react';\n\nexport type UseCreateDecreaseLiquidityParamsProps = {\n poolKey: PoolKey;\n tokenId: string | bigint;\n percentage: string | number;\n positionInfo: ClPositionInfo;\n slippageTolerance: string | number;\n};\n\n\n/**\n * React hook to create the decrease liquidity parameters for a given pool and position.\n *\n * Purpose:\n * - Provides a hook which memoizes the decrease liquidity parameters for a given pool and position.\n *\n * Usage:\n * - Call the function with the pool key, token ID, percentage, position info, and slippage tolerance to create the decrease liquidity parameters.\n *\n * Params:\n * @param poolKey - The pool key of the pool to decrease the liquidity from.\n * @param tokenId - The token ID of the position to decrease the liquidity from.\n * @param percentage - The percentage of liquidity to decrease.\n * @param positionInfo - The position info of the position to decrease the liquidity from.\n * @param slippageTolerance - The slippage tolerance to use for the decrease.\n * @returns The decrease liquidity parameters.\n */\nexport function useCreateDecreaseLiquidityParams({\n poolKey,\n tokenId,\n percentage,\n positionInfo,\n slippageTolerance,\n}: UseCreateDecreaseLiquidityParamsProps): ConcentratedLiquidityDecreaseLiquidityParams {\n return useMemo<ConcentratedLiquidityDecreaseLiquidityParams>(() => {\n return createDecreaseLiquidityParamsProps({ poolKey, tokenId, percentage, positionInfo, slippageTolerance });\n }, [poolKey, tokenId, percentage, positionInfo, slippageTolerance]);\n}\n","import type { CreateAssetWithdrawParams, DestinationParamsType, PoolData, PoolSpokeAssets } from '@sodax/sdk';\nimport { useMemo } from 'react';\nimport { createWithdrawParamsProps } from '@/utils/dex-utils';\n\nexport type UseCreateWithdrawParamsProps = {\n tokenIndex: 0 | 1;\n amount: string | number;\n poolData: PoolData;\n poolSpokeAssets: PoolSpokeAssets;\n dst?: DestinationParamsType;\n};\n\n/**\n * React hook to create the withdrawal parameters for a given pool and token.\n *\n * Purpose:\n * - Provides a hook which memoizes the withdrawal parameters for a given pool and token.\n *\n * Usage:\n * - Call the function with the token index, amount, pool data, pool spoke assets, and destination parameters to create the withdrawal parameters.\n *\n * Params:\n * @param tokenIndex - The index of the token to withdraw.\n * @param amount - The amount of the token to withdraw.\n * @param poolData - The pool data of the pool to withdraw from.\n * @param poolSpokeAssets - The pool spoke assets of the pool to withdraw from.\n * @param dst - The destination parameters for the withdrawal.\n * @returns The withdrawal parameters or undefined if the amount is not set.\n */\nexport function useCreateWithdrawParams({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n dst,\n}: UseCreateWithdrawParamsProps): CreateAssetWithdrawParams | undefined {\n return useMemo<CreateAssetWithdrawParams | undefined>(() => {\n if (!amount || Number.parseFloat(String(amount)) <= 0) {\n return undefined;\n }\n\n return createWithdrawParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, dst });\n }, [tokenIndex, amount, poolData, poolSpokeAssets, dst]);\n}\n","import type {\n ConcentratedLiquidityClaimRewardsParams,\n ConcentratedLiquidityError,\n ConcentratedLiquidityErrorCode,\n SpokeProvider,\n SpokeTxHash,\n HubTxHash,\n} from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext';\nimport { useMutation, type UseMutationResult, useQueryClient } from '@tanstack/react-query';\n\nexport type UseClaimRewardsParams = {\n params: ConcentratedLiquidityClaimRewardsParams;\n spokeProvider: SpokeProvider;\n};\n\n/**\n * React hook for creating a mutation to claim DEX rewards for a concentrated liquidity position.\n *\n * @returns {UseMutationResult<[SpokeTxHash, HubTxHash], ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>, UseClaimRewardsParams>}\n * Returns a react-query mutation result object:\n * - On success: resolves to a tuple `[SpokeTxHash, HubTxHash]`.\n * - On error: the error is of type `ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>`.\n * - The mutation function expects an argument of type {@link UseClaimRewardsParams}\n * containing `params` (the claim parameters) and `spokeProvider` (the target provider).\n * - On mutation success, invalidates the queries `'dex/poolBalances'` and `'dex/positionInfo'`.\n *\n * @example\n * const claimRewardsMutation = useClaimRewards();\n * claimRewardsMutation.mutateAsync({\n * params: { poolKey, tokenId, tickLower, tickUpper },\n * spokeProvider,\n * });\n */\nexport function useClaimRewards(): UseMutationResult<\n [SpokeTxHash, HubTxHash],\n ConcentratedLiquidityError<ConcentratedLiquidityErrorCode>,\n UseClaimRewardsParams\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: async ({ params, spokeProvider }: UseClaimRewardsParams) => {\n if (!spokeProvider) {\n throw new Error('Spoke provider is required');\n }\n const result = await sodax.dex.clService.claimRewards({\n params,\n spokeProvider,\n });\n\n if (!result.ok) {\n throw new Error(`Claim rewards failed: ${result.error?.code || 'Unknown error'}`);\n }\n\n return result.value;\n },\n onSuccess: (_, { params, spokeProvider }) => {\n // Invalidate relevant queries\n queryClient.invalidateQueries({\n queryKey: ['dex', 'poolBalances', params.poolKey, spokeProvider.chainConfig.chain.id],\n });\n queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo', params.tokenId, params.poolKey] });\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolData', params.poolKey] });\n },\n });\n}\n","import type { ReactNode, ReactElement } from 'react';\nimport React from 'react';\n\nimport { Sodax, type SodaxConfig } from '@sodax/sdk';\nimport { SodaxContext } from '@/contexts';\nimport type { RpcConfig } from '@sodax/types';\n\ninterface SodaxProviderProps {\n children: ReactNode;\n testnet?: boolean;\n config?: SodaxConfig;\n rpcConfig: RpcConfig;\n}\n\nexport const SodaxProvider = ({ children, testnet = false, config, rpcConfig }: SodaxProviderProps): ReactElement => {\n const sodax = new Sodax(config);\n\n return <SodaxContext.Provider value={{ sodax, testnet, rpcConfig }}>{children}</SodaxContext.Provider>;\n};\n"]}
1
+ {"version":3,"sources":["../src/hooks/shared/unwrapResult.ts","../src/hooks/shared/useSafeMutation.ts","../src/contexts/index.ts","../src/hooks/shared/useSodaxContext.ts","../src/hooks/shared/useEstimateGas.ts","../src/hooks/shared/useDeriveUserWalletAddress.ts","../src/hooks/shared/useStellarTrustlineCheck.ts","../src/hooks/shared/useRequestTrustline.ts","../src/hooks/shared/useGetUserHubWalletAddress.ts","../src/hooks/shared/useXBalances.ts","../src/hooks/provider/useHubProvider.ts","../src/hooks/bitcoin/useRadfiAuth.ts","../src/hooks/bitcoin/useRadfiSession.ts","../src/hooks/bitcoin/useFundTradingWallet.ts","../src/hooks/bitcoin/useBitcoinBalance.ts","../src/hooks/bitcoin/useTradingWallet.ts","../src/hooks/bitcoin/useTradingWalletBalance.ts","../src/hooks/bitcoin/useExpiredUtxos.ts","../src/hooks/bitcoin/useRenewUtxos.ts","../src/hooks/bitcoin/useRadfiWithdraw.ts","../src/hooks/mm/useBorrow.ts","../src/hooks/mm/useRepay.ts","../src/hooks/mm/useSupply.ts","../src/hooks/mm/useWithdraw.ts","../src/hooks/mm/useUserReservesData.ts","../src/hooks/mm/useReservesData.ts","../src/hooks/mm/useReservesHumanized.ts","../src/hooks/mm/useReservesList.ts","../src/hooks/mm/useMMAllowance.ts","../src/hooks/mm/useMMApprove.ts","../src/hooks/mm/useAToken.ts","../src/hooks/mm/useATokensBalances.ts","../src/hooks/mm/useReservesUsdFormat.ts","../src/hooks/mm/useUserFormattedSummary.ts","../src/hooks/swap/useQuote.ts","../src/hooks/swap/useSwap.ts","../src/hooks/swap/useStatus.ts","../src/hooks/swap/useSwapAllowance.ts","../src/hooks/swap/useSwapApprove.ts","../src/hooks/swap/useCancelSwap.ts","../src/hooks/swap/useCreateLimitOrder.ts","../src/hooks/swap/useCancelLimitOrder.ts","../src/hooks/backend/useBackendIntentByTxHash.ts","../src/hooks/backend/useBackendIntentByHash.ts","../src/hooks/backend/useBackendUserIntents.ts","../src/hooks/backend/useBackendSubmitSwapTx.ts","../src/hooks/backend/useBackendSubmitSwapTxStatus.ts","../src/hooks/backend/useBackendOrderbook.ts","../src/hooks/backend/useBackendMoneyMarketPosition.ts","../src/hooks/backend/useBackendAllMoneyMarketAssets.ts","../src/hooks/backend/useBackendMoneyMarketAsset.ts","../src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts","../src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts","../src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts","../src/hooks/bridge/useBridge.ts","../src/hooks/bridge/useBridgeAllowance.ts","../src/hooks/bridge/useBridgeApprove.ts","../src/hooks/bridge/useGetBridgeableAmount.ts","../src/hooks/bridge/useGetBridgeableTokens.ts","../src/hooks/staking/useStake.ts","../src/hooks/staking/useStakeApprove.ts","../src/hooks/staking/useStakeAllowance.ts","../src/hooks/staking/useUnstake.ts","../src/hooks/staking/useClaim.ts","../src/hooks/staking/useCancelUnstake.ts","../src/hooks/staking/useStakingInfo.ts","../src/hooks/staking/useUnstakingInfoWithPenalty.ts","../src/hooks/staking/useStakingConfig.ts","../src/hooks/staking/useStakeRatio.ts","../src/hooks/staking/useInstantUnstakeRatio.ts","../src/hooks/staking/useConvertedAssets.ts","../src/hooks/staking/useInstantUnstake.ts","../src/hooks/staking/useUnstakeAllowance.ts","../src/hooks/staking/useUnstakeApprove.ts","../src/hooks/staking/useUnstakingInfo.ts","../src/hooks/staking/useInstantUnstakeApprove.ts","../src/hooks/staking/useInstantUnstakeAllowance.ts","../src/hooks/partner/useFetchAssetsBalances.ts","../src/hooks/partner/useGetAutoSwapPreferences.ts","../src/hooks/partner/useIsTokenApproved.ts","../src/hooks/partner/useApproveToken.ts","../src/hooks/partner/useSetSwapPreference.ts","../src/hooks/partner/useFeeClaimSwap.ts","../src/hooks/recovery/useHubAssetBalances.ts","../src/hooks/recovery/useWithdrawHubAsset.ts","../src/hooks/migrate/useMigrateIcxToSoda.ts","../src/hooks/migrate/useRevertMigrateSodaToIcx.ts","../src/hooks/migrate/useMigratebnUSD.ts","../src/hooks/migrate/useMigrateBaln.ts","../src/hooks/migrate/useMigrationApprove.ts","../src/hooks/migrate/useMigrationAllowance.ts","../src/hooks/dex/usePools.ts","../src/hooks/dex/usePoolData.ts","../src/hooks/dex/usePoolBalances.ts","../src/hooks/dex/usePositionInfo.ts","../src/hooks/dex/useDexDeposit.ts","../src/hooks/dex/useDexWithdraw.ts","../src/hooks/dex/useDexAllowance.ts","../src/hooks/dex/useDexApprove.ts","../src/hooks/dex/useLiquidityAmounts.ts","../src/hooks/dex/useSupplyLiquidity.ts","../src/hooks/dex/useDecreaseLiquidity.ts","../src/utils/dex-utils.ts","../src/hooks/dex/useCreateDepositParams.ts","../src/hooks/dex/useCreateSupplyLiquidityParams.ts","../src/hooks/dex/useCreateDecreaseLiquidityParams.ts","../src/hooks/dex/useCreateWithdrawParams.ts","../src/hooks/dex/useClaimRewards.ts","../src/providers/SodaxProvider.tsx","../src/providers/createSodaxQueryClient.ts"],"names":["useQuery","useCallback","token","error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AAM,MAAA,CAAO,IAAA,KAAS,OAAA,IACtB,KAAA,CAAM,QAAA,CAAS,OAAA,CAAQ,IAAA,EAAM,MAAA,KAAW,IAAA,EACxC;AACA,QAAA,eAAA,CAAgB,KAAA,CAAM,OAAO,KAAK,CAAA;AAAA,MACpC;AAAA,IACF,CAAC,CAAA;AACD,IAAA,OAAO,IAAI,YAAY,MAAM,CAAA;AAAA,EAC/B;AAGA,EAAA,OAAO,IAAI,WAAA,CAAY;AAAA,IACrB,GAAG,MAAA;AAAA,IACH,aAAA,EAAe,IAAI,aAAA,CAAc;AAAA,MAC/B,OAAA,EAAS,CAAC,KAAA,EAAO,KAAA,EAAO,MAAM,QAAA,KAAa;AACzC,QAAA,IAAI,QAAA,CAAS,OAAA,CAAQ,IAAA,EAAM,MAAA,KAAW,IAAA,EAAM;AAC5C,QAAA,eAAA,CAAgB,KAAK,CAAA;AAAA,MACvB;AAAA,KACD;AAAA,GACF,CAAA;AACH","file":"index.mjs","sourcesContent":["import type { Result } from '@sodax/sdk';\n\n/**\n * Translates the SDK's `Result<T>` contract into the React Query contract: returns `value` on\n * success, throws `error` on failure. Non-`Error` throwables are wrapped so consumers always get\n * an `Error` in `mutation.error` / catch blocks.\n *\n * Used by every dapp-kit mutation hook so the React Query error model (`isError`, `error`,\n * `onError`, `retry`, `throwOnError`, devtools) engages uniformly.\n */\nexport function unwrapResult<T>(result: Result<T>): T {\n if (!result.ok) {\n if (result.error instanceof Error) throw result.error;\n const e = result.error as { message?: string; detail?: { code?: string; message?: string } };\n const msg = e?.detail?.code ?? e?.detail?.message ?? e?.message ?? 'SDK call failed';\n throw new Error(msg, { cause: result.error });\n }\n return result.value;\n}\n","// packages/dapp-kit/src/hooks/shared/useSafeMutation.ts\nimport type { Result } from '@sodax/sdk';\nimport {\n useMutation,\n type MutateOptions,\n type UseMutationOptions,\n type UseMutationResult,\n} from '@tanstack/react-query';\nimport { useCallback } from 'react';\n\n/**\n * Return shape of every dapp-kit mutation hook. Extends `UseMutationResult` with one extra\n * method, `mutateAsyncSafe`, that never rejects — it returns the SDK's `Result<T>` shape so\n * callers can branch on `.ok` without `try/catch`.\n *\n * The underlying `mutationFn` still throws on SDK failure, so React Query's native error model\n * (`isError`, `error`, `onError`, `retry`, `throwOnError`, devtools) keeps working as documented.\n */\nexport type SafeUseMutationResult<TData, TError, TVars, TContext = unknown> = UseMutationResult<\n TData,\n TError,\n TVars,\n TContext\n> & {\n /**\n * Like `mutateAsync` but never rejects. Returns `Result<TData>` so callers can branch\n * on `.ok` without `try/catch`.\n *\n * Use this for imperative flows where rejection-style errors are awkward — e.g. sequential\n * `if (!hasAllowance) await approve(...); await action(...)` chains where the user-reject\n * case is the modal failure mode, not an exceptional one.\n */\n mutateAsyncSafe: (\n vars: TVars,\n options?: MutateOptions<TData, TError, TVars, TContext>,\n ) => Promise<Result<TData>>;\n};\n\n/**\n * Wraps a `Promise<T>` (typically `mutateAsync(vars)`) into a `Promise<Result<T>>` that never\n * rejects. Pure, side-effect-free — extracted for unit testing.\n */\nexport async function toResult<T>(promise: Promise<T>): Promise<Result<T>> {\n try {\n const value = await promise;\n return { ok: true, value };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * Drop-in replacement for `useMutation` that augments the result with `mutateAsyncSafe`. Used\n * by every dapp-kit mutation hook so consumers can pick rejection-style (`mutateAsync`) or\n * Result-style (`mutateAsyncSafe`) ergonomics without the hook author having to think about it.\n */\nexport function useSafeMutation<TData, TError, TVars, TContext = unknown>(\n options: UseMutationOptions<TData, TError, TVars, TContext>,\n): SafeUseMutationResult<TData, TError, TVars, TContext> {\n const mutation = useMutation<TData, TError, TVars, TContext>(options);\n const { mutateAsync } = mutation;\n const mutateAsyncSafe = useCallback(\n (vars: TVars, opts?: MutateOptions<TData, TError, TVars, TContext>): Promise<Result<TData>> =>\n toResult(mutateAsync(vars, opts)),\n [mutateAsync],\n );\n return { ...mutation, mutateAsyncSafe };\n}\n","import { createContext } from 'react';\nimport type { Sodax } from '@sodax/sdk';\n\nexport interface SodaxContextType {\n sodax: Sodax;\n}\n\nexport const SodaxContext = createContext<SodaxContextType | null>(null);\n","import { SodaxContext, type SodaxContextType } from '@/contexts/index.js';\nimport { useContext } from 'react';\n\n/**\n * Hook to access the Sodax context which provides access to the Sodax SDK instance and chain configuration\n * @throws {Error} If used outside of a SodaxProvider\n * @returns {SodaxContextType} The Sodax context containing SDK instance and configuration\n */\n\nexport const useSodaxContext = (): SodaxContextType => {\n const context = useContext(SodaxContext);\n if (!context) {\n throw new Error('useSodaxContext must be used within a SodaxProvider');\n }\n return context;\n};\n","// packages/dapp-kit/src/hooks/shared/useEstimateGas.ts\nimport type { EstimateGasParams, GetEstimateGasReturnType, SpokeChainKey } from '@sodax/sdk';\nimport { useSodaxContext } from './useSodaxContext.js';\nimport type { MutationHookParams } from './types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';\nimport { unwrapResult } from './unwrapResult.js';\n\nexport function useEstimateGas<C extends SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<GetEstimateGasReturnType<C>, EstimateGasParams<C>> = {}): SafeUseMutationResult<\n GetEstimateGasReturnType<C>,\n Error,\n EstimateGasParams<C>\n> {\n const { sodax } = useSodaxContext();\n return useSafeMutation<GetEstimateGasReturnType<C>, Error, EstimateGasParams<C>>({\n mutationKey: ['shared', 'estimateGas'],\n ...mutationOptions,\n mutationFn: async params => unwrapResult(await sodax.spoke.estimateGas<C>(params)),\n });\n}\n","import type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from './useSodaxContext.js';\nimport type { Address } from 'viem';\nimport type { ReadHookParams } from './types.js';\n\nexport type UseDeriveUserWalletAddressParams = ReadHookParams<\n Address,\n {\n spokeChainId?: SpokeChainKey;\n spokeAddress?: string;\n }\n>;\n\nexport function useDeriveUserWalletAddress({\n params,\n queryOptions,\n}: UseDeriveUserWalletAddressParams = {}): UseQueryResult<Address, Error> {\n const { sodax } = useSodaxContext();\n const spokeChainId = params?.spokeChainId;\n const spokeAddress = params?.spokeAddress;\n\n return useQuery<Address, Error>({\n queryKey: ['shared', 'deriveUserWalletAddress', spokeChainId, spokeAddress],\n queryFn: async (): Promise<Address> => {\n if (!spokeChainId || !spokeAddress) {\n throw new Error('Spoke chain id and address are required');\n }\n return await sodax.hubProvider.getUserHubWalletAddress(spokeAddress, spokeChainId);\n },\n enabled: !!spokeChainId && !!spokeAddress,\n refetchInterval: false,\n ...queryOptions,\n });\n}\n","import { ChainKeys, type IStellarWalletProvider, type SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from './useSodaxContext.js';\nimport type { ReadHookParams } from './types.js';\n\nexport type UseStellarTrustlineCheckParams = ReadHookParams<\n boolean,\n {\n token: string | undefined;\n amount: bigint | undefined;\n chainId: SpokeChainKey | undefined;\n walletProvider: IStellarWalletProvider | undefined;\n }\n>;\n\nexport function useStellarTrustlineCheck({\n params,\n queryOptions,\n}: UseStellarTrustlineCheckParams = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const token = params?.token;\n const amount = params?.amount;\n const chainId = params?.chainId;\n const walletProvider = params?.walletProvider;\n\n return useQuery<boolean, Error>({\n queryKey: ['shared', 'stellarTrustlineCheck', token],\n queryFn: async () => {\n if (chainId !== ChainKeys.STELLAR_MAINNET) return true;\n if (!walletProvider || !token || !amount) return false;\n const walletAddress = await walletProvider.getWalletAddress();\n return sodax.spoke.stellar.hasSufficientTrustline(token, amount, walletAddress);\n },\n enabled: !!walletProvider && !!token && !!amount,\n ...queryOptions,\n });\n}\n","import { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useState } from 'react';\nimport type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';\nimport { useSodaxContext } from './useSodaxContext.js';\n\nexport function useRequestTrustline(token: string | undefined): {\n requestTrustline: (params: {\n token: string;\n amount: bigint;\n srcChainKey: StellarChainKey;\n walletProvider: IStellarWalletProvider;\n }) => Promise<string>;\n isLoading: boolean;\n isRequested: boolean;\n error: Error | null;\n data: string | null;\n} {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isRequested, setIsRequested] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n const [data, setData] = useState<string | null>(null);\n\n const requestTrustline = useCallback(\n async ({\n token,\n amount,\n srcChainKey,\n walletProvider,\n }: {\n token: string;\n amount: bigint;\n srcChainKey: StellarChainKey;\n walletProvider: IStellarWalletProvider;\n }): Promise<string> => {\n if (!token || !amount) {\n const error = new Error('Token and amount are required');\n setError(error);\n throw error;\n }\n setIsLoading(true);\n setError(null);\n try {\n const srcAddress = await walletProvider.getWalletAddress();\n const result = await sodax.spoke.stellar.requestTrustline<false>({\n raw: false,\n srcChainKey,\n srcAddress,\n token,\n amount,\n walletProvider,\n });\n setData(result);\n setIsRequested(true);\n queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck', token] });\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Unknown error occurred');\n setError(error);\n throw error;\n } finally {\n setIsLoading(false);\n }\n },\n [queryClient, sodax],\n );\n\n return { requestTrustline, isLoading, isRequested, error, data };\n}\n","import type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from './useSodaxContext.js';\nimport type { Address } from 'viem';\nimport type { ReadHookParams } from './types.js';\n\nexport type UseGetUserHubWalletAddressParams = ReadHookParams<\n Address,\n {\n spokeChainId?: SpokeChainKey;\n spokeAddress?: string;\n }\n>;\n\n/**\n * Hook for deriving user wallet address for hub abstraction.\n *\n * This hook derives the user's abstracted wallet address for the hub chain based on the spoke chain ID and address.\n * If the spoke chain is the same as the hub chain, it returns the encoded spoke address.\n * Otherwise, it derives and returns the abstracted wallet address for cross-chain operations.\n * NOTE: This hook is different from useDeriveUserWalletAddress because it uses wallet router address instead of CREATE3 address for Sonic (hub).\n *\n * The query is automatically enabled when both `spokeChainId` and `spokeAddress` are provided.\n * This is a deterministic operation, so the result is cached and not refetched automatically.\n *\n * @example\n * ```typescript\n * const { data: derivedAddress, isLoading, error } = useGetUserHubWalletAddress({\n * params: { spokeChainId, spokeAddress: userAddress },\n * });\n * ```\n */\nexport function useGetUserHubWalletAddress({\n params,\n queryOptions,\n}: UseGetUserHubWalletAddressParams = {}): UseQueryResult<Address, Error> {\n const { sodax } = useSodaxContext();\n const spokeChainId = params?.spokeChainId;\n const spokeAddress = params?.spokeAddress;\n\n return useQuery<Address, Error>({\n queryKey: ['shared', 'userHubWalletAddress', spokeChainId, spokeAddress],\n queryFn: async (): Promise<Address> => {\n if (!spokeChainId || !spokeAddress) {\n throw new Error('Spoke chain id and address are required');\n }\n return await sodax.hubProvider.getUserHubWalletAddress(spokeAddress, spokeChainId);\n },\n enabled: !!spokeChainId && !!spokeAddress,\n refetchInterval: false,\n ...queryOptions,\n });\n}\n","import { type UseQueryResult, useQuery } from '@tanstack/react-query';\nimport type { SpokeChainKey, IXServiceBase, XToken } from '@sodax/sdk';\nimport type { ReadHookParams } from './types.js';\n\n/**\n * Domain inputs for {@link useXBalances}. `xChainId` is optional so the hook can be mounted\n * before a chain is selected; `enabled` gates execution on every required field being present.\n */\nexport interface XBalancesInputs {\n xService: IXServiceBase | undefined;\n xChainId: SpokeChainKey | undefined;\n xTokens: readonly XToken[];\n address: string | undefined;\n}\n\nexport type UseXBalancesParams = ReadHookParams<Record<string, bigint>, XBalancesInputs>;\n\nconst REFETCH_INTERVAL_MS = 5_000;\n\n/**\n * Pure builder for {@link useXBalances} query options. Exported for unit\n * tests and for advanced callers that compose their own `useQuery` wrapper.\n */\nexport function getXBalancesQueryOptions({ xService, xChainId, xTokens, address }: XBalancesInputs) {\n return {\n // Pair symbol + address: readable in devtools, unique on-chain (symbol alone\n // can collide — e.g. scam tokens copying legitimate ticker).\n queryKey: ['shared', 'xBalances', xChainId, xTokens.map(x => [x.symbol, x.address] as const), address] as const,\n queryFn: async (): Promise<Record<string, bigint>> => {\n if (!xService) return {};\n return xService.getBalances(address, xTokens);\n },\n enabled: !!xService && !!address && xTokens.length > 0,\n refetchInterval: REFETCH_INTERVAL_MS,\n };\n}\n\n/**\n * Fetch token balances for multiple tokens on a specific chain. Returns an\n * object mapping each token's address to its balance in smallest unit.\n *\n * @example\n * ```tsx\n * const xService = useXService({ xChainType: getXChainType(xChainId) });\n * const { data: balances } = useXBalances({ params: { xService, xChainId, xTokens, address } });\n * ```\n */\nexport function useXBalances({\n params,\n queryOptions,\n}: UseXBalancesParams = {}): UseQueryResult<Record<string, bigint>> {\n return useQuery({\n ...getXBalancesQueryOptions({\n xService: params?.xService,\n xChainId: params?.xChainId,\n xTokens: params?.xTokens ?? [],\n address: params?.address,\n }),\n ...queryOptions,\n });\n}\n","import type { EvmHubProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\n\nexport function useHubProvider(): EvmHubProvider {\n const { sodax } = useSodaxContext();\n\n return sodax.hubProvider;\n}\n","// packages/dapp-kit/src/hooks/bitcoin/useRadfiAuth.ts\nimport { RadfiApiError, type IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\n\nexport type RadfiSession = {\n accessToken: string;\n refreshToken: string;\n tradingAddress: string;\n publicKey: string;\n};\n\nexport type UseRadfiAuthVars = {\n walletProvider: IBitcoinWalletProvider;\n};\n\ntype RadfiAuthResult = {\n accessToken: string;\n refreshToken: string;\n tradingAddress: string;\n};\n\nconst SESSION_KEY = (address: string): string => `radfi_session_${address}`;\n\nexport function saveRadfiSession(address: string, session: RadfiSession): void {\n try {\n localStorage.setItem(SESSION_KEY(address), JSON.stringify(session));\n } catch {}\n}\n\nexport function loadRadfiSession(address: string): RadfiSession | null {\n try {\n const raw = localStorage.getItem(SESSION_KEY(address));\n return raw ? (JSON.parse(raw) as RadfiSession) : null;\n } catch {\n return null;\n }\n}\n\nexport function clearRadfiSession(address: string): void {\n try {\n localStorage.removeItem(SESSION_KEY(address));\n } catch {}\n}\n\n/**\n * React hook for authenticating with Radfi via BIP322-signed message. Pure mutation: pass\n * `{ walletProvider }` to `mutate({...})`. The hook itself takes no arguments other than the\n * structural `mutationOptions` slot.\n */\nexport function useRadfiAuth({\n mutationOptions,\n}: MutationHookParams<RadfiAuthResult, UseRadfiAuthVars> = {}): SafeUseMutationResult<\n RadfiAuthResult,\n Error,\n UseRadfiAuthVars\n> {\n const { sodax } = useSodaxContext();\n return useSafeMutation<RadfiAuthResult, Error, UseRadfiAuthVars>({\n mutationKey: ['bitcoin', 'radfiAuth'],\n ...mutationOptions,\n mutationFn: async ({ walletProvider }) => {\n const radfi = sodax.spoke.bitcoin.radfi;\n const walletAddress = await walletProvider.getWalletAddress();\n const existingSession = loadRadfiSession(walletAddress);\n const cachedPublicKey = existingSession?.publicKey;\n\n try {\n const { accessToken, refreshToken, tradingAddress, publicKey } = await radfi.authenticateWithWallet(\n walletProvider,\n cachedPublicKey,\n );\n saveRadfiSession(walletAddress, { accessToken, refreshToken, tradingAddress, publicKey });\n return { accessToken, refreshToken, tradingAddress };\n } catch (err: unknown) {\n const isAlreadyRegistered = err instanceof RadfiApiError && err.code === '4008';\n\n if (isAlreadyRegistered && existingSession?.refreshToken) {\n try {\n const refreshed = await radfi.refreshAccessToken(existingSession.refreshToken);\n radfi.setRadfiAccessToken(refreshed.accessToken, refreshed.refreshToken);\n saveRadfiSession(walletAddress, {\n ...existingSession,\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n });\n return {\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n tradingAddress: existingSession.tradingAddress,\n };\n } catch {\n clearRadfiSession(walletAddress);\n }\n\n throw new Error(\n 'This wallet is already registered with Radfi from another session. ' +\n 'Please clear your browser storage for this site and try again, ' +\n 'or wait for the previous session to expire.',\n );\n }\n\n throw err;\n }\n },\n });\n}\n","// packages/dapp-kit/src/hooks/bitcoin/useRadfiSession.ts\nimport { useState, useEffect, useRef, useCallback } from 'react';\nimport type { IBitcoinWalletProvider } from '@sodax/sdk';\nimport {\n useRadfiAuth,\n loadRadfiSession,\n saveRadfiSession,\n clearRadfiSession,\n type RadfiSession,\n} from './useRadfiAuth.js';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\n\nconst REFRESH_INTERVAL = 5 * 60 * 1000;\n\nexport type UseRadfiSessionReturn = {\n walletAddress: string | undefined;\n isAuthed: boolean;\n tradingAddress: string | undefined;\n login: () => Promise<void>;\n isLoginPending: boolean;\n};\n\nexport function useRadfiSession(walletProvider: IBitcoinWalletProvider | undefined): UseRadfiSessionReturn {\n const { sodax } = useSodaxContext();\n const [walletAddress, setWalletAddress] = useState<string | undefined>();\n const [isAuthed, setIsAuthed] = useState(false);\n const [tradingAddress, setTradingAddress] = useState<string | undefined>();\n const isRefreshingRef = useRef(false);\n\n const silentRefresh = useCallback(\n async (address: string) => {\n if (!walletProvider || isRefreshingRef.current) return;\n isRefreshingRef.current = true;\n\n try {\n const session = loadRadfiSession(address);\n if (!session?.refreshToken) {\n setIsAuthed(false);\n return;\n }\n\n const radfi = sodax.spoke.bitcoin.radfi;\n const { accessToken, refreshToken } = await radfi.refreshAccessToken(session.refreshToken);\n const updated: RadfiSession = { ...session, accessToken, refreshToken };\n\n saveRadfiSession(address, updated);\n radfi.setRadfiAccessToken(accessToken, refreshToken);\n setIsAuthed(true);\n setTradingAddress(updated.tradingAddress || undefined);\n } catch {\n clearRadfiSession(address);\n sodax.spoke.bitcoin.radfi.setRadfiAccessToken('', '');\n setIsAuthed(false);\n setTradingAddress(undefined);\n } finally {\n isRefreshingRef.current = false;\n }\n },\n [walletProvider, sodax],\n );\n\n useEffect(() => {\n if (!walletProvider) return;\n\n setIsAuthed(false);\n setTradingAddress(undefined);\n setWalletAddress(undefined);\n\n walletProvider\n .getWalletAddress()\n .then((addr: string) => {\n setWalletAddress(addr);\n const session = loadRadfiSession(addr);\n if (!session?.refreshToken) return;\n silentRefresh(addr);\n })\n .catch(() => {});\n }, [walletProvider, silentRefresh]);\n\n useEffect(() => {\n if (!walletAddress || !walletProvider) return;\n\n const id = setInterval(() => {\n silentRefresh(walletAddress);\n }, REFRESH_INTERVAL);\n\n return () => clearInterval(id);\n }, [walletAddress, walletProvider, silentRefresh]);\n\n const { mutateAsyncSafe: loginMutateSafe, isPending: isLoginPending } = useRadfiAuth();\n\n const login = useCallback(async () => {\n if (!walletProvider) {\n return;\n }\n const result = await loginMutateSafe({ walletProvider });\n if (!result.ok) {\n return;\n }\n setIsAuthed(true);\n setTradingAddress(result.value.tradingAddress || undefined);\n }, [loginMutateSafe, walletProvider]);\n\n return { walletAddress, isAuthed, tradingAddress, login, isLoginPending };\n}\n","// packages/dapp-kit/src/hooks/bitcoin/useFundTradingWallet.ts\nimport { useQueryClient } from '@tanstack/react-query';\nimport { ChainKeys, type IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\n\nexport type UseFundTradingWalletVars = {\n amount: bigint;\n walletProvider: IBitcoinWalletProvider;\n};\n\n/**\n * React hook for funding the user's Radfi trading wallet from their personal Bitcoin wallet.\n * Pure mutation: pass `{ amount, walletProvider }` to `mutate({...})`. Returns the broadcast tx\n * id on success.\n */\nexport function useFundTradingWallet({\n mutationOptions,\n}: MutationHookParams<string, UseFundTradingWalletVars> = {}): SafeUseMutationResult<\n string,\n Error,\n UseFundTradingWalletVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<string, Error, UseFundTradingWalletVars>({\n mutationKey: ['bitcoin', 'fundTradingWallet'],\n ...mutationOptions,\n mutationFn: async ({ amount, walletProvider }) => {\n const walletAddress = await walletProvider.getWalletAddress();\n return sodax.spoke.bitcoin.fundTradingWallet(amount, walletAddress, walletProvider);\n },\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'balance'] });\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'tradingWalletBalance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.BITCOIN_MAINNET] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBitcoinBalanceParams = ReadHookParams<\n bigint,\n {\n address: string | undefined;\n rpcUrl?: string;\n }\n>;\n\nconst DEFAULT_RPC_URL = 'https://mempool.space/api';\n\n/**\n * Hook to fetch BTC balance for any Bitcoin address.\n * Sums all UTXOs (confirmed + unconfirmed) from mempool.space API.\n *\n * The UTXO set already excludes spent outputs (even from unconfirmed txs),\n * so the total is always the correct spendable balance.\n */\nexport function useBitcoinBalance({\n params,\n queryOptions,\n}: UseBitcoinBalanceParams = {}): UseQueryResult<bigint, Error> {\n const address = params?.address;\n const rpcUrl = params?.rpcUrl ?? DEFAULT_RPC_URL;\n\n return useQuery<bigint, Error>({\n queryKey: ['bitcoin', 'balance', address],\n queryFn: async () => {\n if (!address) return 0n;\n\n const response = await fetch(`${rpcUrl}/address/${address}/utxo`);\n if (!response.ok) return 0n;\n\n const utxos: Array<{ value: number }> = await response.json();\n return BigInt(utxos.reduce((sum, utxo) => sum + utxo.value, 0));\n },\n enabled: !!address,\n ...queryOptions,\n });\n}\n","import { loadRadfiSession } from './useRadfiAuth.js';\n\ntype UseTradingWalletReturn = {\n tradingAddress: string | undefined;\n};\n\n/**\n * Returns the Radfi trading wallet address from the persisted session.\n * Trading wallet is created automatically during authentication — no API call needed.\n */\nexport function useTradingWallet(walletAddress: string | undefined): UseTradingWalletReturn {\n if (!walletAddress) return { tradingAddress: undefined };\n const session = loadRadfiSession(walletAddress);\n return { tradingAddress: session?.tradingAddress || undefined };\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { RadfiWalletBalance, IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseTradingWalletBalanceParams = ReadHookParams<\n RadfiWalletBalance,\n {\n walletProvider: IBitcoinWalletProvider | undefined;\n tradingAddress: string | undefined;\n }\n>;\n\nexport function useTradingWalletBalance({\n params,\n queryOptions,\n}: UseTradingWalletBalanceParams = {}): UseQueryResult<RadfiWalletBalance, Error> {\n const { sodax } = useSodaxContext();\n const walletProvider = params?.walletProvider;\n const tradingAddress = params?.tradingAddress;\n\n return useQuery<RadfiWalletBalance, Error>({\n queryKey: ['bitcoin', 'tradingWalletBalance', tradingAddress],\n queryFn: () => {\n if (!walletProvider || !tradingAddress) {\n throw new Error('walletProvider and tradingAddress are required');\n }\n return sodax.spoke.bitcoin.radfi.getBalance(tradingAddress);\n },\n enabled: !!walletProvider && !!tradingAddress,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { RadfiUtxo, IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseExpiredUtxosParams = ReadHookParams<\n RadfiUtxo[],\n {\n walletProvider: IBitcoinWalletProvider | undefined;\n tradingAddress: string | undefined;\n }\n>;\n\nexport function useExpiredUtxos({\n params,\n queryOptions,\n}: UseExpiredUtxosParams = {}): UseQueryResult<RadfiUtxo[], Error> {\n const { sodax } = useSodaxContext();\n const walletProvider = params?.walletProvider;\n const tradingAddress = params?.tradingAddress;\n\n return useQuery<RadfiUtxo[], Error>({\n queryKey: ['bitcoin', 'expiredUtxos', tradingAddress],\n queryFn: async () => {\n if (!walletProvider || !tradingAddress) {\n throw new Error('walletProvider and tradingAddress are required');\n }\n const result = await sodax.spoke.bitcoin.radfi.getExpiredUtxos(tradingAddress);\n return result.data;\n },\n enabled: !!walletProvider && !!tradingAddress,\n refetchInterval: 60_000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/bitcoin/useRenewUtxos.ts\nimport { normalizePsbtToBase64, type IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { loadRadfiSession } from './useRadfiAuth.js';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\n\nexport type UseRenewUtxosVars = {\n txIdVouts: string[];\n walletProvider: IBitcoinWalletProvider;\n};\n\n/**\n * React hook for renewing expired UTXOs in the user's Radfi trading wallet. Pure mutation: pass\n * `{ txIdVouts, walletProvider }` to `mutate({...})`.\n */\nexport function useRenewUtxos({\n mutationOptions,\n}: MutationHookParams<string, UseRenewUtxosVars> = {}): SafeUseMutationResult<string, Error, UseRenewUtxosVars> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<string, Error, UseRenewUtxosVars>({\n mutationKey: ['bitcoin', 'renewUtxos'],\n ...mutationOptions,\n mutationFn: async ({ txIdVouts, walletProvider }) => {\n const radfi = sodax.spoke.bitcoin.radfi;\n\n const userAddress = await walletProvider.getWalletAddress();\n const session = loadRadfiSession(userAddress);\n const accessToken = session?.accessToken || radfi.accessToken;\n\n if (!accessToken) {\n throw new Error('Radfi authentication required. Please login first.');\n }\n\n const buildResult = await radfi.buildRenewUtxoTransaction({ userAddress, txIdVouts }, accessToken);\n\n const signedTx = await walletProvider.signTransaction(buildResult.base64Psbt, false);\n\n const signedBase64Tx = normalizePsbtToBase64(signedTx);\n\n return radfi.signAndBroadcastRenewUtxo({ userAddress, signedBase64Tx }, accessToken);\n },\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'expiredUtxos'] });\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'tradingWalletBalance'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/bitcoin/useRadfiWithdraw.ts\nimport { normalizePsbtToBase64, ChainKeys, type IBitcoinWalletProvider } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { loadRadfiSession } from './useRadfiAuth.js';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\n\nexport type UseRadfiWithdrawVars = {\n amount: string;\n tokenId: string;\n withdrawTo: string;\n walletProvider: IBitcoinWalletProvider;\n};\n\ntype WithdrawResult = {\n txId: string;\n fee: number;\n};\n\n/**\n * React hook for withdrawing BTC from the user's Radfi trading wallet back to their personal\n * Bitcoin wallet. Pure mutation: pass all inputs (including the wallet provider) to\n * `mutate({...})`.\n */\nexport function useRadfiWithdraw({\n mutationOptions,\n}: MutationHookParams<WithdrawResult, UseRadfiWithdrawVars> = {}): SafeUseMutationResult<\n WithdrawResult,\n Error,\n UseRadfiWithdrawVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<WithdrawResult, Error, UseRadfiWithdrawVars>({\n mutationKey: ['bitcoin', 'radfiWithdraw'],\n ...mutationOptions,\n mutationFn: async ({ amount, tokenId, withdrawTo, walletProvider }) => {\n const radfi = sodax.spoke.bitcoin.radfi;\n\n const userAddress = await walletProvider.getWalletAddress();\n const session = loadRadfiSession(userAddress);\n const accessToken = session?.accessToken || radfi.accessToken;\n\n if (!accessToken) {\n throw new Error('Radfi authentication required. Please login first.');\n }\n\n const buildResult = await radfi.withdrawToUser({ userAddress, amount, tokenId, withdrawTo }, accessToken);\n\n const signedTx = await walletProvider.signTransaction(buildResult.base64Psbt, false);\n\n const signedBase64Tx = normalizePsbtToBase64(signedTx);\n\n const txId = await radfi.signAndBroadcastWithdraw({ userAddress, signedBase64Tx }, accessToken);\n\n return { txId, fee: buildResult.fee.totalFee };\n },\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'tradingWalletBalance'] });\n queryClient.invalidateQueries({ queryKey: ['bitcoin', 'balance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.BITCOIN_MAINNET] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useBorrow.ts\nimport type { MoneyMarketBorrowActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useBorrow}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseBorrowVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n MoneyMarketBorrowActionParams<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for borrowing tokens from the Sodax money market protocol.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useBorrow<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseBorrowVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseBorrowVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseBorrowVars<K>>({\n mutationKey: ['mm', 'borrow'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.moneyMarket.borrow({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['mm', 'userReservesData', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });\n const balanceChains = new Set([params.srcChainKey, params.dstChainKey ?? params.srcChainKey]);\n for (const chainKey of balanceChains) {\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', chainKey] });\n }\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useRepay.ts\nimport type { MoneyMarketRepayActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useRepay}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseRepayVars<K extends SpokeChainKey = SpokeChainKey> = Omit<MoneyMarketRepayActionParams<K, false>, 'raw'>;\n\n/**\n * React hook for repaying a borrow in the Sodax money market protocol.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useRepay<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseRepayVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseRepayVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseRepayVars<K>>({\n mutationKey: ['mm', 'repay'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.moneyMarket.repay({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['mm', 'userReservesData', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });\n queryClient.invalidateQueries({ queryKey: ['mm', 'allowance', params.srcChainKey, params.token, params.action] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useSupply.ts\nimport type { MoneyMarketSupplyActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useSupply}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseSupplyVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n MoneyMarketSupplyActionParams<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for supplying tokens to the Sodax money market protocol.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n *\n * @example\n * ```tsx\n * const walletProvider = useWalletProvider({ xChainId: chainKey });\n * const { mutateAsync: supply, isError, error } = useSupply();\n * if (!walletProvider) return;\n * try {\n * const { spokeTxHash, hubTxHash } = await supply({ params: supplyParams, walletProvider });\n * } catch (e) {\n * // surfaced via mutation.error / onError\n * }\n * ```\n */\nexport function useSupply<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseSupplyVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseSupplyVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseSupplyVars<K>>({\n mutationKey: ['mm', 'supply'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.moneyMarket.supply({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['mm', 'userReservesData', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });\n queryClient.invalidateQueries({ queryKey: ['mm', 'allowance', params.srcChainKey, params.token, params.action] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useWithdraw.ts\nimport type { MoneyMarketWithdrawActionParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useWithdraw}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n MoneyMarketWithdrawActionParams<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for withdrawing supplied tokens from the Sodax money market protocol.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useWithdraw<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseWithdrawVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseWithdrawVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseWithdrawVars<K>>({\n mutationKey: ['mm', 'withdraw'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.moneyMarket.withdraw({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['mm', 'userReservesData', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['mm', 'userFormattedSummary', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['mm', 'aTokensBalances'] });\n const balanceChains = new Set([params.srcChainKey, params.dstChainKey ?? params.srcChainKey]);\n for (const chainKey of balanceChains) {\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', chainKey] });\n }\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { UserReserveData } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseUserReservesDataParams = ReadHookParams<\n readonly [readonly UserReserveData[], number],\n {\n spokeChainKey: SpokeChainKey | undefined;\n userAddress: string | undefined;\n }\n>;\n\n/**\n * React hook for fetching the raw user reserves data (positions on the hub) for a given spoke\n * chain and user address.\n */\nexport function useUserReservesData({\n params,\n queryOptions,\n}: UseUserReservesDataParams = {}): UseQueryResult<readonly [readonly UserReserveData[], number], Error> {\n const { sodax } = useSodaxContext();\n const spokeChainKey = params?.spokeChainKey;\n const userAddress = params?.userAddress;\n\n return useQuery({\n queryKey: ['mm', 'userReservesData', spokeChainKey, userAddress],\n queryFn: async () => {\n if (!spokeChainKey || !userAddress) {\n throw new Error('spokeChainKey and userAddress are required');\n }\n return sodax.moneyMarket.data.getUserReservesData(spokeChainKey, userAddress);\n },\n enabled: !!spokeChainKey && !!userAddress,\n refetchInterval: 5000,\n ...queryOptions,\n });\n}\n","import type { AggregatedReserveData, BaseCurrencyInfo } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseReservesDataParams = ReadHookParams<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo]>;\n\n/**\n * React hook for fetching the latest aggregated reserves data and base-currency info from the\n * Sodax money market.\n */\nexport function useReservesData({\n queryOptions,\n}: UseReservesDataParams = {}): UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['mm', 'reservesData'],\n queryFn: async () => sodax.moneyMarket.data.getReservesData(),\n refetchInterval: 5000,\n ...queryOptions,\n });\n}\n","import type { ReservesDataHumanized } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseReservesHumanizedParams = ReadHookParams<ReservesDataHumanized>;\n\n/**\n * React hook for fetching the human-readable (decimal-normalized, string-formatted) reserves\n * snapshot from the Sodax money market.\n */\nexport function useReservesHumanized({\n queryOptions,\n}: UseReservesHumanizedParams = {}): UseQueryResult<ReservesDataHumanized, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery({\n queryKey: ['mm', 'reservesHumanized'],\n queryFn: async () => sodax.moneyMarket.data.getReservesHumanized(),\n refetchInterval: 5000,\n ...queryOptions,\n });\n}\n","import type { Address } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseReservesListParams = ReadHookParams<readonly Address[]>;\n\n/**\n * React hook for fetching the list of reserve asset addresses currently registered in the\n * Sodax money market.\n */\nexport function useReservesList({\n queryOptions,\n}: UseReservesListParams = {}): UseQueryResult<readonly Address[], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery<readonly Address[], Error>({\n queryKey: ['mm', 'reservesList'],\n queryFn: async () => sodax.moneyMarket.data.getReservesList(),\n ...queryOptions,\n });\n}\n","import type { MoneyMarketParams } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseMMAllowanceParams<K extends SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: MoneyMarketParams<K> | undefined;\n }\n>;\n\n/**\n * Hook for checking token allowance / trustline sufficiency for money market operations.\n *\n * Skips the on-chain check entirely for `borrow` and `withdraw` actions — those don't require\n * approval, and the SDK already short-circuits to `true` for them. The early `enabled: false`\n * here additionally avoids a render flash with `isLoading: true`.\n *\n * The query key matches the invalidation keys emitted by `useMMApprove` and the four mutation\n * hooks: `['mm', 'allowance', srcChainKey, token, action]`.\n *\n * @example\n * ```tsx\n * const { data: hasAllowance } = useMMAllowance({ params: { payload: supplyParams } });\n * ```\n */\nexport function useMMAllowance<K extends SpokeChainKey>({\n params,\n queryOptions,\n}: UseMMAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: ['mm', 'allowance', payload?.srcChainKey, payload?.token, payload?.action],\n queryFn: async () => {\n if (!payload) {\n throw new Error('Params are required');\n }\n\n // Borrow and withdraw don't require approval; SDK returns true instantly anyway.\n if (payload.action === 'borrow' || payload.action === 'withdraw') {\n return true;\n }\n\n const result = await sodax.moneyMarket.isAllowanceValid({ params: payload });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload && payload.action !== 'borrow' && payload.action !== 'withdraw',\n refetchInterval: 5000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/mm/useMMApprove.ts\nimport type { MoneyMarketApproveActionParams, SpokeChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useMMApprove}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseMMApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n MoneyMarketApproveActionParams<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for approving ERC-20 token spending (or trustline establishment) for a Sodax money\n * market action.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates the matching\n * `['mm', 'allowance', srcChainKey, token, action]` query on confirmed success.\n */\nexport function useMMApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseMMApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseMMApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseMMApproveVars<K>>({\n mutationKey: ['mm', 'approve'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.moneyMarket.approve({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({\n queryKey: ['mm', 'allowance', params.srcChainKey, params.token, params.action],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { Erc20Token } from '@sodax/sdk';\nimport type { ChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { type Address, isAddress } from 'viem';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type ATokenData = Erc20Token & { chainKey: ChainKey };\n\nexport type UseATokenParams = ReadHookParams<\n ATokenData,\n {\n aToken: Address | string | undefined;\n }\n>;\n\n/**\n * React hook to fetch ERC-20 metadata for a given aToken address on the hub chain.\n * Returns `Erc20Token` (`name`, `symbol`, `decimals`, `address`) augmented with the hub\n * `chainKey`. Note: the returned shape is a subset of `XToken` — `hubAsset` and `vault` fields\n * must be resolved separately if needed.\n */\nexport function useAToken({ params, queryOptions }: UseATokenParams = {}): UseQueryResult<ATokenData, Error> {\n const { sodax } = useSodaxContext();\n const aToken = params?.aToken;\n\n return useQuery({\n queryKey: ['mm', 'aToken', aToken],\n queryFn: async () => {\n if (!aToken) {\n throw new Error('aToken address is required');\n }\n if (!isAddress(aToken)) {\n throw new Error('aToken address is not a valid address');\n }\n\n const aTokenData = await sodax.moneyMarket.data.getATokenData(aToken);\n return {\n ...aTokenData,\n chainKey: sodax.hubProvider.chainConfig.chain.key,\n };\n },\n enabled: !!aToken && isAddress(aToken ?? ''),\n ...queryOptions,\n });\n}\n","import type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { type Address, isAddress } from 'viem';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseATokensBalancesParams = ReadHookParams<\n Map<Address, bigint>,\n {\n aTokens: readonly Address[];\n spokeChainKey: SpokeChainKey | undefined;\n userAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch aToken balances for a list of addresses in a single multicall.\n * Derives the user's hub wallet via `EvmHubProvider.getUserHubWalletAddress` from the\n * spoke `chainKey` + spoke wallet `userAddress`.\n */\nexport function useATokensBalances({\n params,\n queryOptions,\n}: UseATokensBalancesParams = {}): UseQueryResult<Map<Address, bigint>, Error> {\n const { sodax } = useSodaxContext();\n const aTokens = params?.aTokens ?? [];\n const spokeChainKey = params?.spokeChainKey;\n const userAddress = params?.userAddress;\n\n return useQuery({\n queryKey: ['mm', 'aTokensBalances', aTokens, spokeChainKey, userAddress],\n queryFn: async () => {\n if (aTokens.length === 0) {\n return new Map<Address, bigint>();\n }\n if (!spokeChainKey || !userAddress) {\n throw new Error('spokeChainKey and userAddress are required');\n }\n for (const aToken of aTokens) {\n if (!isAddress(aToken)) {\n throw new Error(`Invalid aToken address: ${aToken}`);\n }\n }\n\n const hubWalletAddress = await sodax.hubProvider.getUserHubWalletAddress(userAddress, spokeChainKey);\n return sodax.moneyMarket.data.getATokensBalances(aTokens, hubWalletAddress);\n },\n enabled: aTokens.length > 0 && !!spokeChainKey && !!userAddress,\n ...queryOptions,\n });\n}\n","import type { FormatReserveUSDResponse, ReserveDataHumanized } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type ReserveUsdFormat = ReserveDataHumanized & FormatReserveUSDResponse;\n\nexport type UseReservesUsdFormatParams = ReadHookParams<ReserveUsdFormat[]>;\n\n/**\n * React hook returning reserves with USD-formatted values for the Sodax money market.\n * Chains `getReservesHumanized` → `buildReserveDataWithPrice` → `formatReservesUSD`.\n */\nexport function useReservesUsdFormat({\n queryOptions,\n}: UseReservesUsdFormatParams = {}): UseQueryResult<ReserveUsdFormat[], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery<ReserveUsdFormat[], Error>({\n queryKey: ['mm', 'reservesUsdFormat'],\n queryFn: async () => {\n const reserves = await sodax.moneyMarket.data.getReservesHumanized();\n return sodax.moneyMarket.data.formatReservesUSD(sodax.moneyMarket.data.buildReserveDataWithPrice(reserves));\n },\n ...queryOptions,\n });\n}\n","import type { FormatReserveUSDResponse, FormatUserSummaryResponse } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseUserFormattedSummaryParams = ReadHookParams<\n FormatUserSummaryResponse<FormatReserveUSDResponse>,\n {\n spokeChainKey: SpokeChainKey | undefined;\n userAddress: string | undefined;\n }\n>;\n\n/**\n * React hook returning the user's formatted money market portfolio summary (collateral, borrows,\n * health factor, available borrow power, etc.) for the given spoke chain.\n *\n * Internally chains `getReservesHumanized` → `formatReservesUSD` → `getUserReservesHumanized`\n * → `formatUserSummary`.\n */\nexport function useUserFormattedSummary({\n params,\n queryOptions,\n}: UseUserFormattedSummaryParams = {}): UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error> {\n const { sodax } = useSodaxContext();\n const spokeChainKey = params?.spokeChainKey;\n const userAddress = params?.userAddress;\n\n return useQuery({\n queryKey: ['mm', 'userFormattedSummary', spokeChainKey, userAddress],\n queryFn: async () => {\n if (!spokeChainKey || !userAddress) {\n throw new Error('spokeChainKey and userAddress are required');\n }\n\n const [reserves, userReserves] = await Promise.all([\n sodax.moneyMarket.data.getReservesHumanized(),\n sodax.moneyMarket.data.getUserReservesHumanized(spokeChainKey, userAddress),\n ]);\n const formattedReserves = sodax.moneyMarket.data.formatReservesUSD(\n sodax.moneyMarket.data.buildReserveDataWithPrice(reserves),\n );\n\n return sodax.moneyMarket.data.formatUserSummary(\n sodax.moneyMarket.data.buildUserSummaryRequest(reserves, formattedReserves, userReserves),\n );\n },\n enabled: !!spokeChainKey && !!userAddress,\n refetchInterval: 5000,\n ...queryOptions,\n });\n}\n","import type { SolverErrorResponse, SolverIntentQuoteRequest, SolverIntentQuoteResponse } from '@sodax/sdk';\nimport type { Result } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseQuoteParams = ReadHookParams<\n Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined,\n { payload: SolverIntentQuoteRequest | undefined }\n>;\n\n/**\n * Hook for fetching a quote for an intent-based swap.\n *\n * @example\n * ```typescript\n * const { data: quote, isLoading } = useQuote({ params: { payload } });\n * ```\n *\n * @remarks\n * - The quote is automatically refreshed every 3 seconds\n * - The query is disabled when payload is undefined\n */\nexport const useQuote = ({\n params,\n queryOptions,\n}: UseQuoteParams = {}): UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery({\n queryKey: ['swap', 'quote', payload && { ...payload, amount: payload.amount.toString() }],\n queryFn: async () => {\n if (!payload) {\n return undefined;\n }\n return sodax.swaps.getQuote(payload);\n },\n enabled: !!payload,\n refetchInterval: 3000,\n ...queryOptions,\n });\n};\n","// packages/dapp-kit/src/hooks/swap/useSwap.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { SpokeChainKey, SwapActionParams, SwapResponse } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useSwap}. Generic over `K extends SpokeChainKey` (defaults to the\n * full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseSwapVars<K extends SpokeChainKey = SpokeChainKey> = Omit<SwapActionParams<K, false>, 'raw'>;\n\n/**\n * React hook for executing an intent-based cross-chain swap.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.\n */\nexport function useSwap<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<SwapResponse, UseSwapVars<K>> = {}): SafeUseMutationResult<\n SwapResponse,\n Error,\n UseSwapVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<SwapResponse, Error, UseSwapVars<K>>({\n mutationKey: ['swap'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.swaps.swap({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { Hex, SolverErrorResponse, SolverIntentStatusResponse } from '@sodax/sdk';\nimport type { Result } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseStatusParams = ReadHookParams<\n Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined,\n { intentTxHash: Hex | undefined }\n>;\n\n/**\n * Hook for monitoring the status of an intent-based swap.\n *\n * @example\n * ```typescript\n * const { data: status, isLoading } = useStatus({ params: { intentTxHash } });\n * ```\n */\nexport const useStatus = ({\n params,\n queryOptions,\n}: UseStatusParams = {}): UseQueryResult<Result<SolverIntentStatusResponse, SolverErrorResponse> | undefined> => {\n const { sodax } = useSodaxContext();\n const intentTxHash = params?.intentTxHash;\n\n return useQuery({\n queryKey: ['swap', 'status', intentTxHash],\n queryFn: async () => {\n if (!intentTxHash) return undefined;\n return sodax.swaps.getStatus({ intent_tx_hash: intentTxHash });\n },\n enabled: !!intentTxHash,\n refetchInterval: 3000,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { CreateIntentParams, CreateLimitOrderParams } from '@sodax/sdk';\nimport type { GetWalletProviderType, SpokeChainKey } from '@sodax/sdk';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseSwapAllowanceParams<K extends SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: CreateIntentParams | CreateLimitOrderParams | undefined;\n srcChainKey: K | undefined;\n walletProvider: GetWalletProviderType<K> | undefined;\n }\n>;\n\nexport function useSwapAllowance<K extends SpokeChainKey>({\n params,\n queryOptions,\n}: UseSwapAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n const srcChainKey = params?.srcChainKey;\n const walletProvider = params?.walletProvider;\n\n return useQuery<boolean, Error>({\n // Extract the (chain, owner, token, amount) tuple that actually scopes the allowance —\n // raw-object keys break per Rule 4 (bigints) and churn on every render.\n queryKey: [\n 'swap',\n 'allowance',\n payload?.srcChainKey,\n payload?.srcAddress,\n payload?.inputToken,\n payload?.inputAmount?.toString(),\n ],\n queryFn: async () => {\n if (!srcChainKey || !walletProvider || !payload) {\n return false;\n }\n const allowance = await sodax.swaps.isAllowanceValid({\n params: payload as CreateIntentParams,\n raw: false,\n walletProvider,\n });\n return allowance.ok ? allowance.value : false;\n },\n enabled: !!srcChainKey && !!walletProvider && !!payload,\n refetchInterval: 2000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/swap/useSwapApprove.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { useQueryClient } from '@tanstack/react-query';\nimport type {\n CreateIntentParams,\n CreateLimitOrderParams,\n GetWalletProviderType,\n SpokeChainKey,\n TxReturnType,\n} from '@sodax/sdk';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useSwapApprove}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseSwapApproveVars<K extends SpokeChainKey = SpokeChainKey> = {\n params: CreateIntentParams<K> | CreateLimitOrderParams<K>;\n walletProvider: GetWalletProviderType<K>;\n};\n\n/**\n * React hook for approving ERC-20 token spending (or trustline establishment) for a swap or\n * limit-order intent.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates all\n * `['swap', 'allowance', ...]` queries so any pending allowance check refreshes.\n */\nexport function useSwapApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseSwapApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseSwapApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseSwapApproveVars<K>>({\n mutationKey: ['swap', 'approve'],\n ...mutationOptions,\n mutationFn: async ({ params, walletProvider }) =>\n unwrapResult(\n await sodax.swaps.approve<K, false>({\n params: params as CreateIntentParams<K>,\n raw: false,\n walletProvider,\n }),\n ),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['swap', 'allowance'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/swap/useCancelSwap.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\ntype CancelIntentParams<K extends SpokeChainKey = SpokeChainKey> = {\n srcChainKey: K;\n walletProvider: GetWalletProviderType<K>;\n intent: Intent;\n};\n\n/**\n * React hook for cancelling an in-flight swap intent.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useCancelSwap({\n mutationOptions,\n}: MutationHookParams<TxHashPair, CancelIntentParams> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n CancelIntentParams\n> {\n const { sodax } = useSodaxContext();\n\n return useSafeMutation<TxHashPair, Error, CancelIntentParams>({\n mutationKey: ['swap', 'cancel'],\n ...mutationOptions,\n mutationFn: async ({ srcChainKey, walletProvider, intent }) =>\n unwrapResult(await sodax.swaps.cancelIntent({ params: { srcChainKey, intent }, walletProvider })),\n });\n}\n","// packages/dapp-kit/src/hooks/swap/useCreateLimitOrder.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { LimitOrderActionParams, SpokeChainKey, SwapResponse } from '@sodax/sdk';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useCreateLimitOrder}. Generic over `K extends SpokeChainKey`\n * (defaults to the full union). Sophisticated callers can lock K at the call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseCreateLimitOrderVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n LimitOrderActionParams<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for creating a limit-order intent (no deadline).\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `SwapResponse` on success.\n */\nexport function useCreateLimitOrder<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<SwapResponse, UseCreateLimitOrderVars<K>> = {}): SafeUseMutationResult<\n SwapResponse,\n Error,\n UseCreateLimitOrderVars<K>\n> {\n const { sodax } = useSodaxContext();\n\n return useSafeMutation<SwapResponse, Error, UseCreateLimitOrderVars<K>>({\n mutationKey: ['swap', 'limitOrder', 'create'],\n ...mutationOptions,\n mutationFn: async vars =>\n unwrapResult(await sodax.swaps.createLimitOrder({ ...vars, raw: false })),\n });\n}\n","// packages/dapp-kit/src/hooks/swap/useCancelLimitOrder.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { GetWalletProviderType, Intent, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\ntype CancelLimitOrderParams<K extends SpokeChainKey = SpokeChainKey> = {\n srcChainKey: K;\n walletProvider: GetWalletProviderType<K>;\n intent: Intent;\n timeout?: number;\n};\n\n/**\n * React hook for cancelling a limit-order intent.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useCancelLimitOrder({\n mutationOptions,\n}: MutationHookParams<TxHashPair, CancelLimitOrderParams> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n CancelLimitOrderParams\n> {\n const { sodax } = useSodaxContext();\n\n return useSafeMutation<TxHashPair, Error, CancelLimitOrderParams>({\n mutationKey: ['swap', 'limitOrder', 'cancel'],\n ...mutationOptions,\n mutationFn: async ({ srcChainKey, walletProvider, intent, timeout }) =>\n unwrapResult(await sodax.swaps.cancelLimitOrder({ params: { srcChainKey, intent }, walletProvider, timeout })),\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { IntentResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendIntentByTxHashParams = ReadHookParams<\n IntentResponse | undefined,\n {\n txHash: string | undefined;\n }\n>;\n\n/**\n * React hook for fetching intent details from the backend API using a transaction hash.\n *\n * @example\n * const { data: intent } = useBackendIntentByTxHash({ params: { txHash: '0x123...' } });\n *\n * @remarks\n * - Intents are only created on the hub chain, so `txHash` must originate from there.\n * - Default refetch interval is 1 second.\n */\nexport const useBackendIntentByTxHash = ({\n params,\n queryOptions,\n}: UseBackendIntentByTxHashParams = {}): UseQueryResult<IntentResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const txHash = params?.txHash;\n\n return useQuery({\n queryKey: ['backend', 'intent', 'txHash', txHash],\n queryFn: async (): Promise<IntentResponse | undefined> => {\n if (!txHash) return undefined;\n const result = await sodax.backendApi.getIntentByTxHash(txHash);\n return result.ok ? result.value : undefined;\n },\n enabled: !!txHash && txHash.length > 0,\n retry: 3,\n refetchInterval: 1000,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { IntentResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendIntentByHashParams = ReadHookParams<\n IntentResponse | undefined,\n {\n intentHash: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch intent details from the backend API using an intent hash.\n *\n * @example\n * const { data: intent } = useBackendIntentByHash({ params: { intentHash: '0xabc...' } });\n */\nexport const useBackendIntentByHash = ({\n params,\n queryOptions,\n}: UseBackendIntentByHashParams = {}): UseQueryResult<IntentResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const intentHash = params?.intentHash;\n\n return useQuery({\n queryKey: ['backend', 'intent', 'hash', intentHash],\n queryFn: async (): Promise<IntentResponse | undefined> => {\n if (!intentHash) return undefined;\n const result = await sodax.backendApi.getIntentByHash(intentHash);\n return result.ok ? result.value : undefined;\n },\n enabled: !!intentHash && intentHash.length > 0,\n retry: 3,\n ...queryOptions,\n });\n};\n","import type { UserIntentsResponse, Address } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendUserIntentsParams = ReadHookParams<\n UserIntentsResponse | undefined,\n {\n userAddress: Address | undefined;\n startDate?: number;\n endDate?: number;\n }\n>;\n\n/**\n * React hook for fetching user-created intents from the backend API for a given user address.\n *\n * @example\n * const { data: userIntents } = useBackendUserIntents({\n * params: { userAddress: '0x123...' },\n * });\n */\nexport const useBackendUserIntents = ({\n params,\n queryOptions,\n}: UseBackendUserIntentsParams = {}): UseQueryResult<UserIntentsResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const userAddress = params?.userAddress;\n const startDate = params?.startDate;\n const endDate = params?.endDate;\n\n return useQuery({\n queryKey: ['backend', 'intent', 'user', userAddress, startDate, endDate],\n queryFn: async (): Promise<UserIntentsResponse | undefined> => {\n if (!userAddress) return undefined;\n return unwrapResult(await sodax.backendApi.getUserIntents({ userAddress, startDate, endDate }));\n },\n enabled: !!userAddress && userAddress.length > 0,\n retry: 3,\n ...queryOptions,\n });\n};\n","// packages/dapp-kit/src/hooks/backend/useBackendSubmitSwapTx.ts\nimport type { RequestOverrideConfig, SubmitSwapTxRequest, SubmitSwapTxResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\n\n/**\n * Mutation variables for {@link useBackendSubmitSwapTx}. The per-request `apiConfig` override\n * (e.g. base URL) belongs here rather than at the hook level — different submissions in the same\n * component can target different endpoints without re-rendering.\n */\nexport type UseBackendSubmitSwapTxVars = {\n request: SubmitSwapTxRequest;\n apiConfig?: RequestOverrideConfig;\n};\n\n/**\n * React hook for submitting a swap transaction to be processed by the backend (relay, post\n * execution to solver, etc.).\n *\n * Pure mutation: pass `{ request, apiConfig? }` to `mutate({...})`. Default `retry: 3` is applied\n * at the hook level — consumers can override via `mutationOptions.retry`.\n *\n * @example\n * const { mutateAsync: submitSwapTx, isPending, error } = useBackendSubmitSwapTx();\n *\n * const result = await submitSwapTx({\n * request: { txHash: '0x123...', srcChainKey: 'sonic', walletAddress: '0xabc...', intent: { ... }, relayData: '0x...' },\n * apiConfig: { baseURL: 'https://...' },\n * });\n */\nexport const useBackendSubmitSwapTx = ({\n mutationOptions,\n}: MutationHookParams<SubmitSwapTxResponse, UseBackendSubmitSwapTxVars> = {}): SafeUseMutationResult<\n SubmitSwapTxResponse,\n Error,\n UseBackendSubmitSwapTxVars\n> => {\n const { sodax } = useSodaxContext();\n\n return useSafeMutation<SubmitSwapTxResponse, Error, UseBackendSubmitSwapTxVars>({\n mutationKey: ['backend', 'submitSwapTx'],\n retry: 3,\n ...mutationOptions,\n mutationFn: async ({ request, apiConfig }): Promise<SubmitSwapTxResponse> =>\n unwrapResult(await sodax.backendApi.submitSwapTx(request, apiConfig)),\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { RequestOverrideConfig, SubmitSwapTxStatusResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendSubmitSwapTxStatusParams = ReadHookParams<\n SubmitSwapTxStatusResponse | undefined,\n {\n txHash: string | undefined;\n srcChainKey?: string;\n apiConfig?: RequestOverrideConfig;\n }\n>;\n\n/**\n * React hook for polling the processing status of a submitted swap transaction.\n *\n * @example\n * const { data: status } = useBackendSubmitSwapTxStatus({\n * params: { txHash: '0x123...', srcChainKey: 'sonic' },\n * });\n *\n * @remarks\n * - Default refetch interval is 1 second; stops on 'executed' or 'failed' status.\n */\nexport const useBackendSubmitSwapTxStatus = ({\n params,\n queryOptions,\n}: UseBackendSubmitSwapTxStatusParams = {}): UseQueryResult<SubmitSwapTxStatusResponse | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const txHash = params?.txHash;\n const srcChainKey = params?.srcChainKey;\n const apiConfig = params?.apiConfig;\n\n return useQuery({\n queryKey: ['backend', 'submitSwapTx', 'status', txHash, srcChainKey],\n queryFn: async (): Promise<SubmitSwapTxStatusResponse | undefined> => {\n if (!txHash) return undefined;\n return unwrapResult(\n await sodax.backendApi.getSubmitSwapTxStatus(\n {\n txHash,\n srcChainKey,\n },\n apiConfig,\n ),\n );\n },\n enabled: !!txHash && txHash.length > 0,\n retry: 3,\n refetchInterval: query => {\n const status = query.state.data?.data?.status;\n if (status === 'executed' || status === 'failed') return false;\n return 1000;\n },\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { OrderbookResponse } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { BackendPaginationParams } from './types.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendOrderbookParams = ReadHookParams<\n OrderbookResponse,\n {\n pagination: BackendPaginationParams;\n }\n>;\n\n/**\n * Hook for fetching the solver orderbook from the backend API.\n *\n * @example\n * const { data } = useBackendOrderbook({ params: { pagination: { offset: '0', limit: '10' } } });\n */\nexport const useBackendOrderbook = ({\n params,\n queryOptions,\n}: UseBackendOrderbookParams = {}): UseQueryResult<OrderbookResponse> => {\n const { sodax } = useSodaxContext();\n const pagination = params?.pagination;\n\n return useQuery<OrderbookResponse, Error>({\n queryKey: ['backend', 'orderbook', pagination?.offset, pagination?.limit],\n queryFn: async (): Promise<OrderbookResponse> => {\n if (!pagination?.offset || !pagination?.limit) {\n throw new Error('Pagination offset and limit are required');\n }\n return unwrapResult(await sodax.backendApi.getOrderbook(pagination));\n },\n enabled: !!pagination?.offset && !!pagination?.limit,\n staleTime: 30 * 1000,\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketPosition } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendMoneyMarketPositionParams = ReadHookParams<\n MoneyMarketPosition | undefined,\n {\n userAddress: string | undefined;\n }\n>;\n\n/**\n * React hook for fetching a user's money market position from the backend API.\n *\n * @example\n * const { data } = useBackendMoneyMarketPosition({ params: { userAddress: '0xabc...' } });\n */\nexport const useBackendMoneyMarketPosition = ({\n params,\n queryOptions,\n}: UseBackendMoneyMarketPositionParams = {}): UseQueryResult<MoneyMarketPosition | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const userAddress = params?.userAddress;\n\n return useQuery({\n queryKey: ['backend', 'mm', 'position', userAddress],\n queryFn: async (): Promise<MoneyMarketPosition | undefined> => {\n if (!userAddress) return undefined;\n return unwrapResult(await sodax.backendApi.getMoneyMarketPosition(userAddress));\n },\n enabled: !!userAddress && userAddress.length > 0,\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAsset } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendAllMoneyMarketAssetsParams = ReadHookParams<MoneyMarketAsset[]>;\n\n/**\n * React hook to fetch all money market assets from the backend API.\n *\n * @example\n * const { data: assets, isLoading, error } = useBackendAllMoneyMarketAssets();\n */\nexport const useBackendAllMoneyMarketAssets = ({\n queryOptions,\n}: UseBackendAllMoneyMarketAssetsParams = {}): UseQueryResult<MoneyMarketAsset[], Error> => {\n const { sodax } = useSodaxContext();\n\n return useQuery<MoneyMarketAsset[], Error>({\n queryKey: ['backend', 'mm', 'assets', 'all'],\n queryFn: async (): Promise<MoneyMarketAsset[]> => {\n return unwrapResult(await sodax.backendApi.getAllMoneyMarketAssets());\n },\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAsset } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendMoneyMarketAssetParams = ReadHookParams<\n MoneyMarketAsset | undefined,\n {\n reserveAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch a specific money market asset from the backend API.\n *\n * @example\n * const { data: asset } = useBackendMoneyMarketAsset({ params: { reserveAddress: '0xabc...' } });\n */\nexport const useBackendMoneyMarketAsset = ({\n params,\n queryOptions,\n}: UseBackendMoneyMarketAssetParams = {}): UseQueryResult<MoneyMarketAsset | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const reserveAddress = params?.reserveAddress;\n\n return useQuery({\n queryKey: ['backend', 'mm', 'asset', reserveAddress],\n queryFn: async (): Promise<MoneyMarketAsset | undefined> => {\n if (!reserveAddress) return undefined;\n return unwrapResult(await sodax.backendApi.getMoneyMarketAsset(reserveAddress));\n },\n enabled: !!reserveAddress && reserveAddress.length > 0,\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAssetBorrowers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { BackendPaginationParams } from './types.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendMoneyMarketAssetBorrowersParams = ReadHookParams<\n MoneyMarketAssetBorrowers | undefined,\n {\n reserveAddress: string | undefined;\n pagination: BackendPaginationParams;\n }\n>;\n\n/**\n * React hook for fetching borrowers for a specific money market asset from the backend API with pagination.\n *\n * @example\n * const { data: borrowers } = useBackendMoneyMarketAssetBorrowers({\n * params: { reserveAddress: '0xabc...', pagination: { offset: '0', limit: '20' } },\n * });\n */\nexport const useBackendMoneyMarketAssetBorrowers = ({\n params,\n queryOptions,\n}: UseBackendMoneyMarketAssetBorrowersParams = {}): UseQueryResult<MoneyMarketAssetBorrowers | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const reserveAddress = params?.reserveAddress;\n const pagination = params?.pagination;\n\n return useQuery({\n queryKey: ['backend', 'mm', 'asset', 'borrowers', reserveAddress, pagination],\n queryFn: async (): Promise<MoneyMarketAssetBorrowers | undefined> => {\n if (!reserveAddress || !pagination?.offset || !pagination?.limit) {\n return undefined;\n }\n return unwrapResult(\n await sodax.backendApi.getMoneyMarketAssetBorrowers(reserveAddress, {\n offset: pagination.offset,\n limit: pagination.limit,\n }),\n );\n },\n enabled: !!reserveAddress && !!pagination?.offset && !!pagination?.limit,\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketAssetSuppliers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { BackendPaginationParams } from './types.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendMoneyMarketAssetSuppliersParams = ReadHookParams<\n MoneyMarketAssetSuppliers | undefined,\n {\n reserveAddress: string | undefined;\n pagination: BackendPaginationParams;\n }\n>;\n\n/**\n * React hook for fetching suppliers for a specific money market asset from the backend API.\n *\n * @example\n * const { data: suppliers } = useBackendMoneyMarketAssetSuppliers({\n * params: { reserveAddress: '0xabc...', pagination: { offset: '0', limit: '20' } },\n * });\n */\nexport const useBackendMoneyMarketAssetSuppliers = ({\n params,\n queryOptions,\n}: UseBackendMoneyMarketAssetSuppliersParams = {}): UseQueryResult<MoneyMarketAssetSuppliers | undefined, Error> => {\n const { sodax } = useSodaxContext();\n const reserveAddress = params?.reserveAddress;\n const pagination = params?.pagination;\n\n return useQuery({\n queryKey: ['backend', 'mm', 'asset', 'suppliers', reserveAddress, pagination],\n queryFn: async (): Promise<MoneyMarketAssetSuppliers | undefined> => {\n if (!reserveAddress || !pagination?.offset || !pagination?.limit) {\n return undefined;\n }\n return unwrapResult(\n await sodax.backendApi.getMoneyMarketAssetSuppliers(reserveAddress, {\n offset: pagination.offset,\n limit: pagination.limit,\n }),\n );\n },\n enabled: !!reserveAddress && !!pagination?.offset && !!pagination?.limit,\n retry: 3,\n ...queryOptions,\n });\n};\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { MoneyMarketBorrowers } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport { unwrapResult } from './unwrapResult.js';\nimport type { BackendPaginationParams } from './types.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBackendAllMoneyMarketBorrowersParams = ReadHookParams<\n MoneyMarketBorrowers | undefined,\n {\n pagination: BackendPaginationParams;\n }\n>;\n\n/**\n * Hook for fetching all money market borrowers from the backend API.\n *\n * @example\n * ```typescript\n * const { data, isLoading, error } = useBackendAllMoneyMarketBorrowers({\n * params: { pagination: { offset: '0', limit: '50' } },\n * });\n * ```\n */\nexport const useBackendAllMoneyMarketBorrowers = ({\n params,\n queryOptions,\n}: UseBackendAllMoneyMarketBorrowersParams = {}): UseQueryResult<MoneyMarketBorrowers | undefined> => {\n const { sodax } = useSodaxContext();\n const pagination = params?.pagination;\n\n return useQuery({\n queryKey: ['backend', 'mm', 'borrowers', 'all', pagination],\n queryFn: async (): Promise<MoneyMarketBorrowers | undefined> => {\n if (!pagination?.offset || !pagination?.limit) {\n return undefined;\n }\n return unwrapResult(\n await sodax.backendApi.getAllMoneyMarketBorrowers({\n offset: pagination.offset,\n limit: pagination.limit,\n }),\n );\n },\n enabled: !!pagination?.offset && !!pagination?.limit,\n retry: 3,\n ...queryOptions,\n });\n};\n","// packages/dapp-kit/src/hooks/bridge/useBridge.ts\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { BridgeParams, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useBridge}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseBridgeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<BridgeParams<K, false>, 'raw'>;\n\n/**\n * React hook for executing a cross-chain bridge transfer.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useBridge<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseBridgeVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseBridgeVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseBridgeVars<K>>({\n mutationKey: ['bridge'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.bridge.bridge({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.dstChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { CreateBridgeIntentParams, GetWalletProviderType, SpokeChainKey } from '@sodax/sdk';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseBridgeAllowanceParams<K extends SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: CreateBridgeIntentParams<K> | undefined;\n walletProvider: GetWalletProviderType<K> | undefined;\n }\n>;\n\nexport function useBridgeAllowance<K extends SpokeChainKey>({\n params,\n queryOptions,\n}: UseBridgeAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n const walletProvider = params?.walletProvider;\n\n return useQuery<boolean, Error>({\n // Extract the (chain, owner, token, amount) tuple that actually scopes the allowance —\n // raw-object keys break per Rule 4 (bigints) and churn on every render.\n queryKey: [\n 'bridge',\n 'allowance',\n payload?.srcChainKey,\n payload?.srcAddress,\n payload?.srcToken,\n payload?.amount?.toString(),\n ],\n queryFn: async () => {\n if (!payload || !walletProvider) {\n return false;\n }\n const result = await sodax.bridge.isAllowanceValid({\n params: payload,\n raw: false,\n walletProvider,\n });\n return result.ok ? result.value : false;\n },\n enabled: !!payload && !!walletProvider,\n refetchInterval: 2000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/bridge/useBridgeApprove.ts\nimport type { BridgeParams, SpokeChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useBridgeApprove}. Generic over `K extends SpokeChainKey`\n * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow\n * the `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseBridgeApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<BridgeParams<K, false>, 'raw'>;\n\n/**\n * React hook for approving ERC-20 token spending (or trustline establishment) for a bridge\n * action.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success. Invalidates all\n * `['bridge', 'allowance', ...]` queries so any pending allowance check refreshes.\n */\nexport function useBridgeApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseBridgeApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseBridgeApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseBridgeApproveVars<K>>({\n mutationKey: ['bridge', 'approve'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.bridge.approve({ ...vars, raw: false } as BridgeParams<K, false>)),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['bridge', 'allowance'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { BridgeLimit, XToken } from '@sodax/sdk';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseGetBridgeableAmountParams = ReadHookParams<\n BridgeLimit,\n {\n from: XToken | undefined;\n to: XToken | undefined;\n }\n>;\n\nexport function useGetBridgeableAmount({\n params,\n queryOptions,\n}: UseGetBridgeableAmountParams = {}): UseQueryResult<BridgeLimit, Error> {\n const { sodax } = useSodaxContext();\n const from = params?.from;\n const to = params?.to;\n\n return useQuery<BridgeLimit, Error>({\n queryKey: ['bridge', 'bridgeableAmount', from, to],\n queryFn: async () => {\n if (!from || !to) {\n throw new Error('from and to tokens are required');\n }\n const result = await sodax.bridge.getBridgeableAmount(from, to);\n if (!result.ok) {\n throw result.error;\n }\n return result.value;\n },\n enabled: !!from && !!to,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport type { XToken, SpokeChainKey } from '@sodax/sdk';\nimport { useSodaxContext } from '../shared/index.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseGetBridgeableTokensParams = ReadHookParams<\n XToken[],\n {\n from: SpokeChainKey | undefined;\n to: SpokeChainKey | undefined;\n token: string | undefined;\n }\n>;\n\nexport function useGetBridgeableTokens({\n params,\n queryOptions,\n}: UseGetBridgeableTokensParams = {}): UseQueryResult<XToken[], Error> {\n const { sodax } = useSodaxContext();\n const from = params?.from;\n const to = params?.to;\n const token = params?.token;\n\n return useQuery<XToken[], Error>({\n queryKey: ['bridge', 'bridgeableTokens', from, to, token],\n queryFn: () => {\n if (!from || !to || !token) {\n throw new Error('from, to and token are required');\n }\n const result = sodax.bridge.getBridgeableTokens(from, to, token);\n if (!result.ok) {\n throw result.error;\n }\n return result.value;\n },\n enabled: !!from && !!to && !!token,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStake.ts\nimport type { SpokeChainKey, StakeAction, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useStake}. Generic over `K extends SpokeChainKey` (defaults to\n * the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseStakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<StakeAction<K, false>, 'raw'>;\n\n/**\n * React hook for staking SODA tokens.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useStake<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseStakeVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseStakeVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseStakeVars<K>>({\n mutationKey: ['staking', 'stake'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.staking.stake({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'stake'] });\n queryClient.invalidateQueries({ queryKey: ['staking', 'stakeRatio'] });\n queryClient.invalidateQueries({ queryKey: ['staking', 'convertedAssets'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useStakeApprove.ts\nimport type { GetWalletProviderType, SpokeChainKey, StakeParams, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useStakeApprove}. The `action` literal is injected by the hook —\n * callers pass the stake-specific fields only.\n */\nexport type UseStakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {\n params: Omit<StakeParams<K>, 'action'>;\n walletProvider: GetWalletProviderType<K>;\n};\n\n/**\n * React hook for approving SODA spending on the stake action.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useStakeApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseStakeApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseStakeApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseStakeApproveVars<K>>({\n mutationKey: ['staking', 'approve', 'stake'],\n ...mutationOptions,\n mutationFn: async ({ params, walletProvider }) =>\n unwrapResult(\n await sodax.staking.approve({\n params: { ...params, action: 'stake' },\n raw: false,\n walletProvider,\n }),\n ),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', vars.params.srcChainKey, 'stake'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { StakeParams } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseStakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: Omit<StakeParams<K>, 'action'> | undefined;\n }\n>;\n\n/**\n * React hook to check whether the user has approved sufficient SODA spending for the stake\n * action. Read-only — calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`\n * is required.\n */\nexport function useStakeAllowance<K extends SpokeChainKey = SpokeChainKey>({\n params,\n queryOptions,\n}: UseStakeAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: ['staking', 'allowance', payload?.srcChainKey, 'stake', payload?.srcAddress, payload?.amount?.toString()],\n queryFn: async () => {\n if (!payload) {\n throw new Error('Params are required');\n }\n const result = await sodax.staking.isAllowanceValid({\n params: { ...payload, action: 'stake' },\n raw: true,\n });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload,\n refetchInterval: 5_000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useUnstake.ts\nimport type { SpokeChainKey, TxHashPair, UnstakeAction } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<UnstakeAction<K, false>, 'raw'>;\n\n/**\n * React hook for initiating an SODA unstake.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useUnstake<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseUnstakeVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseUnstakeVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseUnstakeVars<K>>({\n mutationKey: ['staking', 'unstake'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.staking.unstake({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });\n // Scope to (srcChainKey, srcAddress) so a user's unstake doesn't refetch every other user's\n // staking data. Matches `useUnstakingInfo` / `useUnstakingInfoWithPenalty` query keys.\n queryClient.invalidateQueries({ queryKey: ['staking', 'unstakingInfo', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'unstake'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useClaim.ts\nimport type { ClaimAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseClaimVars<K extends SpokeChainKey = SpokeChainKey> = Omit<ClaimAction<K, false>, 'raw'>;\n\n/**\n * React hook for claiming an unstaked SODA request that has reached the end of its waiting period.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useClaim<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseClaimVars<K>> = {}): SafeUseMutationResult<TxHashPair, Error, UseClaimVars<K>> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseClaimVars<K>>({\n mutationKey: ['staking', 'claim'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.staking.claim({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['staking', 'unstakingInfo', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useCancelUnstake.ts\nimport type { CancelUnstakeAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseCancelUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<CancelUnstakeAction<K, false>, 'raw'>;\n\n/**\n * React hook for cancelling a pending unstake request.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useCancelUnstake<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseCancelUnstakeVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseCancelUnstakeVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseCancelUnstakeVars<K>>({\n mutationKey: ['staking', 'cancelUnstake'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.staking.cancelUnstake({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['staking', 'unstakingInfo', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { StakingInfo } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseStakingInfoParams = ReadHookParams<\n StakingInfo,\n {\n srcAddress: `0x${string}` | undefined;\n srcChainKey: SpokeChainKey | undefined;\n }\n>;\n\n/**\n * React hook to fetch the user's staking info (xSODA balance, share value, underlying SODA) by\n * deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok` so React\n * Query lands in `error` state.\n */\nexport function useStakingInfo({ params, queryOptions }: UseStakingInfoParams = {}): UseQueryResult<\n StakingInfo,\n Error\n> {\n const { sodax } = useSodaxContext();\n const srcAddress = params?.srcAddress;\n const srcChainKey = params?.srcChainKey;\n\n return useQuery<StakingInfo, Error>({\n queryKey: ['staking', 'info', srcChainKey, srcAddress],\n queryFn: async () => {\n if (!srcAddress || !srcChainKey) {\n throw new Error('srcAddress and srcChainKey are required');\n }\n const result = await sodax.staking.getStakingInfoFromSpoke(srcAddress, srcChainKey);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!srcAddress && !!srcChainKey,\n refetchInterval: 5_000,\n ...queryOptions,\n });\n}\n","import type { UnstakeRequestWithPenalty, UnstakingInfo } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UnstakingInfoWithPenalty = UnstakingInfo & { requestsWithPenalty: UnstakeRequestWithPenalty[] };\n\nexport type UseUnstakingInfoWithPenaltyParams = ReadHookParams<\n UnstakingInfoWithPenalty,\n {\n srcAddress: `0x${string}` | undefined;\n srcChainKey: SpokeChainKey | undefined;\n }\n>;\n\n/**\n * React hook to fetch the user's pending unstake requests **with computed early-exit penalties**\n * by deriving the hub wallet from the spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.\n */\nexport function useUnstakingInfoWithPenalty({\n params,\n queryOptions,\n}: UseUnstakingInfoWithPenaltyParams = {}): UseQueryResult<UnstakingInfoWithPenalty, Error> {\n const { sodax } = useSodaxContext();\n const srcAddress = params?.srcAddress;\n const srcChainKey = params?.srcChainKey;\n\n return useQuery<UnstakingInfoWithPenalty, Error>({\n queryKey: ['staking', 'unstakingInfoWithPenalty', srcChainKey, srcAddress],\n queryFn: async () => {\n if (!srcAddress || !srcChainKey) {\n throw new Error('srcAddress and srcChainKey are required');\n }\n const result = await sodax.staking.getUnstakingInfoWithPenalty(srcAddress, srcChainKey);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!srcAddress && !!srcChainKey,\n refetchInterval: 5_000,\n ...queryOptions,\n });\n}\n","import type { StakingConfig } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseStakingConfigParams = ReadHookParams<StakingConfig>;\n\n/**\n * React hook to fetch the global staking config (unstaking period, min unstaking period, max\n * penalty). Hub-only read; no chain context required. Throws on `!ok`.\n */\nexport function useStakingConfig({\n queryOptions,\n}: UseStakingConfigParams = {}): UseQueryResult<StakingConfig, Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery<StakingConfig, Error>({\n queryKey: ['staking', 'config'],\n queryFn: async () => {\n const result = await sodax.staking.getStakingConfig();\n if (!result.ok) throw result.error;\n return result.value;\n },\n staleTime: Number.POSITIVE_INFINITY,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseStakeRatioParams = ReadHookParams<\n [bigint, bigint],\n {\n amount: bigint | undefined;\n }\n>;\n\n/**\n * React hook to estimate the SODA → xSODA stake ratio for a given amount. Hub-only read. Throws\n * on `!ok`.\n */\nexport function useStakeRatio({\n params,\n queryOptions,\n}: UseStakeRatioParams = {}): UseQueryResult<[bigint, bigint], Error> {\n const { sodax } = useSodaxContext();\n const amount = params?.amount;\n\n return useQuery<[bigint, bigint], Error>({\n queryKey: ['staking', 'stakeRatio', amount?.toString()],\n queryFn: async () => {\n if (amount === undefined) {\n throw new Error('amount is required');\n }\n const result = await sodax.staking.getStakeRatio(amount);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: amount !== undefined,\n refetchInterval: 10_000,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseInstantUnstakeRatioParams = ReadHookParams<\n bigint,\n {\n amount: bigint | undefined;\n }\n>;\n\n/**\n * React hook to estimate the SODA amount received from instant-unstaking a given xSODA amount\n * (after slippage). Hub-only read. Throws on `!ok`.\n */\nexport function useInstantUnstakeRatio({\n params,\n queryOptions,\n}: UseInstantUnstakeRatioParams = {}): UseQueryResult<bigint, Error> {\n const { sodax } = useSodaxContext();\n const amount = params?.amount;\n\n return useQuery<bigint, Error>({\n queryKey: ['staking', 'instantUnstakeRatio', amount?.toString()],\n queryFn: async () => {\n if (amount === undefined) {\n throw new Error('amount is required');\n }\n const result = await sodax.staking.getInstantUnstakeRatio(amount);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: amount !== undefined,\n refetchInterval: 10_000,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseConvertedAssetsParams = ReadHookParams<\n bigint,\n {\n amount: bigint | undefined;\n }\n>;\n\n/**\n * React hook to convert an xSODA share amount to its underlying SODA value via the vault's\n * exchange rate. Hub-only read. Throws on `!ok`.\n */\nexport function useConvertedAssets({\n params,\n queryOptions,\n}: UseConvertedAssetsParams = {}): UseQueryResult<bigint, Error> {\n const { sodax } = useSodaxContext();\n const amount = params?.amount;\n\n return useQuery<bigint, Error>({\n queryKey: ['staking', 'convertedAssets', amount?.toString()],\n queryFn: async () => {\n if (amount === undefined) {\n throw new Error('amount is required');\n }\n const result = await sodax.staking.getConvertedAssets(amount);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: amount !== undefined,\n refetchInterval: 10_000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useInstantUnstake.ts\nimport type { InstantUnstakeAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseInstantUnstakeVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n InstantUnstakeAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for instant-unstaking SODA (bypassing the waiting period at a slippage cost).\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useInstantUnstake<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseInstantUnstakeVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseInstantUnstakeVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseInstantUnstakeVars<K>>({\n mutationKey: ['staking', 'instantUnstake'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.staking.instantUnstake({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({ queryKey: ['staking', 'instantUnstakeRatio'] });\n queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'instantUnstake'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { UnstakeParams } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: Omit<UnstakeParams<K>, 'action'> | undefined;\n }\n>;\n\n/**\n * React hook to check whether the user has approved sufficient xSODA spending for the unstake\n * action. Read-only — calls `staking.isAllowanceValid` with `raw: true` so no `walletProvider`\n * is required.\n */\nexport function useUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({\n params,\n queryOptions,\n}: UseUnstakeAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: [\n 'staking',\n 'allowance',\n payload?.srcChainKey,\n 'unstake',\n payload?.srcAddress,\n payload?.amount?.toString(),\n ],\n queryFn: async () => {\n if (!payload) {\n throw new Error('Params are required');\n }\n const result = await sodax.staking.isAllowanceValid({\n params: { ...payload, action: 'unstake' },\n raw: true,\n });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload,\n refetchInterval: 5_000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useUnstakeApprove.ts\nimport type { GetWalletProviderType, SpokeChainKey, TxReturnType, UnstakeParams } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useUnstakeApprove}. The `action` literal is injected by the hook.\n */\nexport type UseUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {\n params: Omit<UnstakeParams<K>, 'action'>;\n walletProvider: GetWalletProviderType<K>;\n};\n\n/**\n * React hook for approving xSODA spending on the unstake action.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseUnstakeApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseUnstakeApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseUnstakeApproveVars<K>>({\n mutationKey: ['staking', 'approve', 'unstake'],\n ...mutationOptions,\n mutationFn: async ({ params, walletProvider }) =>\n unwrapResult(\n await sodax.staking.approve({\n params: { ...params, action: 'unstake' },\n raw: false,\n walletProvider,\n }),\n ),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', vars.params.srcChainKey, 'unstake'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { UnstakingInfo } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseUnstakingInfoParams = ReadHookParams<\n UnstakingInfo,\n {\n srcAddress: `0x${string}` | undefined;\n srcChainKey: SpokeChainKey | undefined;\n }\n>;\n\n/**\n * React hook to fetch the user's pending unstake requests by deriving the hub wallet from the\n * spoke `srcAddress` + `srcChainKey`. Throws on `!ok`.\n */\nexport function useUnstakingInfo({\n params,\n queryOptions,\n}: UseUnstakingInfoParams = {}): UseQueryResult<UnstakingInfo, Error> {\n const { sodax } = useSodaxContext();\n const srcAddress = params?.srcAddress;\n const srcChainKey = params?.srcChainKey;\n\n return useQuery<UnstakingInfo, Error>({\n queryKey: ['staking', 'unstakingInfo', srcChainKey, srcAddress],\n queryFn: async () => {\n if (!srcAddress || !srcChainKey) {\n throw new Error('srcAddress and srcChainKey are required');\n }\n const result = await sodax.staking.getUnstakingInfo(srcAddress, srcChainKey);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!srcAddress && !!srcChainKey,\n refetchInterval: 5_000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/staking/useInstantUnstakeApprove.ts\nimport type { GetWalletProviderType, InstantUnstakeParams, SpokeChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useInstantUnstakeApprove}. The `action` literal is injected by\n * the hook.\n */\nexport type UseInstantUnstakeApproveVars<K extends SpokeChainKey = SpokeChainKey> = {\n params: Omit<InstantUnstakeParams<K>, 'action'>;\n walletProvider: GetWalletProviderType<K>;\n};\n\n/**\n * React hook for approving xSODA spending on the instant-unstake action.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useInstantUnstakeApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseInstantUnstakeApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseInstantUnstakeApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseInstantUnstakeApproveVars<K>>({\n mutationKey: ['staking', 'approve', 'instantUnstake'],\n ...mutationOptions,\n mutationFn: async ({ params, walletProvider }) =>\n unwrapResult(\n await sodax.staking.approve({\n params: { ...params, action: 'instantUnstake' },\n raw: false,\n walletProvider,\n }),\n ),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({\n queryKey: ['staking', 'allowance', vars.params.srcChainKey, 'instantUnstake'],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { InstantUnstakeParams } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseInstantUnstakeAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: Omit<InstantUnstakeParams<K>, 'action'> | undefined;\n }\n>;\n\n/**\n * React hook to check whether the user has approved sufficient xSODA spending for the\n * instant-unstake action. Read-only — calls `staking.isAllowanceValid` with `raw: true` so no\n * `walletProvider` is required.\n */\nexport function useInstantUnstakeAllowance<K extends SpokeChainKey = SpokeChainKey>({\n params,\n queryOptions,\n}: UseInstantUnstakeAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: [\n 'staking',\n 'allowance',\n payload?.srcChainKey,\n 'instantUnstake',\n payload?.srcAddress,\n payload?.amount?.toString(),\n ],\n queryFn: async () => {\n if (!payload) {\n throw new Error('Params are required');\n }\n const result = await sodax.staking.isAllowanceValid({\n params: { ...payload, action: 'instantUnstake' },\n raw: true,\n });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload,\n refetchInterval: 5_000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","import type { PartnerFeeClaimAssetBalance } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseFetchAssetsBalancesParams = ReadHookParams<\n Map<string, PartnerFeeClaimAssetBalance>,\n {\n queryAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch hub-asset balances on Sonic for a given EVM address. Disabled when\n * `queryAddress` is missing. Throws on `!ok`.\n */\nexport function useFetchAssetsBalances({\n params,\n queryOptions,\n}: UseFetchAssetsBalancesParams = {}): UseQueryResult<Map<string, PartnerFeeClaimAssetBalance>, Error> {\n const { sodax } = useSodaxContext();\n const queryAddress = params?.queryAddress;\n\n return useQuery<Map<string, PartnerFeeClaimAssetBalance>, Error>({\n queryKey: ['partner', 'feeClaim', 'assetsBalances', queryAddress],\n queryFn: async () => {\n if (!queryAddress) {\n throw new Error('queryAddress is required');\n }\n const result = await sodax.partners.feeClaim.fetchAssetsBalances(queryAddress);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!queryAddress,\n ...queryOptions,\n });\n}\n","import type { AutoSwapPreferences } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseGetAutoSwapPreferencesParams = ReadHookParams<\n AutoSwapPreferences,\n {\n queryAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch the auto-swap preferences (output token, destination chain, destination\n * address) for a given EVM address. Disabled when `queryAddress` is missing. Throws on `!ok`.\n */\nexport function useGetAutoSwapPreferences({\n params,\n queryOptions,\n}: UseGetAutoSwapPreferencesParams = {}): UseQueryResult<AutoSwapPreferences, Error> {\n const { sodax } = useSodaxContext();\n const queryAddress = params?.queryAddress;\n\n return useQuery<AutoSwapPreferences, Error>({\n queryKey: ['partner', 'feeClaim', 'autoSwapPreferences', queryAddress],\n queryFn: async () => {\n if (!queryAddress) {\n throw new Error('queryAddress is required');\n }\n const result = await sodax.partners.feeClaim.getAutoSwapPreferences(queryAddress);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!queryAddress,\n ...queryOptions,\n });\n}\n","import type { FeeTokenApproveParams } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseIsTokenApprovedParams = ReadHookParams<\n boolean,\n {\n payload: FeeTokenApproveParams | undefined;\n }\n>;\n\n/**\n * React hook to check whether a token is approved to the protocol-intents contract on Sonic for\n * a given owner. Read-only; throws on `!ok`.\n */\nexport function useIsTokenApproved({\n params,\n queryOptions,\n}: UseIsTokenApprovedParams = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: ['partner', 'feeClaim', 'isTokenApproved', payload?.srcChainKey, payload?.srcAddress, payload?.token],\n queryFn: async () => {\n if (!payload) {\n throw new Error('params are required');\n }\n const result = await sodax.partners.feeClaim.isTokenApproved(payload);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload,\n refetchInterval: 5_000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/partner/useApproveToken.ts\nimport type { FeeTokenApproveAction, HubChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseApproveTokenVars = Omit<FeeTokenApproveAction<HubChainKey, false>, 'raw'>;\n\ntype ApproveTokenData = TxReturnType<HubChainKey, false>;\n\n/**\n * React hook to approve a token to the protocol-intents contract on Sonic with max allowance.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useApproveToken({\n mutationOptions,\n}: MutationHookParams<ApproveTokenData, UseApproveTokenVars> = {}): SafeUseMutationResult<\n ApproveTokenData,\n Error,\n UseApproveTokenVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<ApproveTokenData, Error, UseApproveTokenVars>({\n mutationKey: ['partner', 'approveToken'],\n ...mutationOptions,\n mutationFn: async vars =>\n unwrapResult(await sodax.partners.feeClaim.approveToken<false>({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({\n queryKey: ['partner', 'feeClaim', 'isTokenApproved', params.srcChainKey, params.srcAddress, params.token],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/partner/useSetSwapPreference.ts\nimport type { HubChainKey, SetSwapPreferenceAction, SpokeChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useSetSwapPreference}. Generic over `K extends SpokeChainKey`\n * for compatibility with the SDK signature; at runtime the SDK enforces hub-only\n * (`isHubChainKeyType(srcChainKey)`).\n */\nexport type UseSetSwapPreferenceVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n SetSwapPreferenceAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook to set the partner's auto-swap preferences (output token + destination chain +\n * destination address) on the protocol-intents contract.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useSetSwapPreference<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseSetSwapPreferenceVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseSetSwapPreferenceVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseSetSwapPreferenceVars<K>>({\n mutationKey: ['partner', 'setSwapPreference'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.partners.feeClaim.setSwapPreference({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({\n queryKey: ['partner', 'feeClaim', 'autoSwapPreferences', (vars.params as { srcAddress: string }).srcAddress],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n\n// Helper alias for the common Sonic-only call shape.\nexport type UseSetSwapPreferenceVarsHub = UseSetSwapPreferenceVars<HubChainKey>;\n","// packages/dapp-kit/src/hooks/partner/useFeeClaimSwap.ts\nimport type { HubChainKey, IntentAutoSwapResult, PartnerFeeClaimSwapAction } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseFeeClaimSwapVars = Omit<PartnerFeeClaimSwapAction<HubChainKey, false>, 'raw'>;\n\n/**\n * React hook to create a partner-fee auto-swap intent and wait for the solver execution.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `IntentAutoSwapResult` on success.\n */\nexport function useFeeClaimSwap({\n mutationOptions,\n}: MutationHookParams<IntentAutoSwapResult, UseFeeClaimSwapVars> = {}): SafeUseMutationResult<\n IntentAutoSwapResult,\n Error,\n UseFeeClaimSwapVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<IntentAutoSwapResult, Error, UseFeeClaimSwapVars>({\n mutationKey: ['partner', 'feeClaimSwap'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.partners.feeClaim.swap({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({\n queryKey: ['partner', 'feeClaim', 'assetsBalances', vars.params.srcAddress],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { HubAssetBalance } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseHubAssetBalancesParams = ReadHookParams<\n HubAssetBalance[],\n {\n chainKey: SpokeChainKey | undefined;\n /** The user's address on the spoke chain. The SDK derives the hub wallet abstraction internally. */\n srcAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to fetch the hub-side balances of every supported token on the given spoke chain\n * for the user's hub wallet (derived internally from `srcAddress` + `chainKey`). Disabled when\n * either input is missing. Throws on `!ok`.\n */\nexport function useHubAssetBalances({\n params,\n queryOptions,\n}: UseHubAssetBalancesParams = {}): UseQueryResult<HubAssetBalance[], Error> {\n const { sodax } = useSodaxContext();\n const chainKey = params?.chainKey;\n const srcAddress = params?.srcAddress;\n\n return useQuery<HubAssetBalance[], Error>({\n queryKey: ['recovery', 'hubAssetBalances', chainKey, srcAddress],\n queryFn: async () => {\n if (!chainKey || !srcAddress) {\n throw new Error('chainKey and srcAddress are required');\n }\n const result = await sodax.recovery.fetchHubAssetBalances({ chainKey, srcAddress });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!chainKey && !!srcAddress,\n staleTime: 10_000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/recovery/useWithdrawHubAsset.ts\nimport type { SpokeChainKey, TxReturnType, WithdrawHubAssetAction } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useWithdrawHubAsset}. Generic over `K extends SpokeChainKey`\n * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow\n * the `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseWithdrawHubAssetVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n WithdrawHubAssetAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for withdrawing a hub-side asset back to the user's spoke chain wallet.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useWithdrawHubAsset<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseWithdrawHubAssetVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseWithdrawHubAssetVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseWithdrawHubAssetVars<K>>({\n mutationKey: ['recovery', 'withdrawHubAsset'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.recovery.withdrawHubAsset<K, false>({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({\n queryKey: ['recovery', 'hubAssetBalances', params.srcChainKey, params.srcAddress],\n });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useMigrateIcxToSoda.ts\nimport type { IcxMigrateAction, TxHashPair } from '@sodax/sdk';\nimport { ChainKeys } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useMigrateIcxToSoda}. Wraps `IcxMigrateAction<false>` with `raw`\n * stripped — the hook always submits non-raw and unwraps the SDK Result.\n */\nexport type UseMigrateIcxToSodaVars = Omit<IcxMigrateAction<false>, 'raw'>;\n\n/**\n * React hook for migrating ICX/wICX → SODA on the Sonic hub. Forward-only direction; for the\n * reverse (SODA → ICX) use {@link useRevertMigrateSodaToIcx}.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useMigrateIcxToSoda({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseMigrateIcxToSodaVars> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseMigrateIcxToSodaVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseMigrateIcxToSodaVars>({\n mutationKey: ['migrate', 'icxToSoda'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.migration.migrateIcxToSoda({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.SONIC_MAINNET] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useRevertMigrateSodaToIcx.ts\nimport type { IcxRevertMigrationAction, TxHashPair } from '@sodax/sdk';\nimport { ChainKeys } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseRevertMigrateSodaToIcxVars = Omit<IcxRevertMigrationAction<false>, 'raw'>;\n\n/**\n * React hook for reverting SODA → ICX (the inverse of {@link useMigrateIcxToSoda}).\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useRevertMigrateSodaToIcx({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseRevertMigrateSodaToIcxVars> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseRevertMigrateSodaToIcxVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseRevertMigrateSodaToIcxVars>({\n mutationKey: ['migrate', 'revertSodaToIcx'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.migration.revertMigrateSodaToIcx({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', vars.params.srcChainKey] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.ICON_MAINNET] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useMigratebnUSD.ts\nimport type { SpokeChainKey, TxHashPair, UnifiedBnUSDMigrateAction } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useMigratebnUSD}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Bidirectional — handles both legacy → new and new → legacy bnUSD migration\n * via the same SDK call; the SDK detects direction from the token addresses.\n */\nexport type UseMigratebnUSDVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n UnifiedBnUSDMigrateAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for migrating bnUSD between legacy and new formats across spoke chains via Sonic.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useMigratebnUSD<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseMigratebnUSDVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseMigratebnUSDVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseMigratebnUSDVars<K>>({\n mutationKey: ['migrate', 'bnUSD'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.migration.migratebnUSD({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.dstChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useMigrateBaln.ts\nimport type { BalnMigrateAction, TxHashPair } from '@sodax/sdk';\nimport { ChainKeys } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\nexport type UseMigrateBalnVars = Omit<BalnMigrateAction<false>, 'raw'>;\n\n/**\n * React hook for migrating BALN → SODA on the Sonic hub. Source chain is always Icon. Supports\n * lockup periods (0–24 months) which multiply the SODA reward (0.5x–1.5x).\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useMigrateBaln({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseMigrateBalnVars> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseMigrateBalnVars\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseMigrateBalnVars>({\n mutationKey: ['migrate', 'baln'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.migration.migrateBaln({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.ICON_MAINNET] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', ChainKeys.SONIC_MAINNET] });\n // BALN with stake=true affects staking info too; cheap broad invalidation.\n queryClient.invalidateQueries({ queryKey: ['staking', 'info'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useMigrationApprove.ts\nimport type {\n IcxRevertMigrationAction,\n MigrationAction,\n SpokeChainKey,\n TxReturnType,\n UnifiedBnUSDMigrateAction,\n} from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useMigrationApprove}. The SDK's `approve` accepts a union of\n * action wrappers (Icx-revert OR bnUSD bidirectional) plus a separate `'migrate' | 'revert'`\n * discriminator. Both ride along in `TVars` here so the hook stays a pure pass-through.\n */\nexport type UseMigrationApproveVars<K extends SpokeChainKey = SpokeChainKey> = (\n | Omit<IcxRevertMigrationAction<false>, 'raw'>\n | Omit<UnifiedBnUSDMigrateAction<K, false>, 'raw'>\n) & { action: MigrationAction };\n\n/**\n * React hook for approving token spending on a migration intent. Required before:\n * - SODA → ICX revert (consumes SODA on Sonic via the user's hub router)\n * - bnUSD migrations on EVM/Stellar source chains (consumes the source bnUSD via asset manager)\n *\n * NOT required for ICX → SODA forward migrations or BALN migrations (both originate on Icon\n * which doesn't use ERC-20 allowances).\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useMigrationApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseMigrationApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseMigrationApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseMigrationApproveVars<K>>({\n mutationKey: ['migrate', 'approve'],\n ...mutationOptions,\n mutationFn: async ({ action, ...actionParams }) =>\n unwrapResult(\n await sodax.migration.approve(\n { ...actionParams, raw: false } as\n | IcxRevertMigrationAction<false>\n | UnifiedBnUSDMigrateAction<K, false>,\n action,\n ),\n ),\n onSuccess: async (data, vars, ctx) => {\n // Broad — wipes all migrate allowance variants. The mutation can't know exactly which\n // (action, params) tuple the consumer was reading, so refetch all and let the active\n // queries reconcile.\n queryClient.invalidateQueries({ queryKey: ['migrate', 'allowance'] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/migrate/useMigrationAllowance.ts\nimport type {\n BalnMigrateParams,\n IcxCreateRevertMigrationParams,\n IcxMigrateParams,\n MigrationAction,\n SpokeChainKey,\n UnifiedBnUSDMigrateParams,\n} from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\n/**\n * Domain inputs for {@link useMigrationAllowance}. `params` is the underlying migration params\n * (NOT the action wrapper — no `walletProvider`/`raw`); `action` is the `'migrate' | 'revert'`\n * discriminator the SDK uses to pick the right allowance check path.\n *\n * For ICX forward migration (`migrate`, params={IcxMigrateParams}) and BALN migration the SDK\n * always returns `true` (Icon has no ERC-20-style allowance) — but the hook still works there\n * for code-uniformity at the call site.\n */\nexport type UseMigrationAllowanceInputs<K extends SpokeChainKey = SpokeChainKey> = {\n params:\n | IcxMigrateParams\n | IcxCreateRevertMigrationParams\n | UnifiedBnUSDMigrateParams<K>\n | BalnMigrateParams\n | undefined;\n action: MigrationAction | undefined;\n};\n\nexport type UseMigrationAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<\n boolean,\n UseMigrationAllowanceInputs<K>\n>;\n\nconst REFETCH_INTERVAL_MS = 2_000;\n\n/**\n * React hook to check if migration spending is approved.\n *\n * Returns `false` when params are missing (so the call site can disable the action button).\n * Hook lifecycle (`enabled`, `queryKey`, `queryFn`) is owned internally; consumers can override\n * other React Query knobs via `queryOptions`.\n */\nexport function useMigrationAllowance<K extends SpokeChainKey = SpokeChainKey>({\n params,\n queryOptions,\n}: UseMigrationAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const migrationParams = params?.params;\n const action = params?.action;\n\n return useQuery<boolean, Error>({\n // Extract the (chain, owner, token, amount) tuple that actually scopes the allowance —\n // raw-object keys break per Rule 4 (bigints) and churn on every render.\n queryKey: [\n 'migrate',\n 'allowance',\n action,\n migrationParams?.srcChainKey,\n migrationParams?.srcAddress,\n migrationParams && 'srcbnUSD' in migrationParams ? migrationParams.srcbnUSD : undefined,\n migrationParams?.amount?.toString(),\n ],\n queryFn: async () => {\n if (!migrationParams || !action) return false;\n const result = await sodax.migration.isAllowanceValid<K>(migrationParams, action);\n return result.ok ? result.value : false;\n },\n enabled: !!migrationParams && !!action,\n refetchInterval: REFETCH_INTERVAL_MS,\n ...queryOptions,\n });\n}\n","import type { PoolKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UsePoolsParams = ReadHookParams<PoolKey[]>;\n\n/**\n * Loads the list of concentrated-liquidity pools known to the SDK config. The SDK's `getPools()`\n * is synchronous in v2 (no network), so this hook caches indefinitely by default.\n */\nexport function usePools({ queryOptions }: UsePoolsParams = {}): UseQueryResult<PoolKey[], Error> {\n const { sodax } = useSodaxContext();\n\n return useQuery<PoolKey[], Error>({\n queryKey: ['dex', 'pools'],\n queryFn: () => sodax.dex.clService.getPools(),\n staleTime: Number.POSITIVE_INFINITY,\n ...queryOptions,\n });\n}\n","import type { PoolData, PoolKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UsePoolDataParams = ReadHookParams<PoolData, { poolKey: PoolKey | null }>;\n\n/**\n * React hook to fetch on-chain pool data (sqrt price, tick, fees, token info, etc.) for a given\n * pool key. Reads via the hub `publicClient`. Disabled when `poolKey` is null.\n */\nexport function usePoolData({ params, queryOptions }: UsePoolDataParams = {}): UseQueryResult<PoolData, Error> {\n const { sodax } = useSodaxContext();\n const poolKey = params?.poolKey ?? null;\n\n return useQuery<PoolData, Error>({\n queryKey: ['dex', 'poolData', poolKey],\n queryFn: async () => {\n if (!poolKey) {\n throw new Error('Pool key is required');\n }\n const result = await sodax.dex.clService.getPoolData(poolKey, sodax.hubProvider.publicClient);\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: poolKey !== null,\n staleTime: 10_000,\n refetchInterval: 30_000,\n ...queryOptions,\n });\n}\n","import type { PoolData, PoolKey } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { erc20Abi } from 'viem';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UsePoolBalancesResponse = {\n token0Balance: bigint;\n token1Balance: bigint;\n};\n\nexport type UsePoolBalancesParams = ReadHookParams<\n UsePoolBalancesResponse,\n {\n poolData: PoolData | null;\n poolKey: PoolKey | null;\n spokeChainKey: SpokeChainKey | undefined;\n userAddress: string | undefined;\n }\n>;\n\n/**\n * React hook to query the user's hub-side deposit balances for both pool tokens. Derives the hub\n * wallet once and reads both pool-token balances in parallel via the hub `publicClient`.\n */\nexport function usePoolBalances({\n params,\n queryOptions,\n}: UsePoolBalancesParams = {}): UseQueryResult<UsePoolBalancesResponse, Error> {\n const { sodax } = useSodaxContext();\n const poolData = params?.poolData ?? null;\n const poolKey = params?.poolKey ?? null;\n const spokeChainKey = params?.spokeChainKey;\n const userAddress = params?.userAddress;\n\n return useQuery<UsePoolBalancesResponse, Error>({\n queryKey: ['dex', 'poolBalances', poolData?.poolId, spokeChainKey, userAddress],\n queryFn: async () => {\n if (!poolData || !poolKey || !spokeChainKey || !userAddress) {\n throw new Error('poolData, poolKey, spokeChainKey, and userAddress are required');\n }\n\n const hubWallet = await sodax.hubProvider.getUserHubWalletAddress(userAddress, spokeChainKey);\n\n const [token0Balance, token1Balance] = await Promise.all([\n sodax.hubProvider.publicClient.readContract({\n address: poolData.token0.address,\n abi: erc20Abi,\n functionName: 'balanceOf',\n args: [hubWallet],\n }),\n sodax.hubProvider.publicClient.readContract({\n address: poolData.token1.address,\n abi: erc20Abi,\n functionName: 'balanceOf',\n args: [hubWallet],\n }),\n ]);\n\n return { token0Balance, token1Balance };\n },\n enabled: !!poolData && !!poolKey && !!spokeChainKey && !!userAddress,\n staleTime: 5_000,\n refetchInterval: 10_000,\n ...queryOptions,\n });\n}\n","import type { ClPositionInfo, PoolKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UsePositionInfoResponse = {\n positionInfo: ClPositionInfo;\n isValid: boolean;\n};\n\nexport type UsePositionInfoParams = ReadHookParams<\n UsePositionInfoResponse,\n {\n tokenId: string | null;\n poolKey: PoolKey | null;\n }\n>;\n\n/**\n * React hook to fetch a CL position by NFT token id and validate it against an expected pool key.\n * Reads via the hub `publicClient`. Disabled when `tokenId` or `poolKey` is missing.\n */\nexport function usePositionInfo({\n params,\n queryOptions,\n}: UsePositionInfoParams = {}): UseQueryResult<UsePositionInfoResponse, Error> {\n const { sodax } = useSodaxContext();\n const tokenId = params?.tokenId ?? null;\n const poolKey = params?.poolKey ?? null;\n\n return useQuery<UsePositionInfoResponse, Error>({\n queryKey: ['dex', 'positionInfo', tokenId, poolKey],\n queryFn: async () => {\n if (!tokenId || !poolKey) {\n throw new Error('Token ID and pool key are required');\n }\n\n const infoResult = await sodax.dex.clService.getPositionInfo(BigInt(tokenId), sodax.hubProvider.publicClient);\n if (!infoResult.ok) throw infoResult.error;\n const info = infoResult.value;\n\n const isValid =\n info.poolKey.currency0.toLowerCase() === poolKey.currency0.toLowerCase() &&\n info.poolKey.currency1.toLowerCase() === poolKey.currency1.toLowerCase() &&\n info.poolKey.fee === poolKey.fee;\n\n return { positionInfo: info, isValid };\n },\n enabled: tokenId !== null && tokenId !== '' && poolKey !== null,\n staleTime: 10_000,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/dex/useDexDeposit.ts\nimport type { AssetDepositAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useDexDeposit}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseDexDepositVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;\n\n/**\n * React hook for depositing an asset into a DEX pool.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n *\n * @example\n * ```tsx\n * const walletProvider = useWalletProvider({ xChainId: chainKey });\n * const { mutateAsync: deposit } = useDexDeposit();\n * try {\n * const { spokeTxHash, hubTxHash } = await deposit({ params, walletProvider });\n * } catch (e) {\n * // surfaced via mutation.error / onError\n * }\n * ```\n */\nexport function useDexDeposit<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseDexDepositVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseDexDepositVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseDexDepositVars<K>>({\n mutationKey: ['dex', 'deposit'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.dex.assetService.deposit({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({\n queryKey: ['dex', 'allowance', params.srcChainKey, params.asset, params.amount.toString()],\n });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/dex/useDexWithdraw.ts\nimport type { AssetWithdrawAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useDexWithdraw}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseDexWithdrawVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetWithdrawAction<K, false>, 'raw'>;\n\n/**\n * React hook for withdrawing an asset from a DEX pool.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useDexWithdraw<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseDexWithdrawVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseDexWithdrawVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseDexWithdrawVars<K>>({\n mutationKey: ['dex', 'withdraw'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.dex.assetService.withdraw({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type { CreateAssetDepositParams } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { ReadHookParams } from '../shared/types.js';\n\nexport type UseDexAllowanceParams<K extends SpokeChainKey = SpokeChainKey> = ReadHookParams<\n boolean,\n {\n payload: CreateAssetDepositParams<K> | undefined;\n }\n>;\n\n/**\n * React hook to check whether the user has approved sufficient token allowance (or established a\n * trustline, on Stellar) for a DEX deposit. Read-only — calls `assetService.isAllowanceValid`\n * with `raw: true` so no `walletProvider` is required.\n */\nexport function useDexAllowance<K extends SpokeChainKey = SpokeChainKey>({\n params,\n queryOptions,\n}: UseDexAllowanceParams<K> = {}): UseQueryResult<boolean, Error> {\n const { sodax } = useSodaxContext();\n const payload = params?.payload;\n\n return useQuery<boolean, Error>({\n queryKey: ['dex', 'allowance', payload?.srcChainKey, payload?.asset, payload?.amount?.toString()],\n queryFn: async () => {\n if (!payload) {\n throw new Error('Params are required');\n }\n const result = await sodax.dex.assetService.isAllowanceValid({ params: payload, raw: true });\n if (!result.ok) throw result.error;\n return result.value;\n },\n enabled: !!payload,\n refetchInterval: 5_000,\n gcTime: 0,\n ...queryOptions,\n });\n}\n","// packages/dapp-kit/src/hooks/dex/useDexApprove.ts\nimport type { AssetDepositAction, SpokeChainKey, TxReturnType } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useDexApprove}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseDexApproveVars<K extends SpokeChainKey = SpokeChainKey> = Omit<AssetDepositAction<K, false>, 'raw'>;\n\n/**\n * React hook for approving ERC-20 token spending (or trustline establishment) for a DEX deposit.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped tx return value on success.\n */\nexport function useDexApprove<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxReturnType<K, false>, UseDexApproveVars<K>> = {}): SafeUseMutationResult<\n TxReturnType<K, false>,\n Error,\n UseDexApproveVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxReturnType<K, false>, Error, UseDexApproveVars<K>>({\n mutationKey: ['dex', 'approve'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.dex.assetService.approve({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n queryClient.invalidateQueries({\n queryKey: ['dex', 'allowance', params.srcChainKey, params.asset, params.amount.toString()],\n });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import { useState, useEffect, useCallback, useMemo } from 'react';\nimport { ClService, type PoolData } from '@sodax/sdk';\n\nexport type UseLiquidityAmountsResult = {\n liquidityToken0Amount: string;\n liquidityToken1Amount: string;\n lastEditedToken: 'token0' | 'token1' | null;\n setLiquidityToken0Amount: (value: string) => void;\n setLiquidityToken1Amount: (value: string) => void;\n handleToken0AmountChange: (value: string) => void;\n handleToken1AmountChange: (value: string) => void;\n};\n\n/**\n * Hook for calculating concentrated-liquidity amounts based on the price range. Pure state +\n * math; no SDK calls beyond the static {@link ClService} helpers.\n */\nexport function useLiquidityAmounts(\n minPrice: string,\n maxPrice: string,\n poolData: PoolData | null,\n): UseLiquidityAmountsResult {\n const [liquidityToken0Amount, setLiquidityToken0Amount] = useState<string>('');\n const [liquidityToken1Amount, setLiquidityToken1Amount] = useState<string>('');\n const [lastEditedToken, setLastEditedToken] = useState<'token0' | 'token1' | null>(null);\n\n const { minPriceNum, maxPriceNum, isValidPriceRange } = useMemo(() => {\n const parsedMin = Number.parseFloat(minPrice);\n const parsedMax = Number.parseFloat(maxPrice);\n const isValid = parsedMin > 0 && parsedMax > 0 && parsedMin < parsedMax;\n return { minPriceNum: parsedMin, maxPriceNum: parsedMax, isValidPriceRange: isValid };\n }, [minPrice, maxPrice]);\n\n const { tickLower, tickUpper, currentTick } = useMemo(() => {\n if (!poolData || !isValidPriceRange) {\n return { tickLower: null, tickUpper: null, currentTick: null };\n }\n try {\n const lower = ClService.priceToTick(minPriceNum, poolData.token0, poolData.token1, poolData.tickSpacing);\n const upper = ClService.priceToTick(maxPriceNum, poolData.token0, poolData.token1, poolData.tickSpacing);\n return { tickLower: lower, tickUpper: upper, currentTick: BigInt(poolData.currentTick) };\n } catch (err) {\n console.error('Failed to calculate ticks:', err);\n return { tickLower: null, tickUpper: null, currentTick: null };\n }\n }, [minPriceNum, maxPriceNum, poolData, isValidPriceRange]);\n\n const handleToken0AmountChange = useCallback(\n (value: string): void => {\n setLiquidityToken0Amount(value);\n setLastEditedToken('token0');\n\n if (!value || !poolData || !tickLower || !tickUpper || !currentTick) return;\n const amount0 = Number.parseFloat(value);\n if (amount0 <= 0 || !isValidPriceRange) return;\n\n try {\n const amount0BigInt = BigInt(Math.floor(amount0 * 10 ** poolData.token0.decimals));\n const amount1BigInt = ClService.calculateAmount1FromAmount0(\n amount0BigInt,\n tickLower,\n tickUpper,\n currentTick,\n poolData.sqrtPriceX96,\n );\n const amount1 = Number(amount1BigInt) / 10 ** poolData.token1.decimals;\n setLiquidityToken1Amount(amount1.toFixed(6));\n } catch (err) {\n console.error('Failed to calculate token1 amount:', err);\n }\n },\n [poolData, tickLower, tickUpper, currentTick, isValidPriceRange],\n );\n\n const handleToken1AmountChange = useCallback(\n (value: string): void => {\n setLiquidityToken1Amount(value);\n setLastEditedToken('token1');\n\n if (!value || !poolData || !tickLower || !tickUpper || !currentTick) return;\n const amount1 = Number.parseFloat(value);\n if (amount1 <= 0 || !isValidPriceRange) return;\n\n try {\n const amount1BigInt = BigInt(Math.floor(amount1 * 10 ** poolData.token1.decimals));\n const amount0BigInt = ClService.calculateAmount0FromAmount1(\n amount1BigInt,\n tickLower,\n tickUpper,\n currentTick,\n poolData.sqrtPriceX96,\n );\n const amount0 = Number(amount0BigInt) / 10 ** poolData.token0.decimals;\n setLiquidityToken0Amount(amount0.toFixed(6));\n } catch (err) {\n console.error('Failed to calculate token0 amount:', err);\n }\n },\n [poolData, tickLower, tickUpper, currentTick, isValidPriceRange],\n );\n\n useEffect(() => {\n if (!poolData || !tickLower || !tickUpper || !lastEditedToken || !isValidPriceRange) return;\n if (lastEditedToken === 'token0' && liquidityToken0Amount) {\n handleToken0AmountChange(liquidityToken0Amount);\n } else if (lastEditedToken === 'token1' && liquidityToken1Amount) {\n handleToken1AmountChange(liquidityToken1Amount);\n }\n }, [\n poolData,\n lastEditedToken,\n liquidityToken0Amount,\n liquidityToken1Amount,\n handleToken0AmountChange,\n handleToken1AmountChange,\n tickLower,\n tickUpper,\n isValidPriceRange,\n ]);\n\n return {\n liquidityToken0Amount,\n liquidityToken1Amount,\n lastEditedToken,\n setLiquidityToken0Amount,\n setLiquidityToken1Amount,\n handleToken0AmountChange,\n handleToken1AmountChange,\n };\n}\n","// packages/dapp-kit/src/hooks/dex/useSupplyLiquidity.ts\nimport type {\n ClIncreaseLiquidityParams,\n ClSupplyParams,\n GetWalletProviderType,\n SpokeChainKey,\n TxHashPair,\n} from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { UseCreateSupplyLiquidityParamsResult } from './useCreateSupplyLiquidityParams.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useSupplyLiquidity}. Generic over `K extends SpokeChainKey`\n * (defaults to the full union). The hook fans out internally to either\n * `clService.increaseLiquidity` (when `params.tokenId` + `params.isValidPosition` are present) or\n * `clService.supplyLiquidity` (mint a new position).\n */\nexport type UseSupplyLiquidityVars<K extends SpokeChainKey = SpokeChainKey> = {\n params: UseCreateSupplyLiquidityParamsResult & { srcChainKey: K; srcAddress: string };\n walletProvider: GetWalletProviderType<K>;\n /** Optional relay timeout in ms (default 60_000) */\n timeout?: number;\n};\n\n/**\n * React hook for supplying liquidity to a concentrated-liquidity pool. If the input vars include a\n * valid `tokenId` for an existing position, the hook calls `increaseLiquidity`; otherwise it mints\n * a new position via `supplyLiquidity`.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useSupplyLiquidity<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseSupplyLiquidityVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseSupplyLiquidityVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseSupplyLiquidityVars<K>>({\n mutationKey: ['dex', 'supplyLiquidity'],\n ...mutationOptions,\n mutationFn: async ({ params, walletProvider, timeout }) => {\n const sharedParams = {\n srcChainKey: params.srcChainKey,\n srcAddress: params.srcAddress as ClSupplyParams<K>['srcAddress'],\n poolKey: params.poolKey,\n tickLower: params.tickLower,\n tickUpper: params.tickUpper,\n liquidity: params.liquidity,\n amount0Max: params.amount0Max,\n amount1Max: params.amount1Max,\n sqrtPriceX96: params.sqrtPriceX96,\n } satisfies ClSupplyParams<K>;\n\n if (params.tokenId !== undefined && params.isValidPosition) {\n const increaseParams: ClIncreaseLiquidityParams<K> = {\n ...sharedParams,\n tokenId: typeof params.tokenId === 'bigint' ? params.tokenId : BigInt(params.tokenId),\n };\n return unwrapResult(\n await sodax.dex.clService.increaseLiquidity({ params: increaseParams, raw: false, walletProvider, timeout }),\n );\n }\n\n return unwrapResult(\n await sodax.dex.clService.supplyLiquidity({ params: sharedParams, raw: false, walletProvider, timeout }),\n );\n },\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n // Increase-liquidity branch knows the affected position — scope to it. Mint-new-position\n // branch creates a fresh tokenId that's only known after the tx, so a bare invalidation is\n // the right fallback (refetches all positions, including the new one once it lands).\n if (params.tokenId !== undefined && params.isValidPosition) {\n // `usePositionInfo` keys by string tokenId — coerce here to match its shape regardless of\n // whether the caller passed bigint or string.\n const tokenIdStr = String(params.tokenId);\n queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo', tokenIdStr, params.poolKey] });\n } else {\n queryClient.invalidateQueries({ queryKey: ['dex', 'positionInfo'] });\n }\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolData', params.poolKey] });\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });\n queryClient.invalidateQueries({ queryKey: ['shared', 'xBalances', params.srcChainKey] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","// packages/dapp-kit/src/hooks/dex/useDecreaseLiquidity.ts\nimport type { ClLiquidityDecreaseLiquidityAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useDecreaseLiquidity}. Generic over `K extends SpokeChainKey`\n * (defaults to the full union). Sophisticated callers can lock K at the hook call site to narrow\n * the `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseDecreaseLiquidityVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n ClLiquidityDecreaseLiquidityAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for decreasing liquidity in an existing concentrated-liquidity position.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useDecreaseLiquidity<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseDecreaseLiquidityVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseDecreaseLiquidityVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseDecreaseLiquidityVars<K>>({\n mutationKey: ['dex', 'decreaseLiquidity'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.dex.clService.decreaseLiquidity({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n // Decrease always targets a known position — scope invalidation to (tokenId, poolKey) instead\n // of wiping all positions. `usePositionInfo` keys by string tokenId, so stringify the bigint\n // here to keep the structural match.\n queryClient.invalidateQueries({\n queryKey: ['dex', 'positionInfo', params.tokenId.toString(), params.poolKey],\n });\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolData', params.poolKey] });\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import type {\n UseCreateDecreaseLiquidityParamsProps,\n UseCreateDepositParamsProps,\n UseCreateSupplyLiquidityParamsProps,\n UseCreateSupplyLiquidityParamsResult,\n UseCreateWithdrawParamsProps,\n} from '@/hooks/dex/index.js';\nimport {\n ClService,\n type CreateAssetWithdrawParams,\n type ClDecreaseLiquidityParams,\n type CreateAssetDepositParams,\n} from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { parseUnits } from 'viem';\n\n/**\n * Subset of {@link CreateAssetDepositParams} produced by {@link createDepositParamsProps}.\n * Callers add `srcChainKey` + `srcAddress` at the mutation call site.\n */\nexport type DepositParamsCore = Omit<CreateAssetDepositParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;\n\n/**\n * Subset of {@link CreateAssetWithdrawParams} produced by {@link createWithdrawParamsProps}.\n * Callers add `srcChainKey` + `srcAddress` at the mutation call site.\n */\nexport type WithdrawParamsCore = Omit<CreateAssetWithdrawParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'>;\n\n/**\n * Subset of {@link ClDecreaseLiquidityParams} produced by {@link createDecreaseLiquidityParamsProps}.\n * Callers add `srcChainKey` + `srcAddress` at the mutation call site.\n */\nexport type DecreaseLiquidityParamsCore = Omit<\n ClDecreaseLiquidityParams<SpokeChainKey>,\n 'srcChainKey' | 'srcAddress'\n>;\n\nexport function createDecreaseLiquidityParamsProps({\n poolKey,\n tokenId,\n percentage,\n positionInfo,\n slippageTolerance,\n}: UseCreateDecreaseLiquidityParamsProps): DecreaseLiquidityParamsCore {\n const percentageNum = Number.parseFloat(String(percentage));\n const slippage = Number.parseFloat(String(slippageTolerance));\n\n if (percentageNum <= 0 || percentageNum > 100) {\n throw new Error('Percentage must be between 0 and 100');\n }\n\n if (slippage <= 0 || slippage > 100) {\n throw new Error('Slippage must be between 0 and 100');\n }\n\n // Calculate liquidity to remove based on percentage\n const liquidityToRemove =\n percentageNum === 100\n ? positionInfo.liquidity\n : (positionInfo.liquidity * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n\n // Calculate expected token amounts from this liquidity\n const expectedAmount0 =\n percentageNum === 100\n ? positionInfo.amount0\n : (positionInfo.amount0 * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n const expectedAmount1 =\n percentageNum === 100\n ? positionInfo.amount1\n : (positionInfo.amount1 * BigInt(Math.floor(percentageNum * 100))) / 10000n;\n\n // Apply slippage to minimum amounts\n const slippageMultiplier = BigInt(Math.floor((100 - slippage) * 100));\n const amount0Min = (expectedAmount0 * slippageMultiplier) / 10000n;\n const amount1Min = (expectedAmount1 * slippageMultiplier) / 10000n;\n\n return {\n poolKey,\n tokenId: BigInt(tokenId),\n liquidity: liquidityToRemove,\n amount0Min,\n amount1Min,\n };\n}\n\nexport function createDepositParamsProps({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n}: UseCreateDepositParamsProps): DepositParamsCore {\n const amountNum = Number.parseFloat(String(amount));\n\n if (!amount || amountNum <= 0) {\n throw new Error('Amount must be greater than 0');\n }\n\n const token = tokenIndex === 0 ? poolData.token0 : poolData.token1;\n const originalAsset = tokenIndex === 0 ? poolSpokeAssets.token0 : poolSpokeAssets.token1;\n\n return {\n asset: originalAsset.address,\n // Use deposit token decimals (original asset) for correct unit parsing\n amount: parseUnits(String(amount), originalAsset.decimals),\n poolToken: token.address,\n };\n}\n\nexport function createSupplyLiquidityParamsProps({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n}: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult {\n const slippage = Number.parseFloat(String(slippageTolerance));\n if (slippage <= 0 || slippage > 100) {\n throw new Error('Slippage must be between 0 and 100');\n }\n\n const minPriceNum = Number.parseFloat(minPrice);\n const maxPriceNum = Number.parseFloat(maxPrice);\n const amount0 = Number.parseFloat(liquidityToken0Amount);\n const amount1 = Number.parseFloat(liquidityToken1Amount);\n\n if (minPriceNum <= 0 || maxPriceNum <= 0 || amount0 <= 0 || amount1 <= 0) {\n throw new Error('All values must be greater than 0');\n }\n\n if (minPriceNum >= maxPriceNum) {\n throw new Error('Min price must be less than max price');\n }\n\n const amount0BigInt = parseUnits(liquidityToken0Amount, poolData.token0.decimals);\n const amount1BigInt = parseUnits(liquidityToken1Amount, poolData.token1.decimals);\n\n // Convert prices to ticks\n const token0 = poolData.token0;\n const token1 = poolData.token1;\n const tickSpacing = poolData.tickSpacing;\n\n const tickLower = ClService.priceToTick(minPriceNum, token0, token1, tickSpacing);\n const tickUpper = ClService.priceToTick(maxPriceNum, token0, token1, tickSpacing);\n\n // Calculate liquidity from full amounts (the desired deposit)\n const liquidity = ClService.calculateLiquidityFromAmounts(\n amount0BigInt,\n amount1BigInt,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n );\n\n // Apply slippage to get max amounts — the ceiling the contract is allowed to pull.\n // If price moves unfavorably, the contract may need slightly more tokens than expected.\n const { amount0Max, amount1Max } = ClService.calculateMaxAmountsForSlippage(\n liquidity,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n poolData.sqrtPriceX96,\n slippage,\n );\n\n const tokenId = positionId ? BigInt(positionId) : undefined;\n\n return {\n poolKey,\n tickLower,\n tickUpper,\n liquidity,\n amount0Max,\n amount1Max,\n sqrtPriceX96: poolData.sqrtPriceX96,\n positionId,\n isValidPosition,\n tokenId,\n };\n}\n\nexport function createWithdrawParamsProps({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n dst,\n}: UseCreateWithdrawParamsProps): WithdrawParamsCore {\n const amountNum = Number.parseFloat(String(amount));\n if (!amount || amountNum <= 0) {\n throw new Error('Please enter a valid amount');\n }\n\n const token = tokenIndex === 0 ? poolData.token0 : poolData.token1;\n const originalAsset = tokenIndex === 0 ? poolSpokeAssets.token0 : poolSpokeAssets.token1;\n\n return {\n asset: originalAsset.address,\n amount: parseUnits(String(amount), token.decimals),\n poolToken: token.address,\n dst,\n };\n}\n","import { useMemo } from 'react';\nimport type { PoolData, PoolSpokeAssets } from '@sodax/sdk';\nimport { createDepositParamsProps, type DepositParamsCore } from '@/utils/dex-utils.js';\n\nexport type UseCreateDepositParamsProps = {\n tokenIndex: 0 | 1;\n amount: string | number;\n poolData: PoolData;\n poolSpokeAssets: PoolSpokeAssets;\n};\n\n/**\n * React hook to memoize the deposit-specific subset of {@link CreateAssetDepositParams}\n * (`{ asset, amount, poolToken, dst? }`). Callers add `srcChainKey` + `srcAddress` at the mutation\n * call site.\n */\nexport function useCreateDepositParams({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n}: UseCreateDepositParamsProps): DepositParamsCore | undefined {\n return useMemo<DepositParamsCore | undefined>(() => {\n if (!amount || Number.parseFloat(String(amount)) <= 0) {\n return undefined;\n }\n return createDepositParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets });\n }, [tokenIndex, amount, poolData, poolSpokeAssets]);\n}\n","import { createSupplyLiquidityParamsProps } from '@/utils/dex-utils.js';\nimport type { ClSupplyParams, ClIncreaseLiquidityParams, PoolData, PoolKey } from '@sodax/sdk';\nimport type { SpokeChainKey } from '@sodax/sdk';\nimport { useMemo } from 'react';\n\nexport type UseCreateSupplyLiquidityParamsProps = {\n poolData: PoolData;\n poolKey: PoolKey;\n minPrice: string;\n maxPrice: string;\n liquidityToken0Amount: string;\n liquidityToken1Amount: string;\n slippageTolerance: string | number;\n positionId?: string | null;\n isValidPosition?: boolean;\n};\n\n/**\n * Subset of {@link ClSupplyParams} / {@link ClIncreaseLiquidityParams} produced by\n * {@link useCreateSupplyLiquidityParams}. Callers add `srcChainKey` + `srcAddress` at the mutation\n * call site. `tokenId` and `isValidPosition` distinguish the mint-new vs increase-existing path.\n */\nexport type UseCreateSupplyLiquidityParamsResult = Omit<ClSupplyParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress'> &\n Omit<ClIncreaseLiquidityParams<SpokeChainKey>, 'srcChainKey' | 'srcAddress' | 'tokenId'> & {\n tokenId?: string | bigint;\n positionId?: string | null;\n isValidPosition?: boolean;\n };\n\n/**\n * React hook to memoize concentrated-liquidity supply parameters for a given pool. Returns the\n * pool/tick/liquidity/amount fields without `srcChainKey`/`srcAddress` — callers add those at the\n * mutation call site.\n */\nexport function useCreateSupplyLiquidityParams({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n}: UseCreateSupplyLiquidityParamsProps): UseCreateSupplyLiquidityParamsResult {\n return useMemo<UseCreateSupplyLiquidityParamsResult>(() => {\n return createSupplyLiquidityParamsProps({\n poolData,\n poolKey,\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n positionId,\n isValidPosition,\n });\n }, [\n minPrice,\n maxPrice,\n liquidityToken0Amount,\n liquidityToken1Amount,\n slippageTolerance,\n poolData,\n poolKey,\n positionId,\n isValidPosition,\n ]);\n}\n","import { createDecreaseLiquidityParamsProps, type DecreaseLiquidityParamsCore } from '@/utils/dex-utils.js';\nimport type { ClPositionInfo, PoolKey } from '@sodax/sdk';\nimport { useMemo } from 'react';\n\nexport type UseCreateDecreaseLiquidityParamsProps = {\n poolKey: PoolKey;\n tokenId: string | bigint;\n percentage: string | number;\n positionInfo: ClPositionInfo;\n slippageTolerance: string | number;\n};\n\n/**\n * React hook to memoize the decrease-liquidity-specific subset of {@link ClDecreaseLiquidityParams}\n * (`{ poolKey, tokenId, liquidity, amount0Min, amount1Min }`). Callers add `srcChainKey` +\n * `srcAddress` at the mutation call site.\n */\nexport function useCreateDecreaseLiquidityParams({\n poolKey,\n tokenId,\n percentage,\n positionInfo,\n slippageTolerance,\n}: UseCreateDecreaseLiquidityParamsProps): DecreaseLiquidityParamsCore {\n return useMemo<DecreaseLiquidityParamsCore>(() => {\n return createDecreaseLiquidityParamsProps({ poolKey, tokenId, percentage, positionInfo, slippageTolerance });\n }, [poolKey, tokenId, percentage, positionInfo, slippageTolerance]);\n}\n","import type { DestinationParamsType, PoolData, PoolSpokeAssets } from '@sodax/sdk';\nimport { useMemo } from 'react';\nimport { createWithdrawParamsProps, type WithdrawParamsCore } from '@/utils/dex-utils.js';\n\nexport type UseCreateWithdrawParamsProps = {\n tokenIndex: 0 | 1;\n amount: string | number;\n poolData: PoolData;\n poolSpokeAssets: PoolSpokeAssets;\n dst?: DestinationParamsType;\n};\n\n/**\n * React hook to memoize the withdraw-specific subset of {@link CreateAssetWithdrawParams}\n * (`{ asset, amount, poolToken, dst? }`). Callers add `srcChainKey` + `srcAddress` at the mutation\n * call site.\n */\nexport function useCreateWithdrawParams({\n tokenIndex,\n amount,\n poolData,\n poolSpokeAssets,\n dst,\n}: UseCreateWithdrawParamsProps): WithdrawParamsCore | undefined {\n return useMemo<WithdrawParamsCore | undefined>(() => {\n if (!amount || Number.parseFloat(String(amount)) <= 0) {\n return undefined;\n }\n return createWithdrawParamsProps({ tokenIndex, amount, poolData, poolSpokeAssets, dst });\n }, [tokenIndex, amount, poolData, poolSpokeAssets, dst]);\n}\n","// packages/dapp-kit/src/hooks/dex/useClaimRewards.ts\nimport type { ClLiquidityClaimRewardsAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useSodaxContext } from '../shared/useSodaxContext.js';\nimport type { MutationHookParams } from '../shared/types.js';\nimport { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';\nimport { unwrapResult } from '../shared/unwrapResult.js';\n\n/**\n * Mutation variables for {@link useClaimRewards}. Generic over `K extends SpokeChainKey` (defaults\n * to the full union). Sophisticated callers can lock K at the hook call site to narrow the\n * `walletProvider` and `params.srcChainKey` types.\n */\nexport type UseClaimRewardsVars<K extends SpokeChainKey = SpokeChainKey> = Omit<\n ClLiquidityClaimRewardsAction<K, false>,\n 'raw'\n>;\n\n/**\n * React hook for claiming accrued fees on a concentrated-liquidity position.\n *\n * Throws on SDK failure so React Query's native error model engages (`isError`, `error`,\n * `onError`, `retry`). Returns the unwrapped `TxHashPair` on success.\n */\nexport function useClaimRewards<K extends SpokeChainKey = SpokeChainKey>({\n mutationOptions,\n}: MutationHookParams<TxHashPair, UseClaimRewardsVars<K>> = {}): SafeUseMutationResult<\n TxHashPair,\n Error,\n UseClaimRewardsVars<K>\n> {\n const { sodax } = useSodaxContext();\n const queryClient = useQueryClient();\n\n return useSafeMutation<TxHashPair, Error, UseClaimRewardsVars<K>>({\n mutationKey: ['dex', 'claimRewards'],\n ...mutationOptions,\n mutationFn: async vars => unwrapResult(await sodax.dex.clService.claimRewards({ ...vars, raw: false })),\n onSuccess: async (data, vars, ctx) => {\n const { params } = vars;\n // `usePositionInfo` keys by string tokenId — stringify the bigint to keep the structural match.\n queryClient.invalidateQueries({\n queryKey: ['dex', 'positionInfo', params.tokenId.toString(), params.poolKey],\n });\n queryClient.invalidateQueries({ queryKey: ['dex', 'poolBalances', params.srcChainKey, params.srcAddress] });\n await mutationOptions?.onSuccess?.(data, vars, ctx);\n },\n });\n}\n","import { useMemo, useRef, type ReactNode, type ReactElement } from 'react';\nimport { Sodax, type SodaxConfig } from '@sodax/sdk';\nimport { SodaxContext } from '@/contexts/index.js';\nimport type { DeepPartial } from '@sodax/sdk';\n\ninterface SodaxProviderProps {\n children: ReactNode;\n /**\n * Sodax config (overrides defaults including rpcUrls). **Read-once at mount** —\n * changes after first render are ignored to prevent re-instantiating the SDK\n * from unstable parent references. To switch config (e.g. testnet ↔ mainnet),\n * unmount/remount the provider.\n */\n config?: DeepPartial<SodaxConfig>;\n}\n\nexport const SodaxProvider = ({ children, config }: SodaxProviderProps): ReactElement => {\n // Freeze config on first render so the SDK instance and consumers share one\n // snapshot (matches SodaxWalletProvider semantic).\n const configRef = useRef<DeepPartial<SodaxConfig> | undefined>(config);\n const frozen = configRef.current;\n const sodax = useMemo(() => new Sodax(frozen), [frozen]);\n\n return <SodaxContext.Provider value={{ sodax }}>{children}</SodaxContext.Provider>;\n};\n","// packages/dapp-kit/src/providers/createSodaxQueryClient.ts\nimport { MutationCache, QueryClient, type QueryClientConfig } from '@tanstack/react-query';\n\nexport type CreateSodaxQueryClientOptions = {\n /**\n * Called for every mutation failure (i.e. every time `mutationFn` throws) that does NOT opt out\n * via `meta: { silent: true }` on the mutation. Defaults to `console.error`.\n *\n * This is **global observability** — it runs alongside any per-hook `onError` handler the\n * consumer set, NOT instead of them. In particular, it fires:\n * - whether or not `mutateAsync` was awaited inside `try/catch`\n * - whether or not `mutateAsyncSafe` was used (the wrapper packs into `Result<T>` AFTER React\n * Query has already entered the error state and dispatched its callbacks)\n * - whether or not the consumer's `mutationOptions.onError` already toasted/logged\n *\n * It is NOT a \"did this rejection escape to the global handler?\" detector — accurate\n * unhandled-rejection detection lives at `window.onunhandledrejection`, not here.\n *\n * To silence the default for a specific mutation that the consumer is handling locally, set\n * `meta: { silent: true }`:\n *\n * ```ts\n * useSwap({ mutationOptions: { meta: { silent: true }, onError: (e) => toast(e.message) } });\n * ```\n *\n * To disable the default globally (e.g. wire your own error boundary), pass a no-op:\n *\n * ```ts\n * createSodaxQueryClient({ onMutationError: () => {} });\n * ```\n */\n onMutationError?: (error: unknown) => void;\n /** Pass-through for any other QueryClient config (default queries options, etc.) */\n config?: QueryClientConfig;\n};\n\nconst defaultOnMutationError = (error: unknown): void => {\n console.error('[sodax] Mutation error:', error);\n};\n\n/**\n * Creates a `QueryClient` pre-wired with a mutation-error observability hook that gives dapp-kit\n * consumers a single seam for every mutation failure across the app — wire to Sentry/Datadog/console\n * as you like. Optional opt-in: consumers who construct their own `QueryClient` are unaffected.\n *\n * **Composition with a custom `MutationCache`.** If you pass `config.mutationCache`, we keep your\n * cache instance (preserving its own `onError` / `onSuccess` / etc.) and *additionally* subscribe\n * to its event stream to dispatch `onMutationError`. Both your handler and the dapp-kit handler\n * fire — neither replaces the other. If you don't pass one, we install our own.\n *\n * @example default — logs to console\n * const queryClient = createSodaxQueryClient();\n *\n * @example custom — Sentry\n * const queryClient = createSodaxQueryClient({\n * onMutationError: (e) => Sentry.captureException(e),\n * });\n *\n * @example silent — disable the default\n * const queryClient = createSodaxQueryClient({ onMutationError: () => {} });\n *\n * @example bring-your-own MutationCache\n * const myCache = new MutationCache({ onError: myOwnErrorHandler });\n * const queryClient = createSodaxQueryClient({ config: { mutationCache: myCache } });\n * // myOwnErrorHandler still runs; onMutationError ALSO runs (unless meta.silent).\n */\nexport function createSodaxQueryClient({\n onMutationError = defaultOnMutationError,\n config,\n}: CreateSodaxQueryClientOptions = {}): QueryClient {\n if (config?.mutationCache) {\n // Compose: keep the consumer's cache, attach our observability as an extra subscriber.\n // The consumer's own `MutationCache.onError` (if any) still fires — subscribe is additive.\n config.mutationCache.subscribe(event => {\n if (\n event.type === 'updated' &&\n event.action.type === 'error' &&\n event.mutation.options.meta?.silent !== true\n ) {\n onMutationError(event.action.error);\n }\n });\n return new QueryClient(config);\n }\n\n // No consumer cache: install our own with `onError` directly (cheaper than a subscribe loop).\n return new QueryClient({\n ...config,\n mutationCache: new MutationCache({\n onError: (error, _vars, _ctx, mutation) => {\n if (mutation.options.meta?.silent === true) return;\n onMutationError(error);\n },\n }),\n });\n}\n"]}