@sodax/dapp-kit 1.3.1-beta → 1.4.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -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":["createContext","useContext","useMutation","SpokeService","useQuery","deriveUserWalletAddress","STELLAR_MAINNET_CHAIN_ID","StellarSpokeProvider","StellarSpokeService","useQueryClient","useState","useCallback","token","error","HubService","spokeChainConfig","useMemo","BitcoinSpokeProvider","SONIC_MAINNET_CHAIN_ID","SonicSpokeProvider","EvmSpokeProvider","SuiSpokeProvider","IconSpokeProvider","InjectiveSpokeProvider","SolanaSpokeProvider","NearSpokeProvider","useRef","useEffect","BitcoinSpokeService","normalizePsbtToBase64","isAddress","isLegacyParams","resolveParams","params","parseUnits","ICON_MAINNET_CHAIN_ID","result","isLegacybnUSDToken","ClService","Sodax","React"],"mappings":";;;;;;;;;;;;;AAUO,IAAM,YAAA,GAAeA,oBAAuC,IAAI,CAAA;ACDhE,IAAM,kBAAkB,MAAwB;AACrD,EAAA,MAAM,OAAA,GAAUC,iBAAW,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,OAAOC,sBAAA,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,MAAMC,gBAAA,CAAa,WAAA,CAAY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AAA,IAAQ,eAAe,CAAA,CAAE,CAAA;AAAA,MAClF;AAEA,MAAA,OAAO,MAAA,CAAO,KAAA;AAAA,IAChB,CAAA;AAAA,IACA,WAAW,CAAC,CAAA,EAAG,EAAE,MAAA,EAAQ,eAAc,KAAM;AAE3C,MAAA,WAAA,CAAY,iBAAA,CAAkB;AAAA,QAC5B,QAAA,EAAU,CAAC,KAAA,EAAO,cAAA,EAAgB,OAAO,OAAA,EAAS,aAAA,CAAc,WAAA,CAAY,KAAA,CAAM,EAAE;AAAA,OACrF,CAAA;AACD,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,IAAIqC,SAAA,CAAM,MAAM,CAAA;AAE9B,EAAA,uBAAOC,sBAAA,CAAA,aAAA,CAAC,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,EAAE,KAAA,EAAO,OAAA,EAAS,SAAA,EAAU,EAAA,EAAI,QAAS,CAAA;AAChF","file":"index.js","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} 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} 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 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(amount0BigInt, tickLower, tickUpper, currentTick);\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(amount1BigInt, tickLower, tickUpper, currentTick);\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 amount: parseUnits(String(amount), token.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 // Apply slippage BEFORE calculating liquidity\n const slippageMultiplier = BigInt(Math.floor((100 - slippage) * 100)); // e.g., 0.5% => 9950\n\n const amount0ForLiquidity = (amount0BigInt * slippageMultiplier) / 10000n;\n const amount1ForLiquidity = (amount1BigInt * slippageMultiplier) / 10000n;\n\n // Calculate liquidity based on reduced amounts (accounting for slippage)\n const liquidity = ClService.calculateLiquidityFromAmounts(\n amount0ForLiquidity,\n amount1ForLiquidity,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n );\n const tokenId = positionId ? BigInt(positionId) : undefined;\n\n return {\n poolKey,\n tickLower,\n tickUpper,\n liquidity,\n amount0Max: amount0BigInt,\n amount1Max: amount1BigInt,\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/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":["createContext","useContext","useMutation","SpokeService","useQuery","deriveUserWalletAddress","STELLAR_MAINNET_CHAIN_ID","StellarSpokeProvider","StellarSpokeService","useQueryClient","useState","useCallback","token","error","HubService","spokeChainConfig","useMemo","BitcoinSpokeProvider","SONIC_MAINNET_CHAIN_ID","SonicSpokeProvider","EvmSpokeProvider","SuiSpokeProvider","IconSpokeProvider","InjectiveSpokeProvider","SolanaSpokeProvider","NearSpokeProvider","StacksSpokeProvider","useRef","useEffect","BitcoinSpokeService","normalizePsbtToBase64","isAddress","isLegacyParams","resolveParams","params","parseUnits","ICON_MAINNET_CHAIN_ID","result","isLegacybnUSDToken","ClService","Sodax","React"],"mappings":";;;;;;;;;;;;;AAUO,IAAM,YAAA,GAAeA,oBAAuC,IAAI,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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,IAAIsC,SAAA,CAAM,MAAM,CAAA;AAE9B,EAAA,uBAAOC,sBAAA,CAAA,aAAA,CAAC,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,EAAE,KAAA,EAAO,OAAA,EAAS,SAAA,EAAU,EAAA,EAAI,QAAS,CAAA;AAChF","file":"index.js","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(amount0BigInt, tickLower, tickUpper, currentTick);\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(amount1BigInt, tickLower, tickUpper, currentTick);\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 amount: parseUnits(String(amount), token.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 // Apply slippage BEFORE calculating liquidity\n const slippageMultiplier = BigInt(Math.floor((100 - slippage) * 100)); // e.g., 0.5% => 9950\n\n const amount0ForLiquidity = (amount0BigInt * slippageMultiplier) / 10000n;\n const amount1ForLiquidity = (amount1BigInt * slippageMultiplier) / 10000n;\n\n // Calculate liquidity based on reduced amounts (accounting for slippage)\n const liquidity = ClService.calculateLiquidityFromAmounts(\n amount0ForLiquidity,\n amount1ForLiquidity,\n tickLower,\n tickUpper,\n BigInt(poolData.currentTick),\n );\n const tokenId = positionId ? BigInt(positionId) : undefined;\n\n return {\n poolKey,\n tickLower,\n tickUpper,\n liquidity,\n amount0Max: amount0BigInt,\n amount1Max: amount1BigInt,\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"]}