@sodax/dapp-kit 2.0.0-rc.8 → 2.0.0

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 (74) hide show
  1. package/README.md +20 -11
  2. package/dist/index.d.ts +786 -54
  3. package/dist/index.mjs +864 -150
  4. package/package.json +3 -3
  5. package/src/hooks/_mutationContract.test.ts +15 -2
  6. package/src/hooks/backend/index.ts +1 -5
  7. package/src/hooks/bitcoin/index.ts +2 -0
  8. package/src/hooks/bitcoin/resolveBtcReadAddress.test.ts +54 -0
  9. package/src/hooks/bitcoin/resolveBtcReadAddress.ts +21 -0
  10. package/src/hooks/bitcoin/useBitcoinTradingSetup.ts +45 -0
  11. package/src/hooks/bitcoin/useEnsureRadfiAccessToken.ts +57 -0
  12. package/src/hooks/bitcoin/useFundTradingWallet.ts +1 -1
  13. package/src/hooks/bitcoin/useRadfiAuth.ts +2 -2
  14. package/src/hooks/bitcoin/useRadfiWithdraw.ts +2 -2
  15. package/src/hooks/bitcoin/useRenewUtxos.ts +2 -2
  16. package/src/hooks/bitcoin/useTradingWallet.ts +1 -1
  17. package/src/hooks/index.ts +2 -0
  18. package/src/hooks/leverageYield/index.ts +9 -0
  19. package/src/hooks/leverageYield/useLeverageYieldDeposit.ts +40 -0
  20. package/src/hooks/leverageYield/useLeverageYieldEffectiveApr.ts +42 -0
  21. package/src/hooks/leverageYield/useLeverageYieldNotifySolver.ts +34 -0
  22. package/src/hooks/leverageYield/useLeverageYieldPosition.ts +40 -0
  23. package/src/hooks/leverageYield/useLeverageYieldPreviewRedeem.ts +43 -0
  24. package/src/hooks/leverageYield/useLeverageYieldShareBalances.ts +74 -0
  25. package/src/hooks/leverageYield/useLeverageYieldTotalAssets.ts +36 -0
  26. package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +50 -0
  27. package/src/hooks/leverageYield/useLeverageYieldWithdraw.ts +40 -0
  28. package/src/hooks/mm/useATokensBalances.ts +7 -1
  29. package/src/hooks/mm/useUserFormattedSummary.ts +5 -1
  30. package/src/hooks/mm/useUserReservesData.ts +5 -1
  31. package/src/hooks/partner/index.ts +4 -0
  32. package/src/hooks/partner/useFeeClaimWithdraw.ts +88 -0
  33. package/src/hooks/partner/useGetIntentDetails.ts +39 -0
  34. package/src/hooks/partner/useGetUserIntent.ts +35 -0
  35. package/src/hooks/partner/usePartnerCancelIntent.ts +52 -0
  36. package/src/hooks/shared/index.ts +4 -0
  37. package/src/hooks/shared/isUserRejectedError.test.ts +42 -0
  38. package/src/hooks/shared/isUserRejectedError.ts +30 -0
  39. package/src/hooks/shared/useGetUserHubWalletAddress.ts +5 -1
  40. package/src/hooks/shared/useNearStorageCheck.ts +45 -0
  41. package/src/hooks/shared/useNearStorageGate.ts +60 -0
  42. package/src/hooks/shared/useRegisterNearStorage.ts +46 -0
  43. package/src/hooks/shared/useRequestTrustline.ts +1 -1
  44. package/src/hooks/shared/useStellarTrustlineCheck.test.ts +74 -0
  45. package/src/hooks/shared/useStellarTrustlineCheck.ts +39 -15
  46. package/src/hooks/swapsApi/index.ts +41 -0
  47. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.test.ts +24 -0
  48. package/src/hooks/swapsApi/isTerminalSwapIntentStatus.ts +11 -0
  49. package/src/hooks/swapsApi/useSwapsApiAllowance.ts +40 -0
  50. package/src/hooks/swapsApi/useSwapsApiApprove.ts +42 -0
  51. package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +41 -0
  52. package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +41 -0
  53. package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +41 -0
  54. package/src/hooks/swapsApi/useSwapsApiDeadline.ts +36 -0
  55. package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +40 -0
  56. package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +41 -0
  57. package/src/hooks/swapsApi/useSwapsApiIntent.ts +40 -0
  58. package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +41 -0
  59. package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +40 -0
  60. package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +43 -0
  61. package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +40 -0
  62. package/src/hooks/swapsApi/useSwapsApiQuote.ts +55 -0
  63. package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +40 -0
  64. package/src/hooks/swapsApi/useSwapsApiStatus.ts +45 -0
  65. package/src/hooks/swapsApi/useSwapsApiSubmitIntent.ts +43 -0
  66. package/src/hooks/{backend/useBackendSubmitSwapTx.ts → swapsApi/useSwapsApiSubmitTx.ts} +16 -17
  67. package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +55 -0
  68. package/src/hooks/swapsApi/useSwapsApiTokens.ts +34 -0
  69. package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +40 -0
  70. package/src/providers/SodaxProvider.tsx +2 -3
  71. package/src/utils/index.ts +1 -0
  72. package/src/utils/nearStorageGate.test.ts +46 -0
  73. package/src/utils/nearStorageGate.ts +39 -0
  74. package/src/hooks/backend/useBackendSubmitSwapTxStatus.ts +0 -59
