|
| 1 | +import { createContext, useContext, useEffect, useState } from 'react' |
| 2 | + |
| 3 | +import { useQuery } from '@tanstack/react-query' |
| 4 | + |
| 5 | +import { apiClient } from './api-client' |
| 6 | + |
| 7 | +import type { KeyStore } from '@trustwallet/wallet-core' |
| 8 | + |
| 9 | +type Wallet = KeyStore.Wallet |
| 10 | + |
| 11 | +type WalletContext = { |
| 12 | + currentWallet: Wallet | null |
| 13 | + wallets: Wallet[] |
| 14 | + isLoading: boolean |
| 15 | + hasWallets: boolean |
| 16 | + setCurrentWallet: (id: Wallet['id']) => void |
| 17 | +} |
| 18 | + |
| 19 | +const WalletContext = createContext<WalletContext | undefined>(undefined) |
| 20 | + |
| 21 | +export function useWallet() { |
| 22 | + const context = useContext(WalletContext) |
| 23 | + if (!context) { |
| 24 | + throw new Error('useWallet must be used within WalletProvider') |
| 25 | + } |
| 26 | + return context |
| 27 | +} |
| 28 | + |
| 29 | +export function WalletProvider({ children }: { children: React.ReactNode }) { |
| 30 | + const [selectedWalletId, setSelectedWalletId] = useState<string | null>(null) |
| 31 | + |
| 32 | + const { data: wallets = [], isLoading } = useQuery({ |
| 33 | + queryKey: ['wallets'], |
| 34 | + queryFn: () => apiClient.wallet.all.query(), |
| 35 | + staleTime: 5 * 60 * 1000, // 5 minutes |
| 36 | + }) |
| 37 | + |
| 38 | + const hasWallets = wallets.length > 0 |
| 39 | + |
| 40 | + const currentWallet = useMemo(() => { |
| 41 | + if (!hasWallets) return null |
| 42 | + |
| 43 | + if (selectedWalletId) { |
| 44 | + const selectedWallet = wallets.find( |
| 45 | + wallet => wallet.id === selectedWalletId, |
| 46 | + ) |
| 47 | + if (selectedWallet) return selectedWallet |
| 48 | + } |
| 49 | + |
| 50 | + return wallets[0] || null |
| 51 | + }, [hasWallets, selectedWalletId, wallets]) |
| 52 | + |
| 53 | + useEffect(() => { |
| 54 | + if (hasWallets && !selectedWalletId && wallets[0]) { |
| 55 | + setSelectedWalletId(wallets[0].id) |
| 56 | + } |
| 57 | + }, [hasWallets, selectedWalletId, wallets]) |
| 58 | + |
| 59 | + const setCurrentWallet = (id: string) => { |
| 60 | + setSelectedWalletId(id) |
| 61 | + } |
| 62 | + |
| 63 | + const contextValue: WalletContext = { |
| 64 | + currentWallet, |
| 65 | + wallets, |
| 66 | + isLoading, |
| 67 | + hasWallets, |
| 68 | + setCurrentWallet, |
| 69 | + } |
| 70 | + |
| 71 | + return ( |
| 72 | + <WalletContext.Provider value={contextValue}> |
| 73 | + {children} |
| 74 | + </WalletContext.Provider> |
| 75 | + ) |
| 76 | +} |
0 commit comments