@sodax/dapp-kit 1.0.1-beta-rc3 → 1.0.2-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.
Files changed (40) hide show
  1. package/README.md +130 -39
  2. package/dist/index.d.mts +541 -347
  3. package/dist/index.d.ts +541 -347
  4. package/dist/index.js +317 -176
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +315 -178
  7. package/dist/index.mjs.map +1 -1
  8. package/package.json +4 -4
  9. package/src/hooks/backend/README.md +148 -49
  10. package/src/hooks/backend/index.ts +2 -0
  11. package/src/hooks/backend/types.ts +4 -0
  12. package/src/hooks/backend/useBackendAllMoneyMarketAssets.ts +31 -20
  13. package/src/hooks/backend/useBackendAllMoneyMarketBorrowers.ts +25 -7
  14. package/src/hooks/backend/useBackendIntentByHash.ts +36 -26
  15. package/src/hooks/backend/useBackendIntentByTxHash.ts +41 -29
  16. package/src/hooks/backend/useBackendMoneyMarketAsset.ts +40 -27
  17. package/src/hooks/backend/useBackendMoneyMarketAssetBorrowers.ts +45 -36
  18. package/src/hooks/backend/useBackendMoneyMarketAssetSuppliers.ts +45 -36
  19. package/src/hooks/backend/useBackendMoneyMarketPosition.ts +34 -37
  20. package/src/hooks/backend/useBackendOrderbook.ts +38 -38
  21. package/src/hooks/backend/useBackendUserIntents.ts +81 -0
  22. package/src/hooks/mm/index.ts +1 -0
  23. package/src/hooks/mm/useAToken.ts +37 -20
  24. package/src/hooks/mm/useBorrow.ts +36 -36
  25. package/src/hooks/mm/useMMAllowance.ts +33 -24
  26. package/src/hooks/mm/useMMApprove.ts +43 -48
  27. package/src/hooks/mm/useRepay.ts +32 -36
  28. package/src/hooks/mm/useReservesData.ts +35 -16
  29. package/src/hooks/mm/useReservesHumanized.ts +15 -3
  30. package/src/hooks/mm/useReservesList.ts +28 -15
  31. package/src/hooks/mm/useReservesUsdFormat.ts +30 -21
  32. package/src/hooks/mm/useSupply.ts +34 -36
  33. package/src/hooks/mm/useUserFormattedSummary.ts +42 -20
  34. package/src/hooks/mm/useUserReservesData.ts +34 -19
  35. package/src/hooks/mm/useWithdraw.ts +33 -35
  36. package/src/hooks/swap/index.ts +2 -0
  37. package/src/hooks/swap/useCancelLimitOrder.ts +53 -0
  38. package/src/hooks/swap/useCreateLimitOrder.ts +72 -0
  39. package/src/hooks/swap/useSwapAllowance.ts +7 -7
  40. package/src/hooks/swap/useSwapApprove.ts +6 -6
@@ -1,45 +1,62 @@
1
- import type { Address, XToken } from '@sodax/sdk';
2
- import { useQuery, type UseQueryResult } from '@tanstack/react-query';
1
+ import { isAddress } from 'viem';
2
+ import type { XToken } from '@sodax/sdk';
3
+ import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';
3
4
  import { useSodaxContext } from '../shared/useSodaxContext';
4
5
 