@@ -0,0 +1,60 @@
1
+ import type { GetWalletProviderType, INearWalletProvider, Result, SpokeChainKey } from '@sodax/sdk';
2
+ import { resolveNearStorageGate } from '../../utils/nearStorageGate.js';
3
+ import { useNearStorageCheck } from './useNearStorageCheck.js';
4
+ import { useRegisterNearStorage } from './useRegisterNearStorage.js';
5
+
6
+ interface UseNearStorageGateParams {
7
+ /** Destination chain the token is delivered on. */
8
+ dstChainKey: SpokeChainKey;
9
+ /** Destination token address the recipient must be registered for. */
10
+ token: string | undefined;
11
+ /** Recipient NEAR account id. */
12
+ accountId: string | undefined;
13
+ /** Destination wallet provider; only consumed when it is the NEAR provider. */
14
+ walletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
15
+ }
16
+
17
+ interface NearStorageGate {
18
+ /** Destination is NEAR. */
19
+ isNear: boolean;
20
+ /** Destination is NEAR and the recipient is not yet storage-registered for `token`. */
21
+ needsRegistration: boolean;
22
+ /** The downstream action must stay disabled while the gate is unresolved or unmet. */
23
+ blocksAction: boolean;
24
+ /** The registration-status query is actively fetching. */
25
+ isChecking: boolean;
26
+ /** A `storage_deposit` tx is in flight. */
27
+ isRegistering: boolean;
28
+ /** Submit the `storage_deposit`; resolves to the SDK `Result` or `undefined` if inputs are missing. */
29
+ registerStorage: () => Promise<Result<string> | undefined>;
30
+ }
31
+
32
+ /**
33
+ * NEP-141 storage-registration gate for flows that deliver a token to a user on NEAR.
34
+ */
35
+ export function useNearStorageGate({
36
+ dstChainKey,
37
+ token,
38
+ accountId,
39
+ walletProvider,
40
+ }: UseNearStorageGateParams): NearStorageGate {
41
+ const nearWalletProvider = walletProvider?.chainType === 'NEAR' ? (walletProvider as INearWalletProvider) : undefined;
42
+
43
+ const storageCheck = useNearStorageCheck({ params: { token, accountId, chainId: dstChainKey } });
44
+ const { mutateAsyncSafe: register, isPending: isRegistering } = useRegisterNearStorage();
45
+ const { isNear, needsRegistration, blocksAction } = resolveNearStorageGate(dstChainKey, storageCheck);
46
+
47
+ const registerStorage = async (): Promise<Result<string> | undefined> => {
48
+ if (!nearWalletProvider || !token || !accountId) return undefined;
49
+ return register({ token, accountId, walletProvider: nearWalletProvider });
50
+ };
51
+
52
+ return {
53
+ isNear,
54
+ needsRegistration,
55
+ blocksAction,
56
+ isChecking: storageCheck.isLoading,
57
+ isRegistering,
58
+ registerStorage,
59
+ };
60
+ }
@@ -0,0 +1,46 @@
1
+ import { ChainKeys, type INearWalletProvider } from '@sodax/sdk';
2
+ import { useQueryClient } from '@tanstack/react-query';
3
+ import { useSodaxContext } from './useSodaxContext.js';
4
+ import type { MutationHookParams } from './types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
6
+
7
+ export type UseRegisterNearStorageVars = {
8
+ token: string;
9
+ accountId: string;
10
+ walletProvider: INearWalletProvider;
11
+ /** Storage bond override; defaults to the SDK's `NEAR_STORAGE_DEPOSIT` (0.00125 NEAR). */
12
+ deposit?: bigint;
13
+ };
14
+
15
+ /**
16
+ * Submit a NEP-141 `storage_deposit` so `accountId` can receive `token` on NEAR. NEAR's analogue of
17
+ * requesting a Stellar trustline; pair with {@link useNearStorageCheck} and call this when the check
18
+ * resolves to `false`. The recipient's NEAR wallet signs the registration tx.
19
+ *
20
+ * Pure mutation: pass `{ token, accountId, walletProvider }` to `mutate(...)`. The hook itself only
21
+ * takes the structural `mutationOptions` slot. `registerStorage` throws natively (no `Result<T>`),
22
+ * so this hook is registered as `nativeThrow` in the mutation contract. On success it invalidates
23
+ * the matching {@link useNearStorageCheck} query.
24
+ */
25
+ export function useRegisterNearStorage({
26
+ mutationOptions,
27
+ }: MutationHookParams<string, UseRegisterNearStorageVars> = {}): SafeUseMutationResult<
28
+ string,
29
+ Error,
30
+ UseRegisterNearStorageVars
31
+ > {
32
+ const { sodax } = useSodaxContext();
33
+ const queryClient = useQueryClient();
34
+ return useSafeMutation<string, Error, UseRegisterNearStorageVars>({
35
+ mutationKey: ['shared', 'registerNearStorage'],
36
+ ...mutationOptions,
37
+ mutationFn: async ({ token, accountId, walletProvider, deposit }) =>
38
+ sodax.spoke.near.registerStorage({ token, accountId, walletProvider, deposit, raw: false }),
39
+ onSuccess: async (data, vars, ctx) => {
40
+ queryClient.invalidateQueries({
41
+ queryKey: ['shared', 'nearStorageCheck', ChainKeys.NEAR_MAINNET, vars.token, vars.accountId],
42
+ });
43
+ await mutationOptions?.onSuccess?.(data, vars, ctx);
44
+ },
45
+ });
46
+ }
@@ -53,7 +53,7 @@ export function useRequestTrustline(token: string | undefined): {
53
53
  });
