@sodax/dapp-kit 2.3.0-rc.1 → 2.3.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.
package/README.md CHANGED
@@ -361,6 +361,10 @@ Typed wrappers over the backend Bridge API v2 — one `useBridgeApi*` hook per e
361
361
 
362
362
  See [`src/hooks/bridgeApi/`](https://github.com/gosodax/sodax-sdks/tree/main/packages/dapp-kit/src/hooks/bridgeApi) for the full set (tokens, allowance, approve, create intent, fee, bridgeable amount, bridgeable pair).
363
363
 
364
+ ### API approvals wait for the API to see them
365
+
366
+ The API reads the chain through its own RPC, which can trail the node that confirmed an approve by a few blocks. So once the approval lands, `useSwapsApiApproveAndBroadcast`, `useBridgeApiApproveAndBroadcast`, `useLeverageYieldApiApproveAndBroadcast` and the sequential path of `useSwapsApiBroadcastWithApproval` re-check the API's allowance for up to about 15 seconds before invalidating the allowance query. Without that wait, a stale `valid: false` would re-enable Approve after a successful approval. The hooks resolve after the wait either way, so read the allowance query rather than treating success as `valid`.
367
+
364
368
  ### API-key failures are terminal
365
369
 
366
370
  Every retrying `useSwapsApi*`, `useLeverageYieldApi*` and `useBridgeApi*` hook defaults `retry` to [`retryUnlessAuthFailure()`](https://github.com/gosodax/sodax-sdks/blob/main/packages/dapp-kit/src/hooks/shared/retryUnlessAuthFailure.ts): transport blips retry up to 3 times, a `401`/`403` never replays. `useSwapsApiStatus`, `useSwapsApiSubmitTxStatus`, `useLeverageYieldApiSubmitTxStatus` and `useBridgeApiSubmitTxStatus` stop their 1s poll on a rejected key too, since `retry` bounds attempts within a tick rather than the interval — so a bad key surfaces once, on `error`, instead of re-requesting forever. Override either through `queryOptions` / `mutationOptions`.
package/dist/index.d.ts CHANGED
@@ -1501,7 +1501,10 @@ type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey>
1501
1501
  * ordering the package should own rather than every integration re-deriving it.
1502
1502
  *
1503
1503
  * Because confirmation now happens inside the hook, it can invalidate `['swapsApi','allowance']`
1504
- * itself; callers of `useSwapsApiApprove` have to refetch by hand.
1504
+ * itself; callers of `useSwapsApiApprove` have to refetch by hand. It first waits up to about 15 seconds
1505
+ * for the API to report the allowance as valid, since its RPC can trail the node that confirmed the
1506
+ * approve. It resolves after that wait either way, so read the allowance rather than treating success as
1507
+ * `valid`.
1505
1508
  *
1506
1509
  * Supports the chains the swaps API can approve on — the hub (Sonic), EVM spokes, and Stellar.
1507
1510
  * Every other chain reports its allowance as always sufficient, so approval never runs for it.
@@ -2028,7 +2031,9 @@ type UseBridgeApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeChainKey
2028
2031
  *
2029
2032
  * Prefer this over {@link useBridgeApiApprove}, which hands back the unsigned `{ tx, resetTx? }` and
2030
2033
  * leaves the ordering — reset mined first, then approve — to the caller. Confirmation happens inside
2031
- * the hook, so it invalidates `['bridgeApi','allowance']` itself.
2034
+ * the hook, so it invalidates `['bridgeApi','allowance']` itself — after waiting up to about 15 seconds for
2035
+ * the API to report the allowance as valid, since its RPC can trail the node that confirmed the approve.
2036
+ * It resolves after that wait either way, so read the allowance rather than treating success as `valid`.
2032
2037
  *
2033
2038
  * Supports the chains the bridge API can approve on — the hub (Sonic), EVM spokes, and Stellar.
2034
2039
  * Every other chain reports its allowance as always sufficient, so approval never runs for it.
@@ -3767,7 +3772,9 @@ type UseLeverageYieldApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeC
3767
3772
  * deposit token of the 2017 TetherToken lineage rejects an allowance change from one non-zero value
3768
3773
  * to another, so broadcasting the approve without the reset spends the user's gas on a transaction
3769
3774
  * that is certain to revert. Confirmation happens inside the hook, so it invalidates
3770
- * `['leverageYieldApi','allowance']` itself.
3775
+ * `['leverageYieldApi','allowance']` itself — after waiting up to about 15 seconds for the API to report
3776
+ * the allowance as valid, since its RPC can trail the node that confirmed the approve. It resolves after
3777
+ * that wait either way, so read the allowance rather than treating success as `valid`.
3771
3778
  *
3772
3779
  * Supports the chains the leverage-yield API can approve on — the hub (Sonic), EVM spokes, and
3773
3780
  * Stellar. Every other chain reports its allowance as always sufficient, so approval never runs.
package/dist/index.mjs CHANGED
@@ -1902,6 +1902,34 @@ var useSwapsApiApprove = ({
1902
1902
  mutationFn: async ({ body, apiConfig }) => unwrapResult(await sodax.api.swaps.approve(body, apiConfig))
1903
1903
  });
1904
1904
  };
1905
+ var BUDGET_MS = 15e3;
1906
+ var INTERVAL_MS = 1500;
1907
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1908
+ async function settleWithin(promise, ms) {
1909
+ let timer;
1910
+ const expired = new Promise((resolve) => {
1911
+ timer = setTimeout(() => resolve(void 0), ms);
1912
+ });
1913
+ try {
1914
+ return await Promise.race([promise, expired]);
1915
+ } finally {
1916
+ clearTimeout(timer);
1917
+ }
1918
+ }
1919
+ async function waitForApiAllowance(check, apiConfig, { budgetMs = BUDGET_MS, intervalMs = INTERVAL_MS } = {}) {
1920
+ const deadline = Date.now() + budgetMs;
1921
+ for (; ; ) {
1922
+ const remaining = deadline - Date.now();
1923
+ const timeout = Math.min(apiConfig?.timeout ?? remaining, remaining);
1924
+ const result = await settleWithin(
1925
+ check({ ...apiConfig, timeout }).catch((error) => ({ ok: false, error })),
1926
+ remaining
1927
+ );
1928
+ if (!result || (result.ok ? result.value.valid : isAuthFailure(result.error))) return;
1929
+ if (deadline - Date.now() <= intervalMs) return;
1930
+ await sleep(intervalMs);
1931
+ }
1932
+ }
1905
1933
  var stepLabel = (step) => step === "allowance-reset" ? "allowance reset" : "approve";
1906
1934
  var isRevertedEvmReceiptStatus = (status) => status === "reverted" || status === "0x0";
1907
1935
  function resolveChainSender(srcChainKey, walletProvider, hookName) {
@@ -1990,13 +2018,15 @@ var useSwapsApiApproveAndBroadcast = ({
1990
2018
  ...mutationOptions,
1991
2019
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }) => {
1992
2020
  const plan = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
1993
- return runApprovalPlan({
2021
+ const hashes = await runApprovalPlan({
1994
2022
  plan,
1995
2023
  srcChainKey: body.srcChainKey,
1996
2024
  walletProvider,
1997
2025
  hookName: "useSwapsApiApproveAndBroadcast",
1998
2026
  onProgress
1999
2027
  });
2028
+ await waitForApiAllowance((config) => sodax.api.swaps.checkAllowance(body, config), apiConfig);
2029
+ return hashes;
2000
2030
  },
2001
2031
  onSuccess: async (data, vars, ctx) => {
2002
2032
  await queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
@@ -2067,6 +2097,7 @@ var useSwapsApiBroadcastWithApproval = ({
2067
2097
  );
2068
2098
  }
2069
2099
  const approval = await runApprovalPlan({ plan, srcChainKey, walletProvider, hookName: HOOK_NAME, onProgress });
2100
+ await waitForApiAllowance((config) => sodax.api.swaps.checkAllowance(body, config), apiConfig);
2070
2101
  await queryClient.invalidateQueries({ queryKey: ["swapsApi", "allowance"] });
2071
2102
  const txHash = await walletProvider.sendTransaction(intentTx, {
2072
2103
  expectedChainId: getEvmViemChain(srcChainKey).id
@@ -2580,13 +2611,15 @@ var useBridgeApiApproveAndBroadcast = ({
2580
2611
  ...mutationOptions,
2581
2612
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }) => {
2582
2613
  const plan = unwrapResult(await sodax.api.bridge.approve(body, apiConfig));
2583
- return runApprovalPlan({
2614
+ const hashes = await runApprovalPlan({
2584
2615
  plan,
2585
2616
  srcChainKey: body.srcChainKey,
2586
2617
  walletProvider,
2587
2618
  hookName: "useBridgeApiApproveAndBroadcast",
2588
2619
  onProgress
2589
2620
  });
2621
+ await waitForApiAllowance((config) => sodax.api.bridge.checkAllowance(body, config), apiConfig);
2622
+ return hashes;
2590
2623
  },
2591
2624
  onSuccess: async (data, vars, ctx) => {
2592
2625
  await queryClient.invalidateQueries({ queryKey: ["bridgeApi", "allowance"] });
@@ -4871,13 +4904,15 @@ var useLeverageYieldApiApproveAndBroadcast = ({
4871
4904
  ...mutationOptions,
4872
4905
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }) => {
4873
4906
  const plan = unwrapResult(await sodax.api.leverageYield.approve(body, apiConfig));
4874
- return runApprovalPlan({
4907
+ const hashes = await runApprovalPlan({
4875
4908
  plan,
4876
4909
  srcChainKey: body.srcChainKey,
4877
4910
  walletProvider,
4878
4911
  hookName: "useLeverageYieldApiApproveAndBroadcast",
4879
4912
  onProgress
4880
4913
  });
4914
+ await waitForApiAllowance((config) => sodax.api.leverageYield.checkAllowance(body, config), apiConfig);
4915
+ return hashes;
4881
4916
  },
4882
4917
  onSuccess: async (data, vars, ctx) => {
4883
4918
  await queryClient.invalidateQueries({ queryKey: ["leverageYieldApi", "allowance"] });
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "access": "public"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "2.3.0-rc.1",
8
+ "version": "2.3.0-rc.3",
9
9
  "description": "React hooks for building dApps on the SODAX cross-chain DeFi platform",
10
10
  "keywords": [
11
11
  "sodax",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "viem": "2.29.2",
37
- "@sodax/sdk": "2.3.0-rc.1"
37
+ "@sodax/sdk": "2.3.0-rc.3"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@arethetypeswrong/cli": "0.17.4",
@@ -8,16 +8,17 @@
8
8
 
9
9
  import { ChainKeys } from '@sodax/sdk';
10
10
  import type { ApprovalProgress } from '../../utils/approvalPlan.js';
11
- import { beforeEach, describe, expect, it, vi } from 'vitest';
11
+ import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
12
12
 
13
13
  const approve = vi.fn();
14
+ const checkAllowance = vi.fn();
14
15
  const invalidateQueries = vi.fn();
15
16
 
16
17
  // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
17
18
  let captured: any;
18
19
 
19
20
  vi.mock('../shared/useSodaxContext.js', () => ({
20
- useSodaxContext: () => ({ sodax: { api: { bridge: { approve } } } }),
21
+ useSodaxContext: () => ({ sodax: { api: { bridge: { approve, checkAllowance } } } }),
21
22
  }));
22
23
  vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
23
24
  vi.mock('../shared/useSafeMutation.js', () => ({
@@ -70,6 +71,7 @@ const run = (vars: any) => {
70
71
 
71
72
  beforeEach(() => {
72
73
  vi.clearAllMocks();
74
+ checkAllowance.mockResolvedValue({ ok: true, value: { valid: true } });
73
75
  });
74
76
 
75
77
  describe('useBridgeApiApproveAndBroadcast', () => {
@@ -164,6 +166,34 @@ describe('useBridgeApiApproveAndBroadcast', () => {
164
166
  );
165
167
  });
166
168
 
169
+ it('resolves only once the API sees the allowance — its RPC can trail the confirming node', async () => {
170
+ vi.useFakeTimers();
171
+ onTestFinished(() => {
172
+ vi.useRealTimers();
173
+ });
174
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
175
+ const calls: string[] = [];
176
+ let synced = false;
177
+ checkAllowance.mockImplementation(async () => {
178
+ calls.push('check');
179
+ const response = { ok: true, value: { valid: synced } };
180
+ synced = true;
181
+ return response;
182
+ });
183
+ const vars = {
184
+ body: body(ChainKeys.ARBITRUM_MAINNET),
185
+ walletProvider: evmProvider(calls),
186
+ apiConfig: { baseURL: 'https://api.example' },
187
+ };
188
+
189
+ const pending = run(vars);
190
+ await vi.advanceTimersByTimeAsync(1_500);
191
+
192
+ await expect(pending).resolves.toEqual({ approveTxHash: APPROVE_HASH });
193
+ expect(calls).toEqual(['send:0xapprove', `wait:${APPROVE_HASH}`, 'check', 'check']);
194
+ expect(checkAllowance).toHaveBeenCalledWith(vars.body, { ...vars.apiConfig, timeout: 15_000 });
195
+ });
196
+
167
197
  it('invalidates the bridge allowance query once the approval has confirmed', async () => {
168
198
  useBridgeApiApproveAndBroadcast();
169
199
 
@@ -8,6 +8,7 @@ import type {
8
8
  import { useQueryClient } from '@tanstack/react-query';
9
9
  import { useSodaxContext } from '../shared/useSodaxContext.js';
10
10
  import { unwrapResult } from '../shared/unwrapResult.js';
11
+ import { waitForApiAllowance } from '../shared/waitForApiAllowance.js';
11
12
  import type { MutationHookParams } from '../shared/types.js';
12
13
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
14
  import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
@@ -28,7 +29,9 @@ export type UseBridgeApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeC
28
29
  *
29
30
  * Prefer this over {@link useBridgeApiApprove}, which hands back the unsigned `{ tx, resetTx? }` and
30
31
  * leaves the ordering — reset mined first, then approve — to the caller. Confirmation happens inside
31
- * the hook, so it invalidates `['bridgeApi','allowance']` itself.
32
+ * the hook, so it invalidates `['bridgeApi','allowance']` itself — after waiting up to about 15 seconds for
33
+ * the API to report the allowance as valid, since its RPC can trail the node that confirmed the approve.
34
+ * It resolves after that wait either way, so read the allowance rather than treating success as `valid`.
32
35
  *
33
36
  * Supports the chains the bridge API can approve on — the hub (Sonic), EVM spokes, and Stellar.
34
37
  * Every other chain reports its allowance as always sufficient, so approval never runs for it.
@@ -58,13 +61,15 @@ export const useBridgeApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeC
58
61
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }): Promise<BridgeApiApprovalHashes> => {
59
62
  const plan: BridgeApproveResponseV2 = unwrapResult(await sodax.api.bridge.approve(body, apiConfig));
60
63
 
61
- return runApprovalPlan({
64
+ const hashes = await runApprovalPlan({
62
65
  plan,
63
66
  srcChainKey: body.srcChainKey as SpokeChainKey,
64
67
  walletProvider,
65
68
  hookName: 'useBridgeApiApproveAndBroadcast',
66
69
  onProgress,
67
70
  });
71
+ await waitForApiAllowance(config => sodax.api.bridge.checkAllowance(body, config), apiConfig);
72
+ return hashes;
68
73
  },
69
74
  onSuccess: async (data, vars, ctx) => {
70
75
  // Awaited: the mutation must not resolve — re-enabling Approve — before the allowance query
@@ -15,13 +15,14 @@ import type { ApprovalProgress } from '../../utils/approvalPlan.js';
15
15
  import { beforeEach, describe, expect, it, vi } from 'vitest';
16
16
 
17
17
  const approve = vi.fn();
18
+ const checkAllowance = vi.fn();
18
19
  const invalidateQueries = vi.fn();
19
20
 
20
21
  // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
21
22
  let captured: any;
22
23
 
23
24
  vi.mock('../shared/useSodaxContext.js', () => ({
24
- useSodaxContext: () => ({ sodax: { api: { leverageYield: { approve } } } }),
25
+ useSodaxContext: () => ({ sodax: { api: { leverageYield: { approve, checkAllowance } } } }),
25
26
  }));
26
27
  vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
27
28
  vi.mock('../shared/useSafeMutation.js', () => ({
@@ -73,6 +74,7 @@ const run = (vars: any) => {
73
74
 
74
75
  beforeEach(() => {
75
76
  vi.clearAllMocks();
77
+ checkAllowance.mockResolvedValue({ ok: true, value: { valid: true } });
76
78
  });
77
79
 
78
80
  describe('useLeverageYieldApiApproveAndBroadcast', () => {
@@ -85,6 +87,24 @@ describe('useLeverageYieldApiApproveAndBroadcast', () => {
85
87
  expect(approve).toHaveBeenCalledWith(body(ChainKeys.ARBITRUM_MAINNET), apiConfig);
86
88
  });
87
89
 
90
+ it('re-checks the allowance through the same API once the approve confirms', async () => {
91
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
92
+ const calls: string[] = [];
93
+ checkAllowance.mockImplementation(async () => {
94
+ calls.push('check');
95
+ return { ok: true, value: { valid: true } };
96
+ });
97
+ const apiConfig = { baseURL: 'https://canary-api.example/v1' };
98
+
99
+ await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider: evmProvider(calls), apiConfig });
100
+
101
+ expect(calls).toEqual(['send:0xapprove', `wait:${APPROVE_HASH}`, 'check']);
102
+ expect(checkAllowance).toHaveBeenCalledWith(body(ChainKeys.ARBITRUM_MAINNET), {
103
+ ...apiConfig,
104
+ timeout: expect.any(Number),
105
+ });
106
+ });
107
+
88
108
  it('broadcasts the reset, waits for it, then approves — and reports both hashes', async () => {
89
109
  approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
90
110
  const calls: string[] = [];
@@ -8,6 +8,7 @@ import type {
8
8
  import { useQueryClient } from '@tanstack/react-query';
9
9
  import { useSodaxContext } from '../shared/useSodaxContext.js';
10
10
  import { unwrapResult } from '../shared/unwrapResult.js';
11
+ import { waitForApiAllowance } from '../shared/waitForApiAllowance.js';
11
12
  import type { MutationHookParams } from '../shared/types.js';
12
13
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
14
  import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
@@ -32,7 +33,9 @@ export type UseLeverageYieldApiApproveAndBroadcastVars<K extends SpokeChainKey =
32
33
  * deposit token of the 2017 TetherToken lineage rejects an allowance change from one non-zero value
33
34
  * to another, so broadcasting the approve without the reset spends the user's gas on a transaction
34
35
  * that is certain to revert. Confirmation happens inside the hook, so it invalidates
35
- * `['leverageYieldApi','allowance']` itself.
36
+ * `['leverageYieldApi','allowance']` itself — after waiting up to about 15 seconds for the API to report
37
+ * the allowance as valid, since its RPC can trail the node that confirmed the approve. It resolves after
38
+ * that wait either way, so read the allowance rather than treating success as `valid`.
36
39
  *
37
40
  * Supports the chains the leverage-yield API can approve on — the hub (Sonic), EVM spokes, and
38
41
  * Stellar. Every other chain reports its allowance as always sufficient, so approval never runs.
@@ -65,13 +68,15 @@ export const useLeverageYieldApiApproveAndBroadcast = <K extends SpokeChainKey =
65
68
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }): Promise<LeverageYieldApiApprovalHashes> => {
66
69
  const plan: ApproveResponseV2 = unwrapResult(await sodax.api.leverageYield.approve(body, apiConfig));
67
70
 
68
- return runApprovalPlan({
71
+ const hashes = await runApprovalPlan({
69
72
  plan,
70
73
  srcChainKey: body.srcChainKey as SpokeChainKey,
71
74
  walletProvider,
72
75
  hookName: 'useLeverageYieldApiApproveAndBroadcast',
73
76
  onProgress,
74
77
  });
78
+ await waitForApiAllowance(config => sodax.api.leverageYield.checkAllowance(body, config), apiConfig);
79
+ return hashes;
75
80
  },
76
81
  onSuccess: async (data, vars, ctx) => {
77
82
  // Awaited: the mutation must not resolve — re-enabling Approve — before the allowance query
@@ -0,0 +1,128 @@
1
+ import { type RequestOverrideConfig, SodaxError } from '@sodax/sdk';
2
+ import { describe, expect, it, onTestFinished, vi } from 'vitest';
3
+ import { waitForApiAllowance } from './waitForApiAllowance.js';
4
+
5
+ const valid = (value: boolean) => ({ ok: true as const, value: { valid: value } });
6
+
7
+ /** A backend failure as the API services surface it: `EXTERNAL_API_ERROR` with the status on context. */
8
+ const apiError = (status: number): SodaxError =>
9
+ new SodaxError('EXTERNAL_API_ERROR', `responded with ${status}`, {
10
+ feature: 'backend',
11
+ context: { api: 'bridge', endpoint: '/bridge/allowance/check', status },
12
+ });
13
+
14
+ const useFakeTimers = (): void => {
15
+ vi.useFakeTimers();
16
+ onTestFinished(() => {
17
+ vi.useRealTimers();
18
+ });
19
+ };
20
+
21
+ describe('waitForApiAllowance', () => {
22
+ it('checks once when the API already sees the allowance', async () => {
23
+ const check = vi.fn(async () => valid(true));
24
+
25
+ await waitForApiAllowance(check, undefined, { intervalMs: 0 });
26
+
27
+ expect(check).toHaveBeenCalledOnce();
28
+ });
29
+
30
+ it('re-checks a stale `valid: false` until the API catches up', async () => {
31
+ const check = vi
32
+ .fn()
33
+ .mockResolvedValueOnce(valid(false))
34
+ .mockResolvedValueOnce(valid(false))
35
+ .mockResolvedValue(valid(true));
36
+
37
+ await waitForApiAllowance(check, undefined, { intervalMs: 0 });
38
+
39
+ expect(check).toHaveBeenCalledTimes(3);
40
+ });
41
+
42
+ it('gives up once the 15-second budget is spent', async () => {
43
+ useFakeTimers();
44
+ const check = vi.fn(async () => valid(false));
45
+
46
+ const pending = waitForApiAllowance(check);
47
+ await vi.advanceTimersByTimeAsync(15_000);
48
+
49
+ await expect(pending).resolves.toBeUndefined();
50
+ // Checks at 0, 1.5s, …, 13.5s; one more pause would leave no time for a check.
51
+ expect(check).toHaveBeenCalledTimes(10);
52
+ });
53
+
54
+ it('stops at the budget when a check hangs past it', async () => {
55
+ useFakeTimers();
56
+ const check = vi.fn(
57
+ (_config: RequestOverrideConfig) =>
58
+ new Promise<ReturnType<typeof valid>>(resolve => setTimeout(() => resolve(valid(true)), 30_000)),
59
+ );
60
+ let settled = false;
61
+
62
+ const pending = waitForApiAllowance(check, { baseURL: 'https://api.example' }).then(() => {
63
+ settled = true;
64
+ });
65
+ await vi.advanceTimersByTimeAsync(14_999);
66
+ expect(settled).toBe(false);
67
+
68
+ await vi.advanceTimersByTimeAsync(1);
69
+ await pending;
70
+ expect(settled).toBe(true);
71
+ expect(check).toHaveBeenCalledOnce();
72
+ expect(check).toHaveBeenCalledWith({ baseURL: 'https://api.example', timeout: 15_000 });
73
+ });
74
+
75
+ it('caps each request timeout to the time left, keeping a shorter one from the caller', async () => {
76
+ useFakeTimers();
77
+ const check = vi.fn(async (_config: RequestOverrideConfig) => valid(false));
78
+
79
+ const pending = waitForApiAllowance(check, { baseURL: 'https://api.example', timeout: 14_000 });
80
+ await vi.advanceTimersByTimeAsync(15_000);
81
+ await pending;
82
+
83
+ const timeouts = check.mock.calls.map(([config]) => config.timeout);
84
+ expect(timeouts.slice(0, 3)).toEqual([14_000, 13_500, 12_000]);
85
+ expect(timeouts.at(-1)).toBe(1_500);
86
+ expect(check).toHaveBeenCalledWith({ baseURL: 'https://api.example', timeout: 14_000 });
87
+ });
88
+
89
+ it('stops at an auth failure, which no retry fixes', async () => {
90
+ const check = vi.fn(async () => ({ ok: false as const, error: apiError(401) }));
91
+
92
+ await waitForApiAllowance(check, undefined, { intervalMs: 0 });
93
+
94
+ expect(check).toHaveBeenCalledOnce();
95
+ });
96
+
97
+ it('retries a transient failure, which would otherwise bring the stale-allowance race back', async () => {
98
+ const check = vi
99
+ .fn()
100
+ .mockResolvedValueOnce({ ok: false, error: apiError(503) })
101
+ .mockResolvedValue(valid(true));
102
+
103
+ await waitForApiAllowance(check, undefined, { intervalMs: 0 });
104
+
105
+ expect(check).toHaveBeenCalledTimes(2);
106
+ });
107
+
108
+ it('never throws: a check that rejects is retried, since the approval has already landed', async () => {
109
+ const check = vi.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValue(valid(true));
110
+
111
+ await expect(waitForApiAllowance(check, undefined, { intervalMs: 0 })).resolves.toBeUndefined();
112
+
113
+ expect(check).toHaveBeenCalledTimes(2);
114
+ });
115
+
116
+ it('waits the interval between checks', async () => {
117
+ useFakeTimers();
118
+ const check = vi.fn().mockResolvedValueOnce(valid(false)).mockResolvedValue(valid(true));
119
+
120
+ const pending = waitForApiAllowance(check, undefined, { intervalMs: 1_000 });
121
+ await vi.advanceTimersByTimeAsync(999);
122
+ expect(check).toHaveBeenCalledOnce();
123
+
124
+ await vi.advanceTimersByTimeAsync(1);
125
+ await pending;
126
+ expect(check).toHaveBeenCalledTimes(2);
127
+ });
128
+ });
@@ -0,0 +1,47 @@
1
+ import { isAuthFailure, type RequestOverrideConfig, type Result } from '@sodax/sdk';
2
+
3
+ const BUDGET_MS = 15_000;
4
+ const INTERVAL_MS = 1_500;
5
+
6
+ const sleep = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
7
+
8
+ /** Settles like `promise`, or with `undefined` once `ms` pass first. */
9
+ async function settleWithin<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
10
+ let timer: ReturnType<typeof setTimeout> | undefined;
11
+ const expired = new Promise<undefined>(resolve => {
12
+ timer = setTimeout(() => resolve(undefined), ms);
13
+ });
14
+ try {
15
+ return await Promise.race([promise, expired]);
16
+ } finally {
17
+ clearTimeout(timer);
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Re-checks an API allowance until it reports `valid`, for at most 15 seconds in total. The API reads the chain
23
+ * through its own RPC, which can trail the node that confirmed the approve by a few blocks; resolving on that
24
+ * stale `valid: false` leaves Approve enabled after a successful approval. A failed check is retried like a
25
+ * stale one, except an auth failure, which no retry fixes. Each check gets `apiConfig` with its request timeout
26
+ * capped to the time left and is abandoned when that runs out, so a hanging API cannot stretch the wait. Never
27
+ * throws: the approval has already landed, and the caller's allowance refetch shows whatever the API reports last.
28
+ */
29
+ export async function waitForApiAllowance(
30
+ check: (config: RequestOverrideConfig) => Promise<Result<{ valid: boolean }>>,
31
+ apiConfig?: RequestOverrideConfig,
32
+ { budgetMs = BUDGET_MS, intervalMs = INTERVAL_MS }: { budgetMs?: number; intervalMs?: number } = {},
33
+ ): Promise<void> {
34
+ const deadline = Date.now() + budgetMs;
35
+ for (;;) {
36
+ const remaining = deadline - Date.now();
37
+ const timeout = Math.min(apiConfig?.timeout ?? remaining, remaining);
38
+ const result = await settleWithin(
39
+ check({ ...apiConfig, timeout }).catch((error: unknown) => ({ ok: false as const, error })),
40
+ remaining,
41
+ );
42
+ if (!result || (result.ok ? result.value.valid : isAuthFailure(result.error))) return;
43
+ // Skip a pause that would leave no time for another check.
44
+ if (deadline - Date.now() <= intervalMs) return;
45
+ await sleep(intervalMs);
46
+ }
47
+ }
@@ -13,13 +13,14 @@ import type { ApprovalProgress } from '../../utils/approvalPlan.js';
13
13
  import { beforeEach, describe, expect, it, vi } from 'vitest';
14
14
 
15
15
  const approve = vi.fn();
16
+ const checkAllowance = vi.fn();
16
17
  const invalidateQueries = vi.fn();
17
18
 
18
19
  // biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
19
20
  let captured: any;
20
21
 
21
22
  vi.mock('../shared/useSodaxContext.js', () => ({
22
- useSodaxContext: () => ({ sodax: { api: { swaps: { approve } } } }),
23
+ useSodaxContext: () => ({ sodax: { api: { swaps: { approve, checkAllowance } } } }),
23
24
  }));
24
25
  vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
25
26
  vi.mock('../shared/useSafeMutation.js', () => ({
@@ -65,6 +66,7 @@ const run = (vars: any) => {
65
66
 
66
67
  beforeEach(() => {
67
68
  vi.clearAllMocks();
69
+ checkAllowance.mockResolvedValue({ ok: true, value: { valid: true } });
68
70
  });
69
71
 
70
72
  describe('useSwapsApiApproveAndBroadcast', () => {
@@ -80,6 +82,24 @@ describe('useSwapsApiApproveAndBroadcast', () => {
80
82
  expect(calls).toEqual(['send:0xreset', `wait:${RESET_HASH}`, 'send:0xapprove', `wait:${APPROVE_HASH}`]);
81
83
  });
82
84
 
85
+ it('re-checks the allowance through the same API once the approve confirms', async () => {
86
+ approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
87
+ const calls: string[] = [];
88
+ checkAllowance.mockImplementation(async () => {
89
+ calls.push('check');
90
+ return { ok: true, value: { valid: true } };
91
+ });
92
+ const apiConfig = { baseURL: 'https://api.example' };
93
+
94
+ await run({ body: body(ChainKeys.ARBITRUM_MAINNET), walletProvider: evmProvider(calls), apiConfig });
95
+
96
+ expect(calls).toEqual(['send:0xapprove', `wait:${APPROVE_HASH}`, 'check']);
97
+ expect(checkAllowance).toHaveBeenCalledWith(body(ChainKeys.ARBITRUM_MAINNET), {
98
+ ...apiConfig,
99
+ timeout: expect.any(Number),
100
+ });
101
+ });
102
+
83
103
  it('never sends the approve when the reset fails to confirm', async () => {
84
104
  approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX, resetTx: RESET_TX } });
85
105
  const calls: string[] = [];
@@ -8,6 +8,7 @@ import type {
8
8
  import { useQueryClient } from '@tanstack/react-query';
9
9
  import { useSodaxContext } from '../shared/useSodaxContext.js';
10
10
  import { unwrapResult } from '../shared/unwrapResult.js';
11
+ import { waitForApiAllowance } from '../shared/waitForApiAllowance.js';
11
12
  import type { MutationHookParams } from '../shared/types.js';
12
13
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
13
14
  import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
@@ -35,7 +36,10 @@ export type UseSwapsApiApproveAndBroadcastVars<K extends SpokeChainKey = SpokeCh
35
36
  * ordering the package should own rather than every integration re-deriving it.
36
37
  *
37
38
  * Because confirmation now happens inside the hook, it can invalidate `['swapsApi','allowance']`
38
- * itself; callers of `useSwapsApiApprove` have to refetch by hand.
39
+ * itself; callers of `useSwapsApiApprove` have to refetch by hand. It first waits up to about 15 seconds
40
+ * for the API to report the allowance as valid, since its RPC can trail the node that confirmed the
41
+ * approve. It resolves after that wait either way, so read the allowance rather than treating success as
42
+ * `valid`.
39
43
  *
40
44
  * Supports the chains the swaps API can approve on — the hub (Sonic), EVM spokes, and Stellar.
41
45
  * Every other chain reports its allowance as always sufficient, so approval never runs for it.
@@ -62,13 +66,15 @@ export const useSwapsApiApproveAndBroadcast = <K extends SpokeChainKey = SpokeCh
62
66
  mutationFn: async ({ body, walletProvider, apiConfig, onProgress }): Promise<SwapsApiApprovalHashes> => {
63
67
  const plan: ApproveResponseV2 = unwrapResult(await sodax.api.swaps.approve(body, apiConfig));
64
68
 
65
- return runApprovalPlan({
69
+ const hashes = await runApprovalPlan({
66
70
  plan,
67
71
  srcChainKey: body.srcChainKey as SpokeChainKey,
68
72
  walletProvider,
69
73
  hookName: 'useSwapsApiApproveAndBroadcast',
70
74
  onProgress,
71
75
  });
76
+ await waitForApiAllowance(config => sodax.api.swaps.checkAllowance(body, config), apiConfig);
77
+ return hashes;
72
78
  },
73
79
  onSuccess: async (data, vars, ctx) => {
74
80
  // Awaited: the mutation must not resolve — re-enabling Approve — before the allowance query
@@ -17,15 +17,16 @@ import {
17
17
  type EvmRawTransaction,
18
18
  } from '@sodax/sdk';
19
19
  import { AtomicityNotSupportedError, AtomicReadyWalletRejectedUpgradeError, UserRejectedRequestError } from 'viem';
20
- import { beforeEach, describe, expect, it, vi } from 'vitest';
20
+ import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
21
21
 
22
22
  const approve = vi.fn();
23
+ const checkAllowance = vi.fn();
23
24
  const invalidateQueries = vi.fn();
24
25
 
25
26
  let captured: any;
26
27
 
27
28
  vi.mock('../shared/useSodaxContext.js', () => ({
28
- useSodaxContext: () => ({ sodax: { api: { swaps: { approve } } } }),
29
+ useSodaxContext: () => ({ sodax: { api: { swaps: { approve, checkAllowance } } } }),
29
30
  }));
30
31
  vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries }) }));
31
32
  vi.mock('../shared/useSafeMutation.js', () => ({
@@ -117,6 +118,7 @@ const run = (vars: any) => {
117
118
 
118
119
  beforeEach(() => {
119
120
  vi.clearAllMocks();
121
+ checkAllowance.mockResolvedValue({ ok: true, value: { valid: true } });
120
122
  approve.mockResolvedValue({ ok: true, value: { tx: APPROVE_TX } });
121
123
  });
122
124
 
@@ -219,14 +221,39 @@ describe('useSwapsApiBroadcastWithApproval', () => {
219
221
  const calls: string[] = [];
220
222
  const walletProvider = batchWallet(calls, 'supported');
221
223
  walletProvider.sendAtomicBatch.mockRejectedValueOnce(new AtomicityNotSupportedError(new Error('no atomicity')));
224
+ checkAllowance.mockImplementation(async () => {
225
+ calls.push('check');
226
+ return { ok: true, value: { valid: true } };
227
+ });
222
228
 
223
229
  const result = await run({ walletProvider, fallbackOnRefusal: true });
224
230
 
225
231
  expect(result.approvalStrategy).toBe('sequential');
226
- expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'send:0x03']);
232
+ // The API must see the approval before the intent is sent, or its RPC lag re-offers Approve.
233
+ expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'check', 'send:0x03']);
227
234
  expect(approve).toHaveBeenCalledTimes(1);
228
235
  });
229
236
 
237
+ it('still sends the intent once the wait gives up on an allowance check that hangs', async () => {
238
+ vi.useFakeTimers();
239
+ onTestFinished(() => {
240
+ vi.useRealTimers();
241
+ });
242
+ const calls: string[] = [];
243
+ const walletProvider = batchWallet(calls, 'supported');
244
+ walletProvider.sendAtomicBatch.mockRejectedValueOnce(new AtomicityNotSupportedError(new Error('no atomicity')));
245
+ checkAllowance.mockImplementation(() => {
246
+ calls.push('check');
247
+ return new Promise(() => {});
248
+ });
249
+
250
+ const pending = run({ walletProvider, fallbackOnRefusal: true });
251
+ await vi.advanceTimersByTimeAsync(15_000);
252
+
253
+ await expect(pending).resolves.toMatchObject({ approvalStrategy: 'sequential' });
254
+ expect(calls).toEqual(['send:0x02', 'wait:0xhash02', 'check', 'send:0x03']);
255
+ });
256
+
230
257
  it('keeps a ready wallet sequential when the account upgrade is not allowed', async () => {
231
258
  const calls: string[] = [];
232
259
  const walletProvider = batchWallet(calls, 'ready');
@@ -20,6 +20,7 @@ import {
20
20
  import { useQueryClient } from '@tanstack/react-query';
21
21
  import { useSodaxContext } from '../shared/useSodaxContext.js';
22
22
  import { unwrapResult } from '../shared/unwrapResult.js';
23
+ import { waitForApiAllowance } from '../shared/waitForApiAllowance.js';
23
24
  import type { MutationHookParams } from '../shared/types.js';
24
25
  import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
25
26
  import { runApprovalPlan, type ApprovalHashes, type ApprovalProgressListener } from '../../utils/approvalPlan.js';
@@ -167,6 +168,7 @@ export const useSwapsApiBroadcastWithApproval = ({
167
168
  }
168
169
 
169
170
  const approval = await runApprovalPlan({ plan, srcChainKey, walletProvider, hookName: HOOK_NAME, onProgress });
171
+ await waitForApiAllowance(config => sodax.api.swaps.checkAllowance(body, config), apiConfig);
170
172
  // The allowance is on-chain whatever happens to the intent next; a stale cached `valid: false` would re-offer it.
171
173
  await queryClient.invalidateQueries({ queryKey: ['swapsApi', 'allowance'] });
172
174
  const txHash = await walletProvider.sendTransaction(intentTx, {