@sodax/dapp-kit 2.4.0-rc.1 → 2.4.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.
@@ -1,4 +1,5 @@
1
1
  import {
2
+ SOLVED_PAYOUT_HEADROOM_FACTOR,
2
3
  isAuthFailure,
3
4
  summarizeSwapStatus,
4
5
  type CreateIntentParams,
@@ -14,6 +15,7 @@ import { useRef } from 'react';
14
15
  import { resolveSwapLifecycle, toSwapAttempt, type SwapLifecycleState } from '../../utils/swapLifecycle.js';
15
16
  import { useNearStorageGate, type NearStorageGate } from '../shared/useNearStorageGate.js';
16
17
  import { useStellarGate, type StellarGate } from '../shared/useStellarGate.js';
18
+ import { useXrpGate, type XrpGate } from '../shared/useXrpGate.js';
17
19
  import type { MutationHookOptions } from '../shared/types.js';
18
20
  import type { SafeUseMutationResult } from '../shared/useSafeMutation.js';
19
21
  import { useDetailedStatus, type UseDetailedStatusResult } from './useDetailedStatus.js';
@@ -31,7 +33,7 @@ export type UseSwapLifecycleParams<K extends SpokeChainKey = SpokeChainKey> = {
31
33
  intentParams: CreateIntentParams<K> | undefined;
32
34
  srcWalletProvider: GetWalletProviderType<K> | undefined;
33
35
  /**
34
- * Destination wallet, for the Stellar and NEAR setup actions. The gates check `intentParams.dstAddress`,
36
+ * Destination wallet, for the Stellar, NEAR and XRPL setup actions. The gates check `intentParams.dstAddress`,
35
37
  * the account the swap pays, so this wallet must control it for those actions to clear them.
36
38
  */
37
39
  dstWalletProvider: GetWalletProviderType<SpokeChainKey> | undefined;
@@ -70,11 +72,13 @@ export type SwapLifecycle<K extends SpokeChainKey = SpokeChainKey> = {
70
72
  status: UseQueryResult<UseDetailedStatusResult>;
71
73
  stellar: StellarGate;
72
74
  nearStorage: NearStorageGate;
75
+ /** `blockedReason` names why an XRPL destination cannot receive when the state is `xrpBlocked`. */
76
+ xrp: XrpGate;
73
77
  };
74
78
 
75
79
  /**
76
80
  * One hook for a swap form: approval strategy, destination prerequisites (Stellar account and
77
- * trustline, NEAR storage), source-chain switching, the swap itself (`useSwapWithApproval` — one
81
+ * trustline, NEAR storage, XRPL trustline), source-chain switching, the swap itself (`useSwapWithApproval` — one
78
82
  * signature on an EIP-5792 wallet) and its status (`useDetailedStatus`), as a single discriminated
79
83
  * `state` with one `next()` action. Render from `state.kind`; wire the button to `next()`.
80
84
  *
@@ -112,12 +116,24 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
112
116
  walletProvider: dstWalletProvider,
113
117
  });
114
118
 
119
+ const xrp = useXrpGate({
120
+ dstChainKey: intentParams?.dstChainKey,
121
+ token: intentParams?.outputToken,
122
+ address: intentParams?.dstAddress,
123
+ // Sized as the SDK's check before signing sizes it, so the gate never passes a swap the SDK then refuses.
124
+ amount: intentParams?.minOutputAmount,
125
+ maxAmount: intentParams && intentParams.minOutputAmount * SOLVED_PAYOUT_HEADROOM_FACTOR,
126
+ walletProvider: dstWalletProvider,
127
+ });
128
+
115
129
  // The setup mutations invalidate these checks without awaiting the refetch, so a stale "needs setup"
116
130
  // outlives the tx by one read.
117
131
  const fetchingSetupChecks =
118
132
  useIsFetching({ queryKey: ['sponsoring', 'stellarAccountStatus'] }) +
119
133
  useIsFetching({ queryKey: ['shared', 'stellarTrustlineCheck'] }) +
120
- useIsFetching({ queryKey: ['shared', 'nearStorageCheck'] });
134
+ useIsFetching({ queryKey: ['shared', 'nearStorageCheck'] }) +
135
+ useIsFetching({ queryKey: ['shared', 'xrpDestinationCheck'] }) +
136
+ useIsFetching({ queryKey: ['shared', 'xrpTrustlineReserveCheck'] });
121
137
 
122
138
  const attempt = toSwapAttempt(swap, intentParams);
123
139
  const broadcast = attempt.phase === 'broadcast' ? attempt : undefined;
@@ -132,9 +148,14 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
132
148
  hasInputs: !!intentParams && !!srcWalletProvider,
133
149
  stellar,
134
150
  nearStorage,
151
+ xrp,
135
152
  externalBlocked,
136
153
  setupBusy:
137
- stellar.isActivating || stellar.isRequestingTrustline || nearStorage.isRegistering || fetchingSetupChecks > 0,
154
+ stellar.isActivating ||
155
+ stellar.isRequestingTrustline ||
156
+ nearStorage.isRegistering ||
157
+ xrp.isRequestingTrustline ||
158
+ fetchingSetupChecks > 0,
138
159
  isWrongChain: chainSwitch?.isWrongChain ?? false,
139
160
  strategy: { data: approvalStrategy.data, error: approvalStrategy.error },
140
161
  });
@@ -157,7 +178,9 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
157
178
  if (state.reason === 'nearStorage') return nearStorage.registerStorage();
158
179
  if (state.reason === 'stellarCheckFailed') stellar.retry();
159
180
  if (state.reason === 'nearStorageCheckFailed') nearStorage.retry();
160
- // `stellarFunding` and `external` are for the app to resolve.
181
+ if (state.reason === 'xrpTrustline') return xrp.requestTrustline();
182
+ if (state.reason === 'xrpCheckFailed') xrp.retry();
183
+ // `stellarFunding`, `xrpFunding`, `xrpBlocked` and `external` are for the app to resolve.
161
184
  return undefined;
162
185
  case 'ready':
163
186
  if (!intentParams || !srcWalletProvider) return undefined;
@@ -208,5 +231,6 @@ export function useSwapLifecycle<K extends SpokeChainKey = SpokeChainKey>({
208
231
  status,
209
232
  stellar,
210
233
  nearStorage,
234
+ xrp,
211
235
  };
212
236
  }
@@ -2,3 +2,4 @@ export * from './approvalPlan.js';
2
2
  export * from './dex-utils.js';
3
3
  export * from './nearStorageGate.js';
4
4
  export * from './stellarGate.js';
5
+ export * from './xrpGate.js';
@@ -9,6 +9,7 @@ import {
9
9
  import { describe, expect, it } from 'vitest';
10
10
  import type { NearStorageGateState } from './nearStorageGate.js';
11
11
  import type { StellarGateState } from './stellarGate.js';
12
+ import type { XrpGateState } from './xrpGate.js';
12
13
  import {
13
14
  isSameIntent,
14
15
  resolveSwapLifecycle,
@@ -54,6 +55,14 @@ const OPEN_STELLAR: StellarGateState = {
54
55
  blocksAction: false,
55
56
  };
56
57
  const OPEN_NEAR: NearStorageGateState = { isNear: false, needsRegistration: false, blocksAction: false };
58
+ const OPEN_XRP: XrpGateState = {
59
+ isXrpIssuedToken: false,
60
+ needsTrustline: false,
61
+ needsFunding: false,
62
+ blockedReason: undefined,
63
+ checkFailed: false,
64
+ blocksAction: false,
65
+ };
57
66
 
58
67
  const inputs = (overrides: Partial<SwapLifecycleInputs> = {}): SwapLifecycleInputs => ({
59
68
  attempt: { phase: 'none' },
@@ -62,6 +71,7 @@ const inputs = (overrides: Partial<SwapLifecycleInputs> = {}): SwapLifecycleInpu
62
71
  hasInputs: true,
63
72
  stellar: OPEN_STELLAR,
64
73
  nearStorage: OPEN_NEAR,
74
+ xrp: OPEN_XRP,
65
75
  externalBlocked: false,
66
76
  setupBusy: false,
67
77
  isWrongChain: false,
@@ -230,6 +240,31 @@ describe('resolveSwapLifecycle', () => {
230
240
  });
231
241
  });
232
242
 
243
+ it.each([
244
+ [{ needsTrustline: true, blocksAction: true }, 'xrpTrustline'],
245
+ [{ needsFunding: true, blocksAction: true }, 'xrpFunding'],
246
+ [{ blockedReason: 'issuer_frozen', blocksAction: true }, 'xrpBlocked'],
247
+ [{ checkFailed: true, blocksAction: true }, 'xrpCheckFailed'],
248
+ ] as const)('blocks on the XRPL gate (%o → %s)', (gate, reason) => {
249
+ expect(resolveSwapLifecycle(inputs({ xrp: { ...OPEN_XRP, isXrpIssuedToken: true, ...gate } }))).toEqual({
250
+ kind: 'needsSetup',
251
+ reason,
252
+ });
253
+ });
254
+
255
+ it('is checking while the XRPL gate resolves, or while a TrustSet and its refreshed check run', () => {
256
+ const xrp = { ...OPEN_XRP, isXrpIssuedToken: true, blocksAction: true };
257
+ expect(resolveSwapLifecycle(inputs({ xrp }))).toEqual({ kind: 'checking' });
258
+ expect(resolveSwapLifecycle(inputs({ xrp: { ...xrp, needsTrustline: true }, setupBusy: true }))).toEqual({
259
+ kind: 'checking',
260
+ });
261
+ // Once the trustline is in place the swap goes ahead.
262
+ expect(resolveSwapLifecycle(inputs({ xrp: { ...OPEN_XRP, isXrpIssuedToken: true } }))).toEqual({
263
+ kind: 'ready',
264
+ approvalStrategy: 'atomic-batch',
265
+ });
266
+ });
267
+
233
268
  it('blocks on NEAR storage, then on the app-owned prerequisite', () => {
234
269
  expect(
235
270
  resolveSwapLifecycle(inputs({ nearStorage: { isNear: true, needsRegistration: true, blocksAction: true } })),
@@ -10,6 +10,7 @@ import {
10
10
  } from '@sodax/sdk';
11
11
  import type { NearStorageGateState } from './nearStorageGate.js';
12
12
  import type { StellarGateState } from './stellarGate.js';
13
+ import type { XrpGateState } from './xrpGate.js';
13
14
 
14
15
  /** A prerequisite the user must resolve before the swap can go out. */
15
16
  export type SwapSetupReason =
@@ -19,6 +20,10 @@ export type SwapSetupReason =
19
20
  | 'stellarCheckFailed'
20
21
  | 'nearStorage'
21
22
  | 'nearStorageCheckFailed'
23
+ | 'xrpTrustline'
24
+ | 'xrpFunding'
25
+ | 'xrpBlocked'
26
+ | 'xrpCheckFailed'
22
27
  | 'external';
23
28
 
24
29
  /**
@@ -77,6 +82,7 @@ export type SwapLifecycleInputs = {
77
82
  stellar: StellarGateState;
78
83
  /** `checkFailed`: the registration check errored, so the swap waits for a retry rather than going out blind. */
79
84
  nearStorage: NearStorageGateState & { checkFailed?: boolean };
85
+ xrp: XrpGateState;
80
86
  externalBlocked: boolean;
81
87
  /** A setup tx is in flight, or the check it invalidated is still refreshing: acting now would resend it. */
82
88
  setupBusy: boolean;
@@ -145,7 +151,7 @@ function toFinishedAttempt(mutation: SwapAttemptSource, attempted: CreateIntentP
145
151
 
146
152
  /**
147
153
  * Derives the lifecycle state. Order: an attempt in flight or broadcast wins; then missing inputs;
148
- * then destination prerequisites (Stellar, NEAR, app-owned); then the source chain; then the
154
+ * then destination prerequisites (Stellar, NEAR, XRPL, app-owned); then the source chain; then the
149
155
  * approval strategy. Pure — `useSwapLifecycle` feeds it from its sub-hooks.
150
156
  */
151
157
  export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycleState {
@@ -175,7 +181,9 @@ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycle
175
181
 
176
182
  const reason = setupReason(inputs);
177
183
  if (reason) return inputs.setupBusy ? { kind: 'checking' } : { kind: 'needsSetup', reason };
178
- if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction) return { kind: 'checking' };
184
+ if (inputs.stellar.blocksAction || inputs.nearStorage.blocksAction || inputs.xrp.blocksAction) {
185
+ return { kind: 'checking' };
186
+ }
179
187
  if (inputs.isWrongChain) return { kind: 'needsChainSwitch' };
180
188
  // A failed refetch keeps the last strategy; `swapWithApproval` resolves its own before sending anyway.
181
189
  if (inputs.strategy.error && !inputs.strategy.data) return { kind: 'failed', error: inputs.strategy.error };
@@ -183,13 +191,17 @@ export function resolveSwapLifecycle(inputs: SwapLifecycleInputs): SwapLifecycle
183
191
  return { kind: 'ready', approvalStrategy: inputs.strategy.data };
184
192
  }
185
193
 
186
- function setupReason({ stellar, nearStorage, externalBlocked }: SwapLifecycleInputs): SwapSetupReason | undefined {
194
+ function setupReason({ stellar, nearStorage, xrp, externalBlocked }: SwapLifecycleInputs): SwapSetupReason | undefined {
187
195
  if (stellar.needsActivation) return 'stellarActivation';
188
196
  if (stellar.needsFunding) return 'stellarFunding';
189
197
  if (stellar.needsTrustline) return 'stellarTrustline';
190
198
  if (stellar.checkFailed) return 'stellarCheckFailed';
191
199
  if (nearStorage.needsRegistration) return 'nearStorage';
192
200
  if (nearStorage.checkFailed) return 'nearStorageCheckFailed';
201
+ if (xrp.blockedReason) return 'xrpBlocked';
202
+ if (xrp.needsFunding) return 'xrpFunding';
203
+ if (xrp.needsTrustline) return 'xrpTrustline';
204
+ if (xrp.checkFailed) return 'xrpCheckFailed';
193
205
  if (externalBlocked) return 'external';
194
206
  return undefined;
195
207
  }
@@ -0,0 +1,112 @@
1
+ import { ChainKeys, type XrpDestinationReadiness } from '@sodax/sdk';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { resolveXrpGate, type XrpCheckResult } from './xrpGate.js';
4
+
5
+ const XRP = ChainKeys.XRP_MAINNET;
6
+
7
+ const resolved = <T>(data: T): XrpCheckResult<T> => ({ isLoading: false, isError: false, data });
8
+ const loading = <T>(): XrpCheckResult<T> => ({ isLoading: true, isError: false, data: undefined });
9
+ const errored = <T>(): XrpCheckResult<T> => ({ isLoading: false, isError: true, data: undefined });
10
+ const idle = <T>(): XrpCheckResult<T> => ({ isLoading: false, isError: false, data: undefined });
11
+
12
+ const refused = (reason: Extract<XrpDestinationReadiness, { ready: false }>['reason']): XrpDestinationReadiness => ({
13
+ ready: false,
14
+ reason,
15
+ });
16
+
17
+ const gate = (
18
+ chainKey: typeof XRP | undefined,
19
+ inputs: {
20
+ readinessCheck?: XrpCheckResult<XrpDestinationReadiness>;
21
+ reserveCheck?: XrpCheckResult<boolean>;
22
+ requiresTrustline?: boolean;
23
+ } = {},
24
+ ) =>
25
+ resolveXrpGate(chainKey, {
26
+ readinessCheck: inputs.readinessCheck ?? resolved({ ready: true }),
27
+ reserveCheck: inputs.reserveCheck ?? idle(),
28
+ requiresTrustline: inputs.requiresTrustline ?? true,
29
+ });
30
+
31
+ const OPEN = {
32
+ isXrpIssuedToken: true,
33
+ needsTrustline: false,
34
+ needsFunding: false,
35
+ blockedReason: undefined,
36
+ checkFailed: false,
37
+ blocksAction: false,
38
+ };
39
+
40
+ describe('resolveXrpGate — what it leaves alone', () => {
41
+ it.each([[ChainKeys.STELLAR_MAINNET], [undefined]])('is inert for %s', chainKey => {
42
+ expect(gate(chainKey as undefined, { readinessCheck: refused('no_trustline') as never })).toMatchObject({
43
+ isXrpIssuedToken: false,
44
+ blocksAction: false,
45
+ });
46
+ });
47
+
48
+ it('is inert for native XRP, which needs no trustline', () => {
49
+ expect(gate(XRP, { requiresTrustline: false, readinessCheck: loading() })).toMatchObject({
50
+ isXrpIssuedToken: false,
51
+ blocksAction: false,
52
+ });
53
+ });
54
+ });
55
+
56
+ describe('resolveXrpGate — an XRPL issued token', () => {
57
+ it('lets the swap through once the destination can receive', () => {
58
+ expect(gate(XRP)).toEqual(OPEN);
59
+ });
60
+
61
+ it('fails closed while the readiness read is loading, and reports a failed read', () => {
62
+ expect(gate(XRP, { readinessCheck: loading() })).toEqual({ ...OPEN, blocksAction: true });
63
+ expect(gate(XRP, { readinessCheck: errored() })).toEqual({ ...OPEN, checkFailed: true, blocksAction: true });
64
+ });
65
+
66
+ it.each([
67
+ 'no_trustline',
68
+ 'trustline_limit',
69
+ ] as const)('asks for a trustline on %s when the account can pay for it', reason => {
70
+ expect(gate(XRP, { readinessCheck: resolved(refused(reason)), reserveCheck: resolved(true) })).toEqual({
71
+ ...OPEN,
72
+ needsTrustline: true,
73
+ blocksAction: true,
74
+ });
75
+ });
76
+
77
+ it('asks for funding when the account cannot pay for the trustline', () => {
78
+ expect(gate(XRP, { readinessCheck: resolved(refused('no_trustline')), reserveCheck: resolved(false) })).toEqual({
79
+ ...OPEN,
80
+ needsFunding: true,
81
+ blocksAction: true,
82
+ });
83
+ });
84
+
85
+ it('fails closed while the reserve read is pending, and reports a failed one', () => {
86
+ const readinessCheck = resolved(refused('no_trustline'));
87
+ expect(gate(XRP, { readinessCheck, reserveCheck: idle() })).toEqual({ ...OPEN, blocksAction: true });
88
+ expect(gate(XRP, { readinessCheck, reserveCheck: loading() })).toEqual({ ...OPEN, blocksAction: true });
89
+ expect(gate(XRP, { readinessCheck, reserveCheck: errored() })).toEqual({
90
+ ...OPEN,
91
+ checkFailed: true,
92
+ blocksAction: true,
93
+ });
94
+ });
95
+
96
+ it.each([
97
+ 'account_not_found',
98
+ 'destination_tag_required',
99
+ 'deposit_auth',
100
+ 'issuer_frozen',
101
+ 'issuer_transfer_fee',
102
+ 'trustline_unauthorized',
103
+ 'trustline_frozen',
104
+ ] as const)('blocks with the reason on %s, which no trustline change fixes', reason => {
105
+ // The reserve is irrelevant here, so even an affordable account gets no trustline action.
106
+ expect(gate(XRP, { readinessCheck: resolved(refused(reason)), reserveCheck: resolved(true) })).toEqual({
107
+ ...OPEN,
108
+ blockedReason: reason,
109
+ blocksAction: true,
110
+ });
111
+ });
112
+ });
@@ -0,0 +1,72 @@
1
+ import { ChainKeys, type SpokeChainKey, type XrpDestinationReadiness } from '@sodax/sdk';
2
+ import type { UseQueryResult } from '@tanstack/react-query';
3
+
4
+ /** The subset of a query result the gate reads. A full `UseQueryResult<T>` satisfies it. */
5
+ export type XrpCheckResult<T> = Pick<UseQueryResult<T>, 'isLoading' | 'isError' | 'data'>;
6
+
7
+ /** A destination refusal the account's own trustline cannot fix. */
8
+ export type XrpBlockedReason = Exclude<
9
+ Extract<XrpDestinationReadiness, { ready: false }>['reason'],
10
+ 'no_trustline' | 'trustline_limit'
11
+ >;
12
+
13
+ export interface XrpGateState {
14
+ /** The destination is XRPL and the token is an issued currency, so a trustline is involved. */
15
+ isXrpIssuedToken: boolean;
16
+ /** The trustline is missing or too small, and the account can afford to set it. */
17
+ needsTrustline: boolean;
18
+ /** The trustline needs setting, but the account lacks the spendable XRP for its fee and reserve. */
19
+ needsFunding: boolean;
20
+ /** Why the destination cannot receive, when no trustline change by the user would fix it. */
21
+ blockedReason: XrpBlockedReason | undefined;
22
+ /** A query failed; disabled or unresolved queries do not set this. */
23
+ checkFailed: boolean;
24
+ /** Whether the downstream action must remain disabled. */
25
+ blocksAction: boolean;
26
+ }
27
+
28
+ export interface XrpGateInputs {
29
+ /** Whether the destination can receive the payout, from the same ledger reads the SDK refuses a swap on. */
30
+ readinessCheck: XrpCheckResult<XrpDestinationReadiness>;
31
+ /** Whether the account can pay for the TrustSet. Only read once the trustline is known to need setting. */
32
+ reserveCheck: XrpCheckResult<boolean>;
33
+ /** Resolve from chain config: false for native XRP. */
34
+ requiresTrustline: boolean;
35
+ }
36
+
37
+ const NOT_XRP_ISSUED_TOKEN: XrpGateState = {
38
+ isXrpIssuedToken: false,
39
+ needsTrustline: false,
40
+ needsFunding: false,
41
+ blockedReason: undefined,
42
+ checkFailed: false,
43
+ blocksAction: false,
44
+ };
45
+
46
+ function unresolved<T>(check: XrpCheckResult<T>): boolean {
47
+ return check.isLoading || check.data === undefined;
48
+ }
49
+
50
+ /**
51
+ * Resolve the XRPL destination prerequisites for an issued token. Native XRP and other chains pass through:
52
+ * the SDK still refuses an unreceivable payout before signing. Unknown states fail closed.
53
+ */
54
+ export function resolveXrpGate(chainKey: SpokeChainKey | undefined, inputs: XrpGateInputs): XrpGateState {
55
+ const { readinessCheck, reserveCheck, requiresTrustline } = inputs;
56
+ if (chainKey !== ChainKeys.XRP_MAINNET || !requiresTrustline) return NOT_XRP_ISSUED_TOKEN;
57
+ const base = { ...NOT_XRP_ISSUED_TOKEN, isXrpIssuedToken: true };
58
+
59
+ if (readinessCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
60
+ const readiness = readinessCheck.data;
61
+ if (readinessCheck.isLoading || readiness === undefined) return { ...base, blocksAction: true };
62
+ if (readiness.ready) return base;
63
+
64
+ if (readiness.reason !== 'no_trustline' && readiness.reason !== 'trustline_limit') {
65
+ return { ...base, blockedReason: readiness.reason, blocksAction: true };
66
+ }
67
+
68
+ if (reserveCheck.isError) return { ...base, checkFailed: true, blocksAction: true };
69
+ if (unresolved(reserveCheck)) return { ...base, blocksAction: true };
70
+ if (reserveCheck.data !== true) return { ...base, needsFunding: true, blocksAction: true };
71
+ return { ...base, needsTrustline: true, blocksAction: true };
72
+ }