54
54
  setData(result);
55
55
  setIsRequested(true);
56
- queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck', token] });
56
+ queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck', srcChainKey, token, srcAddress] });
57
57
  return result;
58
58
  } catch (err) {
59
59
  const error = err instanceof Error ? err : new Error('Unknown error occurred');
@@ -0,0 +1,74 @@
1
+ import { ChainKeys } from '@sodax/sdk';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { getStellarTrustlineCheckQueryOptions } from './useStellarTrustlineCheck.js';
4
+
5
+ const TOKEN = 'CTOKEN';
6
+ const STELLAR = ChainKeys.STELLAR_MAINNET;
7
+ const WALLET_A = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
8
+ const WALLET_B = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
9
+
10
+ const makeSodax = (result: boolean) => {
11
+ const hasSufficientTrustline = vi.fn(async () => result);
12
+ return { sodax: { spoke: { stellar: { hasSufficientTrustline } } }, hasSufficientTrustline };
13
+ };
14
+
15
+ const optionsFor = (overrides: Partial<Parameters<typeof getStellarTrustlineCheckQueryOptions>[0]> = {}) =>
16
+ getStellarTrustlineCheckQueryOptions({
17
+ sodax: makeSodax(true).sodax,
18
+ token: TOKEN,
19
+ amount: 100n,
20
+ chainId: STELLAR,
21
+ walletAddress: WALLET_A,
22
+ ...overrides,
23
+ });
24
+
25
+ describe('getStellarTrustlineCheckQueryOptions — query key', () => {
26
+ it('keys on chain, token, account, and stringified amount', () => {
27
+ expect(optionsFor().queryKey).toEqual(['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A, '100']);
28
+ });
29
+
30
+ it('produces independent keys for two accounts with the same token/amount/chain', () => {
31
+ expect(optionsFor({ walletAddress: WALLET_A }).queryKey).not.toEqual(
32
+ optionsFor({ walletAddress: WALLET_B }).queryKey,
33
+ );
34
+ });
35
+
36
+ it('produces a different key when the amount changes', () => {
37
+ expect(optionsFor({ amount: 100n }).queryKey).not.toEqual(optionsFor({ amount: 10_000n }).queryKey);
38
+ });
39
+
40
+ it('produces a different key when the chain changes', () => {
41
+ expect(optionsFor({ chainId: STELLAR }).queryKey).not.toEqual(
42
+ optionsFor({ chainId: ChainKeys.SONIC_MAINNET }).queryKey,
43
+ );
44
+ });
45
+
46
+ it('shares the useRequestTrustline invalidation prefix (chain, token, account) across every amount', () => {
47
+ // useRequestTrustline invalidates ['shared','stellarTrustlineCheck', srcChainKey, token, srcAddress];
48
+ // amount sits after that prefix, so the invalidation covers the account's checks at any amount.
49
+ const invalidationKey = ['shared', 'stellarTrustlineCheck', STELLAR, TOKEN, WALLET_A];
50
+ for (const amount of [100n, 10_000n]) {
51
+ expect(optionsFor({ amount }).queryKey.slice(0, invalidationKey.length)).toEqual(invalidationKey);
52
+ }
53
+ });
54
+ });
55
+
56
+ describe('getStellarTrustlineCheckQueryOptions — enabled + queryFn', () => {
57
+ it('is enabled only when walletAddress, token, and amount are present', () => {
58
+ expect(optionsFor({ walletAddress: WALLET_A }).enabled).toBe(true);
59
+ expect(optionsFor({ walletAddress: undefined }).enabled).toBe(false);
60
+ expect(optionsFor({ token: undefined }).enabled).toBe(false);
61
+ expect(optionsFor({ amount: undefined }).enabled).toBe(false);
62
+ });
63
+
64
+ it('checks the trustline for the given account address', async () => {
65
+ const { sodax, hasSufficientTrustline } = makeSodax(false);
66
+ const result = await optionsFor({ sodax, walletAddress: WALLET_A }).queryFn();
67
+ expect(hasSufficientTrustline).toHaveBeenCalledWith(TOKEN, 100n, WALLET_A);
68
+ expect(result).toBe(false);
69
+ });
70
+
71
+ it('returns true (no trustline needed) for a non-Stellar chain', async () => {
72
+ expect(await optionsFor({ chainId: ChainKeys.SONIC_MAINNET }).queryFn()).toBe(true);
73
+ });
74
+ });
@@ -1,4 +1,4 @@
1
- import { ChainKeys, type IStellarWalletProvider, type SpokeChainKey } from '@sodax/sdk';
1
+ import { ChainKeys, type Sodax, type SpokeChainKey } from '@sodax/sdk';
2
2
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
3
  import { useSodaxContext } from './useSodaxContext.js';
4
4
  import type { ReadHookParams } from './types.js';
@@ -9,29 +9,53 @@ export type UseStellarTrustlineCheckParams = ReadHookParams<
9
9
  token: string | undefined;
10
10
  amount: bigint | undefined;
11
11
  chainId: SpokeChainKey | undefined;
12
- walletProvider: IStellarWalletProvider | undefined;
12
+ /** Resolved Stellar account address (e.g. `useXAccount('STELLAR').address`) — keys the cache per account. */
13
+ walletAddress: string | undefined;
13
14
  }
14
15
  >;
15
16
 
17
+ // Narrow slice of the SDK this query reads — lets tests pass a minimal stub without casting `Sodax`.
18
+ type StellarTrustlineReader = { spoke: { stellar: Pick<Sodax['spoke']['stellar'], 'hasSufficientTrustline'> } };
19
+
20
+ // Pure query options, extracted for unit testing (mirrors `getXBalancesQueryOptions`).
21
+ export function getStellarTrustlineCheckQueryOptions({
22
+ sodax,
23
+ token,
24
+ amount,
25
+ chainId,
26
+ walletAddress,
27
+ }: {
28
+ sodax: StellarTrustlineReader;
29
+ token: string | undefined;
30
+ amount: bigint | undefined;
31
+ chainId: SpokeChainKey | undefined;
32
+ walletAddress: string | undefined;
33
+ }) {
34
+ return {
35
+ // Key on chain, token, account, amount so editing the amount (or switching account/chain) re-queries.
36
+ queryKey: ['shared', 'stellarTrustlineCheck', chainId, token, walletAddress, amount?.toString()] as const,
37
+ queryFn: async (): Promise<boolean> => {
38
+ if (chainId !== ChainKeys.STELLAR_MAINNET) return true;
39
+ if (!walletAddress || !token || !amount) return false;
40
+ return sodax.spoke.stellar.hasSufficientTrustline(token, amount, walletAddress);
41
+ },
42
+ enabled: !!walletAddress && !!token && !!amount,
43
+ };
44
+ }
45
+
16
46
  export function useStellarTrustlineCheck({
17
47
  params,
18
48
  queryOptions,
19
49
  }: UseStellarTrustlineCheckParams = {}): UseQueryResult<boolean, Error> {
20
50
  const { sodax } = useSodaxContext();
21
- const token = params?.token;
22
- const amount = params?.amount;
23
- const chainId = params?.chainId;
24
- const walletProvider = params?.walletProvider;
25
-
26
51
  return useQuery<boolean, Error>({
27
- queryKey: ['shared', 'stellarTrustlineCheck', token],
28
- queryFn: async () => {
29
- if (chainId !== ChainKeys.STELLAR_MAINNET) return true;
30
- if (!walletProvider || !token || !amount) return false;
31
- const walletAddress = await walletProvider.getWalletAddress();
32
- return sodax.spoke.stellar.hasSufficientTrustline(token, amount, walletAddress);
33
- },
34
- enabled: !!walletProvider && !!token && !!amount,
52
+ ...getStellarTrustlineCheckQueryOptions({
53
+ sodax,
54
+ token: params?.token,
55
+ amount: params?.amount,
56
+ chainId: params?.chainId,
57
+ walletAddress: params?.walletAddress,
58
+ }),
35
59
  ...queryOptions,
36
60
  });
37
61
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Swaps API v2 hooks — typed React Query wrappers over `sodax.api.swaps.*` (the SwapsApiService
3
+ * HTTP client). One hook per endpoint of the backend Swaps API v2.
4
+ *
5
+ * Distinct from the on-chain `swap/` hooks (`useQuote`/`useStatus`/`useSwap`/…), which drive the
6
+ * `SwapService` path (wallet → hub chain). These hooks call the backend HTTP API instead.
7
+ */
8
+
9
+ // Tokens
10
+ export * from './useSwapsApiTokens.js';
11
+ export * from './useSwapsApiTokensByChain.js';
12
+
13
+ // Quote · deadline
14
+ export * from './useSwapsApiQuote.js';
15
+ export * from './useSwapsApiDeadline.js';
16
+
17
+ // Allowance · approve · create intent
18
+ export * from './useSwapsApiAllowance.js';
19
+ export * from './useSwapsApiApprove.js';
20
+ export * from './useSwapsApiCreateIntent.js';
21
+
22
+ // Intent lifecycle: submit · status · cancel · hash · packet · extra-data · lookup
23
+ export * from './useSwapsApiSubmitIntent.js';
24
+ export * from './useSwapsApiStatus.js';
25
+ export * from './isTerminalSwapIntentStatus.js'; // terminal-status predicate (drives the status hook's polling)
26
+ export * from './useSwapsApiCancelIntent.js';
27
+ export * from './useSwapsApiIntentHash.js';
28
+ export * from './useSwapsApiIntentPacket.js';
29
+ export * from './useSwapsApiIntentExtraData.js';
30
+ export * from './useSwapsApiFilledIntent.js';
31
+ export * from './useSwapsApiIntent.js';
32
+
33
+ // Limit orders · gas · fees
34
+ export * from './useSwapsApiCreateLimitOrder.js';
35
+ export * from './useSwapsApiEstimateGas.js';
36
+ export * from './useSwapsApiPartnerFee.js';
37
+ export * from './useSwapsApiSolverFee.js';
38
+
39
+ // Submit-tx state machine
40
+ export * from './useSwapsApiSubmitTx.js';
41
+ export * from './useSwapsApiSubmitTxStatus.js';
@@ -0,0 +1,24 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { isTerminalSwapIntentStatus } from './isTerminalSwapIntentStatus.js';
3
+
4
+ /**
5
+ * Guards the polling-stop invariant for `useSwapsApiStatus.refetchInterval`: the hook keeps polling
6
+ * (1s) until the solver reports a terminal status, then stops. Tested as a pure predicate because
7
+ * dapp-kit's vitest runs in the `node` environment (no hook rendering) — see nearStorageGate.test.ts.
8
+ */
9
+ describe('isTerminalSwapIntentStatus', () => {
10
+ it('is terminal for SOLVED (3) and FAILED (4)', () => {
11
+ expect(isTerminalSwapIntentStatus(3)).toBe(true);
12
+ expect(isTerminalSwapIntentStatus(4)).toBe(true);
13
+ });
14
+
15
+ it('is non-terminal for NOT_FOUND (-1), NOT_STARTED_YET (1), and STARTED_NOT_FINISHED (2)', () => {
16
+ expect(isTerminalSwapIntentStatus(-1)).toBe(false);
17
+ expect(isTerminalSwapIntentStatus(1)).toBe(false);
18
+ expect(isTerminalSwapIntentStatus(2)).toBe(false);
19
+ });
20
+
21
+ it('is non-terminal when no status has arrived yet (undefined) — keeps polling', () => {
22
+ expect(isTerminalSwapIntentStatus(undefined)).toBe(false);
23
+ });
24
+ });
@@ -0,0 +1,11 @@
1
+ import type { SwapIntentStatusCodeV2 } from '@sodax/sdk';
2
+
3
+ /**
4
+ * Terminal solver intent states: once reached, the intent is resolved and polling stops.
5
+ * `3` = SOLVED, `4` = FAILED (per `SwapIntentStatusCodeV2`); `-1` / `1` / `2` are non-terminal.
6
+ *
7
+ * Kept in its own pure module (no React/context imports) so it is unit-testable in dapp-kit's
8
+ * `node` test environment — importing the hook itself pulls in `useSodaxContext`.
9
+ */
10
+ export const isTerminalSwapIntentStatus = (status: SwapIntentStatusCodeV2 | undefined): boolean =>
11
+ status === 3 || status === 4;
@@ -0,0 +1,40 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { AllowanceCheckResponseV2, CreateIntentParamsV2, RequestOverrideConfig } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { unwrapResult } from '../shared/unwrapResult.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseSwapsApiAllowanceParams = ReadHookParams<
8
+ AllowanceCheckResponseV2 | undefined,
9
+ {
10
+ body: CreateIntentParamsV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to check whether the source-token allowance is already sufficient for an intent via
17
+ * the swaps API — `sodax.api.swaps.checkAllowance`. Returns `{ valid }`.
18
+ *
19
+ * @example
20
+ * const { data: allowance } = useSwapsApiAllowance({ params: { body: createIntentParams } });
21
+ */
22
+ export const useSwapsApiAllowance = ({
23
+ params,
24
+ queryOptions,
25
+ }: UseSwapsApiAllowanceParams = {}): UseQueryResult<AllowanceCheckResponseV2 | undefined, Error> => {
26
+ const { sodax } = useSodaxContext();
27
+ const body = params?.body;
28
+ const apiConfig = params?.apiConfig;
29
+
30
+ return useQuery({
31
+ queryKey: ['swapsApi', 'allowance', body?.srcChainKey, body?.inputToken, body?.inputAmount, body?.srcAddress],
32
+ queryFn: async (): Promise<AllowanceCheckResponseV2 | undefined> => {
33
+ if (!body) return undefined;
34
+ return unwrapResult(await sodax.api.swaps.checkAllowance(body, apiConfig));
35
+ },
36
+ enabled: !!body,
37
+ retry: 3,
38
+ ...queryOptions,
39
+ });
40
+ };
@@ -0,0 +1,42 @@
1
+ import type { ApproveResponseV2, CreateIntentParamsV2, RequestOverrideConfig } from '@sodax/sdk';
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+
7
+ /**
8
+ * Mutation variables for {@link useSwapsApiApprove}. The per-request `apiConfig` override belongs
9
+ * here rather than at the hook level — different calls in the same component can target different
10
+ * endpoints without re-rendering.
11
+ */
12
+ export type UseSwapsApiApproveVars = {
13
+ body: CreateIntentParamsV2;
14
+ apiConfig?: RequestOverrideConfig;
15
+ };
16
+
17
+ /**
18
+ * React hook to build an unsigned token-approval transaction for the source token via the swaps
19
+ * API — `sodax.api.swaps.approve`. Returns `{ tx }` (chain-specific unsigned tx) to sign and
20
+ * broadcast yourself; it does not change state, so no queries are invalidated.
21
+ *
22
+ * @example
23
+ * const { mutateAsync: approve } = useSwapsApiApprove();
24
+ * const { tx } = await approve({ body: createIntentParams });
25
+ */
26
+ export const useSwapsApiApprove = ({
27
+ mutationOptions,
28
+ }: MutationHookParams<ApproveResponseV2, UseSwapsApiApproveVars> = {}): SafeUseMutationResult<
29
+ ApproveResponseV2,
30
+ Error,
31
+ UseSwapsApiApproveVars
32
+ > => {
33
+ const { sodax } = useSodaxContext();
34
+
35
+ return useSafeMutation<ApproveResponseV2, Error, UseSwapsApiApproveVars>({
36
+ mutationKey: ['swapsApi', 'approve'],
37
+ retry: 3,
38
+ ...mutationOptions,
39
+ mutationFn: async ({ body, apiConfig }): Promise<ApproveResponseV2> =>
40
+ unwrapResult(await sodax.api.swaps.approve(body, apiConfig)),
41
+ });
42
+ };
@@ -0,0 +1,41 @@
1
+ import type { CancelIntentRequestV2, CancelIntentResponseV2, RequestOverrideConfig } from '@sodax/sdk';
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+
7
+ /**
8
+ * Mutation variables for {@link useSwapsApiCancelIntent}. The per-request `apiConfig` override
9
+ * belongs here rather than at the hook level.
10
+ */
11
+ export type UseSwapsApiCancelIntentVars = {
12
+ body: CancelIntentRequestV2;
13
+ apiConfig?: RequestOverrideConfig;
14
+ };
15
+
16
+ /**
17
+ * React hook to build an unsigned cancel-intent transaction via the swaps API —
18
+ * `sodax.api.swaps.cancelIntent`. The `intent` carries `bigint` numerics. Returns `{ tx }` to sign
19
+ * and broadcast yourself; it does not change state, so no queries are invalidated.
20
+ *
21
+ * @example
22
+ * const { mutateAsync: cancelIntent } = useSwapsApiCancelIntent();
23
+ * const { tx } = await cancelIntent({ body: { srcChainKey: 'sonic', intent } });
24
+ */
25
+ export const useSwapsApiCancelIntent = ({
26
+ mutationOptions,
27
+ }: MutationHookParams<CancelIntentResponseV2, UseSwapsApiCancelIntentVars> = {}): SafeUseMutationResult<
28
+ CancelIntentResponseV2,
29
+ Error,
30
+ UseSwapsApiCancelIntentVars
31
+ > => {
32
+ const { sodax } = useSodaxContext();
33
+
34
+ return useSafeMutation<CancelIntentResponseV2, Error, UseSwapsApiCancelIntentVars>({
35
+ mutationKey: ['swapsApi', 'cancelIntent'],
36
+ retry: 3,
37
+ ...mutationOptions,
38
+ mutationFn: async ({ body, apiConfig }): Promise<CancelIntentResponseV2> =>
39
+ unwrapResult(await sodax.api.swaps.cancelIntent(body, apiConfig)),
40
+ });
41
+ };
@@ -0,0 +1,41 @@
1
+ import type { CreateIntentParamsV2, CreateIntentResponseV2, RequestOverrideConfig } from '@sodax/sdk';
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+
7
+ /**
8
+ * Mutation variables for {@link useSwapsApiCreateIntent}. The per-request `apiConfig` override
9
+ * belongs here rather than at the hook level.
10
+ */
11
+ export type UseSwapsApiCreateIntentVars = {
12
+ body: CreateIntentParamsV2;
13
+ apiConfig?: RequestOverrideConfig;
14
+ };
15
+
16
+ /**
17
+ * React hook to build an unsigned create-intent transaction via the swaps API —
18
+ * `sodax.api.swaps.createIntent`. Returns `{ tx, intent, relayData }` to sign and broadcast
19
+ * yourself; it does not change state, so no queries are invalidated.
20
+ *
21
+ * @example
22
+ * const { mutateAsync: createIntent } = useSwapsApiCreateIntent();
23
+ * const { tx, intent, relayData } = await createIntent({ body: createIntentParams });
24
+ */
25
+ export const useSwapsApiCreateIntent = ({
26
+ mutationOptions,
27
+ }: MutationHookParams<CreateIntentResponseV2, UseSwapsApiCreateIntentVars> = {}): SafeUseMutationResult<
28
+ CreateIntentResponseV2,
29
+ Error,
30
+ UseSwapsApiCreateIntentVars
31
+ > => {
32
+ const { sodax } = useSodaxContext();
33
+
34
+ return useSafeMutation<CreateIntentResponseV2, Error, UseSwapsApiCreateIntentVars>({
35
+ mutationKey: ['swapsApi', 'createIntent'],
36
+ retry: 3,
37
+ ...mutationOptions,
38
+ mutationFn: async ({ body, apiConfig }): Promise<CreateIntentResponseV2> =>
39
+ unwrapResult(await sodax.api.swaps.createIntent(body, apiConfig)),
40
+ });
41
+ };
@@ -0,0 +1,41 @@
1
+ import type { CreateLimitOrderParamsV2, CreateLimitOrderResponseV2, RequestOverrideConfig } from '@sodax/sdk';
2
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
3
+ import { unwrapResult } from '../shared/unwrapResult.js';
4
+ import type { MutationHookParams } from '../shared/types.js';
5
+ import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
6
+
7
+ /**
8
+ * Mutation variables for {@link useSwapsApiCreateLimitOrder}. The per-request `apiConfig` override
9
+ * belongs here rather than at the hook level.
10
+ */
11
+ export type UseSwapsApiCreateLimitOrderVars = {
12
+ body: CreateLimitOrderParamsV2;
13
+ apiConfig?: RequestOverrideConfig;
14
+ };
15
+
16
+ /**
17
+ * React hook to build an unsigned create-limit-order-intent transaction via the swaps API —
18
+ * `sodax.api.swaps.createLimitOrderIntent` (same as create-intent but `deadline` is optional).
19
+ * Returns `{ tx, intent, relayData }`; it does not change state, so no queries are invalidated.
20
+ *
21
+ * @example
22
+ * const { mutateAsync: createLimitOrder } = useSwapsApiCreateLimitOrder();
23
+ * const { tx, intent, relayData } = await createLimitOrder({ body: createLimitOrderParams });
24
+ */
25
+ export const useSwapsApiCreateLimitOrder = ({
26
+ mutationOptions,
27
+ }: MutationHookParams<CreateLimitOrderResponseV2, UseSwapsApiCreateLimitOrderVars> = {}): SafeUseMutationResult<
28
+ CreateLimitOrderResponseV2,
29
+ Error,
30
+ UseSwapsApiCreateLimitOrderVars
31
+ > => {
32
+ const { sodax } = useSodaxContext();
33
+
34
+ return useSafeMutation<CreateLimitOrderResponseV2, Error, UseSwapsApiCreateLimitOrderVars>({
35
+ mutationKey: ['swapsApi', 'createLimitOrder'],
36
+ retry: 3,
37
+ ...mutationOptions,
38
+ mutationFn: async ({ body, apiConfig }): Promise<CreateLimitOrderResponseV2> =>
39
+ unwrapResult(await sodax.api.swaps.createLimitOrderIntent(body, apiConfig)),
40
+ });
41
+ };
@@ -0,0 +1,36 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { DeadlineQueryV2, DeadlineResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { unwrapResult } from '../shared/unwrapResult.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseSwapsApiDeadlineParams = ReadHookParams<
8
+ DeadlineResponseV2,
9
+ {
10
+ query?: DeadlineQueryV2;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to compute a swap deadline (hub timestamp + `offsetSeconds`, default 300s) via the
17
+ * swaps API — `sodax.api.swaps.getDeadline`.
18
+ *
19
+ * @example
20
+ * const { data: deadline } = useSwapsApiDeadline({ params: { query: { offsetSeconds: 600 } } });
21
+ */
22
+ export const useSwapsApiDeadline = ({
23
+ params,
24
+ queryOptions,
25
+ }: UseSwapsApiDeadlineParams = {}): UseQueryResult<DeadlineResponseV2, Error> => {
26
+ const { sodax } = useSodaxContext();
27
+ const query = params?.query;
28
+ const apiConfig = params?.apiConfig;
29
+
30
+ return useQuery<DeadlineResponseV2, Error>({
31
+ queryKey: ['swapsApi', 'deadline', query?.offsetSeconds ?? null],
32
+ queryFn: async (): Promise<DeadlineResponseV2> => unwrapResult(await sodax.api.swaps.getDeadline(query, apiConfig)),
33
+ retry: 3,
34
+ ...queryOptions,
35
+ });
36
+ };
@@ -0,0 +1,40 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { GasEstimateRequestV2, GasEstimateResponseV2, RequestOverrideConfig } from '@sodax/sdk';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import { unwrapResult } from '../shared/unwrapResult.js';
5
+ import type { ReadHookParams } from '../shared/types.js';
6
+
7
+ export type UseSwapsApiEstimateGasParams = ReadHookParams<
8
+ GasEstimateResponseV2 | undefined,
9
+ {
10
+ body: GasEstimateRequestV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to estimate gas for a raw transaction on a spoke chain via the swaps API —
17
+ * `sodax.api.swaps.estimateGas`. Returns `{ gas }` (chain-specific shape).
18
+ *
19
+ * @example
20
+ * const { data } = useSwapsApiEstimateGas({ params: { body: { chainKey: 'sonic', tx } } });
21
+ */
22
+ export const useSwapsApiEstimateGas = ({
23
+ params,
24
+ queryOptions,
25
+ }: UseSwapsApiEstimateGasParams = {}): UseQueryResult<GasEstimateResponseV2 | undefined, Error> => {
26
+ const { sodax } = useSodaxContext();
27
+ const body = params?.body;
28
+ const apiConfig = params?.apiConfig;
29
+
30
+ return useQuery({
31
+ queryKey: ['swapsApi', 'estimateGas', body?.chainKey, body?.tx],
32
+ queryFn: async (): Promise<GasEstimateResponseV2 | undefined> => {
33
+ if (!body) return undefined;
34
+ return unwrapResult(await sodax.api.swaps.estimateGas(body, apiConfig));
35
+ },
36
+ enabled: !!body,
37
+ retry: 3,
38
+ ...queryOptions,
39
+ });
40
+ };