forked from SmartDropLabs/smartdrop-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSorobanQuery.ts
More file actions
654 lines (599 loc) · 18.7 KB
/
Copy pathuseSorobanQuery.ts
File metadata and controls
654 lines (599 loc) · 18.7 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/**
* Custom React Query hooks for Soroban contract interactions
* Provides caching, error handling, and automatic refetching
*/
import { useEffect, useRef, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
getStellarBalance,
rpcServer,
simulateLockAssets,
simulateUnlockAssets,
sorobanService,
type UserPosition,
type TransactionResult,
} from '@/lib/soroban';
import { useStellarWallet } from '@/context/StellarWalletContext';
import { useToast } from '@chakra-ui/react';
// Query Keys
export const QUERY_KEYS = {
POOLS: 'pools',
USER_POSITION: 'userPosition',
USER_CREDITS: 'userCredits',
PLATFORM_STATS: 'platformStats',
BOOST_CONFIG: 'boostConfig',
} as const;
/**
* Hook to fetch all available farming pools
*/
export const usePools = () => {
return useQuery({
queryKey: [QUERY_KEYS.POOLS],
queryFn: () => sorobanService.getFactoryPools(),
staleTime: 30000, // 30 seconds
gcTime: 5 * 60 * 1000, // 5 minutes
refetchInterval: 60000, // 1 minute
retry: 3,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
});
};
/**
* Hook to fetch a pool's top depositors, replacing the one-shot
* getPoolDepositors() useEffect PoolDetailClient used to call directly
* (#143) — this way depositor data also refreshes on an interval instead
* of being frozen at mount for the lifetime of the page view.
*/
export const usePoolDepositors = (poolId: string, limit: number = 20) => {
return useQuery({
queryKey: ['poolDepositors', poolId, limit],
queryFn: () => sorobanService.getPoolDepositors(poolId, limit),
enabled: !!poolId,
staleTime: 30000,
gcTime: 5 * 60 * 1000,
refetchInterval: 60000,
retry: 2,
});
};
/**
* Hook to fetch user position for a specific pool
*/
export const useUserPosition = (poolId: string, enabled: boolean = true) => {
const { publicKey } = useStellarWallet();
return useQuery({
queryKey: [QUERY_KEYS.USER_POSITION, poolId, publicKey],
queryFn: () => sorobanService.getUserPosition(poolId, publicKey!),
enabled: enabled && !!publicKey && !!poolId,
staleTime: 15000, // 15 seconds
gcTime: 5 * 60 * 1000,
refetchInterval: 30000, // 30 seconds
retry: 2,
});
};
/**
* Hook to calculate user credits for a specific pool
*/
export const useUserCredits = (poolId: string, enabled: boolean = true) => {
const { publicKey } = useStellarWallet();
return useQuery({
queryKey: [QUERY_KEYS.USER_CREDITS, poolId, publicKey],
queryFn: () => sorobanService.calculateUserCredits(poolId, publicKey!),
enabled: enabled && !!publicKey && !!poolId,
staleTime: 5000, // 5 seconds (credits change frequently)
gcTime: 5 * 60 * 1000,
refetchInterval: 10000, // 10 seconds
retry: 2,
});
};
export const useStellarBalance = (publicKey?: string) => {
return useQuery({
queryKey: ['stellarBalance', publicKey],
queryFn: () => getStellarBalance(publicKey!),
enabled: !!publicKey,
staleTime: 15000,
gcTime: 5 * 60 * 1000,
retry: 2,
});
};
// Matches the debounce pattern already used for search input elsewhere in
// this codebase (`useLeaderboard`'s `SEARCH_DEBOUNCE_MS`).
const LOCK_ASSETS_FEE_PREVIEW_DEBOUNCE_MS = 350;
/**
* Debounced so a keystroke burst in the deposit amount field doesn't fire a
* `simulateTransaction` RPC round trip per keystroke (#134) — the query
* only keys/fires on `amount` once it has stopped changing for
* `LOCK_ASSETS_FEE_PREVIEW_DEBOUNCE_MS`. Debouncing here, inside the hook,
* means every caller gets the fix automatically rather than each call site
* having to remember to debounce its own input state.
*/
export const useLockAssetsFeePreview = (args: {
publicKey?: string | null;
poolContractId?: string | null;
amount?: string;
}) => {
const amount = args.amount?.trim() ?? '';
// Starts empty (not seeded from `amount`) so a caller that mounts with a
// non-empty amount already still goes through the debounce window once,
// the same as any other change — matching `useLeaderboard`'s
// `searchQuery`/`searchInput` split, which starts `searchQuery` at `""`
// rather than at the initial `searchInput` value.
const [debouncedAmount, setDebouncedAmount] = useState('');
useEffect(() => {
const id = setTimeout(
() => setDebouncedAmount(amount),
LOCK_ASSETS_FEE_PREVIEW_DEBOUNCE_MS,
);
return () => clearTimeout(id);
}, [amount]);
const numericAmount = Number(debouncedAmount);
// A live amount that hasn't settled into debouncedAmount yet is not
// reflected in the query at all (queryKey/queryFn/enabled all read
// debouncedAmount below) — surface that as "still fetching" so UI keyed
// off isFetching shows a pending state for the whole debounce window,
// not just the network request that follows it.
const isDebouncing = amount !== debouncedAmount;
const query = useQuery({
queryKey: [
'lockAssetsFeePreview',
args.publicKey,
args.poolContractId,
debouncedAmount,
],
queryFn: () =>
simulateLockAssets({
publicKey: args.publicKey!,
poolContractId: args.poolContractId!,
amount: debouncedAmount,
}),
enabled:
!!args.publicKey &&
!!args.poolContractId &&
!!debouncedAmount &&
Number.isFinite(numericAmount) &&
numericAmount > 0,
staleTime: 10000,
gcTime: 5 * 60 * 1000,
retry: 1,
});
return { ...query, isFetching: query.isFetching || isDebouncing };
};
/**
* Same live, debounced fee-preview pattern as useLockAssetsFeePreview, for
* unlock_assets — issue #240: UnlockModal submitted transactions with no fee
* estimate shown before the Freighter signing prompt.
*/
export const useUnlockAssetsFeePreview = (args: {
publicKey?: string | null;
poolContractId?: string | null;
amount?: string;
}) => {
const amount = args.amount?.trim() ?? '';
const [debouncedAmount, setDebouncedAmount] = useState('');
useEffect(() => {
const id = setTimeout(
() => setDebouncedAmount(amount),
LOCK_ASSETS_FEE_PREVIEW_DEBOUNCE_MS,
);
return () => clearTimeout(id);
}, [amount]);
const numericAmount = Number(debouncedAmount);
const isDebouncing = amount !== debouncedAmount;
const query = useQuery({
queryKey: [
'unlockAssetsFeePreview',
args.publicKey,
args.poolContractId,
debouncedAmount,
],
queryFn: () =>
simulateUnlockAssets({
publicKey: args.publicKey!,
poolContractId: args.poolContractId!,
amount: debouncedAmount,
}),
enabled:
!!args.publicKey &&
!!args.poolContractId &&
!!debouncedAmount &&
Number.isFinite(numericAmount) &&
numericAmount > 0,
staleTime: 10000,
gcTime: 5 * 60 * 1000,
retry: 1,
});
return { ...query, isFetching: query.isFetching || isDebouncing };
};
/**
* Hook to lock assets in a pool.
*
* Accepts an optional onStep callback so callers can drive step-by-step UI
* without coupling the mutation to internal implementation details.
*/
export const useLockAssets = (options?: {
onHash?: (hash: string) => void;
onStep?: (step: "simulating" | "signing" | "submitting") => void;
}) => {
const { walletApi, publicKey } = useStellarWallet();
const queryClient = useQueryClient();
const toast = useToast();
const walletApiRef = useRef(walletApi);
walletApiRef.current = walletApi;
return useMutation({
mutationFn: async ({
poolId,
amount,
}: {
poolId: string;
amount: string;
}) => {
if (!walletApi || !publicKey) {
throw new Error('Wallet not connected. Please connect Freighter before depositing.');
}
const result = await sorobanService.lockAssets(
poolId,
publicKey,
amount,
walletApi,
{
onHash: options?.onHash,
onStep: options?.onStep,
},
() => walletApiRef.current === walletApi,
);
return result;
},
onSuccess: (result: TransactionResult, variables) => {
if (result.success) {
const shortHash = (result.transactionHash ?? result.hash ?? "").slice(0, 10);
toast({
title: 'Assets locked',
description: shortHash ? `Tx ${shortHash}… confirmed` : 'Deposit confirmed on Stellar',
status: 'success',
duration: 6000,
isClosable: true,
});
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.POOLS] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_POSITION] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_POSITION, variables.poolId] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_POSITION, 'all', publicKey] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.USER_CREDITS, variables.poolId] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.PLATFORM_STATS] });
queryClient.invalidateQueries({ queryKey: ['stellarBalance', publicKey] });
} else {
toast({
title: 'Deposit failed',
description: result.error ?? 'Unknown error — please try again',
status: 'error',
duration: 8000,
isClosable: true,
});
}
},
onError: (error: Error) => {
toast({
title: 'Transaction error',
description: error.message,
status: 'error',
duration: 8000,
isClosable: true,
});
},
});
};
/**
* Hook to unlock assets from a pool
*/
export const useUnlockAssets = () => {
const { walletApi, publicKey } = useStellarWallet();
const queryClient = useQueryClient();
const toast = useToast();
const walletApiRef = useRef(walletApi);
walletApiRef.current = walletApi;
return useMutation({
mutationFn: async ({
poolId,
amount,
}: {
poolId: string;
amount: string;
}) => {
if (!walletApi || !publicKey) {
throw new Error('Wallet not connected');
}
return sorobanService.unlockAssets(
poolId,
publicKey,
amount,
walletApi,
undefined,
() => walletApiRef.current === walletApi,
);
},
onSuccess: (result: TransactionResult, variables) => {
if (result.success) {
toast({
title: 'Assets Unlocked Successfully',
description: `Transaction: ${result.transactionHash?.slice(0, 8)}...`,
status: 'success',
duration: 5000,
isClosable: true,
});
// Invalidate related queries
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.USER_POSITION, variables.poolId],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.USER_CREDITS, variables.poolId],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.PLATFORM_STATS],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.POOLS],
});
// Unlocking returns principal to the user's own account, directly
// changing spendable balance — must invalidate like useLockAssets
// does, or "Available balance" in the Deposit modal serves a stale
// value for up to staleTime (issue #138).
queryClient.invalidateQueries({
queryKey: ['stellarBalance', publicKey],
});
} else {
toast({
title: 'Unlock Assets Failed',
description: result.error || 'Unknown error occurred',
status: 'error',
duration: 8000,
isClosable: true,
});
}
},
onError: (error: Error) => {
toast({
title: 'Transaction Error',
description: error.message,
status: 'error',
duration: 8000,
isClosable: true,
});
},
});
};
/**
* Hook to set boost configuration
*/
export const useSetBoost = () => {
const { walletApi, publicKey } = useStellarWallet();
const queryClient = useQueryClient();
const toast = useToast();
return useMutation({
mutationFn: async ({
poolId,
allocationPercentage,
}: {
poolId: string;
allocationPercentage: number;
}) => {
if (!walletApi || !publicKey) {
throw new Error('Wallet not connected');
}
return sorobanService.setBoost(poolId, publicKey, allocationPercentage, walletApi);
},
onSuccess: (result: TransactionResult, variables) => {
if (result.success) {
toast({
title: 'Boost Configuration Updated',
description: `Boost set to ${variables.allocationPercentage}%`,
status: 'success',
duration: 5000,
isClosable: true,
});
// Invalidate related queries
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.USER_POSITION, variables.poolId],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.USER_CREDITS, variables.poolId],
});
queryClient.invalidateQueries({
queryKey: [QUERY_KEYS.BOOST_CONFIG, variables.poolId],
});
} else {
toast({
title: 'Boost Configuration Failed',
description: result.error || 'Unknown error occurred',
status: 'error',
duration: 8000,
isClosable: true,
});
}
},
onError: (error: Error) => {
toast({
title: 'Transaction Error',
description: error.message,
status: 'error',
duration: 8000,
isClosable: true,
});
},
});
};
/**
* Hook to get all user positions across all pools
*/
export const useAllUserPositions = () => {
const { publicKey } = useStellarWallet();
const { data: pools } = usePools();
return useQuery({
queryKey: [QUERY_KEYS.USER_POSITION, 'all', publicKey],
queryFn: async () => {
if (!publicKey || !pools) return [];
const positions = await Promise.allSettled(
pools.map(pool => sorobanService.getUserPosition(pool.id, publicKey))
);
return positions
.map((result, index) => ({
pool: pools[index],
position: result.status === 'fulfilled' ? result.value : null,
}))
.filter(item => item.position !== null);
},
enabled: !!publicKey && !!pools && pools.length > 0,
staleTime: 15000,
gcTime: 5 * 60 * 1000,
refetchInterval: 30000,
});
};
/**
* Hook to get total user credits across all pools
*/
export const useTotalUserCredits = () => {
const { publicKey } = useStellarWallet();
const { data: pools } = usePools();
return useQuery({
queryKey: [QUERY_KEYS.USER_CREDITS, 'total', publicKey],
queryFn: async () => {
if (!publicKey || !pools) return '0';
const credits = await Promise.allSettled(
pools.map(pool => sorobanService.calculateUserCredits(pool.id, publicKey))
);
const totalCredits = credits.reduce((total, result) => {
if (result.status === 'fulfilled') {
return total + parseFloat(result.value);
}
return total;
}, 0);
return totalCredits.toString();
},
enabled: !!publicKey && !!pools && pools.length > 0,
staleTime: 10000,
gcTime: 5 * 60 * 1000,
refetchInterval: 15000,
});
};
/**
* Hook for real-time updates with optimistic UI updates
*/
export const useOptimisticUpdate = () => {
const queryClient = useQueryClient();
const updateUserPosition = (
poolId: string,
userAddress: string,
updateFn: (old: UserPosition | null) => UserPosition | null
) => {
queryClient.setQueryData(
[QUERY_KEYS.USER_POSITION, poolId, userAddress],
updateFn
);
};
const updateCredits = (
poolId: string,
userAddress: string,
newCredits: string
) => {
queryClient.setQueryData(
[QUERY_KEYS.USER_CREDITS, poolId, userAddress],
newCredits
);
};
const updatePlatformStats = (
updateFn: (old: UIPlatformStats | undefined) => UIPlatformStats
) => {
queryClient.setQueryData([QUERY_KEYS.PLATFORM_STATS], updateFn);
};
return {
updateUserPosition,
updateCredits,
updatePlatformStats,
};
};
/**
* Hook for managing loading states across multiple operations
*/
export const useTransactionStates = () => {
const lockMutation = useLockAssets();
const unlockMutation = useUnlockAssets();
const boostMutation = useSetBoost();
const isLoading =
lockMutation.isPending ||
unlockMutation.isPending ||
boostMutation.isPending;
const hasError =
lockMutation.isError ||
unlockMutation.isError ||
boostMutation.isError;
const error =
lockMutation.error ||
unlockMutation.error ||
boostMutation.error;
const reset = () => {
lockMutation.reset();
unlockMutation.reset();
boostMutation.reset();
};
return {
isLoading,
hasError,
error,
reset,
lockAssets: lockMutation.mutate,
unlockAssets: unlockMutation.mutate,
setBoost: boostMutation.mutate,
};
};
export interface UIPlatformStats {
tvl: string;
activePools: number;
totalFarmers: number;
creditVelocity: string;
totalValueLocked?: string;
totalPools?: number;
totalUsers?: number;
onlineUsers?: number;
}
export function usePlatformStats(initialData?: UIPlatformStats) {
return useQuery<UIPlatformStats>({
queryKey: [QUERY_KEYS.PLATFORM_STATS],
queryFn: async () => {
const [stats, velocity] = await Promise.all([
sorobanService.getPlatformStats(),
sorobanService.getCreditVelocity(24)
]);
return {
tvl: stats.totalValueLocked || "0",
activePools: stats.totalPools || 0,
totalFarmers: stats.totalUsers || 0,
creditVelocity: velocity,
totalValueLocked: stats.totalValueLocked,
totalPools: stats.totalPools,
totalUsers: stats.totalUsers,
onlineUsers: stats.onlineUsers,
};
},
staleTime: 60000, // Keeps data fresh for 1 minute
gcTime: 5 * 60 * 1000,
refetchInterval: 120000, // Re-checks the blockchain automatically every 2 minutes
initialData: initialData
});
}
/**
* Global Soroban RPC connectivity check (issue #248). When the RPC endpoint
* is unreachable, individual pages each show their own query error with no
* indication it's a shared, RPC-wide outage rather than a one-off failure.
* A single, cheap getHealth() poll gives a global "is the chain reachable"
* signal a top-level banner can react to.
*/
export function useRpcHealth() {
const query = useQuery({
queryKey: ['rpcHealth'],
queryFn: () => rpcServer.getHealth(),
staleTime: 15000,
gcTime: 5 * 60 * 1000,
refetchInterval: 30000,
retry: 1,
// Never let this surface a spinner/blank state anywhere it's used —
// it's a background signal, not something a page should block on.
refetchOnWindowFocus: true,
});
return { isUnreachable: query.isError };
}