@sodax/dapp-kit 2.1.0-rc.1 → 2.1.0-rc.3

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.
@@ -0,0 +1,42 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { BridgeAllowanceCheckResponseV2, CreateBridgeIntentParamsV2, 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 UseBridgeApiAllowanceParams = ReadHookParams<
8
+ BridgeAllowanceCheckResponseV2 | undefined,
9
+ {
10
+ body: CreateBridgeIntentParamsV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to check whether the source-token allowance is already sufficient for a bridge via
17
+ * the bridge API — `sodax.api.bridge.checkAllowance`. Returns `{ valid }`.
18
+ *
19
+ * The `body` uses the wire DTO field names (`inputToken`/`inputAmount`).
20
+ *
21
+ * @example
22
+ * const { data: allowance } = useBridgeApiAllowance({ params: { body: createBridgeIntentParams } });
23
+ */
24
+ export const useBridgeApiAllowance = ({
25
+ params,
26
+ queryOptions,
27
+ }: UseBridgeApiAllowanceParams = {}): UseQueryResult<BridgeAllowanceCheckResponseV2 | undefined, Error> => {
28
+ const { sodax } = useSodaxContext();
29
+ const body = params?.body;
30
+ const apiConfig = params?.apiConfig;
31
+
32
+ return useQuery({
33
+ queryKey: ['bridgeApi', 'allowance', body?.srcChainKey, body?.inputToken, body?.inputAmount, body?.srcAddress],
34
+ queryFn: async (): Promise<BridgeAllowanceCheckResponseV2 | undefined> => {
35
+ if (!body) return undefined;
36
+ return unwrapResult(await sodax.api.bridge.checkAllowance(body, apiConfig));
37
+ },
38
+ enabled: !!body,
39
+ retry: 3,
40
+ ...queryOptions,
41
+ });
42
+ };
@@ -0,0 +1,42 @@
1
+ import type { BridgeApproveResponseV2, CreateBridgeIntentParamsV2, 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 useBridgeApiApprove}. 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 UseBridgeApiApproveVars = {
13
+ body: CreateBridgeIntentParamsV2;
14
+ apiConfig?: RequestOverrideConfig;
15
+ };
16
+
17
+ /**
18
+ * React hook to build an unsigned token-approval transaction for the source token via the bridge
19
+ * API — `sodax.api.bridge.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 } = useBridgeApiApprove();
24
+ * const { tx } = await approve({ body: createBridgeIntentParams });
25
+ */
26
+ export const useBridgeApiApprove = ({
27
+ mutationOptions,
28
+ }: MutationHookParams<BridgeApproveResponseV2, UseBridgeApiApproveVars> = {}): SafeUseMutationResult<
29
+ BridgeApproveResponseV2,
30
+ Error,
31
+ UseBridgeApiApproveVars
32
+ > => {
33
+ const { sodax } = useSodaxContext();
34
+
35
+ return useSafeMutation<BridgeApproveResponseV2, Error, UseBridgeApiApproveVars>({
36
+ mutationKey: ['bridgeApi', 'approve'],
37
+ retry: 3,
38
+ ...mutationOptions,
39
+ mutationFn: async ({ body, apiConfig }): Promise<BridgeApproveResponseV2> =>
40
+ unwrapResult(await sodax.api.bridge.approve(body, apiConfig)),
41
+ });
42
+ };
@@ -0,0 +1,45 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { BridgeableAmountResponseV2, BridgeQuoteRequestV2, 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 UseBridgeApiBridgeableAmountParams = ReadHookParams<
8
+ BridgeableAmountResponseV2 | undefined,
9
+ {
10
+ body: BridgeQuoteRequestV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to fetch the deposit capacity / withdrawal liquidity limit for a (from, to) token pair
17
+ * via the bridge API — `sodax.api.bridge.getBridgeableAmount`. Returns `{ limit }`.
18
+ *
19
+ * Computable client-side from config + vault reserves — prefer `sodax.bridge.getBridgeableAmount`
20
+ * for a no-round-trip read; this HTTP variant mirrors the `/bridge/bridgeable-amount` endpoint.
21
+ *
22
+ * The `body` uses the wire DTO field names (`srcChainKey`/`dstChainKey`/`inputToken`/`outputToken`).
23
+ *
24
+ * @example
25
+ * const { data } = useBridgeApiBridgeableAmount({ params: { body: quote } });
26
+ */
27
+ export const useBridgeApiBridgeableAmount = ({
28
+ params,
29
+ queryOptions,
30
+ }: UseBridgeApiBridgeableAmountParams = {}): UseQueryResult<BridgeableAmountResponseV2 | undefined, Error> => {
31
+ const { sodax } = useSodaxContext();
32
+ const body = params?.body;
33
+ const apiConfig = params?.apiConfig;
34
+
35
+ return useQuery({
36
+ queryKey: ['bridgeApi', 'bridgeableAmount', body?.srcChainKey, body?.dstChainKey, body?.inputToken, body?.outputToken],
37
+ queryFn: async (): Promise<BridgeableAmountResponseV2 | undefined> => {
38
+ if (!body) return undefined;
39
+ return unwrapResult(await sodax.api.bridge.getBridgeableAmount(body, apiConfig));
40
+ },
41
+ enabled: !!body,
42
+ retry: 3,
43
+ ...queryOptions,
44
+ });
45
+ };
@@ -0,0 +1,42 @@
1
+ import type { CreateBridgeIntentParamsV2, CreateBridgeIntentResponseV2, 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 useBridgeApiCreateBridgeIntent}. The per-request `apiConfig`
9
+ * override belongs here rather than at the hook level.
10
+ */
11
+ export type UseBridgeApiCreateBridgeIntentVars = {
12
+ body: CreateBridgeIntentParamsV2;
13
+ apiConfig?: RequestOverrideConfig;
14
+ };
15
+
16
+ /**
17
+ * React hook to build an unsigned spoke-deposit (create-bridge-intent) transaction via the bridge
18
+ * API — `sodax.api.bridge.createBridgeIntent`. Returns `{ tx, relayData }` (no `intent` struct —
19
+ * bridge is vault-backed) to sign and broadcast yourself; it does not change state, so no queries
20
+ * are invalidated.
21
+ *
22
+ * @example
23
+ * const { mutateAsync: createBridgeIntent } = useBridgeApiCreateBridgeIntent();
24
+ * const { tx, relayData } = await createBridgeIntent({ body: createBridgeIntentParams });
25
+ */
26
+ export const useBridgeApiCreateBridgeIntent = ({
27
+ mutationOptions,
28
+ }: MutationHookParams<CreateBridgeIntentResponseV2, UseBridgeApiCreateBridgeIntentVars> = {}): SafeUseMutationResult<
29
+ CreateBridgeIntentResponseV2,
30
+ Error,
31
+ UseBridgeApiCreateBridgeIntentVars
32
+ > => {
33
+ const { sodax } = useSodaxContext();
34
+
35
+ return useSafeMutation<CreateBridgeIntentResponseV2, Error, UseBridgeApiCreateBridgeIntentVars>({
36
+ mutationKey: ['bridgeApi', 'createBridgeIntent'],
37
+ retry: 3,
38
+ ...mutationOptions,
39
+ mutationFn: async ({ body, apiConfig }): Promise<CreateBridgeIntentResponseV2> =>
40
+ unwrapResult(await sodax.api.bridge.createBridgeIntent(body, apiConfig)),
41
+ });
42
+ };
@@ -0,0 +1,44 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { BridgeFeeRequestV2, BridgeFeeResponseV2, 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 UseBridgeApiFeeParams = ReadHookParams<
8
+ BridgeFeeResponseV2 | undefined,
9
+ {
10
+ body: BridgeFeeRequestV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to fetch the bridge partner fee for an input amount via the bridge API (uses a per-request
17
+ * `body.partnerFee` override when supplied, else the backend-configured fee) —
18
+ * `sodax.api.bridge.getFee`. Returns `{ fee }` (smallest unit, decimal string).
19
+ *
20
+ * The fee is computable client-side (config-driven, token-independent) — prefer `sodax.bridge.getFee`
21
+ * for a no-round-trip read; this HTTP variant mirrors the `/bridge/fee` endpoint for parity.
22
+ *
23
+ * @example
24
+ * const { data: fee } = useBridgeApiFee({ params: { body: { inputAmount } } });
25
+ */
26
+ export const useBridgeApiFee = ({
27
+ params,
28
+ queryOptions,
29
+ }: UseBridgeApiFeeParams = {}): UseQueryResult<BridgeFeeResponseV2 | undefined, Error> => {
30
+ const { sodax } = useSodaxContext();
31
+ const body = params?.body;
32
+ const apiConfig = params?.apiConfig;
33
+
34
+ return useQuery({
35
+ queryKey: ['bridgeApi', 'fee', body?.inputAmount, body?.partnerFee],
36
+ queryFn: async (): Promise<BridgeFeeResponseV2 | undefined> => {
37
+ if (!body) return undefined;
38
+ return unwrapResult(await sodax.api.bridge.getFee(body, apiConfig));
39
+ },
40
+ enabled: !!body,
41
+ retry: 3,
42
+ ...queryOptions,
43
+ });
44
+ };
@@ -0,0 +1,45 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { BridgeableCheckResponseV2, BridgeQuoteRequestV2, 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 UseBridgeApiIsBridgeableParams = ReadHookParams<
8
+ BridgeableCheckResponseV2 | undefined,
9
+ {
10
+ body: BridgeQuoteRequestV2 | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to check whether a (from, to) token pair is bridgeable via the bridge API —
17
+ * `sodax.api.bridge.isBridgeable`. Returns `{ bridgeable }`.
18
+ *
19
+ * Computable client-side from config + vault reserves — prefer `sodax.bridge.isBridgeable`
20
+ * for a no-round-trip read; this HTTP variant mirrors the `/bridge/bridgeable/check` endpoint.
21
+ *
22
+ * The `body` uses the wire DTO field names (`srcChainKey`/`dstChainKey`/`inputToken`/`outputToken`).
23
+ *
24
+ * @example
25
+ * const { data } = useBridgeApiIsBridgeable({ params: { body: quote } });
26
+ */
27
+ export const useBridgeApiIsBridgeable = ({
28
+ params,
29
+ queryOptions,
30
+ }: UseBridgeApiIsBridgeableParams = {}): UseQueryResult<BridgeableCheckResponseV2 | undefined, Error> => {
31
+ const { sodax } = useSodaxContext();
32
+ const body = params?.body;
33
+ const apiConfig = params?.apiConfig;
34
+
35
+ return useQuery({
36
+ queryKey: ['bridgeApi', 'bridgeable', body?.srcChainKey, body?.dstChainKey, body?.inputToken, body?.outputToken],
37
+ queryFn: async (): Promise<BridgeableCheckResponseV2 | undefined> => {
38
+ if (!body) return undefined;
39
+ return unwrapResult(await sodax.api.bridge.isBridgeable(body, apiConfig));
40
+ },
41
+ enabled: !!body,
42
+ retry: 3,
43
+ ...queryOptions,
44
+ });
45
+ };
@@ -0,0 +1,50 @@
1
+ import type { BridgeSubmitTxRequestV2, BridgeSubmitTxResponseV2, 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 useBridgeApiSubmitTx}. The per-request `apiConfig` override
9
+ * (e.g. base URL) belongs here rather than at the hook level — different submissions in the same
10
+ * component can target different endpoints without re-rendering.
11
+ */
12
+ export type UseBridgeApiSubmitTxVars = {
13
+ request: BridgeSubmitTxRequestV2;
14
+ apiConfig?: RequestOverrideConfig;
15
+ };
16
+
17
+ /**
18
+ * React hook for submitting a broadcast bridge (spoke-deposit) transaction to be processed
19
+ * (relayed server-side) via the bridge API — `sodax.api.bridge.submitTx`. Called AFTER signing +
20
+ * broadcasting the spoke-deposit tx, handing it (with the FULL `relayData { address, payload }`
21
+ * envelope) to the backend.
22
+ *
23
+ * Pure mutation: pass `{ request, apiConfig? }` to `mutate({...})`. Default `retry: 3` is applied
24
+ * at the hook level — consumers can override via `mutationOptions.retry`.
25
+ *
26
+ * @example
27
+ * const { mutateAsync: submitBridgeTx, isPending, error } = useBridgeApiSubmitTx();
28
+ *
29
+ * const result = await submitBridgeTx({
30
+ * request: { txHash: '0x123...', srcChainKey: '0xa4b1.arbitrum', walletAddress: '0xabc...', relayData: { address: '0x...', payload: '0x...' } },
31
+ * apiConfig: { baseURL: 'https://...' },
32
+ * });
33
+ */
34
+ export const useBridgeApiSubmitTx = ({
35
+ mutationOptions,
36
+ }: MutationHookParams<BridgeSubmitTxResponseV2, UseBridgeApiSubmitTxVars> = {}): SafeUseMutationResult<
37
+ BridgeSubmitTxResponseV2,
38
+ Error,
39
+ UseBridgeApiSubmitTxVars
40
+ > => {
41
+ const { sodax } = useSodaxContext();
42
+
43
+ return useSafeMutation<BridgeSubmitTxResponseV2, Error, UseBridgeApiSubmitTxVars>({
44
+ mutationKey: ['bridgeApi', 'submitTx'],
45
+ retry: 3,
46
+ ...mutationOptions,
47
+ mutationFn: async ({ request, apiConfig }): Promise<BridgeSubmitTxResponseV2> =>
48
+ unwrapResult(await sodax.api.bridge.submitTx(request, apiConfig)),
49
+ });
50
+ };
@@ -0,0 +1,60 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { BridgeSubmitTxStatusResponseV2, 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 UseBridgeApiSubmitTxStatusParams = ReadHookParams<
8
+ BridgeSubmitTxStatusResponseV2 | undefined,
9
+ {
10
+ txHash: string | undefined;
11
+ srcChainKey?: string;
12
+ apiConfig?: RequestOverrideConfig;
13
+ }
14
+ >;
15
+
16
+ /**
17
+ * React hook for polling the processing status of a submitted bridge transaction via the bridge
18
+ * API — `sodax.api.bridge.getSubmitTxStatus`. Both `txHash` and `srcChainKey` are required for the
19
+ * query to run.
20
+ *
21
+ * @example
22
+ * const { data: status } = useBridgeApiSubmitTxStatus({
23
+ * params: { txHash: '0x123...', srcChainKey: '0xa4b1.arbitrum' },
24
+ * });
25
+ *
26
+ * @remarks
27
+ * - Default refetch interval is 1 second; stops on 'executed' or 'failed' status, or when the
28
+ * backend marks the submission abandoned (`abandonedAt`) while `status` stays non-terminal —
29
+ * mirroring the SDK's backend submit-tx poll (no solver `posting_execution` state — bridge has
30
+ * no post-execution).
31
+ */
32
+ export const useBridgeApiSubmitTxStatus = ({
33
+ params,
34
+ queryOptions,
35
+ }: UseBridgeApiSubmitTxStatusParams = {}): UseQueryResult<BridgeSubmitTxStatusResponseV2 | undefined, Error> => {
36
+ const { sodax } = useSodaxContext();
37
+ const txHash = params?.txHash;
38
+ const srcChainKey = params?.srcChainKey;
39
+ const apiConfig = params?.apiConfig;
40
+
41
+ return useQuery({
42
+ queryKey: ['bridgeApi', 'submitTx', 'status', txHash, srcChainKey],
43
+ queryFn: async (): Promise<BridgeSubmitTxStatusResponseV2 | undefined> => {
44
+ // `srcChainKey` is required by the bridge API status query. The `enabled` gate below ensures
45
+ // both are present; this guard also narrows the types for the call.
46
+ if (!txHash || !srcChainKey) return undefined;
47
+ return unwrapResult(await sodax.api.bridge.getSubmitTxStatus({ txHash, srcChainKey }, apiConfig));
48
+ },
49
+ enabled: !!txHash && txHash.length > 0 && !!srcChainKey,
50
+ retry: 3,
51
+ refetchInterval: query => {
52
+ const data = query.state.data?.data;
53
+ // `abandonedAt` is terminal even when `status` is still non-terminal (e.g. 'relayed') —
54
+ // same rule as the SDK's pollBackendSubmitTx.
55
+ if (data?.status === 'executed' || data?.status === 'failed' || data?.abandonedAt) return false;
56
+ return 1000;
57
+ },
58
+ ...queryOptions,
59
+ });
60
+ };
@@ -0,0 +1,35 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { GetBridgeTokensResponseV2, 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 UseBridgeApiTokensParams = ReadHookParams<
8
+ GetBridgeTokensResponseV2,
9
+ {
10
+ apiConfig?: RequestOverrideConfig;
11
+ }
12
+ >;
13
+
14
+ /**
15
+ * React hook to fetch all supported bridge tokens grouped by SpokeChainKey via the bridge API —
16
+ * `sodax.api.bridge.getTokens`. The token list is backend-served; the bridgeable-amount quote is
17
+ * computable client-side via `useGetBridgeableAmount` (also mirrored by `useBridgeApiBridgeableAmount`).
18
+ *
19
+ * @example
20
+ * const { data: tokensByChain } = useBridgeApiTokens();
21
+ */
22
+ export const useBridgeApiTokens = ({
23
+ params,
24
+ queryOptions,
25
+ }: UseBridgeApiTokensParams = {}): UseQueryResult<GetBridgeTokensResponseV2, Error> => {
26
+ const { sodax } = useSodaxContext();
27
+ const apiConfig = params?.apiConfig;
28
+
29
+ return useQuery<GetBridgeTokensResponseV2, Error>({
30
+ queryKey: ['bridgeApi', 'tokens'],
31
+ queryFn: async (): Promise<GetBridgeTokensResponseV2> => unwrapResult(await sodax.api.bridge.getTokens(apiConfig)),
32
+ retry: 3,
33
+ ...queryOptions,
34
+ });
35
+ };
@@ -0,0 +1,40 @@
1
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { GetBridgeTokensByChainResponseV2, 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 UseBridgeApiTokensByChainParams = ReadHookParams<
8
+ GetBridgeTokensByChainResponseV2 | undefined,
9
+ {
10
+ chainKey: string | undefined;
11
+ apiConfig?: RequestOverrideConfig;
12
+ }
13
+ >;
14
+
15
+ /**
16
+ * React hook to fetch supported bridge tokens for a single SpokeChainKey via the bridge API —
17
+ * `sodax.api.bridge.getTokensByChain`. Use `useBridgeApiTokens` for every chain at once.
18
+ *
19
+ * @example
20
+ * const { data: tokens } = useBridgeApiTokensByChain({ params: { chainKey: '0xa4b1.arbitrum' } });
21
+ */
22
+ export const useBridgeApiTokensByChain = ({
23
+ params,
24
+ queryOptions,
25
+ }: UseBridgeApiTokensByChainParams = {}): UseQueryResult<GetBridgeTokensByChainResponseV2 | undefined, Error> => {
26
+ const { sodax } = useSodaxContext();
27
+ const chainKey = params?.chainKey;
28
+ const apiConfig = params?.apiConfig;
29
+
30
+ return useQuery({
31
+ queryKey: ['bridgeApi', 'tokens', chainKey],
32
+ queryFn: async (): Promise<GetBridgeTokensByChainResponseV2 | undefined> => {
33
+ if (!chainKey) return undefined;
34
+ return unwrapResult(await sodax.api.bridge.getTokensByChain(chainKey, apiConfig));
35
+ },
36
+ enabled: !!chainKey && chainKey.length > 0,
37
+ retry: 3,
38
+ ...queryOptions,
39
+ });
40
+ };
@@ -6,6 +6,7 @@ export * from './swap/index.js';
6
6
  export * from './backend/index.js';
7
7
  export * from './swapsApi/index.js';
8
8
  export * from './bridge/index.js';
9
+ export * from './bridgeApi/index.js';
9
10
  export * from './staking/index.js';
10
11
  export * from './partner/index.js';
11
12
  export * from './recovery/index.js';
@@ -17,6 +17,7 @@ export * from './useSwapsApiDeadline.js';
17
17
  // Allowance · approve · create intent
18
18
  export * from './useSwapsApiAllowance.js';
19
19
  export * from './useSwapsApiApprove.js';
20
+ export * from './useSwapsApiApproveAndBroadcast.js';
20
21
  export * from './useSwapsApiCreateIntent.js';
21
22
 
22
23
  // Intent lifecycle: submit · status · cancel · hash · packet · extra-data · lookup
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The swaps API can return two approval transactions, and the second is only a valid state
3
+ * transition once the first has been mined. That ordering is what this hook exists to own — before
4
+ * it, every integration re-implemented it and could drop the wait or the abort, which costs the user
5
+ * gas on a transaction certain to revert.
6
+ *
7
+ * Follows the package convention of testing hooks without a renderer: the React Query wrapper is
8
+ * mocked so `mutationFn` can be captured and driven directly.
9
+ */
10
+
11
+ import { ChainKeys } from '@sodax/sdk';
12
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
13
+
14
+ const approve = vi.fn();
15
+ const invalidateQueries = vi.fn();
16
+
17
+ // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
18
+ let captured: any;
19
+
20
+ vi.mock('../shared/useSodaxContext.js', () => ({
21
+ useSodaxContext: () => ({ sodax: { api: { swaps: { approve } } } }),
22
+ }));
23
+ vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
24
+ vi.mock('../shared/useSafeMutation.js', () => ({
25
+ // biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
26
+ useSafeMutation: (options: any) => {
27
+ captured = options;
28
+ return {};
29
+ },
30
+ }));
31
+
32
+ const { useSwapsApiApproveAndBroadcast } = await import('./useSwapsApiApproveAndBroadcast.js');
33
+
34
+ const RESET_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xreset' };
35
+ const APPROVE_TX = { from: '0x1', to: '0x2', value: 0n, data: '0xapprove' };
36
+ const RESET_HASH = '0xreset-hash';
37
+ const APPROVE_HASH = '0xapprove-hash';
38
+
39
+ const body = (srcChainKey: string) => ({ srcChainKey, inputToken: '0xtoken', inputAmount: '1' });
40
+
41
+ /**
42
+ * Records the interleaving of sends and waits so ordering can be asserted, not assumed.
43
+ * `onWait` either throws (the receipt never arrives) or returns the mined status.
44
+ */
45
+ function evmProvider(calls: string[], onWait?: (hash: string) => string | void) {
46
+ return {
47
+ sendTransaction: vi.fn(async (tx: { data: string }) => {
48
+ calls.push(`send:${tx.data}`);
49
+ return tx.data === '0xreset' ? RESET_HASH : APPROVE_HASH;
50
+ }),
51
+ waitForTransactionReceipt: vi.fn(async (hash: string) => {
52
+ calls.push(`wait:${hash}`);
53
+ return { status: onWait?.(hash) ?? 'success' };
54
+ }),
55
+ };
56
+ }
57
+
58
+ /** One render, then the captured `mutationFn` invoked with `vars`. */
59
+ // biome-ignore lint/suspicious/noExplicitAny: vars mirror the hook's generic mutation variables.
60
+ const run = (vars: any) => {
61
+ useSwapsApiApproveAndBroadcast();
62
+ return captured.mutationFn(vars);
63
+ };
64
+
65
+ beforeEach(() => {
66
+ vi.clearAllMocks();
67
+ });
68
+
69
+ describe('useSwapsApiApproveAndBroadcast', () => {
70
+ it('broadcasts the reset, waits for it, then approves — and reports both hashes', async () => {
71
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
72
+ const calls: string[] = [];
73
+ const walletProvider = evmProvider(calls);
74
+
75
+ const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
76
+
77
+ expect(result).toEqual({ resetTxHash: RESET_HASH, approveTxHash: APPROVE_HASH });
78
+ // The wait has to sit between the two sends; approving over an unconfirmed reset reverts.
79
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`, 'send:0xapprove', `wait:${APPROVE_HASH}`]);
80
+ });
81
+
82
+ it('never sends the approve when the reset fails to confirm', async () => {
83
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
84
+ const calls: string[] = [];
85
+ const walletProvider = evmProvider(calls, hash => {
86
+ if (hash === RESET_HASH) throw new Error('reset reverted');
87
+ });
88
+
89
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow('reset reverted');
90
+
91
+ // A retry is cheap — the allowance is untouched, so the next plan is a single transaction.
92
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
93
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`]);
94
+ });
95
+
96
+ it('never sends the approve when the reset is mined but reverts', async () => {
97
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
98
+ const calls: string[] = [];
99
+ // A paused or blacklisted token mines the reset and reverts it; the allowance never moved, so
100
+ // the approve that follows is certain to revert too and would be paid for.
101
+ const walletProvider = evmProvider(calls, hash => (hash === RESET_HASH ? 'reverted' : 'success'));
102
+
103
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow(
104
+ /allowance reset transaction .* reverted/,
105
+ );
106
+
107
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
108
+ expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`]);
109
+ });
110
+
111
+ it('reports a reverted approve, whichever spelling of the status the provider returns', async () => {
112
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
113
+ // `EvmWalletProvider` forwards viem's `'reverted'`; a provider reading the JSON-RPC receipt
114
+ // directly returns `'0x0'`. Both mean the same thing.
115
+ const walletProvider = evmProvider([], () => '0x0');
116
+
117
+ await expect(run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider })).rejects.toThrow(
118
+ /approve transaction .* reverted/,
119
+ );
120
+ });
121
+
122
+ it('sends one transaction and omits resetTxHash for an ordinary token', async () => {
123
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
124
+ const calls: string[] = [];
125
+ const walletProvider = evmProvider(calls);
126
+
127
+ const result = await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider });
128
+
129
+ expect(result).toEqual({ approveTxHash: APPROVE_HASH });
130
+ expect(walletProvider.sendTransaction).toHaveBeenCalledTimes(1);
131
+ });
132
+
133
+ it('works on the hub chain, not just EVM spokes', async () => {
134
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
135
+ const walletProvider = evmProvider([]);
136
+
137
+ const result = await run({ body: body(ChainKeys.SONIC_MAINNET), walletProvider });
138
+
139
+ expect(result).toEqual({ approveTxHash: APPROVE_HASH });
140
+ });
141
+
142
+ it('signs a Stellar trustline through signAndSendTransaction', async () => {
143
+ const trustlineTx = { unsignedTx: 'AAAA' };
144
+ approve.mockResolvedValue({ ok: true, value: { tx: trustlineTx } });
145
+ const walletProvider = {
146
+ signAndSendTransaction: vi.fn().mockResolvedValue('stellar-hash'),
147
+ waitForTransactionReceipt: vi.fn().mockResolvedValue({ successful: true }),
148
+ };
149
+
150
+ const result = await run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider });
151
+
152
+ expect(result).toEqual({ approveTxHash: 'stellar-hash' });
153
+ expect(walletProvider.signAndSendTransaction).toHaveBeenCalledWith(trustlineTx);
154
+ });
155
+
156
+ it('reports a Stellar trustline that Horizon records as unsuccessful', async () => {
157
+ approve.mockResolvedValue({ ok: true, value: { tx: { unsignedTx: 'AAAA' } } });
158
+ const walletProvider = {
159
+ signAndSendTransaction: vi.fn().mockResolvedValue('stellar-hash'),
160
+ waitForTransactionReceipt: vi.fn().mockResolvedValue({ successful: false }),
161
+ };
162
+
163
+ await expect(run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider })).rejects.toThrow(
164
+ /approve transaction .* failed on chain/,
165
+ );
166
+ });
167
+
168
+ it('names the missing capability when a Stellar wallet cannot sign', async () => {
169
+ approve.mockResolvedValue({ ok: true, value: { tx: { unsignedTx: 'AAAA' } } });
170
+
171
+ await expect(
172
+ run({ body: body(ChainKeys.STELLAR_MAINNET), walletProvider: { waitForTransactionReceipt: vi.fn() } }),
173
+ ).rejects.toThrow(/signAndSendTransaction/);
174
+ });
175
+
176
+ it('rejects a chain the swaps API cannot approve on', async () => {
177
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
178
+
179
+ await expect(run({ body: body(ChainKeys.SOLANA_MAINNET), walletProvider: {} })).rejects.toThrow(
180
+ /the hub \(Sonic\), EVM spokes, and Stellar/,
181
+ );
182
+ });
183
+
184
+ it('invalidates the allowance query once the approval has confirmed', async () => {
185
+ useSwapsApiApproveAndBroadcast();
186
+
187
+ await captured.onSuccess({ approveTxHash: APPROVE_HASH }, {}, undefined);
188
+
189
+ // The hook owns confirmation now, so unlike useSwapsApiApprove it can refresh this itself.
190
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['swapsApi', 'allowance'] });
191
+ });
192
+ });