UNPKG

wallet-engine-lib

Version:

Professional, reusable wallet UI components with Gelato SDK integration. Enterprise-grade React components for building smart wallet applications.

515 lines (394 loc) โ€ข 14 kB
# Wallet Engine Lib A professional, enterprise-grade React component library for building Web3 wallet applications with Gelato's Smart Wallet SDK. Built with TypeScript, featuring comprehensive error handling, accessibility, and production-ready performance optimizations. ## ๐Ÿš€ Features - **๐Ÿ” Smart Wallet Management**: Create and manage ERC-7702 smart wallets with Gelato SDK - **๐Ÿ’ฐ Token Operations**: Mint, transfer, and check token balances across multiple chains - **โšก Gasless Transactions**: Built-in support for Gelato Relay with sponsored gas - **๐ŸŽจ Professional UI**: Beautiful, responsive components with Tailwind CSS - **๐Ÿ›ก๏ธ Type Safety**: Full TypeScript support with comprehensive type definitions - **โ™ฟ Accessibility**: WCAG compliant with ARIA labels and keyboard navigation - **๐Ÿงช Testing**: 100% test coverage with React Testing Library - **๐Ÿ“š Documentation**: Comprehensive API docs and interactive Storybook examples ## ๐Ÿ› ๏ธ Tech Stack - **React 18+** - Modern React with hooks and concurrent features - **TypeScript** - Full type safety and excellent developer experience - **Tailwind CSS** - Utility-first CSS framework for consistent styling - **Vite** - Lightning-fast build tool and development server - **Vitest** - Modern testing framework with excellent performance - **Storybook** - Interactive component documentation and testing ## ๐Ÿ“ฆ Installation ```bash # Using npm npm install wallet-engine-lib # Using pnpm (recommended) pnpm add wallet-engine-lib # Using yarn yarn add wallet-engine-lib ``` ## ๐ŸŽฏ Quick Start ```tsx import { CreateWallet, BalanceChecker, TokenMinter, WalletDetails, ActivityLog } from 'wallet-engine-lib' function App() { const [walletClient, setWalletClient] = useState(null) const handleWalletCreated = (client) => { setWalletClient(client) console.log('Wallet created:', client) } return ( <div className="p-6"> <CreateWallet apiKey="your-gelato-api-key" onWalletCreated={handleWalletCreated} /> <WalletDetails client={walletClient} /> <BalanceChecker client={walletClient} /> <TokenMinter client={walletClient} /> <ActivityLog walletAddress={walletClient?.address} activities={[]} /> </div> ) } ``` ## ๐Ÿงฉ Components ### CreateWallet Create new ERC-7702 smart wallets with a simple, professional interface. ```tsx import { CreateWallet } from 'wallet-engine-lib' <CreateWallet apiKey="your-gelato-api-key" chain={sepolia} // viem chain object onWalletCreated={(client) => console.log('Wallet created:', client)} onError={(error) => console.error('Creation failed:', error)} disabled={false} className="custom-styles" /> ``` **Props:** - `apiKey` (string, required): Gelato API key for wallet creation - `chain` (Chain, optional): Target blockchain network (default: Base Sepolia) - `onWalletCreated` (function, optional): Callback when wallet is created - `onError` (function, optional): Error handling callback - `disabled` (boolean, optional): Disable the component - `className` (string, optional): Additional CSS classes ### BalanceChecker Check wallet balances across multiple tokens and chains with real-time updates. ```tsx import { BalanceChecker } from 'wallet-engine-lib' <BalanceChecker client={walletClient} onRefresh={() => console.log('Refreshing balances')} onError={(error) => console.error('Balance error:', error)} autoRefreshInterval={30000} // 30 seconds disableAutoFetch={false} disabled={false} className="custom-styles" /> ``` **Props:** - `client` (GelatoWalletClient, optional): Connected wallet client - `onRefresh` (function, optional): Manual refresh callback - `onError` (function, optional): Error handling callback - `autoRefreshInterval` (number, optional): Auto-refresh interval in ms - `disableAutoFetch` (boolean, optional): Disable automatic balance fetching - `disabled` (boolean, optional): Disable the component - `className` (string, optional): Additional CSS classes ### TokenMinter Mint new tokens with gasless transaction support and multiple payment methods. ```tsx import { TokenMinter } from 'wallet-engine-lib' <TokenMinter client={walletClient} onMintSuccess={(amount, hash) => console.log('Minted:', amount, hash)} onError={(error) => console.error('Mint error:', error)} maxAmount={1000} disabled={false} className="custom-styles" /> ``` **Props:** - `client` (GelatoWalletClient, optional): Connected wallet client - `onMintSuccess` (function, optional): Success callback with amount and transaction hash - `onError` (function, optional): Error handling callback - `maxAmount` (number, optional): Maximum mint amount (default: 1000) - `disabled` (boolean, optional): Disable the component - `className` (string, optional): Additional CSS classes ### WalletDetails Display comprehensive wallet information, connection status, and network details. ```tsx import { WalletDetails } from 'wallet-engine-lib' <WalletDetails client={walletClient} onAddressCopied={(address) => console.log('Address copied:', address)} onError={(error) => console.error('Error:', error)} showExtendedInfo={true} disabled={false} explorerUrlTemplate="https://etherscan.io/address/{address}" className="custom-styles" /> ``` **Props:** - `client` (GelatoWalletClient, optional): Connected wallet client - `onAddressCopied` (function, optional): Callback when address is copied - `onError` (function, optional): Error handling callback - `showExtendedInfo` (boolean, optional): Show additional wallet information - `disabled` (boolean, optional): Disable the component - `explorerUrlTemplate` (string, optional): Custom explorer URL template - `className` (string, optional): Additional CSS classes ### ActivityLog Professional transaction history with filtering, search, and real-time updates. ```tsx import { ActivityLog } from 'wallet-engine-lib' <ActivityLog walletAddress={walletClient?.address} activities={activityList} onRefresh={() => console.log('Refreshing activities')} onError={(error) => console.error('Activity error:', error)} filterByType="token_mint" filterByStatus="completed" searchQuery="DROP" maxActivities={50} showActivityCount={true} disabled={false} className="custom-styles" /> ``` **Props:** - `walletAddress` (string, required): Wallet address to display activities for - `activities` (ActivityItem[], optional): List of activity items - `onRefresh` (function, optional): Manual refresh callback - `onError` (function, optional): Error handling callback - `filterByType` (string, optional): Filter activities by type - `filterByStatus` (string, optional): Filter activities by status - `searchQuery` (string, optional): Search activities by description - `maxActivities` (number, optional): Maximum activities to display - `showActivityCount` (boolean, optional): Show activity count - `disabled` (boolean, optional): Disable the component - `className` (string, optional): Additional CSS classes ## ๐Ÿช Hooks ### useWallet Manage wallet connection and status. ```tsx import { useWallet } from 'wallet-engine-lib' const { client, isConnected, connect, disconnect } = useWallet() ``` ### useBalance Track token balances and updates. ```tsx import { useBalance } from 'wallet-engine-lib' const { balances, isLoading, error, refresh } = useBalance(client) ``` ### useTokenOperations Handle token minting, transfers, and approvals. ```tsx import { useTokenOperations } from 'wallet-engine-lib' const { mint, transfer, isLoading, error } = useTokenOperations(client) ``` ## ๐Ÿงช Testing ```bash # Run all tests pnpm test # Run tests with coverage pnpm test:coverage # Run tests in watch mode pnpm test:watch # Run tests with UI pnpm test:ui ``` ## ๐Ÿ—๏ธ Development ```bash # Install dependencies pnpm install # Start development server pnpm dev # Start Storybook pnpm storybook # Build library pnpm build # Type checking pnpm type-check # Linting pnpm lint ``` ## ๐Ÿ”ง Configuration ### TypeScript The library is built with TypeScript and provides comprehensive type definitions. All components and utilities are fully typed. ### Styling The library is built with accessibility in mind and includes: #### Built-in Accessibility Features - **ARIA Labels**: All interactive elements have proper ARIA labels - **Keyboard Navigation**: Full keyboard support (Tab, Enter, Escape, Arrow keys) - **Screen Reader Support**: Live announcements for state changes - **Focus Management**: Proper focus handling and visible focus indicators - **Semantic HTML**: Proper HTML structure for screen readers - **Error Handling**: Accessible error messages and announcements #### Accessibility Utilities ```tsx import { announceToScreenReader, getAccessibleErrorMessage, getAccessibilitySupport } from 'wallet-engine-lib' // Announce messages to screen readers announceToScreenReader('Wallet created successfully!', 'polite') // Get user-friendly error messages const userMessage = getAccessibleErrorMessage(error) // Check accessibility support const support = getAccessibilitySupport() console.log('Reduced motion:', support.reducedMotion) ``` #### Testing Accessibility ```tsx import { getAccessibilityChecklist } from 'wallet-engine-lib' // Get accessibility checklist for components const checklist = getAccessibilityChecklist('CreateWallet') checklist.forEach(item => console.log(item)) ``` #### Customization Components can be customized with: - Custom CSS classes via `className` prop - CSS custom properties for theming - Tailwind configuration overrides - Accessibility utilities for custom implementations ### Error Handling All components include comprehensive error handling: - `onError` callbacks for error events - Graceful degradation for disconnected states - User-friendly error messages - Error boundaries for component-level error handling ## ๐Ÿšจ Troubleshooting ### Common Issues **1. "Cannot find module 'wallet-engine-lib'"** ```bash # Make sure the package is installed pnpm add wallet-engine-lib # Check your import statement import { CreateWallet } from 'wallet-engine-lib' ``` **2. TypeScript errors with component props** ```tsx // Make sure you're using the correct types import type { GelatoWalletClient } from 'wallet-engine-lib' const client: GelatoWalletClient = { address: '0x...', chainId: 11155111, isConnected: true } ``` **3. Components not rendering** ```tsx // Check if you have the required props <CreateWallet apiKey="your-api-key" /> // apiKey is required // Make sure you have a wallet client for dependent components <BalanceChecker client={walletClient} /> ``` **4. Styling issues** ```tsx // Make sure Tailwind CSS is included in your project import 'wallet-engine-lib/styles' // Or import the CSS file directly import 'wallet-engine-lib/dist/index.css' ``` ### Performance Optimization **1. Bundle Size** The library is optimized for tree-shaking. Use named imports to reduce bundle size: ```tsx // โœ… Good - only imports what you need import { CreateWallet } from 'wallet-engine-lib' // โŒ Avoid - imports everything import * as WalletLib from 'wallet-engine-lib' ``` **2. Component Memoization** All components are memoized for optimal performance. For custom implementations: ```tsx import React from 'react' const MyComponent = React.memo(({ prop1, prop2 }) => { // Your component logic }) ``` ### Accessibility **1. Screen Readers** All components include proper ARIA labels and semantic HTML. For custom implementations: ```tsx <button aria-label="Create new wallet" aria-describedby="wallet-description" > Create Wallet </button> ``` **2. Keyboard Navigation** Components support full keyboard navigation. Test with: - Tab navigation - Enter/Space for activation - Escape for cancellation ## ๐Ÿ“š Documentation The library includes comprehensive documentation: - **[API Reference](docs/API.md)**: Complete API documentation with examples - **[Performance Guide](docs/PERFORMANCE.md)**: Optimization strategies and best practices - **Storybook**: Interactive component examples and testing ## ๐Ÿ“š API Reference ### Types ```tsx // Wallet client interface interface GelatoWalletClient { address: string chainId: number isConnected: boolean } // Token balance interface interface TokenBalance { symbol: string balance: string decimals: number address: string } // Activity item interface interface ActivityItem { id: string type: 'wallet_created' | 'token_mint' | 'gas_sponsored' | 'balance_change' | 'transaction' status: 'completed' | 'pending' | 'failed' timestamp: Date description: string details?: Record<string, any> } ``` ### Utilities ```tsx // Address formatting import { formatAddress } from 'wallet-engine-lib' const shortAddress = formatAddress('0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6') // Returns: "0x742d35...C4b4d8b6" // Address validation import { validateAddress } from 'wallet-engine-lib' const isValid = validateAddress('0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6') // Returns: true/false // Balance formatting import { formatBalance } from 'wallet-engine-lib' const formatted = formatBalance('1000000000000000000') // Returns: "1.0" ``` ## ๐Ÿค Contributing This is a professional component library built for the Gelato Frontend Engineering Challenge. The codebase follows strict quality standards: - 100% test coverage required - TypeScript strict mode - ESLint with strict rules - Accessibility compliance - Performance optimization ## ๐Ÿ“„ License MIT License - see [LICENSE](LICENSE) file for details. ## ๐Ÿ†˜ Support For issues and questions: - Check the [troubleshooting section](#-troubleshooting) - Review the [API reference](#-api-reference) - Open an issue on GitHub - Check the interactive [Storybook documentation](http://localhost:6006) --- **Built with โค๏ธ for the Gelato Frontend Engineering Challenge**