@sodax/dapp-kit 1.0.1-beta → 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 +3 -3
  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,37 +1,46 @@
1
1
  import type { FormatReserveUSDResponse, ReserveData } 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
4
 
5
+ export type UseReservesUsdFormatParams = {
6
+ queryOptions?: UseQueryOptions<
7
+ (ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[],
8
+ Error
9
+ >;
10
+ };
11
+
5
12
  /**
6
- * Hook for fetching formatted summary of Sodax user portfolio (holdings, total liquidity,
7
- * collateral, borrows, liquidation threshold, health factor, available borrowing power, etc..).
13
+ * Hook for fetching reserves data formatted with USD values in the Sodax money market.
8
14
  *
9
- * This hook provides access to the current state of user portfolio in the money market protocol.
10
- * The data is automatically fetched and cached using React Query.
15
+ * This hook returns an array of reserve objects, each extended with its price in the market reference
16
+ * currency and formatted USD values. Data is automatically fetched and cached using React Query.
11
17
  *
12
- * @example
13
- * ```typescript
14
- * const { data: userFormattedSummary, isLoading, error } = useUserFormattedSummary();
15
- * ```
18
+ * @param params (optional) - Object including:
19
+ * - queryOptions: Custom React Query options such as `queryKey`, cache behavior, or refetching policy.
20
+ *
21
+ * @returns {UseQueryResult<(ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[], Error>} React Query result object containing:
22
+ * - data: Array of reserves with USD-formatted values, or undefined if loading
23
+ * - isLoading: Boolean loading state
24
+ * - isError: Boolean error state
25
+ * - error: Error object, if present
16
26
  *
17
- * @returns A React Query result object containing:
18
- * - data: The formatted summary of Sodax user portfolio when available
19
- * - isLoading: Loading state indicator
20
- * - error: Any error that occurred during data fetching
27
+ * @example
28
+ * const { data: reservesUSD, isLoading, error } = useReservesUsdFormat();
21
29
  */
22
- export function useReservesUsdFormat(): UseQueryResult<
23
- (ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[],
24
- Error
25
- > {
30
+ export function useReservesUsdFormat(
31
+ params?: UseReservesUsdFormatParams,
32
+ ): UseQueryResult<(ReserveData & { priceInMarketReferenceCurrency: string } & FormatReserveUSDResponse)[], Error> {
26
33
  const { sodax } = useSodaxContext();
34
+ const defaultQueryOptions = { queryKey: ['mm', 'reservesUsdFormat'] };
35
+ const queryOptions = {
36
+ ...defaultQueryOptions,
37
+ ...params?.queryOptions, // override default query options if provided
38
+ };
27
39
 
28
40
  return useQuery({
29
- queryKey: ['reservesUsdFormat'],
41
+ ...queryOptions,
30
42
  queryFn: async () => {
31
- // fetch reserves and hub wallet address
32
43
  const reserves = await sodax.moneyMarket.data.getReservesHumanized();
33
-
34
- // format reserves
35
44
  return sodax.moneyMarket.data.formatReservesUSD(sodax.moneyMarket.data.buildReserveDataWithPrice(reserves));
36
45
  },
37
46
  });
@@ -1,7 +1,5 @@
1
- import type { SpokeProvider } from '@sodax/sdk';
2
- import type { SpokeChainId, XToken } from '@sodax/types';
1
+ import type { MoneyMarketError, MoneyMarketSupplyParams, 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 SupplyResponse {
@@ -9,58 +7,58 @@ interface SupplyResponse {
9
7
  value: [string, string];
10
8
  }
11
9
 
10
+ export type UseSupplyParams = {
11
+ params: MoneyMarketSupplyParams;
12
+ spokeProvider: SpokeProvider;
13
+ };
14
+
12
15
  /**
13
- * Hook for supplying tokens to the Sodax money market.
14
- *
15
- * This hook provides functionality to supply tokens to the money market protocol,
16
- * handling the entire supply process including transaction creation, submission,
17
- * and cross-chain communication.
16
+ * React hook for supplying tokens to the Sodax money market protocol.
18
17
  *
19
- * @param {XToken} spokeToken - The token to supply 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 supply transaction. Must be a valid SpokeProvider instance.
18
+ * Provides a mutation for performing the supply operation using React Query. Useful
19
+ * for UI components needing to manage the full state (pending, error, etc.) of a supply
20
+ * transaction. It handles transaction creation, cross-chain logic, and errors.
21
21
  *
22
- * @returns {UseMutationResult<SupplyResponse, Error, string>} A mutation result object with the following properties:
23
- * - mutateAsync: Function to execute the supply 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<SupplyResponse, MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>, UseSupplyParams>}
23
+ * Mutation result object from React Query, where:
24
+ * - mutateAsync(params: UseSupplyParams): Promise<SupplyResponse>
25
+ * Initiates a supply transaction using the given MoneyMarketSupplyParams and SpokeProvider.
26
+ * - isPending: boolean indicating if a transaction is in progress.
27
+ * - error: MoneyMarketError if an error occurred while supplying, otherwise undefined.
26
28
  *
27
29
  * @example
28
30
  * ```typescript
29
- * const { mutateAsync: supply, isPending, error } = useSupply(spokeToken);
30
- * await supply('100');
31
+ * const { mutateAsync: supply, isPending, error } = useSupply();
32
+ * await supply({ params: supplyParams, spokeProvider });
31
33
  * ```
32
34
  *
33
- * @throws {Error} When:
34
- * - spokeProvider is not available
35
+ * @throws {Error|MoneyMarketError<...>} When:
36
+ * - `spokeProvider` is not provided or invalid.
37
+ * - The underlying supply transaction fails.
35
38
  */
36
- export function useSupply(
37
- spokeToken: XToken,
38
- spokeProvider: SpokeProvider | undefined,
39
- ): UseMutationResult<SupplyResponse, Error, string> {
39
+ export function useSupply(): UseMutationResult<
40
+ SupplyResponse,
41
+ MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>,
42
+ UseSupplyParams
43
+ > {
40
44
  const { sodax } = useSodaxContext();
41
45
 
42
- return useMutation<SupplyResponse, Error, string>({
43
- mutationFn: async (amount: string, toChainId?: SpokeChainId, toAddress?: string) => {
46
+ return useMutation<
47
+ SupplyResponse,
48
+ MoneyMarketError<'CREATE_SUPPLY_INTENT_FAILED' | 'SUPPLY_UNKNOWN_ERROR' | RelayErrorCode>,
49
+ UseSupplyParams
50
+ >({
51
+ mutationFn: async ({ params, spokeProvider }: UseSupplyParams) => {
44
52
  if (!spokeProvider) {
45
53
  throw new Error('spokeProvider is not found');
46
54
  }
47
55
 
48
- const response = await sodax.moneyMarket.supply(
49
- {
50
- token: spokeToken.address,
51
- amount: parseUnits(amount, spokeToken.decimals),
52
- action: 'supply',
53
- toChainId: toChainId,
54
- toAddress: toAddress,
55
- },
56
- spokeProvider,
57
- );
56
+ const response = await sodax.moneyMarket.supply(params, spokeProvider);
58
57
 
59
58
  if (!response.ok) {
60
- throw new Error('Failed to supply tokens');
59
+ throw response.error;
61
60
  }
62
61
 
63
- console.log('Supply transaction submitted:', response);
64
62
  return response;
65
63
  },
66
64
  });
@@ -1,34 +1,58 @@
1
1
  import type { FormatUserSummaryResponse, FormatReserveUSDResponse, SpokeProvider } 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
4
 
5
+ export type UseUserFormattedSummaryParams = {
6
+ spokeProvider?: SpokeProvider;
7
+ address?: string;
8
+ queryOptions?: UseQueryOptions<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>;
9
+ };
10
+
5
11
  /**
6
- * Hook for fetching formatted summary of Sodax user portfolio (holdings, total liquidity,
7
- * collateral, borrows, liquidation threshold, health factor, available borrowing power, etc..).
12
+ * React hook to fetch a formatted summary of a user's Sodax money market portfolio.
8
13
  *
9
- * This hook provides access to the current state of user portfolio in the money market protocol.
10
- * The data is automatically fetched and cached using React Query.
14
+ * Accepts an optional params object:
15
+ * - `spokeProvider`: The SpokeProvider instance for the target chain
16
+ * - `address`: The user wallet address to get the summary for
17
+ * - `queryOptions`: Optional React Query options (key, caching, intervals, etc)
11
18
  *
12
- * @example
13
- * ```typescript
14
- * const { data: userFormattedSummary, isLoading, error } = useUserFormattedSummary(spokeProvider, address);
15
- * ```
19
+ * The hook returns a React Query result object containing the formatted summary, loading and error state.
20
+ * The query is enabled only if both the spokeProvider and address are provided.
21
+ *
22
+ * @param params Optional parameters:
23
+ * - spokeProvider: SpokeProvider to query chain data (required for enabled query)
24
+ * - address: User account address (required for enabled query)
25
+ * - queryOptions: React Query options for customization (optional)
26
+ *
27
+ * @returns {UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error>}
28
+ * A result object from React Query including:
29
+ * - data: The user's formatted portfolio summary (or undefined if not loaded)
30
+ * - isLoading: Boolean loading state
31
+ * - isError: Boolean error state
32
+ * - error: Error if thrown in fetching
16
33
  *
17
- * @returns A React Query result object containing:
18
- * - data: The formatted summary of Sodax user portfolio when available
19
- * - isLoading: Loading state indicator
20
- * - error: Any error that occurred during data fetching
34
+ * @example
35
+ * const { data, isLoading, error } = useUserFormattedSummary({ spokeProvider, address });
21
36
  */
22
37
  export function useUserFormattedSummary(
23
- spokeProvider: SpokeProvider | undefined,
24
- address: string | undefined,
38
+ params?: UseUserFormattedSummaryParams,
25
39
  ): UseQueryResult<FormatUserSummaryResponse<FormatReserveUSDResponse>, Error> {
26
40
  const { sodax } = useSodaxContext();
41
+ const defaultQueryOptions = {
42
+ queryKey: ['mm', 'userFormattedSummary', params?.spokeProvider?.chainConfig.chain.id, params?.address],
43
+ enabled: !!params?.spokeProvider && !!params?.address,
44
+ refetchInterval: 5000,
45
+ };
46
+
47
+ const queryOptions = {
48
+ ...defaultQueryOptions,
49
+ ...params?.queryOptions, // override default query options if provided
50
+ }
27
51
 
28
52
  return useQuery({
29
- queryKey: ['userFormattedSummary', spokeProvider?.chainConfig.chain.id, address],
53
+ ...queryOptions,
30
54
  queryFn: async () => {
31
- if (!spokeProvider || !address) {
55
+ if (!params?.spokeProvider || !params?.address) {
32
56
  throw new Error('Spoke provider or address is not defined');
33
57
  }
34
58
 
@@ -41,14 +65,12 @@ export function useUserFormattedSummary(
41
65
  );
42
66
 
43
67
  // fetch user reserves
44
- const userReserves = await sodax.moneyMarket.data.getUserReservesHumanized(spokeProvider);
68
+ const userReserves = await sodax.moneyMarket.data.getUserReservesHumanized(params?.spokeProvider);
45
69
 
46
70
  // format user summary
47
71
  return sodax.moneyMarket.data.formatUserSummary(
48
72
  sodax.moneyMarket.data.buildUserSummaryRequest(reserves, formattedReserves, userReserves),
49
73
  );
50
74
  },
51
- enabled: !!spokeProvider && !!address,
52
- refetchInterval: 5000,
53
75
  });
54
76
  }
@@ -1,40 +1,55 @@
1
1
  import type { SpokeProvider, UserReserveData } 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
4
 
5
+ export type UseUserReservesDataParams = {
6
+ spokeProvider: SpokeProvider | undefined;
7
+ address: string | undefined;
8
+ queryOptions?: UseQueryOptions<readonly [readonly UserReserveData[], number], Error>;
9
+ };
10
+
5
11
  /**
6
12
  * Hook for fetching user reserves data from the Sodax money market.
7
13
  *
8
- * This hook provides access to the current state of user reserves in the money market protocol.
9
- * The data is automatically fetched and cached using React Query.
14
+ * @param params (optional) - Object including:
15
+ * - spokeProvider: The SpokeProvider instance required for data fetching. If not provided, data fetching is disabled.
16
+ * - address: The user's address (string) whose reserves data will be fetched. If not provided, data fetching is disabled.
17
+ * - queryOptions: (optional) Custom React Query options such as `queryKey`, `enabled`, or cache policy.
10
18
  *
11
- * @example
12
- * ```typescript
13
- * const { data: userReservesData, isLoading, error } = useUserReservesData(spokeProvider, address);
14
- * ```
19
+ * @returns {UseQueryResult<readonly [readonly UserReserveData[], number], Error>} React Query result object containing:
20
+ * - data: A tuple with array of UserReserveData and associated number, or undefined if loading
21
+ * - isLoading: Boolean loading state
22
+ * - isError: Boolean error state
23
+ * - error: Error object, if present
15
24
  *
16
- * @returns A React Query result object containing:
17
- * - data: The user reserves data when available
18
- * - isLoading: Loading state indicator
19
- * - error: Any error that occurred during data fetching
25
+ * @example
26
+ * const { data: userReservesData, isLoading, error } = useUserReservesData({
27
+ * spokeProvider,
28
+ * address,
29
+ * });
20
30
  */
21
31
  export function useUserReservesData(
22
- spokeProvider: SpokeProvider | undefined,
23
- address: string | undefined,
24
- refetchInterval = 5000,
32
+ params?: UseUserReservesDataParams,
25
33
  ): UseQueryResult<readonly [readonly UserReserveData[], number], Error> {
26
34
  const { sodax } = useSodaxContext();
35
+ const defaultQueryOptions = {
36
+ queryKey: ['mm', 'userReservesData', params?.spokeProvider?.chainConfig.chain.id, params?.address],
37
+ enabled: !!params?.spokeProvider && !!params?.address,
38
+ refetchInterval: 5000,
39
+ };
40
+ const queryOptions = {
41
+ ...defaultQueryOptions,
42
+ ...params?.queryOptions, // override default query options if provided
43
+ };
27
44
 
28
45
  return useQuery({
29
- queryKey: ['userReserves', spokeProvider?.chainConfig.chain.id, address],
46
+ ...queryOptions,
30
47
  queryFn: async () => {
31
- if (!spokeProvider) {
48
+ if (!params?.spokeProvider || !params?.address) {
32
49
  throw new Error('Spoke provider or address is not defined');
33
50
  }
34
51
 
35
- return await sodax.moneyMarket.data.getUserReservesData(spokeProvider);
52
+ return await sodax.moneyMarket.data.getUserReservesData(params.spokeProvider);
36
53
  },
37
- enabled: !!spokeProvider && !!address,
38
- refetchInterval,
39
54
  });
40
55
  }
@@ -1,66 +1,64 @@
1
- import type { SpokeProvider } from '@sodax/sdk';
2
- import type { SpokeChainId, XToken } from '@sodax/types';
1
+ import type { MoneyMarketError, MoneyMarketWithdrawParams, 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
 
5
+ export type UseWithdrawParams = {
6
+ params: MoneyMarketWithdrawParams;
7
+ spokeProvider: SpokeProvider;
8
+ };
9
+
7
10
  interface WithdrawResponse {
8
11
  ok: true;
9
12
  value: [string, string];
10
13
  }
11
14
 
12
15
  /**
13
- * Hook for withdrawing supplied tokens from the Sodax money market.
16
+ * Hook for performing withdrawals from the Sodax money market.
14
17
  *
15
- * This hook provides functionality to withdraw previously supplied tokens from the money market protocol,
16
- * handling the entire withdrawal process including transaction creation, submission,
17
- * and cross-chain communication.
18
+ * This hook exposes a mutation that executes the complete withdrawal logic, including transaction
19
+ * creation and handling cross-chain communication. It leverages React Query's mutation API for
20
+ * easy asynchronous handling and status tracking within UI components.
18
21
  *
19
- * @param {XToken} spokeToken - The token to withdraw from the spoke chain. Must be an XToken with valid address and chain information.
20
- * @param {SpokeProvider} spokeProvider - The spoke provider to use for the withdraw transaction. Must be a valid SpokeProvider instance.
22
+ * @returns {UseMutationResult<WithdrawResponse, MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>, UseWithdrawParams>}
23
+ * Mutation result object, with:
24
+ * - mutateAsync: (params: UseWithdrawParams) => Promise<WithdrawResponse>
25
+ * Initiates the withdrawal using the provided params.
26
+ * - isPending: boolean indicating if a transaction is in progress.
27
+ * - error: MoneyMarketError if an error occurred while withdrawing, otherwise undefined.
21
28
  *
22
- * @returns {UseMutationResult<WithdrawResponse, Error, string>} A mutation result object with the following properties:
23
- * - mutateAsync: Function to execute the withdraw transaction
24
- * - isPending: Boolean indicating if a transaction is in progress
25
29
  * @example
26
30
  * ```typescript
27
- * const { mutateAsync: withdraw, isPending, error } = useWithdraw(spokeToken);
28
- * await withdraw('100');
31
+ * const { mutateAsync: withdraw, isPending, error } = useWithdraw();
32
+ * await withdraw({ params: withdrawParams, spokeProvider });
29
33
  * ```
30
34
  *
31
35
  * @throws {Error} When:
32
- * - spokeProvider is not available
33
- * - Transaction execution fails
36
+ * - spokeProvider is not provided or invalid.
37
+ * - Underlying withdrawal logic fails.
34
38
  */
35
- export function useWithdraw(
36
- spokeToken: XToken,
37
- spokeProvider: SpokeProvider | undefined,
38
- ): UseMutationResult<WithdrawResponse, Error, string> {
39
+ export function useWithdraw(): UseMutationResult<
40
+ WithdrawResponse,
41
+ MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>,
42
+ UseWithdrawParams
43
+ > {
39
44
  const { sodax } = useSodaxContext();
40
45
 
41
- return useMutation<WithdrawResponse, Error, string>({
42
- mutationFn: async (amount: string, toChainId?: SpokeChainId, toAddress?: string) => {
46
+ return useMutation<
47
+ WithdrawResponse,
48
+ MoneyMarketError<'CREATE_WITHDRAW_INTENT_FAILED' | 'WITHDRAW_UNKNOWN_ERROR' | RelayErrorCode>,
49
+ UseWithdrawParams
50
+ >({
51
+ mutationFn: async ({ params, spokeProvider }) => {
43
52
  if (!spokeProvider) {
44
53
  throw new Error('spokeProvider is not found');
45
54
  }
46
55
 
47
- const response = await sodax.moneyMarket.withdraw(
48
- {
49
- token: spokeToken.address,
50
- // vault token on hub chain decimals is 18
51
- amount: parseUnits(amount, 18),
52
- action: 'withdraw',
53
- toChainId: toChainId,
54
- toAddress: toAddress,
55
- },
56
- spokeProvider,
57
- );
56
+ const response = await sodax.moneyMarket.withdraw(params, spokeProvider);
58
57
 
59
58
  if (!response.ok) {
60
- throw new Error('Failed to withdraw tokens');
59
+ throw response.error;
61
60
  }
62
61
 
63
- console.log('Withdraw transaction submitted:', response);
64
62
  return response;
65
63
  },
66
64
  });
@@ -4,3 +4,5 @@ export * from './useStatus';
4
4
  export * from './useSwapAllowance';
5
5
  export * from './useSwapApprove';
6
6
  export * from './useCancelSwap';
7
+ export * from './useCreateLimitOrder';
8
+ export * from './useCancelLimitOrder';
@@ -0,0 +1,53 @@
1
+ import { useSodaxContext } from '../shared/useSodaxContext';
2
+ import type { Intent, IntentError, IntentErrorCode, Result, SpokeProvider } from '@sodax/sdk';
3
+ import { useMutation, type UseMutationResult } from '@tanstack/react-query';
4
+
5
+ type CancelLimitOrderParams = {
6
+ intent: Intent;
7
+ spokeProvider: SpokeProvider;
8
+ timeout?: number;
9
+ };
10
+
11
+ type CancelLimitOrderResult = Result<[string, string], IntentError<IntentErrorCode>>;
12
+
13
+ /**
14
+ * Hook for canceling a limit order intent and submitting it to the Relayer API.
15
+ * Uses React Query's useMutation for better state management and caching.
16
+ *
17
+ * This hook wraps cancelLimitOrder which cancels the intent on the spoke chain,
18
+ * submits it to the relayer API, and waits for execution on the destination/hub chain.
19
+ *
20
+ * @returns {UseMutationResult} Mutation result object containing mutation function and state
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const { mutateAsync: cancelLimitOrder, isPending } = useCancelLimitOrder();
25
+ *
26
+ * const handleCancelLimitOrder = async () => {
27
+ * const result = await cancelLimitOrder({
28
+ * intent: intentObject,
29
+ * spokeProvider,
30
+ * timeout: 60000 // optional, defaults to 60 seconds
31
+ * });
32
+ *
33
+ * if (result.ok) {
34
+ * const [cancelTxHash, dstTxHash] = result.value;
35
+ * console.log('Cancel transaction hash:', cancelTxHash);
36
+ * console.log('Destination transaction hash:', dstTxHash);
37
+ * }
38
+ * };
39
+ * ```
40
+ */
41
+ export function useCancelLimitOrder(): UseMutationResult<CancelLimitOrderResult, Error, CancelLimitOrderParams> {
42
+ const { sodax } = useSodaxContext();
43
+
44
+ return useMutation<CancelLimitOrderResult, Error, CancelLimitOrderParams>({
45
+ mutationFn: async ({ intent, spokeProvider, timeout }: CancelLimitOrderParams): Promise<CancelLimitOrderResult> => {
46
+ return sodax.swaps.cancelLimitOrder({
47
+ intent,
48
+ spokeProvider,
49
+ timeout,
50
+ });
51
+ },
52
+ });
53
+ }
@@ -0,0 +1,72 @@
1
+ import { useSodaxContext } from '../shared/useSodaxContext';
2
+ import { useMutation, type UseMutationResult } from '@tanstack/react-query';
3
+ import type {
4
+ CreateLimitOrderParams,
5
+ SolverExecutionResponse,
6
+ Intent,
7
+ IntentError,
8
+ IntentErrorCode,
9
+ IntentDeliveryInfo,
10
+ Result,
11
+ SpokeProvider,
12
+ } from '@sodax/sdk';
13
+
14
+ type CreateLimitOrderResult = Result<
15
+ [SolverExecutionResponse, Intent, IntentDeliveryInfo],
16
+ IntentError<IntentErrorCode>
17
+ >;
18
+
19
+ /**
20
+ * Hook for creating a limit order intent (no deadline, must be cancelled manually by user).
21
+ * Uses React Query's useMutation for better state management and caching.
22
+ *
23
+ * Limit orders remain active until manually cancelled by the user. Unlike swaps, limit orders
24
+ * do not have a deadline (deadline is automatically set to 0n).
25
+ *
26
+ * @param {SpokeProvider} spokeProvider - The spoke provider to use for creating the limit order
27
+ * @returns {UseMutationResult} Mutation result object containing mutation function and state
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const { mutateAsync: createLimitOrder, isPending } = useCreateLimitOrder(spokeProvider);
32
+ *
33
+ * const handleCreateLimitOrder = async () => {
34
+ * const result = await createLimitOrder({
35
+ * inputToken: '0x...',
36
+ * outputToken: '0x...',
37
+ * inputAmount: 1000000000000000000n,
38
+ * minOutputAmount: 900000000000000000n,
39
+ * allowPartialFill: false,
40
+ * srcChain: '0xa4b1.arbitrum',
41
+ * dstChain: '0x89.polygon',
42
+ * srcAddress: '0x...',
43
+ * dstAddress: '0x...',
44
+ * solver: '0x0000000000000000000000000000000000000000',
45
+ * data: '0x'
46
+ * });
47
+ *
48
+ * if (result.ok) {
49
+ * const [solverExecutionResponse, intent, intentDeliveryInfo] = result.value;
50
+ * console.log('Limit order created:', intent);
51
+ * console.log('Intent hash:', solverExecutionResponse.intent_hash);
52
+ * }
53
+ * };
54
+ * ```
55
+ */
56
+ export function useCreateLimitOrder(
57
+ spokeProvider: SpokeProvider | undefined,
58
+ ): UseMutationResult<CreateLimitOrderResult, Error, CreateLimitOrderParams> {
59
+ const { sodax } = useSodaxContext();
60
+
61
+ return useMutation<CreateLimitOrderResult, Error, CreateLimitOrderParams>({
62
+ mutationFn: async (params: CreateLimitOrderParams) => {
63
+ if (!spokeProvider) {
64
+ throw new Error('Spoke provider not found');
65
+ }
66
+ return sodax.swaps.createLimitOrder({
67
+ intentParams: params,
68
+ spokeProvider,
69
+ });
70
+ },
71
+ });
72
+ }
@@ -1,14 +1,14 @@
1
1
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
2
  import { useSodaxContext } from '../shared/useSodaxContext';
3
- import type { CreateIntentParams, SpokeProvider } from '@sodax/sdk';
3
+ import type { CreateIntentParams, CreateLimitOrderParams, SpokeProvider } from '@sodax/sdk';
4
4
 
5
5
  /**
6
- * Hook for checking token allowance for money market operations.
6
+ * Hook for checking token allowance for swap operations.
7
7
  *
8
- * This hook verifies if the user has approved enough tokens for a specific money market action
9
- * (borrow/repay). It automatically queries and tracks the allowance status.
8
+ * This hook verifies if the user has approved enough tokens for a specific swap action.
9
+ * It automatically queries and tracks the allowance status.
10
10
  *
11
- * @param {CreateIntentParams} params - The parameters for the intent to check allowance for.
11
+ * @param {CreateIntentParams | CreateLimitOrderParams} params - The parameters for the intent to check allowance for.
12
12
  * @param {SpokeProvider} spokeProvider - The spoke provider to use for allowance checks
13
13
  *
14
14
  * @returns {UseQueryResult<boolean, Error>} A React Query result containing:
@@ -18,11 +18,11 @@ import type { CreateIntentParams, SpokeProvider } from '@sodax/sdk';
18
18
  *
19
19
  * @example
20
20
  * ```typescript
21
- * const { data: hasAllowed, isLoading } = useMMAllowance(params, spokeProvider);
21
+ * const { data: hasAllowed, isLoading } = useSwapAllowance(params, spokeProvider);
22
22
  * ```
23
23
  */
24
24
  export function useSwapAllowance(
25
- params: CreateIntentParams | undefined,
25
+ params: CreateIntentParams | CreateLimitOrderParams | undefined,
26
26
  spokeProvider: SpokeProvider | undefined,
27
27
  ): UseQueryResult<boolean, Error> {
28
28
  const { sodax } = useSodaxContext();
@@ -1,17 +1,17 @@
1
1
  import { useSodaxContext } from '../shared/useSodaxContext';
2
2
  import { useMutation, useQueryClient } from '@tanstack/react-query';
3
- import type { CreateIntentParams, SpokeProvider } from '@sodax/sdk';
3
+ import type { CreateIntentParams, CreateLimitOrderParams, SpokeProvider } from '@sodax/sdk';
4
4
 
5
5
  interface UseApproveReturn {
6
- approve: ({ params }: { params: CreateIntentParams }) => Promise<boolean>;
6
+ approve: ({ params }: { params: CreateIntentParams | CreateLimitOrderParams }) => Promise<boolean>;
7
7
  isLoading: boolean;
8
8
  error: Error | null;
9
9
  resetError: () => void;
10
10
  }
11
11
 
12
12
  /**
13
- * Hook for approving token spending for money market actions
14
- * @param token The token to approve spending for
13
+ * Hook for approving token spending for swap actions
14
+ * @param params The parameters for the intent to approve spending for
15
15
  * @param spokeProvider The spoke provider instance for the chain
16
16
  * @returns Object containing approve function, loading state, error state and reset function
17
17
  * @example
@@ -24,7 +24,7 @@ interface UseApproveReturn {
24
24
  */
25
25
 
26
26
  export function useSwapApprove(
27
- params: CreateIntentParams | undefined,
27
+ params: CreateIntentParams | CreateLimitOrderParams | undefined,
28
28
  spokeProvider: SpokeProvider | undefined,
29
29
  ): UseApproveReturn {
30
30
  const { sodax } = useSodaxContext();
@@ -36,7 +36,7 @@ export function useSwapApprove(
36
36
  error,
37
37
  reset: resetError,
38
38
  } = useMutation({
39
- mutationFn: async ({ params }: { params: CreateIntentParams | undefined }) => {
39
+ mutationFn: async ({ params }: { params: CreateIntentParams | CreateLimitOrderParams | undefined }) => {
40
40
  if (!spokeProvider) {
41
41
  throw new Error('Spoke provider not found');
42
42
  }