@sodax/dapp-kit 2.1.0-rc.2 → 2.1.0-rc.4

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,124 @@
1
+ import type { LeverageYieldQuoteParams, PartnerFee, Sodax } from '@sodax/sdk';
2
+ import { useQuery, type UseQueryResult } from '@tanstack/react-query';
3
+ import { useSodaxContext } from '../shared/useSodaxContext.js';
4
+ import type { ReadHookParams } from '../shared/types.js';
5
+
6
+ /**
7
+ * Derived from the SDK method rather than restated, so the public error union
8
+ * (`SolverErrorResponse | LeverageYieldLookupError`) stays exact and cannot drift.
9
+ * `undefined` is the disabled state, before a `payload` exists.
10
+ */
11
+ type LeverageYieldQuote = Awaited<ReturnType<Sodax['leverageYield']['getQuote']>> | undefined;
12
+
13
+ export type UseLeverageYieldQuoteParams = ReadHookParams<
14
+ LeverageYieldQuote,
15
+ { payload: LeverageYieldQuoteParams | undefined }
16
+ >;
17
+
18
+ type LeverageYieldQuoteReader = {
19
+ config: Pick<Sodax['config'], 'leverageYieldPartnerFee'>;
20
+ leverageYield: Pick<Sodax['leverageYield'], 'getQuote'>;
21
+ };
22
+
23
+ /** React Query hashes keys with `JSON.stringify`, which throws on a bigint fee amount. */
24
+ function feeKeyPart(fee: PartnerFee | undefined) {
25
+ if (!fee) return undefined;
26
+ return 'amount' in fee ? { ...fee, amount: fee.amount.toString() } : fee;
27
+ }
28
+
29
+ /**
30
+ * Keys on the **effective** fee, not `payload.partnerFee`: when the caller omits it, `getQuote`
31
+ * falls back to `config.leverageYieldPartnerFee`, so the configured fee is a real input to the
32
+ * result. Leaving it out lets two providers configured with different fees share one cache entry,
33
+ * and lets a reconfigured provider serve the previous fee's quote until the next poll — either way
34
+ * a `minOutputAmount` derived from that quote can be unfillable.
35
+ *
36
+ * Fields are named explicitly rather than spread. A spread would carry any future bigint field on
37
+ * `SolverIntentQuoteRequest` straight into the key, and React Query hashes keys with
38
+ * `JSON.stringify`, which throws on bigint — so a spread fails *open* into a render crash, while an
39
+ * allow-list fails *closed* into a missing key segment. Add new fields here deliberately.
40
+ *
41
+ * `String(...)` rather than `.toString()`: a payload assembled from partially-validated form state
42
+ * may not have an `amount` yet, and key derivation runs during render. Staying total lets the SDK's
43
+ * own validation surface it as a `VALIDATION_FAILED` result instead of throwing past React Query.
44
+ */
45
+ function quoteKeyPart(payload: LeverageYieldQuoteParams | undefined, effectiveFee: PartnerFee | undefined) {
46
+ if (!payload) return undefined;
47
+ return {
48
+ token_src: payload.token_src,
49
+ token_src_blockchain_id: payload.token_src_blockchain_id,
50
+ token_dst: payload.token_dst,
51
+ token_dst_blockchain_id: payload.token_dst_blockchain_id,
52
+ amount: String(payload.amount),
53
+ quote_type: payload.quote_type,
54
+ partnerFee: feeKeyPart(effectiveFee),
55
+ };
56
+ }
57
+
58
+ export function getLeverageYieldQuoteQueryOptions({
59
+ sodax,
60
+ payload,
61
+ }: {
62
+ sodax: LeverageYieldQuoteReader;
63
+ payload: LeverageYieldQuoteParams | undefined;
64
+ }) {
65
+ const effectiveFee = payload?.partnerFee ?? sodax.config.leverageYieldPartnerFee;
66
+ return {
67
+ queryKey: ['leverageYield', 'quote', quoteKeyPart(payload, effectiveFee)],
68
+ queryFn: async (): Promise<LeverageYieldQuote> => {
69
+ if (!payload) return undefined;
70
+ return sodax.leverageYield.getQuote(payload);
71
+ },
72
+ enabled: !!payload,
73
+ refetchInterval: 3000,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Quotes a leverage-yield vault deposit or withdraw. Pass the vault address as `token_dst` to
79
+ * quote a deposit, or as `token_src` to quote a withdraw; subtract your slippage tolerance from
80
+ * `quoted_amount` to size `minOutputAmount`.
81
+ *
82
+ * Use this rather than {@link useQuote}: the swap quote deducts the effective *swap* fee, while a
83
+ * vault intent charges the effective *leverage-yield* fee, so the two disagree whenever the feature
84
+ * fees differ. When overriding the fee per intent, pass the same `partnerFee` here and to whichever
85
+ * builder you use — `useLeverageYieldDeposit`, `useLeverageYieldWithdraw`, or
86
+ * `useLeverageYieldVaultSwap` — or omit it on all of them, which resolves the same configured fee on
87
+ * each side. Both directions are charged, so this applies to withdrawals as much as deposits.
88
+ *
89
+ * Returns the SDK `Result` as query data rather than unwrapping it, matching {@link useQuote}: a
90
+ * quote failure ("no path", thin liquidity) is an expected UI branch, and keeping the `Result`
91
+ * preserves the solver's `detail.code` instead of flattening it to an error message.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const { data: quote } = useLeverageYieldQuote({
96
+ * params: {
97
+ * payload: {
98
+ * token_src: inputToken,
99
+ * token_src_blockchain_id: ChainKeys.ARBITRUM_MAINNET,
100
+ * token_dst: vault.vault,
101
+ * token_dst_blockchain_id: ChainKeys.SONIC_MAINNET,
102
+ * amount: parseUnits('1', 18),
103
+ * quote_type: 'exact_input',
104
+ * },
105
+ * },
106
+ * });
107
+ * if (quote?.ok) setMinOutput((quote.value.quoted_amount * 9_950n) / 10_000n);
108
+ * ```
109
+ *
110
+ * @remarks
111
+ * - Refreshes every 3 seconds, like `useQuote` — solver prices go stale.
112
+ * - Disabled while `payload` is undefined.
113
+ */
114
+ export function useLeverageYieldQuote({
115
+ params,
116
+ queryOptions,
117
+ }: UseLeverageYieldQuoteParams = {}): UseQueryResult<LeverageYieldQuote, Error> {
118
+ const { sodax } = useSodaxContext();
119
+
120
+ return useQuery<LeverageYieldQuote, Error>({
121
+ ...getLeverageYieldQuoteQueryOptions({ sodax, payload: params?.payload }),
122
+ ...queryOptions,
123
+ });
124
+ }
@@ -0,0 +1,136 @@
1
+ import {
2
+ ChainKeys,
3
+ type PartnerFee,
4
+ type Sodax,
5
+ type SolverIntentQuoteRequest,
6
+ SolverIntentErrorCode,
7
+ } from '@sodax/sdk';
8
+ import { hashKey } from '@tanstack/react-query';
9
+ import { describe, expect, it, vi } from 'vitest';
10
+ import { getSwapQuoteQueryOptions } from './useQuote.js';
11
+
12
+ const TOKEN_SRC = '0x2170Ed0880ac9A755fd29B2688956BD959F933F8';
13
+ const TOKEN_DST = '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f';
14
+ const FEE_RECIPIENT = '0x4444444444444444444444444444444444444444' as const;
15
+
16
+ const PAYLOAD: SolverIntentQuoteRequest = {
17
+ token_src: TOKEN_SRC,
18
+ token_src_blockchain_id: ChainKeys.BSC_MAINNET,
19
+ token_dst: TOKEN_DST,
20
+ token_dst_blockchain_id: ChainKeys.ARBITRUM_MAINNET,
21
+ amount: 1_000_000n,
22
+ quote_type: 'exact_input',
23
+ };
24
+
25
+ /** The SDK's own quote Result, derived so the doubles stay honest without an unsafe cast. */
26
+ type QuoteResult = Awaited<ReturnType<Sodax['swaps']['getQuote']>>;
27
+
28
+ const QUOTE: QuoteResult = { ok: true, value: { quoted_amount: 990_000n } };
29
+
30
+ const makeSodax = (result: QuoteResult = QUOTE, partnerFee?: PartnerFee) => {
31
+ const getQuote = vi.fn(async () => result);
32
+ return { sodax: { swaps: { getQuote, partnerFee } }, getQuote };
33
+ };
34
+
35
+ describe('getSwapQuoteQueryOptions', () => {
36
+ it('keys on the swap feature and the quote action', () => {
37
+ const { sodax } = makeSodax();
38
+ const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD });
39
+ expect(queryKey[0]).toBe('swap');
40
+ expect(queryKey[1]).toBe('quote');
41
+ });
42
+
43
+ it('returns the SDK Result as data so callers can branch on `ok`', async () => {
44
+ const { sodax, getQuote } = makeSodax();
45
+ await expect(getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD }).queryFn()).resolves.toEqual(QUOTE);
46
+ expect(getQuote).toHaveBeenCalledWith(PAYLOAD);
47
+ });
48
+
49
+ it('passes a solver failure through as data rather than throwing', async () => {
50
+ const error = { detail: { code: SolverIntentErrorCode.NO_PATH_FOUND, message: 'no path' } };
51
+ const { sodax } = makeSodax({ ok: false, error });
52
+ await expect(getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD }).queryFn()).resolves.toEqual({
53
+ ok: false,
54
+ error,
55
+ });
56
+ });
57
+
58
+ it('is disabled and resolves undefined without calling the SDK when payload is undefined', async () => {
59
+ const { sodax, getQuote } = makeSodax();
60
+ const options = getSwapQuoteQueryOptions({ sodax, payload: undefined });
61
+ expect(options.enabled).toBe(false);
62
+ await expect(options.queryFn()).resolves.toBeUndefined();
63
+ expect(getQuote).not.toHaveBeenCalled();
64
+ });
65
+
66
+ it('keys the amount as a string so it survives hashing', () => {
67
+ const { sodax } = makeSodax();
68
+ const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD });
69
+ expect(hashKey(queryKey)).toContain('"amount":"1000000"');
70
+ });
71
+
72
+ // `getQuote` deducts the configured fee from `amount` before quoting, so it is an input to the
73
+ // result even though it never appears in `payload`. Two providers with different swap fees must
74
+ // not share a cache entry, and a reconfigured provider must not serve the old fee's quote.
75
+ it('keys the configured swap partner fee', () => {
76
+ const noFee = getSwapQuoteQueryOptions({ sodax: makeSodax().sodax, payload: PAYLOAD }).queryKey;
77
+ const withFee = getSwapQuoteQueryOptions({
78
+ sodax: makeSodax(QUOTE, { address: FEE_RECIPIENT, percentage: 100 }).sodax,
79
+ payload: PAYLOAD,
80
+ }).queryKey;
81
+
82
+ expect(hashKey(noFee)).not.toBe(hashKey(withFee));
83
+ });
84
+
85
+ it('keys two differently-configured providers apart for an identical payload', () => {
86
+ const a = getSwapQuoteQueryOptions({
87
+ sodax: makeSodax(QUOTE, { address: FEE_RECIPIENT, percentage: 100 }).sodax,
88
+ payload: PAYLOAD,
89
+ }).queryKey;
90
+ const b = getSwapQuoteQueryOptions({
91
+ sodax: makeSodax(QUOTE, { address: FEE_RECIPIENT, percentage: 25 }).sodax,
92
+ payload: PAYLOAD,
93
+ }).queryKey;
94
+
95
+ expect(hashKey(a)).not.toBe(hashKey(b));
96
+ });
97
+
98
+ it('keys a bigint configured fee without throwing', () => {
99
+ const { sodax } = makeSodax(QUOTE, { address: FEE_RECIPIENT, amount: 7_000n });
100
+ const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD });
101
+ expect(() => hashKey(queryKey)).not.toThrow();
102
+ expect(hashKey(queryKey)).toContain('7000');
103
+ });
104
+
105
+ // Pins the allow-list. If `SolverIntentQuoteRequest` gains a field, this fails and forces a
106
+ // decision about whether it belongs in the key — rather than a spread silently carrying a new
107
+ // bigint in and crashing `hashKey` at render time.
108
+ it('keys exactly the known request fields', () => {
109
+ const { sodax } = makeSodax();
110
+ const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: PAYLOAD });
111
+
112
+ expect(Object.keys(queryKey[2] as object).sort()).toEqual(
113
+ [
114
+ 'amount',
115
+ 'partnerFee',
116
+ 'quote_type',
117
+ 'token_dst',
118
+ 'token_dst_blockchain_id',
119
+ 'token_src',
120
+ 'token_src_blockchain_id',
121
+ ].sort(),
122
+ );
123
+ });
124
+
125
+ // Key derivation runs during render, so it must not throw on a payload assembled from
126
+ // partially-validated form state.
127
+ it('derives a hashable key even when amount is missing', () => {
128
+ const { sodax } = makeSodax();
129
+ const malformed = { ...PAYLOAD, amount: undefined } as unknown as SolverIntentQuoteRequest;
130
+
131
+ const { queryKey } = getSwapQuoteQueryOptions({ sodax, payload: malformed });
132
+
133
+ expect(() => hashKey(queryKey)).not.toThrow();
134
+ expect(hashKey(queryKey)).toContain('"amount":"undefined"');
135
+ });
136
+ });
@@ -1,17 +1,79 @@
1
- import type { SolverErrorResponse, SolverIntentQuoteRequest, SolverIntentQuoteResponse } from '@sodax/sdk';
2
- import type { Result } from '@sodax/sdk';
1
+ import type { PartnerFee, Sodax, SolverIntentQuoteRequest } from '@sodax/sdk';
3
2
  import { useSodaxContext } from '../shared/useSodaxContext.js';
4
3
  import { useQuery, type UseQueryResult } from '@tanstack/react-query';
5
4
  import type { ReadHookParams } from '../shared/types.js';
6
5
 
7
- export type UseQuoteParams = ReadHookParams<
8
- Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined,
9
- { payload: SolverIntentQuoteRequest | undefined }
10
- >;
6
+ /**
7
+ * Derived from the SDK method rather than restated, so the error union stays exact and cannot
8
+ * drift. `undefined` is the disabled state, before a `payload` exists.
9
+ */
10
+ type SwapQuote = Awaited<ReturnType<Sodax['swaps']['getQuote']>> | undefined;
11
+
12
+ export type UseQuoteParams = ReadHookParams<SwapQuote, { payload: SolverIntentQuoteRequest | undefined }>;
13
+
14
+ type SwapQuoteReader = { swaps: Pick<Sodax['swaps'], 'getQuote' | 'partnerFee'> };
15
+
16
+ /** React Query hashes keys with `JSON.stringify`, which throws on a bigint fee amount. */
17
+ function feeKeyPart(fee: PartnerFee | undefined) {
18
+ if (!fee) return undefined;
19
+ return 'amount' in fee ? { ...fee, amount: fee.amount.toString() } : fee;
20
+ }
21
+
22
+ /**
23
+ * Includes the configured partner fee: `getQuote` deducts it from `amount` before quoting, so it
24
+ * is a real input to the result even though it never appears in `payload`. Leaving it out lets two
25
+ * providers configured with different fees share one cache entry, and lets a reconfigured provider
26
+ * serve the previous fee's quote until the next poll — either way a `minOutputAmount` derived from
27
+ * that quote can be unfillable.
28
+ *
29
+ * Fields are named explicitly rather than spread. A spread would carry any future bigint field on
30
+ * `SolverIntentQuoteRequest` straight into the key, and `JSON.stringify` throws on bigint — so a
31
+ * spread fails *open* into a render crash, while an allow-list fails *closed* into a missing key
32
+ * segment. Add new fields here deliberately.
33
+ *
34
+ * `String(...)` rather than `.toString()`: a payload assembled from partially-validated form state
35
+ * may not have an `amount` yet, and key derivation runs during render. Staying total lets the SDK's
36
+ * own validation surface it instead of throwing past React Query.
37
+ */
38
+ function quoteKeyPart(payload: SolverIntentQuoteRequest | undefined, configuredFee: PartnerFee | undefined) {
39
+ if (!payload) return undefined;
40
+ return {
41
+ token_src: payload.token_src,
42
+ token_src_blockchain_id: payload.token_src_blockchain_id,
43
+ token_dst: payload.token_dst,
44
+ token_dst_blockchain_id: payload.token_dst_blockchain_id,
45
+ amount: String(payload.amount),
46
+ quote_type: payload.quote_type,
47
+ partnerFee: feeKeyPart(configuredFee),
48
+ };
49
+ }
50
+
51
+ export function getSwapQuoteQueryOptions({
52
+ sodax,
53
+ payload,
54
+ }: {
55
+ sodax: SwapQuoteReader;
56
+ payload: SolverIntentQuoteRequest | undefined;
57
+ }) {
58
+ return {
59
+ queryKey: ['swap', 'quote', quoteKeyPart(payload, sodax.swaps.partnerFee)],
60
+ queryFn: async (): Promise<SwapQuote> => {
61
+ if (!payload) {
62
+ return undefined;
63
+ }
64
+ return sodax.swaps.getQuote(payload);
65
+ },
66
+ enabled: !!payload,
67
+ refetchInterval: 3000,
68
+ };
69
+ }
11
70
 
12
71
  /**
13
72
  * Hook for fetching a quote for an intent-based swap.
14
73
  *
74
+ * For a leverage-yield vault deposit or withdraw use `useLeverageYieldQuote` instead — this hook
75
+ * deducts the effective *swap* fee, which is not what a vault intent charges.
76
+ *
15
77
  * @example
16
78
  * ```typescript
