@sodax/dapp-kit 2.1.0 → 2.2.0-rc.2
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 +2 -0
- package/dist/index.d.ts +120 -8
- package/dist/index.mjs +126 -61
- package/package.json +3 -3
- package/src/hooks/_apiKeyWire.test.ts +487 -0
- package/src/hooks/_mutationContract.test.ts +6 -0
- package/src/hooks/backend/index.ts +4 -0
- package/src/hooks/backend/useBackendOracleCandles.ts +47 -0
- package/src/hooks/backend/useBackendOracleMarkets.ts +30 -0
- package/src/hooks/bitcoin/useFundTradingWallet.ts +2 -1
- package/src/hooks/bitcoin/useRadfiWithdraw.ts +2 -1
- package/src/hooks/bridge/useBridge.test.ts +104 -0
- package/src/hooks/bridge/useBridge.ts +2 -2
- package/src/hooks/dex/useDexDeposit.ts +2 -1
- package/src/hooks/dex/useDexWithdraw.ts +2 -1
- package/src/hooks/dex/useSupplyLiquidity.ts +2 -1
- package/src/hooks/leverageYield/useLeverageYieldVaultSwap.ts +2 -2
- package/src/hooks/migrate/useMigrateBaln.ts +2 -2
- package/src/hooks/migrate/useMigrateIcxToSoda.ts +2 -2
- package/src/hooks/migrate/useMigratebnUSD.ts +2 -2
- package/src/hooks/migrate/useRevertMigrateSodaToIcx.ts +2 -2
- package/src/hooks/mm/useBorrow.ts +2 -4
- package/src/hooks/mm/useRepay.ts +2 -1
- package/src/hooks/mm/useSupply.ts +2 -1
- package/src/hooks/mm/useWithdraw.ts +2 -4
- package/src/hooks/partner/useFeeClaimWithdraw.ts +2 -1
- package/src/hooks/recovery/useWithdrawHubAsset.ts +2 -1
- package/src/hooks/shared/index.ts +3 -0
- package/src/hooks/shared/invalidateBalances.test.ts +71 -0
- package/src/hooks/shared/invalidateBalances.ts +25 -0
- package/src/hooks/shared/retryUnlessAuthFailure.test.ts +38 -0
- package/src/hooks/shared/retryUnlessAuthFailure.ts +18 -0
- package/src/hooks/shared/useBalances.test.ts +118 -0
- package/src/hooks/shared/useBalances.ts +81 -0
- package/src/hooks/shared/useEstablishTrustline.test.ts +2 -0
- package/src/hooks/shared/useEstablishTrustline.ts +2 -1
- package/src/hooks/shared/useStellarGate.test.ts +1 -1
- package/src/hooks/sponsoring/useActivateStellarAccount.test.ts +6 -4
- package/src/hooks/sponsoring/useActivateStellarAccount.ts +2 -1
- package/src/hooks/sponsoring/useActivateStellarAccount.wire.test.ts +109 -0
- package/src/hooks/sponsoring/useSponsorConfig.test.ts +8 -2
- package/src/hooks/sponsoring/useStellarAccountActive.test.ts +2 -2
- package/src/hooks/sponsoring/useStellarAccountStatus.test.ts +8 -2
- package/src/hooks/staking/useClaim.ts +2 -1
- package/src/hooks/staking/useInstantUnstake.ts +2 -1
- package/src/hooks/staking/useStake.ts +2 -1
- package/src/hooks/swap/useDetailedStatus.test.ts +2 -2
- package/src/hooks/swap/useSwap.test.ts +128 -0
- package/src/hooks/swap/useSwap.ts +2 -2
- package/src/hooks/swapsApi/useSwapsApiAllowance.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiApprove.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiCancelIntent.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiCreateIntent.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiCreateLimitOrder.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiDeadline.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiEstimateGas.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiFilledIntent.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiIntent.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiIntentExtraData.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiIntentHash.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiIntentPacket.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiPartnerFee.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiQuote.ts +5 -1
- package/src/hooks/swapsApi/useSwapsApiSolverFee.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiStatus.ts +10 -4
- package/src/hooks/swapsApi/useSwapsApiSubmitTx.ts +5 -3
- package/src/hooks/swapsApi/useSwapsApiSubmitTxStatus.ts +8 -4
- package/src/hooks/swapsApi/useSwapsApiTokens.ts +2 -1
- package/src/hooks/swapsApi/useSwapsApiTokensByChain.ts +2 -1
- package/src/providers/SodaxProvider.test.ts +41 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import type { Result, Sodax, XToken } from '@sodax/sdk';
|
|
3
|
+
import { getBalancesQueryOptions } from './useBalances.js';
|
|
4
|
+
|
|
5
|
+
const makeToken = (symbol: string, address: string): XToken =>
|
|
6
|
+
({
|
|
7
|
+
symbol,
|
|
8
|
+
name: symbol,
|
|
9
|
+
decimals: 18,
|
|
10
|
+
address,
|
|
11
|
+
chainKey: 'sonic',
|
|
12
|
+
hubAsset: '0x0000000000000000000000000000000000000000',
|
|
13
|
+
vault: '0x0000000000000000000000000000000000000000',
|
|
14
|
+
}) as XToken;
|
|
15
|
+
|
|
16
|
+
const makeSodax = (result: Result<Record<string, bigint>>) =>
|
|
17
|
+
({
|
|
18
|
+
spoke: {
|
|
19
|
+
getWalletBalances: vi.fn().mockResolvedValue(result),
|
|
20
|
+
},
|
|
21
|
+
}) as unknown as Sodax; // Minimal stub: only the `spoke.getWalletBalances` path the hook uses.
|
|
22
|
+
|
|
23
|
+
describe('getBalancesQueryOptions', () => {
|
|
24
|
+
const tokenA = makeToken('AAA', '0xaaa');
|
|
25
|
+
const tokenB = makeToken('BBB', '0xbbb');
|
|
26
|
+
|
|
27
|
+
it('builds a queryKey pairing each token symbol with its address', () => {
|
|
28
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
29
|
+
chainKey: 'sonic',
|
|
30
|
+
tokens: [tokenA, tokenB],
|
|
31
|
+
address: '0xuser',
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
expect(opts.queryKey).toEqual([
|
|
35
|
+
'shared',
|
|
36
|
+
'balances',
|
|
37
|
+
'sonic',
|
|
38
|
+
[
|
|
39
|
+
['AAA', '0xaaa'],
|
|
40
|
+
['BBB', '0xbbb'],
|
|
41
|
+
],
|
|
42
|
+
'0xuser',
|
|
43
|
+
]);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('is disabled when chainKey is missing', () => {
|
|
47
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
48
|
+
chainKey: undefined,
|
|
49
|
+
tokens: [tokenA],
|
|
50
|
+
address: '0xuser',
|
|
51
|
+
});
|
|
52
|
+
expect(opts.enabled).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('is disabled when address is missing', () => {
|
|
56
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
57
|
+
chainKey: 'sonic',
|
|
58
|
+
tokens: [tokenA],
|
|
59
|
+
address: undefined,
|
|
60
|
+
});
|
|
61
|
+
expect(opts.enabled).toBe(false);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('is disabled when tokens is empty', () => {
|
|
65
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
66
|
+
chainKey: 'sonic',
|
|
67
|
+
tokens: [],
|
|
68
|
+
address: '0xuser',
|
|
69
|
+
});
|
|
70
|
+
expect(opts.enabled).toBe(false);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('is enabled when all inputs are present', () => {
|
|
74
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
75
|
+
chainKey: 'sonic',
|
|
76
|
+
tokens: [tokenA],
|
|
77
|
+
address: '0xuser',
|
|
78
|
+
});
|
|
79
|
+
expect(opts.enabled).toBe(true);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('queryFn delegates to sodax.spoke.getWalletBalances and unwraps the Result value', async () => {
|
|
83
|
+
const expected = { '0xaaa': 42n, '0xbbb': 0n };
|
|
84
|
+
const sodax = makeSodax({ ok: true, value: expected });
|
|
85
|
+
|
|
86
|
+
const opts = getBalancesQueryOptions(sodax, { chainKey: 'sonic', tokens: [tokenA, tokenB], address: '0xuser' });
|
|
87
|
+
|
|
88
|
+
const result = await opts.queryFn();
|
|
89
|
+
expect(result).toEqual(expected);
|
|
90
|
+
expect(sodax.spoke.getWalletBalances).toHaveBeenCalledWith({
|
|
91
|
+
srcChainKey: 'sonic',
|
|
92
|
+
srcAddress: '0xuser',
|
|
93
|
+
tokens: [tokenA, tokenB],
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('queryFn throws when the SDK returns an unsuccessful Result', async () => {
|
|
98
|
+
const boom = new Error('rpc down');
|
|
99
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: false, error: boom }), {
|
|
100
|
+
chainKey: 'sonic',
|
|
101
|
+
tokens: [tokenA],
|
|
102
|
+
address: '0xuser',
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
await expect(opts.queryFn()).rejects.toThrow('rpc down');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('queryFn returns {} when chainKey/address are missing (defensive, enabled should prevent this)', async () => {
|
|
109
|
+
const opts = getBalancesQueryOptions(makeSodax({ ok: true, value: {} }), {
|
|
110
|
+
chainKey: undefined,
|
|
111
|
+
tokens: [tokenA],
|
|
112
|
+
address: undefined,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const result = await opts.queryFn();
|
|
116
|
+
expect(result).toEqual({});
|
|
117
|
+
});
|
|
118
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type UseQueryResult, useQuery } from '@tanstack/react-query';
|
|
2
|
+
import type { Sodax, SpokeChainKey, XToken } from '@sodax/sdk';
|
|
3
|
+
import { useSodaxContext } from './useSodaxContext.js';
|
|
4
|
+
import { unwrapResult } from './unwrapResult.js';
|
|
5
|
+
import type { ReadHookParams } from './types.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Domain inputs for {@link useBalances}. `chainKey` is optional so the hook can be mounted before a
|
|
9
|
+
* chain is selected; `enabled` gates execution on every required field being present.
|
|
10
|
+
*
|
|
11
|
+
* The SDK reads the chain named by `chainKey` and ignores `token.chainKey`, so a token that does
|
|
12
|
+
* not live on that chain reads as `0n` rather than erroring — keep the two in step.
|
|
13
|
+
*/
|
|
14
|
+
export interface BalancesInputs {
|
|
15
|
+
chainKey: SpokeChainKey | undefined;
|
|
16
|
+
tokens: readonly XToken[];
|
|
17
|
+
address: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type UseBalancesParams = ReadHookParams<Record<string, bigint>, BalancesInputs>;
|
|
21
|
+
|
|
22
|
+
const REFETCH_INTERVAL_MS = 5_000;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Pure builder for {@link useBalances} query options. Exported for unit tests and for advanced
|
|
26
|
+
* callers that compose their own `useQuery` wrapper. Takes the SDK instance explicitly (the hook
|
|
27
|
+
* supplies it from context).
|
|
28
|
+
*/
|
|
29
|
+
export function getBalancesQueryOptions(sodax: Sodax, { chainKey, tokens, address }: BalancesInputs) {
|
|
30
|
+
return {
|
|
31
|
+
// Pair symbol + address: readable in devtools, unique on-chain (symbol alone can collide —
|
|
32
|
+
// e.g. scam tokens copying a legitimate ticker).
|
|
33
|
+
queryKey: ['shared', 'balances', chainKey, tokens.map(t => [t.symbol, t.address] as const), address] as const,
|
|
34
|
+
queryFn: async (): Promise<Record<string, bigint>> => {
|
|
35
|
+
if (!chainKey || !address) return {};
|
|
36
|
+
return unwrapResult(await sodax.spoke.getWalletBalances({ srcChainKey: chainKey, srcAddress: address, tokens }));
|
|
37
|
+
},
|
|
38
|
+
enabled: !!chainKey && !!address && tokens.length > 0,
|
|
39
|
+
refetchInterval: REFETCH_INTERVAL_MS,
|
|
40
|
+
// Deliberately NOT `placeholderData: keepPreviousData`: the query key carries the chain, so a
|
|
41
|
+
// chain switch would surface the previous chain's map — and every EVM chain shares the native
|
|
42
|
+
// token address, so its native balance would render as the new chain's until the fetch lands.
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Fetch a user's own wallet balances for multiple tokens on a specific chain, straight from the
|
|
48
|
+
* core SDK (`sodax.spoke.getWalletBalances`) — no wallet SDK / `xService` required. Returns an
|
|
49
|
+
* object mapping each token's address to its balance in smallest units.
|
|
50
|
+
*
|
|
51
|
+
* This is the SDK-backed successor to {@link useXBalances} (which wraps a wallet-layer `xService`).
|
|
52
|
+
* Prefer this when the app already has a `SodaxProvider`.
|
|
53
|
+
*
|
|
54
|
+
* Failure model: a token that could not be read is logged by the SDK and reported as `0n`, so a
|
|
55
|
+
* flaky RPC is indistinguishable from an empty wallet — always the conservative direction, since
|
|
56
|
+
* under-reporting blocks a spend rather than permitting one. The query only errors when the whole
|
|
57
|
+
* batch is unusable: a shared round-trip every token depends on, or a batch in which no token
|
|
58
|
+
* could be read at all.
|
|
59
|
+
*
|
|
60
|
+
* Chain-specific notes: Stellar XLM reports the *spendable* amount (total minus the minimum reserve
|
|
61
|
+
* and selling liabilities); Bitcoin returns `0n` for Rune tokens, whose amounts are not exposed by
|
|
62
|
+
* the UTXO endpoint.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```tsx
|
|
66
|
+
* const { data: balances } = useBalances({ params: { chainKey, address, tokens } });
|
|
67
|
+
* const usdcBalance = balances?.[usdc.address] ?? 0n;
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export function useBalances({ params, queryOptions }: UseBalancesParams = {}): UseQueryResult<Record<string, bigint>> {
|
|
71
|
+
const { sodax } = useSodaxContext();
|
|
72
|
+
|
|
73
|
+
return useQuery({
|
|
74
|
+
...getBalancesQueryOptions(sodax, {
|
|
75
|
+
chainKey: params?.chainKey,
|
|
76
|
+
tokens: params?.tokens ?? [],
|
|
77
|
+
address: params?.address,
|
|
78
|
+
}),
|
|
79
|
+
...queryOptions,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
@@ -47,6 +47,7 @@ describe('useEstablishTrustline — invalidation after a broadcast trustline', (
|
|
|
47
47
|
expect(invalidatedKeys()).toEqual([
|
|
48
48
|
['shared', 'stellarTrustlineCheck', ChainKeys.STELLAR_MAINNET, TOKEN, ADDRESS],
|
|
49
49
|
['sponsoring', 'stellarAccountStatus', ADDRESS],
|
|
50
|
+
['shared', 'balances', ChainKeys.STELLAR_MAINNET],
|
|
50
51
|
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
51
52
|
]);
|
|
52
53
|
});
|
|
@@ -64,6 +65,7 @@ describe('useEstablishTrustline — invalidation after a broadcast trustline', (
|
|
|
64
65
|
expect(invalidatedKeys()).toEqual([
|
|
65
66
|
['shared', 'stellarTrustlineCheck'],
|
|
66
67
|
['sponsoring', 'stellarAccountStatus'],
|
|
68
|
+
['shared', 'balances', ChainKeys.STELLAR_MAINNET],
|
|
67
69
|
['shared', 'xBalances', ChainKeys.STELLAR_MAINNET],
|
|
68
70
|
]);
|
|
69
71
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { IStellarWalletProvider, StellarChainKey } from '@sodax/sdk';
|
|
2
2
|
import { ChainKeys } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
|
+
import { invalidateBalances } from './invalidateBalances.js';
|
|
4
5
|
import type { MutationHookParams } from './types.js';
|
|
5
6
|
import { useSafeMutation, type SafeUseMutationResult } from './useSafeMutation.js';
|
|
6
7
|
import { useSodaxContext } from './useSodaxContext.js';
|
|
@@ -65,7 +66,7 @@ export function useEstablishTrustline({
|
|
|
65
66
|
? ['sponsoring', 'stellarAccountStatus', srcAddress]
|
|
66
67
|
: ['sponsoring', 'stellarAccountStatus'],
|
|
67
68
|
});
|
|
68
|
-
queryClient
|
|
69
|
+
invalidateBalances(queryClient, ChainKeys.STELLAR_MAINNET);
|
|
69
70
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
70
71
|
},
|
|
71
72
|
});
|
|
@@ -89,7 +89,7 @@ describe('useStellarGate — the trustline read is gated on account existence',
|
|
|
89
89
|
it('does not read a Stellar trustline for a non-Stellar destination', () => {
|
|
90
90
|
const { gate, trustlineAddress } = run(
|
|
91
91
|
{ data: { exists: true, canAffordTrustline: true } },
|
|
92
|
-
{ dstChainKey: ChainKeys.
|
|
92
|
+
{ dstChainKey: ChainKeys.SONIC_MAINNET },
|
|
93
93
|
);
|
|
94
94
|
|
|
95
95
|
expect(trustlineAddress).toBeUndefined();
|
|
@@ -23,8 +23,8 @@ function invalidatedKeyPrefixes(): string[][] {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
describe('useActivateStellarAccount — cache invalidation', () => {
|
|
26
|
-
it('
|
|
27
|
-
expect(invalidatedKeyPrefixes()).toHaveLength(
|
|
26
|
+
it('hand-rolls exactly three query invalidations on success, the fourth routed through invalidateBalances', () => {
|
|
27
|
+
expect(invalidatedKeyPrefixes()).toHaveLength(3);
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
it("invalidates the account-active query using that query's own key prefix", () => {
|
|
@@ -63,8 +63,10 @@ describe('useActivateStellarAccount — cache invalidation', () => {
|
|
|
63
63
|
expect(invalidatedKeyPrefixes()).toContainEqual(['shared', 'stellarTrustlineCheck']);
|
|
64
64
|
});
|
|
65
65
|
|
|
66
|
-
it('invalidates the
|
|
67
|
-
|
|
66
|
+
it('invalidates Stellar balances through the shared invalidateBalances helper', () => {
|
|
67
|
+
// Routed through invalidateBalances (covers both useBalances and useXBalances) rather than a
|
|
68
|
+
// hand-rolled invalidateQueries call, so it is not one of the literal matches above.
|
|
69
|
+
expect(SRC).toMatch(/invalidateBalances\(queryClient,\s*ChainKeys\.STELLAR_MAINNET\)/);
|
|
68
70
|
});
|
|
69
71
|
|
|
70
72
|
it('passes the whole mutation vars through to the SDK', () => {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ChainKeys, type ActivateStellarAccountParams, type ActivateStellarAccountResult } from '@sodax/sdk';
|
|
2
2
|
import { useQueryClient } from '@tanstack/react-query';
|
|
3
3
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
4
|
+
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
4
5
|
import type { MutationHookParams } from '../shared/types.js';
|
|
5
6
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
6
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
@@ -31,7 +32,7 @@ export function useActivateStellarAccount({
|
|
|
31
32
|
queryClient.invalidateQueries({ queryKey: ['sponsoring', 'stellarAccountStatus', vars.address] });
|
|
32
33
|
// Clear trustline errors cached while the account did not exist.
|
|
33
34
|
queryClient.invalidateQueries({ queryKey: ['shared', 'stellarTrustlineCheck'] });
|
|
34
|
-
queryClient
|
|
35
|
+
invalidateBalances(queryClient, ChainKeys.STELLAR_MAINNET);
|
|
35
36
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
36
37
|
},
|
|
37
38
|
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useActivateStellarAccount` wire test for the per-request API key: `requestConfig.apiKey` in the
|
|
3
|
+
* mutation vars must reach the sponsoring `/accounts` POST as `x-api-key`, beating the
|
|
4
|
+
* instance-level key.
|
|
5
|
+
*
|
|
6
|
+
* Follows the package convention of testing hooks without a renderer (captured `mutationFn`),
|
|
7
|
+
* driving a real keyed `Sodax` end to end the way packages/sdk/src/sponsoring/SponsoringService.test.ts
|
|
8
|
+
* does: Horizon is stubbed on the instance, the wallet signs with a real throwaway keypair, and the
|
|
9
|
+
* config GET + account POST run call-through to a stubbed global fetch.
|
|
10
|
+
*
|
|
11
|
+
* `@stellar/stellar-sdk` is not a dapp-kit dependency, so it is loaded through `@sodax/sdk`'s own
|
|
12
|
+
* module graph — the same copy the SDK builds and verifies the transaction with.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createRequire } from 'node:module';
|
|
16
|
+
import { Sodax } from '@sodax/sdk';
|
|
17
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
18
|
+
|
|
19
|
+
const sdkRequire = createRequire(createRequire(import.meta.url).resolve('@sodax/sdk/package.json'));
|
|
20
|
+
const { Keypair, Networks, TransactionBuilder } = sdkRequire('@stellar/stellar-sdk');
|
|
21
|
+
|
|
22
|
+
// biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
|
|
23
|
+
let captured: any;
|
|
24
|
+
|
|
25
|
+
const sodax = new Sodax({ apiKey: 'instance-key', logger: 'silent' });
|
|
26
|
+
|
|
27
|
+
vi.mock('../shared/useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax }) }));
|
|
28
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries: vi.fn() }) }));
|
|
29
|
+
vi.mock('../shared/useSafeMutation.js', () => ({
|
|
30
|
+
// biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
|
|
31
|
+
useSafeMutation: (options: any) => {
|
|
32
|
+
captured = options;
|
|
33
|
+
return {};
|
|
34
|
+
},
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
const { useActivateStellarAccount } = await import('./useActivateStellarAccount.js');
|
|
38
|
+
|
|
39
|
+
const SPONSOR = Keypair.random();
|
|
40
|
+
const USER = Keypair.random();
|
|
41
|
+
|
|
42
|
+
const SPONSOR_CONFIG = {
|
|
43
|
+
sponsorAccount: SPONSOR.publicKey(),
|
|
44
|
+
networkPassphrase: Networks.PUBLIC,
|
|
45
|
+
minTotalFeeStroops: '3000',
|
|
46
|
+
maxTotalFeeStroops: '10000',
|
|
47
|
+
operationCount: 3,
|
|
48
|
+
minPerOperationFeeStroops: '1000',
|
|
49
|
+
maxPerOperationFeeStroops: '3333',
|
|
50
|
+
recommendedPerOperationFeeStroops: '1000',
|
|
51
|
+
maxTimeboundSeconds: 3600,
|
|
52
|
+
requiredStartingBalance: '0',
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const fetchMock = vi.fn();
|
|
56
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
57
|
+
|
|
58
|
+
const jsonOk = (data: unknown): Response =>
|
|
59
|
+
new Response(JSON.stringify(data), { status: 200, headers: { 'content-type': 'application/json' } });
|
|
60
|
+
|
|
61
|
+
// The account being created signs; the wallet parses and re-emits the SDK-built envelope as XDR.
|
|
62
|
+
const wallet = {
|
|
63
|
+
chainType: 'STELLAR',
|
|
64
|
+
getWalletAddress: vi.fn(async () => USER.publicKey()),
|
|
65
|
+
waitForTransactionReceipt: vi.fn(),
|
|
66
|
+
signTransaction: vi.fn(async (xdr: string) => {
|
|
67
|
+
const tx = TransactionBuilder.fromXDR(xdr, Networks.PUBLIC);
|
|
68
|
+
tx.sign(USER);
|
|
69
|
+
return tx.toXDR();
|
|
70
|
+
}),
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
beforeEach(() => {
|
|
74
|
+
fetchMock.mockReset();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('useActivateStellarAccount — requestConfig.apiKey on the sponsoring wire', () => {
|
|
78
|
+
it('lands the per-request key on the /accounts POST, beating the instance key', async () => {
|
|
79
|
+
// Horizon uses its own HTTP client, so stub it on the instance rather than through fetch.
|
|
80
|
+
vi.spyOn(sodax.spoke.stellar.server, 'loadAccount').mockImplementation(async (address: string) => {
|
|
81
|
+
if (address === SPONSOR.publicKey()) return { sequenceNumber: () => '100' } as never;
|
|
82
|
+
throw Object.assign(new Error('Not Found'), { response: { status: 404 } });
|
|
83
|
+
});
|
|
84
|
+
fetchMock
|
|
85
|
+
.mockResolvedValueOnce(jsonOk(SPONSOR_CONFIG))
|
|
86
|
+
.mockResolvedValueOnce(jsonOk({ hash: 'abc123', alreadyActive: false }));
|
|
87
|
+
|
|
88
|
+
useActivateStellarAccount();
|
|
89
|
+
const result = await captured.mutationFn({
|
|
90
|
+
address: USER.publicKey(),
|
|
91
|
+
walletProvider: wallet,
|
|
92
|
+
requestConfig: { apiKey: 'hook-key' },
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
expect(result).toEqual({ status: 'submitted', hash: 'abc123', attempts: 1 });
|
|
96
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
97
|
+
|
|
98
|
+
const post = fetchMock.mock.calls.find(([url]) => String(url).endsWith('/sponsorships/stellar/accounts'));
|
|
99
|
+
expect(post).toBeDefined();
|
|
100
|
+
expect(post?.[1]?.method).toBe('POST');
|
|
101
|
+
const headers = post?.[1]?.headers as Record<string, string>;
|
|
102
|
+
expect(Object.keys(headers).filter(name => name.toLowerCase() === 'x-api-key')).toHaveLength(1);
|
|
103
|
+
expect(new Headers(headers).get('x-api-key')).toBe('hook-key');
|
|
104
|
+
|
|
105
|
+
// The same requestConfig rides the preceding sponsor-config GET.
|
|
106
|
+
const configGet = fetchMock.mock.calls.find(([url]) => String(url).endsWith('/sponsorships/stellar/config'));
|
|
107
|
+
expect(new Headers(configGet?.[1]?.headers).get('x-api-key')).toBe('hook-key');
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
SodaxError,
|
|
3
|
+
SPONSOR_CONFIG_TTL_MS,
|
|
4
|
+
type Result,
|
|
5
|
+
type SponsoringConfigError,
|
|
6
|
+
type StellarSponsorConfig,
|
|
7
|
+
} from '@sodax/sdk';
|
|
2
8
|
import { describe, expect, it, vi } from 'vitest';
|
|
3
9
|
import { getSponsorConfigQueryOptions } from './useSponsorConfig.js';
|
|
4
10
|
|
|
@@ -15,7 +21,7 @@ const CONFIG: StellarSponsorConfig = {
|
|
|
15
21
|
requiredStartingBalance: '0',
|
|
16
22
|
};
|
|
17
23
|
|
|
18
|
-
const makeSodax = (result:
|
|
24
|
+
const makeSodax = (result: Result<StellarSponsorConfig, SponsoringConfigError>) => {
|
|
19
25
|
const getStellarSponsorConfig = vi.fn(async () => result);
|
|
20
26
|
return { sodax: { sponsoring: { getStellarSponsorConfig } }, getStellarSponsorConfig };
|
|
21
27
|
};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { SodaxError } from '@sodax/sdk';
|
|
1
|
+
import { SodaxError, type Result, type SponsoringLookupError } from '@sodax/sdk';
|
|
2
2
|
import { describe, expect, it, vi } from 'vitest';
|
|
3
3
|
import { getStellarAccountActiveQueryOptions } from './useStellarAccountActive.js';
|
|
4
4
|
|
|
5
5
|
const ADDRESS = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
|
6
6
|
const OTHER = 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
|
|
7
7
|
|
|
8
|
-
const makeSodax = (result:
|
|
8
|
+
const makeSodax = (result: Result<boolean, SponsoringLookupError>) => {
|
|
9
9
|
const isStellarAccountActive = vi.fn(async () => result);
|
|
10
10
|
return { sodax: { sponsoring: { isStellarAccountActive } }, isStellarAccountActive };
|
|
11
11
|
};
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
SodaxError,
|
|
3
|
+
STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
|
|
4
|
+
type Result,
|
|
5
|
+
type SponsoringLookupError,
|
|
6
|
+
type StellarAccountStatus,
|
|
7
|
+
} from '@sodax/sdk';
|
|
2
8
|
import { describe, expect, it, vi } from 'vitest';
|
|
3
9
|
import { getStellarAccountStatusQueryOptions } from './useStellarAccountStatus.js';
|
|
4
10
|
|
|
@@ -13,7 +19,7 @@ const FUNDED: StellarAccountStatus = {
|
|
|
13
19
|
trustlineMinXlmStroops: STELLAR_TRUSTLINE_MIN_XLM_STROOPS,
|
|
14
20
|
};
|
|
15
21
|
|
|
16
|
-
const makeSodax = (result:
|
|
22
|
+
const makeSodax = (result: Result<StellarAccountStatus, SponsoringLookupError>) => {
|
|
17
23
|
const getStellarAccountStatus = vi.fn(async () => result);
|
|
18
24
|
return { sodax: { sponsoring: { getStellarAccountStatus } }, getStellarAccountStatus };
|
|
19
25
|
};
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type { ClaimAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
|
+
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
5
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
6
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
@@ -30,7 +31,7 @@ export function useClaim<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
30
31
|
queryClient.invalidateQueries({
|
|
31
32
|
queryKey: ['staking', 'unstakingInfoWithPenalty', params.srcChainKey, params.srcAddress],
|
|
32
33
|
});
|
|
33
|
-
queryClient
|
|
34
|
+
invalidateBalances(queryClient, params.srcChainKey);
|
|
34
35
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
35
36
|
},
|
|
36
37
|
});
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type { InstantUnstakeAction, SpokeChainKey, TxHashPair } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
|
+
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
5
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
6
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
@@ -36,7 +37,7 @@ export function useInstantUnstake<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
36
37
|
queryClient.invalidateQueries({ queryKey: ['staking', 'info', params.srcChainKey, params.srcAddress] });
|
|
37
38
|
queryClient.invalidateQueries({ queryKey: ['staking', 'instantUnstakeRatio'] });
|
|
38
39
|
queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'instantUnstake'] });
|
|
39
|
-
queryClient
|
|
40
|
+
invalidateBalances(queryClient, params.srcChainKey);
|
|
40
41
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
41
42
|
},
|
|
42
43
|
});
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type { SpokeChainKey, StakeAction, TxHashPair } from '@sodax/sdk';
|
|
3
3
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { useSodaxContext } from '../shared/useSodaxContext.js';
|
|
5
|
+
import { invalidateBalances } from '../shared/invalidateBalances.js';
|
|
5
6
|
import type { MutationHookParams } from '../shared/types.js';
|
|
6
7
|
import { useSafeMutation, type SafeUseMutationResult } from '../shared/useSafeMutation.js';
|
|
7
8
|
import { unwrapResult } from '../shared/unwrapResult.js';
|
|
@@ -35,7 +36,7 @@ export function useStake<K extends SpokeChainKey = SpokeChainKey>({
|
|
|
35
36
|
queryClient.invalidateQueries({ queryKey: ['staking', 'allowance', params.srcChainKey, 'stake'] });
|
|
36
37
|
queryClient.invalidateQueries({ queryKey: ['staking', 'stakeRatio'] });
|
|
37
38
|
queryClient.invalidateQueries({ queryKey: ['staking', 'convertedAssets'] });
|
|
38
|
-
queryClient
|
|
39
|
+
invalidateBalances(queryClient, params.srcChainKey);
|
|
39
40
|
await mutationOptions?.onSuccess?.(data, vars, ctx);
|
|
40
41
|
},
|
|
41
42
|
});
|
|
@@ -63,7 +63,7 @@ describe('getDetailedStatusRefetchInterval', () => {
|
|
|
63
63
|
// Both terminal states of the `SubmitSwapTxStatusV2` wire contract. `'failed'` is unreachable via
|
|
64
64
|
// `getDetailedStatus` today (the SDK routes abandoned records to the solver) — asserted here as
|
|
65
65
|
// the hook's own contract, so a terminal record is never polled forever if that routing changes.
|
|
66
|
-
it.each(['solved', 'failed'])('stops on a backend record at the terminal status %s', status => {
|
|
66
|
+
it.each(['solved', 'failed'] as const)('stops on a backend record at the terminal status %s', status => {
|
|
67
67
|
expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(false);
|
|
68
68
|
});
|
|
69
69
|
|
|
@@ -73,7 +73,7 @@ describe('getDetailedStatusRefetchInterval', () => {
|
|
|
73
73
|
'relayed',
|
|
74
74
|
'posting_execution',
|
|
75
75
|
'posted_execution',
|
|
76
|
-
])('keeps polling a backend record at %s', status => {
|
|
76
|
+
] as const)('keeps polling a backend record at %s', status => {
|
|
77
77
|
expect(getDetailedStatusRefetchInterval(ok(backend(status)), 0)).toBe(STATUS_POLL_MS);
|
|
78
78
|
});
|
|
79
79
|
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `useSwap` wire test for the per-action API key: `extras.apiKey` in the mutation vars must reach
|
|
3
|
+
* the backend submit-tx leg as `x-api-key` — on the POST and on the status poll — beating the
|
|
4
|
+
* instance-level key.
|
|
5
|
+
*
|
|
6
|
+
* Follows the package convention of testing hooks without a renderer (captured `mutationFn`), with
|
|
7
|
+
* the SDK stubbed at the same seams its own backend 2-step tests use: `createIntent` is spied on a
|
|
8
|
+
* real keyed `Sodax` so no wallet or chain is touched, while `POST /swaps/submit-tx` and
|
|
9
|
+
* `GET /swaps/submit-tx/status` run call-through to a stubbed global fetch serving the schema-valid
|
|
10
|
+
* fixtures from packages/sdk/src/swap/SwapService.test.ts.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { ChainKeys, Sodax } from '@sodax/sdk';
|
|
14
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
15
|
+
|
|
16
|
+
// biome-ignore lint/suspicious/noExplicitAny: the captured mutation options are driven directly.
|
|
17
|
+
let captured: any;
|
|
18
|
+
|
|
19
|
+
const sodax = new Sodax({ apiKey: 'instance-key', logger: 'silent' });
|
|
20
|
+
|
|
21
|
+
vi.mock('../shared/useSodaxContext.js', () => ({ useSodaxContext: () => ({ sodax }) }));
|
|
22
|
+
vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({ invalidateQueries: vi.fn() }) }));
|
|
23
|
+
vi.mock('../shared/useSafeMutation.js', () => ({
|
|
24
|
+
// biome-ignore lint/suspicious/noExplicitAny: mirrors the real wrapper's opaque options bag.
|
|
25
|
+
useSafeMutation: (options: any) => {
|
|
26
|
+
captured = options;
|
|
27
|
+
return {};
|
|
28
|
+
},
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
const { useSwap } = await import('./useSwap.js');
|
|
32
|
+
|
|
33
|
+
const fetchMock = vi.fn();
|
|
34
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
35
|
+
|
|
36
|
+
const jsonOk = (data: unknown): Response =>
|
|
37
|
+
new Response(JSON.stringify(data), { status: 200, headers: { 'content-type': 'application/json' } });
|
|
38
|
+
|
|
39
|
+
// Only the six IntentRequestV2 bigint fields carry bigints — the wire serializer rejects any other.
|
|
40
|
+
const INTENT = {
|
|
41
|
+
intentId: 1n,
|
|
42
|
+
creator: '0x3333333333333333333333333333333333333333',
|
|
43
|
+
inputToken: '0x4444444444444444444444444444444444444444',
|
|
44
|
+
outputToken: '0x5555555555555555555555555555555555555555',
|
|
45
|
+
inputAmount: 1_000_000n,
|
|
46
|
+
minOutputAmount: 900_000n,
|
|
47
|
+
deadline: 0n,
|
|
48
|
+
allowPartialFill: false,
|
|
49
|
+
srcChain: 4n,
|
|
50
|
+
dstChain: 44n,
|
|
51
|
+
srcAddress: '0x1111111111111111111111111111111111111111',
|
|
52
|
+
dstAddress: '0x2222222222222222222222222222222222222222',
|
|
53
|
+
solver: '0x0000000000000000000000000000000000000000',
|
|
54
|
+
data: '0x',
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const SWAP_PARAMS = {
|
|
58
|
+
inputToken: '0x4444444444444444444444444444444444444444',
|
|
59
|
+
outputToken: '0x5555555555555555555555555555555555555555',
|
|
60
|
+
inputAmount: 1_000_000n,
|
|
61
|
+
minOutputAmount: 900_000n,
|
|
62
|
+
deadline: 0n,
|
|
63
|
+
allowPartialFill: false,
|
|
64
|
+
srcChainKey: ChainKeys.BSC_MAINNET,
|
|
65
|
+
dstChainKey: ChainKeys.ARBITRUM_MAINNET,
|
|
66
|
+
srcAddress: '0x1111111111111111111111111111111111111111',
|
|
67
|
+
dstAddress: '0x2222222222222222222222222222222222222222',
|
|
68
|
+
solver: '0x0000000000000000000000000000000000000000',
|
|
69
|
+
data: '0x',
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const SUBMIT_ACCEPTED = { success: true, data: { status: 'inserted', message: 'accepted' } };
|
|
73
|
+
const STATUS_SOLVED = {
|
|
74
|
+
success: true,
|
|
75
|
+
data: {
|
|
76
|
+
txHash: '0xspokeTx',
|
|
77
|
+
srcChainKey: ChainKeys.BSC_MAINNET,
|
|
78
|
+
status: 'solved',
|
|
79
|
+
processingAttempts: 1,
|
|
80
|
+
result: { dstIntentTxHash: '0xDST', intent_hash: '0xHASH' },
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
beforeEach(() => {
|
|
85
|
+
vi.restoreAllMocks();
|
|
86
|
+
fetchMock.mockReset();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe('useSwap — extras.apiKey on the backend submit-tx wire', () => {
|
|
90
|
+
it('lands the per-action key on the submit-tx POST and the status poll, beating the instance key', async () => {
|
|
91
|
+
vi.spyOn(sodax.swaps, 'createIntent').mockResolvedValueOnce({
|
|
92
|
+
ok: true,
|
|
93
|
+
value: {
|
|
94
|
+
tx: '0xspokeTx',
|
|
95
|
+
intent: { ...INTENT, feeAmount: 0n },
|
|
96
|
+
relayData: { address: INTENT.creator, payload: '0xpay' },
|
|
97
|
+
},
|
|
98
|
+
} as never);
|
|
99
|
+
fetchMock.mockImplementation(async (url: string | URL, init?: RequestInit) => {
|
|
100
|
+
const { pathname } = new URL(String(url));
|
|
101
|
+
if (pathname === '/v1/swaps/submit-tx/status' && init?.method === 'GET') return jsonOk(STATUS_SOLVED);
|
|
102
|
+
if (pathname === '/v1/swaps/submit-tx' && init?.method === 'POST') return jsonOk(SUBMIT_ACCEPTED);
|
|
103
|
+
throw new Error(`unexpected fetch: ${String(url)}`);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
useSwap();
|
|
107
|
+
const result = await captured.mutationFn({
|
|
108
|
+
params: SWAP_PARAMS,
|
|
109
|
+
extras: { apiKey: 'action-key' },
|
|
110
|
+
walletProvider: {},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// Completed on the backend path: reconstructed from the solved status, no relay fallback fetches.
|
|
114
|
+
expect(result.intentDeliveryInfo.dstTxHash).toBe('0xDST');
|
|
115
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
116
|
+
|
|
117
|
+
const submit = fetchMock.mock.calls.find(
|
|
118
|
+
([url, init]) => new URL(String(url)).pathname === '/v1/swaps/submit-tx' && init?.method === 'POST',
|
|
119
|
+
);
|
|
120
|
+
const poll = fetchMock.mock.calls.find(
|
|
121
|
+
([url, init]) => new URL(String(url)).pathname === '/v1/swaps/submit-tx/status' && init?.method === 'GET',
|
|
122
|
+
);
|
|
123
|
+
expect(submit).toBeDefined();
|
|
124
|
+
expect(poll).toBeDefined();
|
|
125
|
+
expect(new Headers(submit?.[1]?.headers).get('x-api-key')).toBe('action-key');
|
|
126
|
+
expect(new Headers(poll?.[1]?.headers).get('x-api-key')).toBe('action-key');
|
|
127
|
+
});
|
|
128
|
+
});
|