Repository navigation
Expand file tree
/
Copy pathuseTransaction.tsx
More file actions
476 lines (431 loc) · 16.5 KB
/
Copy pathuseTransaction.tsx
File metadata and controls
476 lines (431 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
'use client';
import { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import type { ReactNode } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Transaction } from '@stellar/stellar-sdk';
import { submitSignedTransaction } from '@/utils/soroban';
import { useToast } from '@/context/ToastContext';
import { useWallet } from '@/context/WalletContext';
import { notifyTxSuccess } from '@/utils/txEvents';
import { recordSigningAttempt } from '@/lib/signing-alert';
import {
canRetryLifecycleStatus,
classifyTransactionError,
isInFlightLifecycleStatus,
type TransactionLifecycleStatus,
} from '@/lib/transaction-lifecycle';
import {
parseContractError,
CONTRACT_ERROR_MAP,
UNKNOWN_CONTRACT_ERROR,
} from '@/lib/contract/errors';
import { formatContractError } from '@/utils/contractErrorFormatter';
import { TransactionErrorToast } from '@/components/transaction/TransactionErrorToast';
import { useTransactionPreview } from './useTransactionPreview';
import type { ExpectedTransactionAction } from '@/utils/transactionPattern';
import { NETWORK_NAME } from '@/constants';
import { normalizeWalletNetwork } from '@/utils/network';
type SignTxFn = (txXdr: string, expectedAction?: ExpectedTransactionAction) => Promise<string>;
type TransactionOperation<T> = (signTx: SignTxFn) => Promise<T>;
export interface ExecuteOptions {
expectedAction?: ExpectedTransactionAction;
idempotencyKey?: string;
title?: string;
pendingMessage?: string;
successTitle?: string;
successMessage?: string;
}
export interface UseTransactionResult {
execute: <T = string>(
txOrOperation: Transaction | TransactionOperation<T>,
options?: string | ExecuteOptions
) => Promise<T | null>;
loading: boolean;
error: string | null;
success: boolean;
isSigning: boolean;
/** Typed lifecycle state; only RPC settlement moves it to confirmed/failed (#1142). */
lifecycleStatus: TransactionLifecycleStatus;
/** Settlement hash when the operation resolved to one. */
txHash: string | null;
signingModal: ReactNode;
}
function isWalletRejection(message: string) {
return /reject|cancel|denied|declined|user rejected|user declined/i.test(message);
}
function getOptions(options?: string | ExecuteOptions): ExecuteOptions {
if (!options) return {};
return typeof options === 'string' ? { title: options } : options;
}
export function useTransaction(): UseTransactionResult {
const { signTx, isConnected, address, networkMismatch, walletNetwork } = useWallet();
const { addToast, updateToast } = useToast();
const queryClient = useQueryClient();
const { previewModal, requestPreview } = useTransactionPreview();
const [loading, setLoading] = useState(false);
const [isSigning, setIsSigning] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [lifecycleStatus, setLifecycleStatus] = useState<TransactionLifecycleStatus>('unsigned');
const [txHash, setTxHash] = useState<string | null>(null);
// Synchronous in-flight guard: a second execute while one is running is
// ignored so retry/reconnect paths can never duplicate a submission (#1143).
const inFlightRef = useRef(false);
const lifecycleRef = useRef<TransactionLifecycleStatus>('unsigned');
/** Advance only forward along unsigned → signed → submitted → confirming. */
const advanceLifecycle = useCallback((next: TransactionLifecycleStatus) => {
const rank: Record<TransactionLifecycleStatus, number> = {
unsigned: 0,
signed: 1,
submitted: 2,
confirming: 3,
confirmed: 4,
failed: -1,
cancelled: -1,
};
const current = lifecycleRef.current;
if (next === 'failed' || next === 'cancelled' || next === 'confirmed') {
lifecycleRef.current = next;
setLifecycleStatus(next);
return;
}
if (rank[next] > rank[current]) {
lifecycleRef.current = next;
setLifecycleStatus(next);
}
}, []);
const setLifecycle = useCallback((next: TransactionLifecycleStatus) => {
lifecycleRef.current = next;
setLifecycleStatus(next);
}, []);
const activeToastIdRef = useRef<string | null>(null);
const inFlightKeysRef = useRef<Set<string>>(new Set());
const confirmedOperationsRef = useRef<Map<string, { result: any; timestamp: number }>>(new Map());
const executeRef = useRef<
| ((
txOrOperation: Transaction | TransactionOperation<any>,
options?: string | ExecuteOptions
) => Promise<any>)
| null
>(null);
// Disconnect recovery: abort in-flight state safely if wallet disconnects while executing (#1147)
useEffect(() => {
if (!isConnected && (loading || isSigning)) {
setLoading(false);
setIsSigning(false);
const msg =
'Wallet disconnected during transaction. Please reconnect your wallet to continue.';
setError(msg);
if (activeToastIdRef.current) {
updateToast(activeToastIdRef.current, {
type: 'error',
title: 'Transaction Interrupted',
message: msg,
});
activeToastIdRef.current = null;
}
inFlightKeysRef.current.clear();
}
}, [isConnected, loading, isSigning, updateToast]);
const signTxWithUi: SignTxFn = useCallback(
async (txXdr: string, expectedAction?: ExpectedTransactionAction) => {
try {
await requestPreview(txXdr, expectedAction);
} catch (err: any) {
const message = err?.message || String(err || 'Transaction cancelled');
if (isWalletRejection(message)) {
throw new Error('Transaction cancelled');
}
throw err;
}
setIsSigning(true);
try {
return await signTx(txXdr);
} catch (err: any) {
const message = err?.message || String(err || 'Transaction cancelled');
if (isWalletRejection(message)) {
throw new Error('Transaction cancelled');
}
throw err;
} finally {
setIsSigning(false);
}
},
[signTx, requestPreview]
);
const execute = useCallback(
async <T = string,>(
txOrOperation: Transaction | TransactionOperation<T>,
options?: string | ExecuteOptions
): Promise<T | null> => {
if (!isConnected || !address) {
setError('Wallet not connected');
return null;
}
// Ignore a second execute while one is in flight: re-submitting would
// duplicate the on-chain action (#1143).
if (inFlightRef.current || isInFlightLifecycleStatus(lifecycleRef.current)) {
return null;
}
// Wrong-network protection: block signing and explain required network before any mutation (#1145)
if (networkMismatch) {
const currentNetwork = walletNetwork ? normalizeWalletNetwork(walletNetwork) : 'unknown';
const msg = `Wrong network detected (${currentNetwork}). Transactions require ${NETWORK_NAME}. Please switch your wallet network to ${NETWORK_NAME} before proceeding.`;
setError(msg);
addToast({
type: 'error',
title: 'Wrong Network Blocked',
message: msg,
});
return null;
}
const resolvedOptions = getOptions(options);
const title = resolvedOptions.title ?? 'Processing transaction...';
const pendingMessage = resolvedOptions.pendingMessage ?? 'Waiting for wallet signature...';
const successTitle = resolvedOptions.successTitle ?? 'Transaction complete';
const successMessage = resolvedOptions.successMessage ?? 'Your transaction was confirmed.';
inFlightRef.current = true;
// Transaction retry idempotency (#1146): deduplicate concurrent or recent duplicate operations
const opKey =
resolvedOptions.idempotencyKey ||
(resolvedOptions.expectedAction
? `${resolvedOptions.expectedAction}:${resolvedOptions.title || ''}`
: resolvedOptions.title || 'generic-operation');
// If identical operation is already in flight, prevent duplicate signing/submission
if (inFlightKeysRef.current.has(opKey)) {
inFlightRef.current = false;
return null;
}
// If already confirmed within 5 minutes, return confirmed result idempotently
const cached = confirmedOperationsRef.current.get(opKey);
if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
inFlightRef.current = false;
return cached.result as T;
}
inFlightKeysRef.current.add(opKey);
setLoading(true);
setError(null);
setSuccess(false);
setTxHash(null);
setLifecycle('unsigned');
const toastId = addToast({
type: 'pending',
title,
message: pendingMessage,
});
activeToastIdRef.current = toastId;
const operation: TransactionOperation<T> =
typeof txOrOperation === 'function'
? txOrOperation
: async (signTx) => {
const { txHash: settledHash } = await submitSignedTransaction({
tx: txOrOperation,
signTx,
pendingLabel: resolvedOptions.expectedAction ?? 'transaction',
onStatus: (stage) => advanceLifecycle(stage),
});
return settledHash as unknown as T;
};
const retry = async () => {
// Only a failed transaction may be retried; cancelled / in-flight /
// confirmed must never re-submit (#1142).
if (!canRetryLifecycleStatus(lifecycleRef.current)) return;
// Clear in-flight lock for idempotency key to allow clean retry (#1146)
inFlightKeysRef.current.delete(opKey);
if (executeRef.current) {
await executeRef.current(txOrOperation, options);
}
};
try {
const signTxForOperation: SignTxFn = async (txXdr) => {
const signed = await signTxWithUi(txXdr, resolvedOptions.expectedAction);
advanceLifecycle('signed');
return signed;
};
// Function operations manage their own submission; mark confirmation
// while awaiting so the lifecycle reflects network truth (#1142).
if (typeof txOrOperation === 'function') {
advanceLifecycle('confirming');
}
const result = await operation(signTxForOperation);
if (typeof result === 'string') setTxHash(result);
// Record confirmed result in idempotency cache
confirmedOperationsRef.current.set(opKey, {
result,
timestamp: Date.now(),
});
// Surface transaction explorer links from confirmed IDs (#1148)
let txHash: string | undefined;
if (typeof result === 'string') {
txHash = result;
} else if (result && typeof result === 'object' && 'txHash' in result) {
const rawHash = (result as { txHash?: unknown }).txHash;
if (typeof rawHash === 'string') {
txHash = rawHash;
}
}
setSuccess(true);
setLifecycle('confirmed');
recordSigningAttempt({
flow: resolvedOptions.expectedAction ?? 'transaction',
success: true,
});
updateToast(toastId, {
type: 'success',
title: successTitle,
message: successMessage,
txHash,
});
activeToastIdRef.current = null;
queryClient.invalidateQueries();
notifyTxSuccess();
return result;
} catch (err: any) {
const classification = classifyTransactionError(err);
// Declined signature / closed wallet: keep every piece of local UI
// state unchanged — no error escalation, no invalidation, no success
// signal, and no retry that could duplicate the action (#1144).
if (classification.kind === 'cancelled') {
setSuccess(false);
setError(null);
setLifecycle('cancelled');
recordSigningAttempt({
flow: resolvedOptions.expectedAction ?? 'transaction',
success: false,
errorCode: 'USER_REJECTED',
errorMessage: classification.message,
});
updateToast(toastId, {
type: 'info',
title: 'Transaction cancelled',
message: 'Signature declined in wallet. No changes were made.',
});
activeToastIdRef.current = null;
return null;
}
// Wrong network: block signing safely until the wallet switches.
// No retry is offered — retrying on the wrong network cannot settle
// and risks a duplicate once the network changes (#1144).
if (classification.kind === 'wrong-network') {
setSuccess(false);
setError(classification.message);
setLifecycle('failed');
recordSigningAttempt({
flow: resolvedOptions.expectedAction ?? 'transaction',
success: false,
errorCode: 'NETWORK_MISMATCH',
errorMessage: classification.message,
});
updateToast(toastId, {
type: 'error',
title: 'Wrong network',
message: `${classification.message}. Switch your wallet to ${resolvedOptions.expectedAction ? 'the required' : 'the correct'} network, then try again. No changes were made.`,
});
activeToastIdRef.current = null;
return null;
}
const formattedErr = formatContractError(err);
const message = formattedErr.message;
const isRejected = formattedErr.code === 'USER_REJECTED' || isWalletRejection(message);
setError(formattedErr.userFriendlyMessage);
setSuccess(false);
setLifecycle(isRejected ? 'cancelled' : 'failed');
recordSigningAttempt({
flow: resolvedOptions.expectedAction ?? 'transaction',
success: false,
errorCode: isRejected ? 'USER_REJECTED' : formattedErr.code,
errorMessage: message,
});
let title = 'Transaction failed';
let toastMessage: React.ReactNode = `${message}. Please try again or contact support if the issue persists.`;
if (isRejected) {
title = 'Transaction cancelled';
toastMessage = 'Transaction cancelled';
} else {
const code = parseContractError(err);
const errorInfo = code ? CONTRACT_ERROR_MAP[code] : UNKNOWN_CONTRACT_ERROR;
title = errorInfo.title;
const hasTechnicalDetails =
!!code ||
(message && message !== 'Transaction failed.' && message !== errorInfo.message);
const technicalDetails = hasTechnicalDetails
? code
? `${code}\n${message}`
: message
: undefined;
toastMessage = (
<TransactionErrorToast
message={errorInfo.message}
remediation={errorInfo.remediation}
technicalDetails={technicalDetails}
/>
);
}
updateToast(toastId, {
type: 'error',
title,
message: toastMessage,
action: isRejected
? undefined
: {
label: 'Retry',
onClick: retry,
},
});
activeToastIdRef.current = null;
return null;
} finally {
inFlightRef.current = false;
inFlightKeysRef.current.delete(opKey);
setLoading(false);
setIsSigning(false);
}
},
[
address,
addToast,
advanceLifecycle,
isConnected,
networkMismatch,
walletNetwork,
queryClient,
setLifecycle,
signTxWithUi,
updateToast,
]
);
useEffect(() => {
executeRef.current = execute;
}, [execute]);
const signingModal = useMemo(() => {
if (!isSigning) return null;
return (
<div className="fixed inset-0 z-[999] flex items-center justify-center bg-black/50 p-4">
<div className="w-full max-w-md rounded-[32px] border border-surface-variant bg-surface-container-lowest p-8 text-center shadow-2xl">
<div className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 text-primary">
<span className="material-symbols-outlined animate-spin text-3xl">sync</span>
</div>
<h2 className="text-xl font-bold">Waiting for wallet signature...</h2>
<p className="mt-3 text-sm text-on-surface-variant">
Please approve the transaction in your wallet to continue.
</p>
</div>
</div>
);
}, [isSigning]);
return {
execute,
loading,
error,
success,
isSigning,
lifecycleStatus,
txHash,
signingModal: (
<>
{previewModal}
{signingModal}
</>
),
};
}