17
79
  * const { data: quote, isLoading } = useQuote({ params: { payload } });
@@ -20,24 +82,13 @@ export type UseQuoteParams = ReadHookParams<
20
82
  * @remarks
21
83
  * - The quote is automatically refreshed every 3 seconds
22
84
  * - The query is disabled when payload is undefined
85
+ * - Returns the SDK `Result` as `data`; branch on `data?.ok` rather than reading `isError`
23
86
  */
24
- export const useQuote = ({
25
- params,
26
- queryOptions,
27
- }: UseQuoteParams = {}): UseQueryResult<Result<SolverIntentQuoteResponse, SolverErrorResponse> | undefined> => {
87
+ export const useQuote = ({ params, queryOptions }: UseQuoteParams = {}): UseQueryResult<SwapQuote> => {
28
88
  const { sodax } = useSodaxContext();
29
- const payload = params?.payload;
30
89
 
31
90
  return useQuery({
32
- queryKey: ['swap', 'quote', payload && { ...payload, amount: payload.amount.toString() }],
33
- queryFn: async () => {
34
- if (!payload) {
35
- return undefined;
36
- }
37
- return sodax.swaps.getQuote(payload);
38
- },
39
- enabled: !!payload,
40
- refetchInterval: 3000,
91
+ ...getSwapQuoteQueryOptions({ sodax, payload: params?.payload }),
41
92
  ...queryOptions,
42
93
  });
43
94
  };
@@ -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
+ });