6
+ export type UseATokenParams = {
7
+ aToken: string;
8
+ queryOptions?: UseQueryOptions<XToken, Error>;
9
+ };
10
+
5
11
  /**
6
- * React hook for fetching an AToken's ERC20 metadata from the Sodax money market.
12
+ * React hook to fetch and cache metadata for a given aToken address.
13
+ *
14
+ * Accepts an aToken address and React Query options to control query behavior.
15
+ * Returns the aToken's ERC20-style metadata from the Sodax money market, with querying/caching
16
+ * powered by React Query.
7
17
  *
8
- * Fetches and caches the metadata (name, symbol, decimals, address) for a given aToken address and chain using React Query.
9
- * This metadata is typically required for rendering balances and labels in UI components.
18
+ * @param {UseATokenParams} params - Required params object:
19
+ * @property {Address} aToken - The aToken contract address to query.
20
+ * @property {UseQueryOptions<XToken, Error>} queryOptions - React Query options to control query (e.g., staleTime, refetch, etc.).
10
21
  *
11
- * @param {Address | undefined} aToken - The aToken contract address to look up. Should be an EVM address.
12
- * @param {ChainId | undefined} chainId - The EVM chain ID for the aToken.
22
+ * @returns {UseQueryResult<XToken, Error>} React Query result object:
23
+ * - data: XToken metadata, if available
24
+ * - isLoading: Boolean loading state
25
+ * - error: Error, if API call fails
13
26
  *
14
27
  * @example
15
- * ```typescript
16
- * const { data: aToken, isLoading, error } = useAToken(aTokenAddress, chainId);
17
- * if (aToken) {
18
- * console.log(aToken.symbol); // 'aETH'
28
+ * const { data: xToken, isLoading, error } = useAToken({ aToken: aTokenAddress, queryOptions: {} });
29
+ * if (xToken) {
30
+ * console.log(xToken.symbol);
19
31
  * }
20
- * ```
21
- *
22
- * @returns {UseQueryResult<Erc20Token, Error>} A React Query result object containing:
23
- * - data: The aToken ERC20 metadata when available.
24
- * - isLoading: Loading state indicator.
25
- * - error: Any error that occurred during data fetching.
26
32
  */
27
- export function useAToken(aToken: Address | undefined): UseQueryResult<XToken, Error> {
33
+ export function useAToken({ aToken, queryOptions }: UseATokenParams): UseQueryResult<XToken, Error> {
28
34
  const { sodax } = useSodaxContext();
35
+ const defaultQueryOptions = {
36
+ queryKey: ['mm', 'aToken', aToken],
37
+ enabled: !!aToken,
38
+ };
39
+ queryOptions = {
40
+ ...defaultQueryOptions,
41
+ ...queryOptions, // override default query options if provided
42
+ };
29
43
 
30
44
  return useQuery({
31
- queryKey: ['aToken', sodax.hubProvider.chainConfig.chain.id, aToken],
45
+ ...queryOptions,
32
46
  queryFn: async () => {
33
47
  if (!aToken) {
34
48
  throw new Error('aToken address or hub provider is not defined');
35
49
  }
36
50
 
51
+ if (!isAddress(aToken)) {
52
+ throw new Error('aToken address is not a valid address');
53
+ }
54
+
37
55
  const aTokenData = await sodax.moneyMarket.data.getATokenData(aToken);
38
56
  return {
39
57
  ...aTokenData,
40
58
  xChainId: sodax.hubProvider.chainConfig.chain.id,
41
59
  };
42
60
  },
43
- enabled: !!aToken,
44
61
  });
45
62
  }
@@ -1,66 +1,66 @@
1
- import type { SpokeChainId, XToken } from '@sodax/types';
2
1
  import { useMutation, type UseMutationResult } from '@tanstack/react-query';
3
- import { parseUnits } from 'viem';
4
2
  import { useSodaxContext } from '../shared/useSodaxContext';
5
- import type { SpokeProvider } from '@sodax/sdk';
3
+ import type { MoneyMarketBorrowParams, MoneyMarketError, RelayErrorCode, SpokeProvider } from '@sodax/sdk';
4
+
6
5
  interface BorrowResponse {
7
6
  ok: true;
8
7
  value: [string, string];
9
8
  }
10
9
 
10
+ export type UseBorrowParams = {
11
+ params: MoneyMarketBorrowParams;
12
+ spokeProvider: SpokeProvider;
13
+ };
14
+
11
15
  /**
12
- * Hook for borrowing tokens from the Sodax money market.
13
- *
14
- * This hook provides functionality to borrow tokens from the money market protocol,
15
- * handling the entire borrow process including transaction creation, submission,
16
- * and cross-chain communication.
16
+ * React hook for borrowing tokens in the Sodax money market protocol.
17
17
  *
18
- * @param {XToken} spokeToken - The token to borrow from the spoke chain. Must be an XToken with valid address and chain information.
19
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the borrow transaction. Must be a valid SpokeProvider instance.
18
+ * Encapsulates the async process to initiate a borrow transaction via the money market,
19
+ * handling transaction creation, submission, and cross-chain logic.
20
20
  *
21
- * @returns {UseMutationResult<BorrowResponse, Error, string>} A mutation result object with the following properties:
22
- * - mutateAsync: Function to execute the borrow transaction
23
- * - isPending: Boolean indicating if a transaction is in progress
24
- * - error: Error object if the last transaction failed, null otherwise
21
+ * @returns {UseMutationResult<
22
+ * BorrowResponse,
23
+ * MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,
24
+ * UseBorrowParams
25
+ * >} A React Query mutation result object containing:
26
+ * - mutateAsync: (params: UseBorrowParams) => Promise<BorrowResponse>
27
+ * Triggers the borrow action. Expects an object with valid borrow params and a `SpokeProvider`.
28
+ * - isPending: `boolean` if a borrow transaction is in progress.
29
+ * - error: `MoneyMarketError` if the transaction fails, or `null`.
25
30
  *
26
31
  * @example
27
32
  * ```typescript
28
- * const { mutateAsync: borrow, isPending, error } = useBorrow(spokeToken);
29
- * await borrow('100');
33
+ * const { mutateAsync: borrow, isPending, error } = useBorrow();
34
+ * await borrow({ params: borrowParams, spokeProvider });
30
35
  * ```
31
36
  *
32
37
  * @throws {Error} When:
33
- * - spokeProvider is not available
34
- * - Transaction execution fails
38
+ * - `spokeProvider` is missing or invalid.
39
+ * - The underlying borrow transaction fails.
35
40
  */
36
- export function useBorrow(
37
- spokeToken: XToken,
38
- spokeProvider: SpokeProvider | undefined,
39
- ): UseMutationResult<BorrowResponse, Error, string> {
41
+ export function useBorrow(): UseMutationResult<
42
+ BorrowResponse,
43
+ MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,
44
+ UseBorrowParams
45
+ > {
40
46
  const { sodax } = useSodaxContext();
41
47
 
42
- return useMutation<BorrowResponse, Error, string>({
43
- mutationFn: async (amount: string, toChainId?: SpokeChainId, toAddress?: string) => {
48
+ return useMutation<
49
+ BorrowResponse,
50
+ MoneyMarketError<'CREATE_BORROW_INTENT_FAILED' | 'BORROW_UNKNOWN_ERROR' | RelayErrorCode>,
51
+ UseBorrowParams
52
+ >({
53
+ mutationFn: async ({ params, spokeProvider }: UseBorrowParams) => {
44
54
  if (!spokeProvider) {
45
55
  throw new Error('spokeProvider is not found');
46
56
  }
47
57
 
48
- const response = await sodax.moneyMarket.borrow(
49
- {
50
- token: spokeToken.address,
51
- amount: parseUnits(amount, 18),
52
- action: 'borrow',
53
- toChainId: toChainId,
54
- toAddress: toAddress,
55
- },
56
- spokeProvider,
57
- );
58
+ const response = await sodax.moneyMarket.borrow(params, spokeProvider);
58
59
 
59
60
  if (!response.ok) {
60
- throw new Error('Failed to borrow tokens');
61
+ throw response.error;
61
62
  }
62
63
 
63
- console.log('Borrow transaction submitted:', response);
64
64
  return response;
65
65
  },
66
66
  });
@@ -1,8 +1,12 @@
1
- import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
- import type { XToken } from '@sodax/types';
1
+ import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';
3
2
  import { useSodaxContext } from '../shared/useSodaxContext';
4
- import { parseUnits } from 'viem';
5
- import type { MoneyMarketAction, SpokeProvider } from '@sodax/sdk';
3
+ import type { MoneyMarketParams, SpokeProvider } from '@sodax/sdk';
4
+
5
+ export type UseMMAllowanceParams = {
6
+ params: MoneyMarketParams | undefined;
7
+ spokeProvider: SpokeProvider | undefined;
8
+ queryOptions?: UseQueryOptions<boolean, Error>;
9
+ };
6
10
 
7
11
  /**
8
12
  * Hook for checking token allowance for money market operations.
@@ -25,32 +29,37 @@ import type { MoneyMarketAction, SpokeProvider } from '@sodax/sdk';
25
29
  * const { data: hasAllowed, isLoading } = useMMAllowance(token, "100", "repay", provider);
26
30
  * ```
27
31
  */
28
- export function useMMAllowance(
29
- token: XToken,
30
- amount: string,
31
- action: MoneyMarketAction,
32
- spokeProvider: SpokeProvider | undefined,
33
- ): UseQueryResult<boolean, Error> {
32
+ export function useMMAllowance({
33
+ params,
34
+ spokeProvider,
35
+ queryOptions,
36
+ }: UseMMAllowanceParams): UseQueryResult<boolean, Error> {
34
37
  const { sodax } = useSodaxContext();
35
38
 
39
+ const defaultQueryOptions = {
40
+ queryKey: ['mm', 'allowance', params?.token, params?.action],
41
+ enabled: !!spokeProvider,
42
+ refetchInterval: 5000,
43
+ };
44
+
45
+ queryOptions = {
46
+ ...defaultQueryOptions,
47
+ ...queryOptions, // override default query options if provided
48
+ }
49
+
36
50
  return useQuery({
37
- queryKey: ['allowance', token.address, amount, action],
51
+ ...queryOptions,
38
52
  queryFn: async () => {
39
53
  if (!spokeProvider) throw new Error('Spoke provider is required');
40
- const actionBasedDecimals = action === 'withdraw' || action === 'borrow' ? 18 : token.decimals; // withdraw and borrow actions are in aToken decimals
41
- const allowance = await sodax.moneyMarket.isAllowanceValid(
42
- {
43
- token: token.address,
44
- amount: parseUnits(amount, actionBasedDecimals),
45
- action,
46
- },
47
- spokeProvider,
48
- );
49
- if (allowance.ok) {
50
- return allowance.value;
54
+ if (!params) throw new Error('Params are required');
55
+
56
+ const allowance = await sodax.moneyMarket.isAllowanceValid(params, spokeProvider);
57
+
58
+ if (!allowance.ok) {
59
+ throw allowance.error;
51
60
  }
52
- return false;
61
+
62
+ return allowance.value;
53
63
  },
54
- enabled: !!spokeProvider,
55
64
  });
56
65
  }
@@ -1,68 +1,63 @@
1
1
  import { useSodaxContext } from '../shared/useSodaxContext';
2
- import type { XToken } from '@sodax/types';
3
- import { parseUnits } from 'viem';
4
- import { useMutation, useQueryClient } from '@tanstack/react-query';
5
- import type { MoneyMarketAction, SpokeProvider } from '@sodax/sdk';
2
+ import { useMutation, type UseMutationResult, useQueryClient } from '@tanstack/react-query';
3
+ import type { MoneyMarketParams, SpokeProvider } from '@sodax/sdk';
6
4
 
7
- interface UseApproveReturn {
8
- approve: ({ amount, action }: { amount: string; action: MoneyMarketAction }) => Promise<boolean>;
9
- isLoading: boolean;
10
- error: Error | null;
11
- resetError: () => void;
12
- }
5
+ export type UseMMApproveParams = {
6
+ params: MoneyMarketParams;
7
+ spokeProvider: SpokeProvider | undefined;
8
+ };
13
9
 
14
10
  /**
15
- * Hook for approving token spending for money market actions
16
- * @param token The token to approve spending for
17
- * @param spokeProvider The spoke provider instance for the chain
18
- * @returns Object containing approve function, loading state, error state and reset function
11
+ * Hook for approving ERC20 token spending for Sodax money market actions.
12
+ *
13
+ * This hook manages the approval transaction, allowing the user
14
+ * to grant the protocol permission to spend their tokens for specific money market actions
15
+ * (such as supply, borrow, or repay). Upon successful approval, it also invalidates and
16
+ * refetches the associated allowance status so the UI remains up-to-date.
17
+ *
18
+ * @returns {UseMutationResult<string, Error, UseMMApproveParams>} A React Query mutation result containing:
19
+ * - mutateAsync: Function to trigger the approval (see below)
20
+ * - isPending: Boolean indicating if approval transaction is in progress
21
+ * - error: Error object if the last approval failed, null otherwise
22
+ *
19
23
  * @example
20
24
  * ```tsx
21
- * const { approve, isLoading, error } = useMMApprove(token, spokeProvider);
22
- *
23
- * // Approve tokens for supply action
24
- * await approve({ amount: "100", action: "supply" });
25
+ * const { mutateAsync: approve, isPending, error } = useMMApprove();
26
+ * await approve({ params: { token, amount: "100", action: "supply", ... }, spokeProvider });
25
27
  * ```
28
+ *
29
+ * @throws {Error} When:
30
+ * - spokeProvider is undefined or invalid
31
+ * - Approval transaction fails for any reason
26
32
  */
27
-
28
- export function useMMApprove(token: XToken, spokeProvider: SpokeProvider | undefined): UseApproveReturn {
33
+ export function useMMApprove(): UseMutationResult<string, Error, UseMMApproveParams> {
29
34
  const { sodax } = useSodaxContext();
30
35
  const queryClient = useQueryClient();
31
36
 
32
- const {
33
- mutateAsync: approve,
34
- isPending,
35
- error,
36
- reset: resetError,
37
- } = useMutation({
38
- mutationFn: async ({ amount, action }: { amount: string; action: MoneyMarketAction }) => {
37
+ return useMutation({
38
+ mutationFn: async ({ params, spokeProvider }: UseMMApproveParams) => {
39
39
  if (!spokeProvider) {
40
40
  throw new Error('Spoke provider not found');
41
41
  }
42
- const actionBasedDecimals = action === 'withdraw' || action === 'borrow' ? 18 : token.decimals; // withdraw and borrow actions are in aToken decimals
43
- const allowance = await sodax.moneyMarket.approve(
44
- {
45
- token: token.address,
46
- amount: parseUnits(amount, actionBasedDecimals),
47
- action,
48
- },
49
- spokeProvider,
50
- );
42
+ const allowance = await sodax.moneyMarket.approve(params, spokeProvider, false);
51
43
  if (!allowance.ok) {
52
- throw new Error('Failed to approve tokens');
44
+ throw allowance.error;
53
45
  }
54
- return allowance.ok;
46
+
47
+ return allowance.value;
55
48
  },
56
- onSuccess: () => {
57
- // Invalidate allowance query to refetch the new allowance
58
- queryClient.invalidateQueries({ queryKey: ['allowance', token.address] });
49
+ onSuccess: (_, { params, spokeProvider }: UseMMApproveParams) => {
50
+ console.log('onSuccess invoked with queryKey:', [
51
+ 'mm',
52
+ 'allowance',
53
+ spokeProvider?.chainConfig.chain.id,
54
+ params.token,
55
+ params.action,
56
+ ]);
57
+ // Invalidate allowance query to refetch updated approval status
58
+ queryClient.invalidateQueries({
59
+ queryKey: ['mm', 'allowance', spokeProvider?.chainConfig.chain.id, params.token, params.action],
60
+ });
59
61
  },
60
62
  });
61
-
62
- return {
63
- approve,
64
- isLoading: isPending,
65
- error: error,
66
- resetError,
67
- };
68
63
  }
@@ -1,7 +1,5 @@
1
- import type { SpokeProvider } from '@sodax/sdk';
2
- import type { SpokeChainId, XToken } from '@sodax/types';
1
+ import type { MoneyMarketError, MoneyMarketRepayParams, RelayErrorCode, SpokeProvider } from '@sodax/sdk';
3
2
  import { useMutation, type UseMutationResult } from '@tanstack/react-query';
4
- import { parseUnits } from 'viem';
5
3
  import { useSodaxContext } from '../shared/useSodaxContext';
6
4
 
7
5
  interface RepayResponse {
@@ -9,59 +7,57 @@ interface RepayResponse {
9
7
  value: [string, string];
10
8
  }
11
9
 
10
+ export type UseRepayParams = {
11
+ params: MoneyMarketRepayParams;
12
+ spokeProvider: SpokeProvider;
13
+ };
14
+
12
15
  /**
13
- * Hook for repaying borrowed tokens to the Sodax money market.
14
- *
15
- * This hook provides functionality to repay borrowed tokens back to the money market protocol,
16
- * handling the entire repayment process including transaction creation, submission,
17
- * and cross-chain communication.
16
+ * React hook for repaying a borrow in the Sodax money market protocol.
18
17
  *
19
- * @param {XToken} spokeToken - The token to repay on the spoke chain. Must be an XToken with valid address and chain information.
20
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the repay transaction. Must be a valid SpokeProvider instance.
18
+ * This hook encapsulates the process of sending a repay transaction to the money market.
19
+ * It manages the asynchronous operation for repayment, including sending the transaction
20
+ * and error handling.
21
21
  *
22
- * @returns {UseMutationResult<RepayResponse, Error, string>} A mutation result object with the following properties:
23
- * - mutateAsync: Function to execute the repay transaction
24
- * - isPending: Boolean indicating if a transaction is in progress
25
- * - error: Error object if the last transaction failed, null otherwise
22
+ * @returns {UseMutationResult<RepayResponse, MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>, UseRepayParams>} React Query mutation result object containing:
23
+ * - mutateAsync: (params: UseRepayParams) => Promise<RepayResponse>
24
+ * Initiates a repay transaction using the given MoneyMarketRepayParams and SpokeProvider.
25
+ * - isPending: boolean indicating if a transaction is in progress.
26
+ * - error: MoneyMarketError if an error occurred while repaying, otherwise undefined.
26
27
  *
27
28
  * @example
28
29
  * ```typescript
29
- * const { mutateAsync: repay, isPending, error } = useRepay(spokeToken);
30
- * await repay('100');
30
+ * const { mutateAsync: repay, isPending, error } = useRepay();
31
+ * await repay({ params: repayParams, spokeProvider });
31
32
  * ```
32
33
  *
33
34
  * @throws {Error} When:
34
- * - spokeProvider is not available
35
- * - Transaction execution fails
35
+ * - `spokeProvider` is missing or invalid.
36
+ * - The underlying repay transaction fails.
36
37
  */
37
- export function useRepay(
38
- spokeToken: XToken,
39
- spokeProvider: SpokeProvider | undefined,
40
- ): UseMutationResult<RepayResponse, Error, string> {
38
+ export function useRepay(): UseMutationResult<
39
+ RepayResponse,
40
+ MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>,
41
+ UseRepayParams
42
+ > {
41
43
  const { sodax } = useSodaxContext();
42
44
 
43
- return useMutation<RepayResponse, Error, string>({
44
- mutationFn: async (amount: string, toChainId?: SpokeChainId, toAddress?: string) => {
45
+ return useMutation<
46
+ RepayResponse,
47
+ MoneyMarketError<'CREATE_REPAY_INTENT_FAILED' | 'REPAY_UNKNOWN_ERROR' | RelayErrorCode>,
48
+ UseRepayParams
49
+ >({
50
+ mutationFn: async ({ params, spokeProvider }: UseRepayParams) => {
45
51
  if (!spokeProvider) {
46
52
  throw new Error('spokeProvider is not found');
47
53
  }
48
54
 
49
- const response = await sodax.moneyMarket.repay(
50
- {
51
- token: spokeToken.address,
52
- amount: parseUnits(amount, spokeToken.decimals),
53
- action: 'repay',
54
- toChainId: toChainId,
55
- toAddress: toAddress,
56
- },
57
- spokeProvider,
58
- );
55
+ const response = await sodax.moneyMarket.repay(params, spokeProvider);
59
56
 
60
57
  if (!response.ok) {
61
- throw new Error('Failed to repay tokens');
58
+ throw response.error;
62
59
  }
63
60
 
64
- console.log('Repay transaction submitted:', response);
65
61
  return response;
66
62
  },
67
63
  });
@@ -1,29 +1,48 @@
1
- import { useQuery } from '@tanstack/react-query';
1
+ import { useQuery, type UseQueryResult, type UseQueryOptions } from '@tanstack/react-query';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext';
3
+ import type { AggregatedReserveData, BaseCurrencyInfo } from '@sodax/sdk';
4
+
5
+ export type UseReservesDataParams = {
6
+ queryOptions?: UseQueryOptions<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>;
7
+ };
8
+
3
9
  /**
4
- * Hook for fetching reserves data from the Sodax money market.
10
+ * React hook for fetching the latest reserves data from the Sodax money market.
5
11
  *
6
- * This hook provides access to the current state of all reserves in the money market protocol,
7
- * including liquidity, interest rates, and other key metrics. The data is automatically
8
- * fetched and cached using React Query.
12
+ * Provides the full set of aggregated reserves and base currency information.
13
+ * Optionally accepts React Query options for customizing the query key, cache time, and related behaviors.
9
14
  *
10
- * @example
11
- * ```typescript
12
- * const { data: reservesData, isLoading, error } = useReservesData();
13
- * ```
15
+ * @param params (optional) - Object including:
16
+ * - queryOptions: Custom React Query options
14
17
  *
15
- * @returns A React Query result object containing:
16
- * - data: The reserves data when available
17
- * - isLoading: Loading state indicator
18
- * - error: Any error that occurred during data fetching
18
+ * @returns {UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error>}
19
+ * React Query result object containing:
20
+ * - data: [aggregated reserves[], base currency info], or undefined if not loaded
21
+ * - isLoading: True if the request is loading
22
+ * - isError: True if the request failed
23
+ * - error: Error object, if present
24
+ *
25
+ * @example
26
+ * const { data, isLoading, error } = useReservesData();
27
+ * const { data } = useReservesData({ queryOptions: { queryKey: ['custom', 'reservesData'] } });
19
28
  */
29
+ export function useReservesData(
30
+ params?: UseReservesDataParams,
31
+ ): UseQueryResult<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo], Error> {
32
+ const defaultQueryOptions = {
33
+ queryKey: ['mm', 'reservesData'],
34
+ refetchInterval: 5000,
35
+ };
20
36
 
21
- export function useReservesData() {
37
+ const queryOptions = {
38
+ ...defaultQueryOptions,
39
+ ...params?.queryOptions, // override default query options if provided
40
+ }
22
41
  const { sodax } = useSodaxContext();
23
42
 
24
43
  return useQuery({
25
- queryKey: ['reservesData'],
26
- queryFn: async () => {
44
+ ...queryOptions,
45
+ queryFn: async (): Promise<readonly [readonly AggregatedReserveData[], BaseCurrencyInfo]> => {
27
46
  return await sodax.moneyMarket.data.getReservesData();
28
47
  },
29
48
  });
@@ -1,6 +1,11 @@
1
1
  import type { ReservesDataHumanized } from '@sodax/sdk';
2
- import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import { useQuery, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';
3
3
  import { useSodaxContext } from '../shared/useSodaxContext';
4
+
5
+ export type UseReservesHumanizedParams = {
6
+ queryOptions?: UseQueryOptions<ReservesDataHumanized, Error>;
7
+ };
8
+
4
9
  /**
5
10
  * Hook for fetching humanized reserves data from the Sodax money market.
6
11
  *
@@ -18,11 +23,18 @@ import { useSodaxContext } from '../shared/useSodaxContext';
18
23
  * - isLoading: Loading state indicator
19
24
  * - error: Any error that occurred during data fetching
20
25
  */
21
- export function useReservesHumanized(): UseQueryResult<ReservesDataHumanized, Error> {
26
+ export function useReservesHumanized(
27
+ params?: UseReservesHumanizedParams,
28
+ ): UseQueryResult<ReservesDataHumanized, Error> {
29
+ const defaultQueryOptions = { queryKey: ['mm', 'reservesHumanized'], refetchInterval: 5000 };
30
+ const queryOptions = {
31
+ ...defaultQueryOptions,
32
+ ...params?.queryOptions, // override default query options if provided
33
+ };
22
34
  const { sodax } = useSodaxContext();
23
35
 
24
36
  return useQuery({
25
- queryKey: ['reservesHumanized'],
37
+ ...queryOptions,
26
38
  queryFn: async () => {
27
39
  return await sodax.moneyMarket.data.getReservesHumanized();
28
40
  },
@@ -1,28 +1,41 @@
1
- import { useQuery } from '@tanstack/react-query';
1
+ import { useQuery, type UseQueryResult, type UseQueryOptions } from '@tanstack/react-query';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext';
3
+ import type { Address } from '@sodax/sdk';
4
+
5
+ export type UseReservesListParams = {
6
+ queryOptions?: UseQueryOptions<readonly Address[], Error>;
7
+ };
3
8
 
4
9
  /**
5
- * Hook for fetching list of reserves from the Sodax money market.
10
+ * React hook for fetching the list of reserve addresses from the Sodax money market.
11
+ *
12
+ * This hook returns a React Query result object containing the array of all reserve `Address`
13
+ * values currently available in the protocol. Optionally, custom React Query options can be provided.
6
14
  *
7
- * This hook provides access to the list of addresses of all reserves in the money market protocol.
8
- * The data is automatically fetched and cached using React Query.
15
+ * @param params (optional) - Object including:
16
+ * - queryOptions: Custom React Query options such as `queryKey`, cache behavior, or refetching policy
17
+ *
18
+ * @returns {UseQueryResult<readonly Address[], Error>} React Query result object containing:
19
+ * - data: Array of reserve addresses, or undefined if loading
20
+ * - isLoading: Boolean loading state
21
+ * - isError: Boolean error state
22
+ * - error: Error object, if present
9
23
  *
10
24
  * @example
11
- * ```typescript
12
25
  * const { data: reservesList, isLoading, error } = useReservesList();
13
- * ```
14
- *
15
- * @returns A React Query result object containing:
16
- * - data: The reserves list when available
17
- * - isLoading: Loading state indicator
18
- * - error: Any error that occurred during data fetching
26
+ * const { data } = useReservesList({ queryOptions: { queryKey: ['custom', 'reservesList'] } });
19
27
  */
20
- export function useReservesList() {
28
+ export function useReservesList(params?: UseReservesListParams): UseQueryResult<readonly Address[], Error> {
29
+ const defaultQueryOptions = { queryKey: ['mm', 'reservesList'] };
30
+ const queryOptions = {
31
+ ...defaultQueryOptions,
32
+ ...params?.queryOptions, // override default query options if provided
33
+ };
21
34
  const { sodax } = useSodaxContext();
22
35
 
23
- return useQuery({
24
- queryKey: ['reservesList'],
25
- queryFn: async () => {
36
+ return useQuery<readonly Address[], Error>({
37
+ ...queryOptions,
38
+ queryFn: async (): Promise<readonly Address[]> => {
26
39
  return await sodax.moneyMarket.data.getReservesList();
27
40
  },
28
41
  });