# Authentication URL: /docs/authentication Deep dive into Bitcoin-based authentication flows *** title: Authentication description: Deep dive into Bitcoin-based authentication flows -------------------------------------------------------------- # Authentication Learn how Bitcoin-based authentication works in BigBlocks. ## Overview BigBlocks implements `bitcoin-auth`, using public-private key pairs as a primary authentication mechanism. This enables compatibility with Identity related blocks, which use [Bitcoin Attestation Protocol](https://github.com/b-open-io/bap) under the hood to establish a self-sovereign identity. ## Key Principles ### 1. Client-Side Key Generation * Private keys are generated on the client, never shared with the backend * Componenets never directly expose keys with two exceptions: * local backup componenets: downloads encrypted/unencrypted backup files, * cloud backup componenets uploads encrypted backups to the cloud * Keys never leave the user's device unencrypted * Leverages cryptographic standards like: * Type42 key derivation for identity * BRC77 message signing for authentication ### 2. Password Encryption * Users set a password to encrypt their private keys * Password is used for local encryption only * Lost passwords cannot be recovered (by design) * `bitcoin-backup` encryption functions for storing encrypted backups ### 3. OAuth Backup Storage * Encrypted backups stored via OAuth providers (Google, GitHub, X) * OAuth is used for storage only, not authentication * Multiple backup locations for redundancy ### 4. BSM/BRC77 Authentication * Bitcoin Signed Messages (BSM) or BRC77 can be used to authenticate API requests * `bitcoin-auth` abstracts the underlying auth token generation * Time-bound signatures prevent replay attacks * body-bound signatures ensure the message is not tampered with * Bigblocks provides compatibility with JWT based authentication flows ## Authentication Components ### AuthFlowOrchestrator Complete authentication flow management: ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; function AuthPage() { return ( { console.log('Authenticated:', user); }} onError={(error) => { console.error('Auth failed:', error); }} /> ); } ``` ### LoginForm Standalone login component: ```tsx import { LoginForm } from 'bigblocks'; function LoginPage() { return ( router.push('/dashboard')} showBackupImport={true} showOAuthRestore={true} /> ); } ``` ### SignupFlow Multi-step signup process: ```tsx import { SignupFlow } from 'bigblocks'; function SignupPage() { return ( { console.log('Signup complete:', user); }} /> ); } ``` ## Authentication Flow ### 1. New User Signup ```mermaid graph TD A[User Clicks Signup] --> B[Generate HD Keys] B --> C[User Sets Password] C --> D[Encrypt Private Keys] D --> E[Create BAP Identity] E --> F[OAuth Backup Storage] F --> G[Authentication Complete] ``` ### 2. Existing User Login ```mermaid graph TD A[User Enters Password] --> B[Decrypt Local Storage] B --> C{Keys Found?} C -->|Yes| D[Authenticate with BSM] C -->|No| E[Import from Backup] E --> F[OAuth Provider Selection] F --> G[Download Encrypted Backup] G --> H[Decrypt with Password] H --> D ``` ### 3. OAuth Restore Flow ```tsx import { OAuthRestoreFlow } from 'bigblocks'; function RestorePage() { return ( { console.log('Backup restored:', backup); }} /> ); } ``` ## API Authentication ### Setting Up API Routes ```typescript // api/protected/route.ts import { verifyBSM } from 'bigblocks/auth'; export async function POST(request: Request) { try { const { address, signature, message } = await request.json(); // Verify the BSM signature const isValid = await verifyBSM({ address, signature, message, maxAge: 600 // 10 minutes }); if (!isValid) { return new Response('Unauthorized', { status: 401 }); } // Process authenticated request return new Response('Success'); } catch (error) { return new Response('Invalid signature', { status: 401 }); } } ``` ### Client-Side API Calls ```typescript import { useAuth, signMessage } from 'bigblocks'; function MyComponent() { const { address, privateKey } = useAuth(); const callAPI = async () => { const message = `Authenticate ${Date.now()}`; const signature = await signMessage(message, privateKey); const response = await fetch('/api/protected', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ address, signature, message, }), }); }; } ``` ## Security Considerations ### Password Requirements * Minimum 8 characters recommended * Password strength indicator included * No password recovery possible (feature, not bug) ### Backup Security * Backups are AES-256 encrypted * Encryption happens client-side * OAuth providers cannot decrypt backups * Multiple backup locations recommended ### Key Storage * Keys stored in browser's localStorage * Always encrypted at rest * Session storage for temporary decryption * Auto-lock after inactivity ## Best Practices 1. **Always use HTTPS** in production 2. **Implement rate limiting** on authentication endpoints 3. **Use time-bound signatures** for API calls 4. **Educate users** about password importance 5. **Provide backup download** options 6. **Test restore flows** thoroughly ## Troubleshooting ### Common Issues **"Invalid signature" errors** * Check system clock synchronization * Verify message format matches * Ensure private key is correct **"Backup not found" errors** * User may have wrong OAuth account * Check all linked providers * Verify backup was created **"Decryption failed" errors** * Wrong password entered * Backup may be corrupted * Try alternative backup sources ## Next Steps * Implement [Profile Management](/docs/components/profiles) * Add [Social Features](/docs/components/social) * Set up [Wallet Integration](/docs/components/wallet) # Components Overview URL: /docs/components Full reference for all BigBlocks components *** title: Components Overview description: Full reference for all BigBlocks components -------------------------------------------------------- # Components Overview BigBlocks provides 96+ production-ready components organized into logical categories. ## Component Categories ### Authentication Components Core components for Bitcoin-based authentication flows. ```tsx import { AuthButton } from 'bigblocks'; // Simple authentication button // With custom text Sign In with Bitcoin // With callback console.log('Authenticated:', user)} /> ``` **Key Components:** * `AuthFlowOrchestrator` - Complete authentication flow * `LoginForm` - Standalone login interface * `SignupFlow` - Multi-step signup process * `OAuthProviders` - OAuth provider selection * `BackupImport` - Import encrypted backups * `PasswordInput` - Secure password field ### Profile & Identity Manage Bitcoin Attestation Protocol (BAP) profiles. ```tsx import { ProfileCard } from 'bigblocks'; console.log('Edit profile')} onViewDetails={() => console.log('View details')} /> ``` **Key Components:** * `ProfileCard` - Display user profiles * `ProfileEditor` - Edit profile information * `ProfileSwitcher` - Switch between identities * `ProfileManager` - Complete profile system * `IdentityGeneration` - Create new identities ### Wallet Components Bitcoin wallet functionality and transaction management. **Key Components:** * `WalletConnect` - Connect wallets * `WalletOverview` - Display balance and history * `SendBSVButton` - Send Bitcoin transactions * `DonateButton` - Accept donations * `TokenBalance` - Display token balances * `TransactionHistory` - Show transaction list ### Social Components Build social features with on-chain interactions. **Key Components:** * `PostCard` - Display social posts * `PostButton` - Create new posts * `LikeButton` - Like content on-chain * `FollowButton` - Follow users * `SocialFeed` - Content feed display * `FriendsDialog` - Manage connections ### Market Components Ordinals marketplace and trading functionality. **Key Components:** * `MarketTable` - Display marketplace listings * `CreateListingButton` - List items for sale * `BuyListingButton` - Purchase items * `CompactMarketTable` - Minimal market view ### MetaLens Commenting System Universal commenting for any context type. **Key Components:** * `MetaLensProvider` - Commenting system provider * `MetaLensComments` - Full commenting interface * `MetaLensBadge` - Comment count badges * `MetaLensEmbed` - Embedded comments * `MetaLensReactions` - Like/reaction system * `MetaLensThread` - Threaded discussions ### UI Primitives Basic building blocks for your application. ```tsx import { LoadingButton, StepIndicator, WarningCard, ErrorDisplay } from 'bigblocks'; // Loading button states Save Saving... // Multi-step indicator // Warning messages This action cannot be undone. // Error handling ``` **Key Components:** * `Modal` - Accessible modal dialogs * `LoadingButton` - Button with loading states * `ErrorDisplay` - Error message display * `SuccessLayout` - Success confirmations * `StepIndicator` - Multi-step indicators * `TerminalCodeBlock` - Code display ### Advanced BAP Components Advanced Bitcoin Attestation Protocol features. **Key Components:** * `KeyManager` - HD key management * `BapEncryption` - Encrypt/decrypt data * `FileSignature` - Sign files * `KeyRotation` - Rotate keys * `Type42KeyDerivation` - Advanced derivation * `ShamirSecretSharing` - Split keys ## Component Requirements ### Provider Requirements Most components require these providers: ```tsx {/* Your components */} ``` ### Authentication Requirements Components are marked with requirement badges: * **No Auth Required** - Works without authentication * **Auth Required** - Requires signed-in user * **Funding Required** - Needs BSV balance * **Droplit Required** - Uses gasless transactions ## Using Components ### Import Components ```tsx import { AuthButton, ProfileCard, WalletOverview } from 'bigblocks'; ``` ### Add Individual Components ```bash npx bigblocks add AuthButton ProfileCard ``` ### Component Props All components are fully typed with TypeScript. Use your IDE's IntelliSense for prop discovery or refer to individual component documentation. ## Next Steps * Browse the [Component Browser](/components) for live demos * Check [Component Examples](/docs/examples) for usage patterns * Read about [Theme Customization](/docs/themes) # Documentation URL: /docs BigBlocks documentation overview *** title: Documentation description: BigBlocks documentation overview --------------------------------------------- # Documentation Welcome to the BigBlocks documentation. Choose a section below to get started: ## Getting Started * [What is BigBlocks?](/docs/introduction/what-is-bigblocks) - Overview and key features * [Quick Start](/docs/introduction/quickstart) - Get up and running fast ## Core Documentation * [Authentication](/docs/authentication) - Bitcoin auth system * [Components](/docs/components) - 96+ production-ready components * [MCP Server](/docs/mcp-server) - AI assistant integration * [MetaLens](/docs/metalens) - Universal commenting system ## External Resources * [LLMs.txt](/llms.txt) - AI-readable documentation format # MetaLens Commenting System URL: /docs/metalens Universal commenting system for any context *** title: MetaLens Commenting System description: Universal commenting system for any context -------------------------------------------------------- # MetaLens Commenting System MetaLens is a universal commenting system that enables comments on any context type - URLs, transactions, geohashes, ISBNs, and more. ## Overview MetaLens provides a complete commenting solution with: * Zero-cost transactions via Droplit integration * Full B:// and MAP protocol support * Real-time updates * Moderation capabilities * Multiple context types ## Supported Context Types * `url` - Web pages and resources * `tx` - Bitcoin transactions * `upc` - Product barcodes * `geohash` - Geographic locations * `ipfs` - IPFS content hashes * `isbn` - Books and publications * `doi` - Digital object identifiers ## Basic Usage ### Simple Comments Section ```tsx import { MetaLensProvider, MetaLensComments } from 'bigblocks'; function MyPage() { return ( ); } ``` ### Comment Count Badge Display comment counts inline with content: ```tsx ``` ### Reactions Add likes and reactions to any content: ```tsx ``` ## Advanced Features ### Threaded Discussions Enable nested comment threads: ```tsx ``` ### Embedded Comments Lightweight comment widget: ```tsx ``` ### Custom Styling MetaLens components support custom styling: ```tsx ``` ## Configuration ### Provider Options ```tsx {children} ``` ### Comment Options ```tsx console.log('New comment:', comment)} onError={(error) => console.error('Comment error:', error)} /> ``` ## Integration Examples ### E-commerce Product Comments ```tsx function ProductPage({ productUPC }) { return (

Product Name

); } ``` ### Transaction Explorer Comments ```tsx function TransactionDetails({ txid }) { return (

Transaction {txid}

); } ``` ### Location-Based Comments ```tsx function LocationComments({ latitude, longitude }) { const geohash = encodeGeohash(latitude, longitude); return ( ); } ``` ## Zero-Cost Transactions MetaLens uses Droplit integration for gasless operations: 1. Comments are created without requiring BSV balance 2. Droplit handles transaction fees 3. Comments are still recorded on-chain 4. Full ownership and immutability preserved ## Data Structure MetaLens comments follow the MAP protocol: ```json { "app": "metalens", "type": "comment", "context": "url", "contextValue": "https://example.com", "content": "This is a comment", "timestamp": 1704067200, "author": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" } ``` ## Best Practices 1. **Choose appropriate context types** - Use the most specific context for your use case 2. **Enable moderation** - For public-facing applications 3. **Implement rate limiting** - Prevent spam 4. **Cache comment counts** - For performance 5. **Handle errors gracefully** - Network issues may occur ## API Integration ### Backend Setup ```typescript // api/metalens/comments/route.ts import { getMetaLensComments } from 'bigblocks/metalens'; export async function GET(request: Request) { const { searchParams } = new URL(request.url); const context = searchParams.get('context'); const value = searchParams.get('value'); const comments = await getMetaLensComments({ context, value, limit: 50, offset: 0, }); return Response.json(comments); } ``` ### Creating Comments ```typescript import { createMetaLensComment } from 'bigblocks/metalens'; export async function POST(request: Request) { const { context, value, content, author } = await request.json(); const comment = await createMetaLensComment({ context, value, content, author, droplit: true, // Use gasless transaction }); return Response.json(comment); } ``` ## Next Steps * Explore [Component Examples](/docs/examples) for more patterns * Learn about [Droplit Integration](/docs/droplit) * Read the [MAP Protocol Guide](/docs/protocols) # Storage Adapter URL: /docs/components/storage-adapter Pluggable storage interface for BigBlocks authentication and data persistence *** title: Storage Adapter description: Pluggable storage interface for BigBlocks authentication and data persistence category: utilities ------------------- import { StorageAdapterDemo } from '@/components/docs/demos/StorageAdapterDemo'; # Storage Adapter A pluggable storage interface that provides a consistent API for data persistence across different environments. BigBlocks uses storage adapters for authentication data, session management, and backup persistence. ## Installation ```bash npx bigblocks add storage-adapter ``` ## Import ```typescript import { createMemoryStorage, createLocalStorage } from 'bigblocks'; ``` ## Interface All storage adapters implement the `StorageAdapter` interface: ```typescript interface StorageAdapter { get: (key: string) => Promise; set: (key: string, value: string) => Promise; delete: (key: string) => Promise; clear?: () => Promise; } ``` ## Built-in Adapters ### Memory Storage For testing and development without persistence: ```typescript import { createMemoryStorage } from 'bigblocks'; const storage = createMemoryStorage(); // Usage with auth const authManager = createAuthManager({ apiUrl: '/api', storage: storage }); ``` ### Local Storage For browser-based persistence: ```typescript import { createLocalStorage } from 'bigblocks'; const storage = createLocalStorage(); // With namespace const namespacedStorage = createLocalStorage('myapp'); ``` ### Session Storage For temporary session-based storage: ```typescript import { createSessionStorage } from 'bigblocks'; const storage = createSessionStorage(); ``` ## Custom Storage Adapters ### Server-Side Storage For Node.js environments: ```typescript import { StorageAdapter } from 'bigblocks'; class ServerStorageAdapter implements StorageAdapter { private storage = new Map(); async get(key: string): Promise { // Implement database/file system retrieval return this.storage.get(key) || null; } async set(key: string, value: string): Promise { // Implement database/file system storage this.storage.set(key, value); } async delete(key: string): Promise { // Implement database/file system removal this.storage.delete(key); } async clear(): Promise { // Clear all stored data this.storage.clear(); } } const auth = createAuthManager({ apiUrl: '/api', storage: new ServerStorageAdapter() }); ``` ### Redis Storage For distributed applications: ```typescript import Redis from 'ioredis'; import { StorageAdapter } from 'bigblocks'; class RedisStorageAdapter implements StorageAdapter { private redis: Redis; private namespace: string; constructor(redisUrl: string, namespace = 'bigblocks:') { this.redis = new Redis(redisUrl); this.namespace = namespace; } async get(key: string): Promise { return this.redis.get(this.namespace + key); } async set(key: string, value: string): Promise { await this.redis.set(this.namespace + key, value); } async delete(key: string): Promise { await this.redis.del(this.namespace + key); } async clear(): Promise { const keys = await this.redis.keys(this.namespace + '*'); if (keys.length > 0) { await this.redis.del(...keys); } } } const auth = createBigBlocksAuth({ storage: new RedisStorageAdapter(process.env.REDIS_URL!) }); ``` ### Encrypted Storage For enhanced security: ```typescript import { StorageAdapter } from 'bigblocks'; import CryptoJS from 'crypto-js'; class EncryptedStorageAdapter implements StorageAdapter { private storage: StorageAdapter; private encryptionKey: string; constructor(storage: StorageAdapter, encryptionKey: string) { this.storage = storage; this.encryptionKey = encryptionKey; } async get(key: string): Promise { const encrypted = await this.storage.get(key); if (!encrypted) return null; try { const bytes = CryptoJS.AES.decrypt(encrypted, this.encryptionKey); return bytes.toString(CryptoJS.enc.Utf8); } catch { return null; // Invalid or corrupted data } } async set(key: string, value: string): Promise { const encrypted = CryptoJS.AES.encrypt(value, this.encryptionKey).toString(); await this.storage.set(key, encrypted); } async delete(key: string): Promise { await this.storage.delete(key); } async clear(): Promise { await this.storage.clear(); } } // Usage const baseStorage = createLocalStorage(); const encryptedStorage = new EncryptedStorageAdapter(baseStorage, 'secret-key'); const auth = createAuthManager({ apiUrl: '/api', storage: encryptedStorage }); ``` ## Usage with Components ### AuthManager ```typescript import { createAuthManager, createMemoryStorage } from 'bigblocks'; const authManager = createAuthManager({ apiUrl: '/api', storage: createMemoryStorage(), // For testing storageNamespace: 'auth:' }); ``` ### BitcoinAuthProvider ```typescript import { BitcoinAuthProvider, createLocalStorage } from 'bigblocks'; function App() { return ( {/* Your app */} ); } ``` ### createBigBlocksAuth ```typescript import { createBigBlocksAuth, createSessionStorage } from 'bigblocks'; const auth = createBigBlocksAuth({ apiUrl: '/api', storage: createSessionStorage(), storageNamespace: 'bigblocks:auth:' }); ``` ## Configuration Options ### Storage Namespacing Use namespaces to avoid key conflicts: ```typescript const auth = createAuthManager({ apiUrl: '/api', storage: createLocalStorage(), storageNamespace: 'myapp:auth:' // Prefix for all keys }); ``` ### Multiple Storage Instances Use different storage for different purposes: ```typescript const sessionStorage = createSessionStorage(); const localStorage = createLocalStorage(); // Session data const auth = createAuthManager({ apiUrl: '/api', storage: sessionStorage }); // Persistent user preferences const preferences = { storage: localStorage, get: (key: string) => localStorage.get(`prefs:${key}`), set: (key: string, value: string) => localStorage.set(`prefs:${key}`, value) }; ``` ## Testing ### Mock Storage For unit tests: ```typescript import { StorageAdapter } from 'bigblocks'; class MockStorageAdapter implements StorageAdapter { private data: Record = {}; async get(key: string): Promise { return this.data[key] || null; } async set(key: string, value: string): Promise { this.data[key] = value; } async delete(key: string): Promise { delete this.data[key]; } async clear(): Promise { this.data = {}; } // Test helpers getData() { return { ...this.data }; } setData(data: Record) { this.data = { ...data }; } } // In tests const mockStorage = new MockStorageAdapter(); const auth = createAuthManager({ apiUrl: '/api', storage: mockStorage }); // Verify storage calls expect(mockStorage.getData()).toEqual({ 'auth:session': 'encrypted-session-data' }); ``` ## Error Handling ### Graceful Degradation ```typescript class FallbackStorageAdapter implements StorageAdapter { private primary: StorageAdapter; private fallback: StorageAdapter; constructor(primary: StorageAdapter, fallback: StorageAdapter) { this.primary = primary; this.fallback = fallback; } async get(key: string): Promise { try { return await this.primary.get(key); } catch { return await this.fallback.get(key); } } async set(key: string, value: string): Promise { try { await this.primary.set(key, value); } catch { await this.fallback.set(key, value); } } async delete(key: string): Promise { await Promise.all([ this.primary.delete(key).catch(() => {}), this.fallback.delete(key).catch(() => {}) ]); } async clear(): Promise { await Promise.all([ this.primary.clear().catch(() => {}), this.fallback.clear().catch(() => {}) ]); } } // Usage const storage = new FallbackStorageAdapter( createLocalStorage(), createMemoryStorage() ); ``` ### Storage Quota Management ```typescript class QuotaAwareStorage implements StorageAdapter { private storage: StorageAdapter; private maxSize: number; constructor(storage: StorageAdapter, maxSize = 5 * 1024 * 1024) { // 5MB this.storage = storage; this.maxSize = maxSize; } async setItem(key: string, value: string): Promise { if (value.length > this.maxSize) { throw new Error('Value exceeds storage quota'); } try { await this.storage.set(key, value); } catch (error) { if (error.name === 'QuotaExceededError') { // Clear old data and retry await this.cleanupOldData(); await this.storage.set(key, value); } else { throw error; } } } private async cleanupOldData(): Promise { // Implement cleanup strategy console.warn('Storage quota exceeded, cleaning up old data'); } async get(key: string): Promise { return this.storage.get(key); } async delete(key: string): Promise { return this.storage.delete(key); } async clear(): Promise { return this.storage.clear(); } } ``` ## Best Practices 1. **Choose the Right Adapter**: Use memory storage for testing, local storage for browsers, custom adapters for servers 2. **Handle Async Operations**: Many storage operations are async, always await them 3. **Use Namespaces**: Prevent key conflicts with proper namespacing 4. **Error Handling**: Implement fallback strategies for storage failures 5. **Security**: Use encrypted storage for sensitive data 6. **Testing**: Mock storage for unit tests to avoid side effects ## Common Patterns ### Configuration Factory ```typescript function createStorageConfig(env: 'development' | 'test' | 'production') { switch (env) { case 'test': return createMemoryStorage(); case 'development': return createLocalStorage('dev'); case 'production': return new EncryptedStorageAdapter( createLocalStorage(), process.env.ENCRYPTION_KEY! ); } } const storage = createStorageConfig(process.env.NODE_ENV); ``` ### Multi-Layer Storage ```typescript class CachedStorageAdapter implements StorageAdapter { private cache: StorageAdapter; private persistent: StorageAdapter; constructor(cache: StorageAdapter, persistent: StorageAdapter) { this.cache = cache; this.persistent = persistent; } async get(key: string): Promise { // Try cache first let value = await this.cache.get(key); if (value === null) { // Fallback to persistent storage value = await this.persistent.get(key); if (value !== null) { // Cache for next time await this.cache.set(key, value); } } return value; } async set(key: string, value: string): Promise { await Promise.all([ this.cache.set(key, value), this.persistent.set(key, value) ]); } async delete(key: string): Promise { await Promise.all([ this.cache.delete(key), this.persistent.delete(key) ]); } async clear(): Promise { await Promise.all([ this.cache.clear(), this.persistent.clear() ]); } } ``` ## Related Components * [createMemoryStorage](/docs/components/create-memory-storage) - Memory-based storage utility * [createLocalStorage](/docs/components/create-local-storage) - Browser localStorage wrapper * [AuthManager](/docs/components/auth-manager) - Uses storage for session persistence * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - Provider with storage configuration ## API Reference This component provides a consistent storage interface for all BigBlocks components and utilities. The interface supports both synchronous and asynchronous operations to accommodate different storage backends. ### Core Interface ```typescript interface StorageAdapter { get: (key: string) => Promise; set: (key: string, value: string) => Promise; delete: (key: string) => Promise; clear?: () => Promise; } ``` ### Built-in Utilities * `createMemoryStorage()` - In-memory storage for testing * `createLocalStorage(namespace?)` - Browser localStorage wrapper * `createSessionStorage(namespace?)` - Browser sessionStorage wrapper # Quick Start URL: /docs/introduction/quickstart Get up and running with BigBlocks in minutes *** title: Quick Start description: Get up and running with BigBlocks in minutes --------------------------------------------------------- Get up and running with BigBlocks in minutes. ## Installation ### Using npm/yarn/bun ```bash # npm npm install bigblocks@latest # yarn yarn add bigblocks@latest # bun bun add bigblocks@latest ``` ### Using init-prism For a complete project setup with BigBlocks pre-configured: ```bash npm install -g init-prism@latest init-prism create my-app --bigblocks ``` ## Basic Setup ### 1. Add Required Providers Wrap your application with the necessary providers: ```tsx import { BitcoinAuthProvider, BitcoinQueryProvider, BitcoinThemeProvider } from 'bigblocks'; function App() { return ( {/* Your app content */} ); } ``` ### 2. Add Your First Component Import and use any BigBlocks component: ```tsx import { AuthButton, ProfileCard } from 'bigblocks'; function MyComponent() { return (
); } ``` ### 3. Framework-Specific Setup #### Next.js (App Router) ```typescript // app/api/auth/[...nextauth]/route.ts import { createNextJSBigBlocks } from 'bigblocks/nextjs'; const { auth, handlers } = createNextJSBigBlocks({ // Your config }); export { handlers.GET, handlers.POST }; ``` #### Express ```typescript import { createExpressBigBlocks } from 'bigblocks/express'; const bigblocks = createExpressBigBlocks({ // Your config }); app.use('/auth', bigblocks.router); ``` #### Astro ```typescript import { createAstroBigBlocks } from 'bigblocks/astro'; const bigblocks = createAstroBigBlocks({ // Your config }); ``` ## Core Concepts ### Bitcoin as Identity In BigBlocks, Bitcoin private keys ARE the user's identity: * No traditional usernames or passwords * Client-side key generation only * BSM (Bitcoin Signed Messages) for authentication * Encrypted backup storage via OAuth providers ### Required Providers Most BigBlocks components require these context providers: 1. **BitcoinAuthProvider** - Manages authentication state 2. **BitcoinQueryProvider** - Handles data fetching 3. **BitcoinThemeProvider** - Provides theme context ### Component Categories BigBlocks components are organized into categories: * **Authentication** - Login, signup, OAuth flows * **Profiles** - Identity and profile management * **Wallet** - Bitcoin transactions and balances * **Social** - Posts, likes, follows * **Market** - Trading and marketplace * **MetaLens** - Universal commenting system * **UI Primitives** - Basic building blocks ## Next Steps * Explore the [Component Browser](/components) to see all available components * Learn about [Bitcoin Authentication](/docs/authentication) * Try the [Theme Builder](/themes) to customize your app * Check out [Common Patterns](/docs/guides) for best practices # What is BigBlocks? URL: /docs/introduction/what-is-bigblocks Complete guide to Bitcoin authentication components *** title: What is BigBlocks? description: Complete guide to Bitcoin authentication components ---------------------------------------------------------------- # What is BigBlocks? Welcome to BigBlocks - your complete guide to building Bitcoin applications with 96+ production-ready components. ## Overview BigBlocks is a comprehensive Bitcoin UI component library for React applications with framework-agnostic adapters. It provides everything you need to build Bitcoin-powered applications where private keys ARE the identity. ### Key Features * **Bitcoin-based Authentication** - No usernames or passwords required * **96+ Production Components** - Complete UI library from auth flows to social features * **Radix Themes Integration** - Full theme customization with dark/light mode support * **MetaLens Commenting System** (v0.0.17) - Universal commenting for any context * **Framework Adapters** - Native support for Next.js, Express, and Astro * **Zero-cost Transactions** - Droplit integration for gasless operations ## Quick Links * [Getting Started](/docs/getting-started) - Installation and setup * [Authentication](/docs/authentication) - Bitcoin auth flows * [Components](/docs/components) - Full component reference * [MetaLens](/docs/metalens) - Commenting system guide * [API Reference](/docs/api) - Backend integration * [Guides](/docs/guides) - Common patterns and recipes # MCP Server URL: /docs/mcp-server Bitcoin development toolkit for AI assistants via Model Context Protocol *** title: MCP Server description: Bitcoin development toolkit for AI assistants via Model Context Protocol ------------------------------------------------------------------------------------- # BigBlocks MCP Server The BigBlocks MCP (Model Context Protocol) Server provides Bitcoin development capabilities directly to AI assistants like Claude, enabling seamless Bitcoin application development. ## What is MCP? Model Context Protocol (MCP) is an open standard that allows AI assistants to securely connect to external systems and tools. The BigBlocks MCP Server exposes Bitcoin functionality as a set of tools that AI assistants can use to help you build Bitcoin applications. ## Features * **Component Generation** - Access to 90+ BigBlocks component prompts * **Bitcoin Operations** - Wallet creation, transaction signing, broadcasting * **BSV Blockchain** - Full Bitcoin SV blockchain integration * **Code Examples** - Production-ready code snippets and templates * **Best Practices** - Bitcoin development patterns and security guidelines ## Quick Start ### Installation ```bash # Install globally npm install -g bigblocks-mcp # Or run directly npx bigblocks-mcp ``` ### Connect to Claude 1. **Install the MCP Server**: ```bash npm install -g bigblocks-mcp ``` 2. **Add to Claude Desktop**: Open Claude Desktop settings and add: ```json { "mcpServers": { "bigblocks": { "command": "npx", "args": ["bigblocks-mcp"] } } } ``` 3. **Restart Claude Desktop** and you'll see BigBlocks tools available ## Available Tools ### Component Tools * `get_component_prompt` - Get prompts for specific BigBlocks components * `search_components` - Search components by category or functionality * `list_categories` - List all available component categories ### Bitcoin Tools * `create_wallet` - Generate new Bitcoin wallets * `sign_transaction` - Sign Bitcoin transactions * `broadcast_transaction` - Broadcast transactions to BSV network * `get_balance` - Check wallet balances * `get_utxos` - Retrieve unspent transaction outputs ### Development Tools * `generate_template` - Create project templates with BigBlocks * `validate_setup` - Check development environment * `get_examples` - Access code examples and patterns ## Example Usage Once connected, you can ask Claude: > "Create a Bitcoin payment button component using BigBlocks" Claude will use the MCP server to: 1. Fetch the appropriate component prompt 2. Generate the code with proper Bitcoin integration 3. Provide setup and usage instructions 4. Include security best practices ## Configuration The MCP server supports various configuration options: ```json { "mcpServers": { "bigblocks": { "command": "npx", "args": ["bigblocks-mcp"], "env": { "BIGBLOCKS_API_URL": "https://api.bigblocks.dev", "BSV_NETWORK": "mainnet" } } } } ``` ## Supported AI Assistants * **Claude Desktop** - Full support * **VS Code with MCP** - Full support * **Cursor** - Full support * **Other MCP-compatible tools** - Basic support ## Security The MCP server follows security best practices: * No private keys are stored or transmitted * All Bitcoin operations use proper signing workflows * API calls are authenticated and rate-limited * Local development mode available for testing ## Getting Help * [MCP Server Documentation](/mcp-server) * [Component Reference](/docs/components) * [GitHub Issues](https://github.com/b-open-io/bigblocks/issues) * [Discord Community](https://discord.gg/bigblocks) ## Next Steps 1. [Install the MCP Server](/mcp-server) 2. [Explore Components](/docs/components) 3. [Read the Getting Started Guide](/docs/introduction/quickstart) 4. [Join the Community](https://discord.gg/bigblocks) # AuthButton URL: /docs/components/authentication/auth-button Bitcoin authentication button component for sign-in and sign-up flows *** title: AuthButton description: Bitcoin authentication button component for sign-in and sign-up flows categories: \['auth', 'ui', 'onboarding'] providers: \['BitcoinAuthProvider'] ----------------------------------- import { AuthButtonDemo } from '@/components/docs/demos/AuthButtonDemo' import { ComponentBadges } from '@/components/docs/ComponentBadges' Authentication button that integrates with Bitcoin authentication flows and providers. AuthButton extends the [Radix Button primitive](https://www.radix-ui.com/themes/docs/components/button) with Bitcoin-specific authentication modes and seamless integration with [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider). ## Installation ```bash npx bigblocks add auth-button ``` ## Import ```tsx import { AuthButton } from 'bigblocks'; ``` ## API Reference This component extends the [Button primitive](https://www.radix-ui.com/themes/docs/components/button) and inherits all its props. | Prop | Type | Default | Description | | -------------- | --------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------ | | mode | `'signin' \| 'signup' \| 'signout'` | `'signin'` | Authentication mode - determines flow behavior | | size | `Responsive<"1" \| "2" \| "3" \| "4">` | `"3"` | Button size | | variant | `"classic" \| "solid" \| "soft" \| "surface" \| "outline" \| "ghost"` | `"solid"` | Button variant style | | color | Radix color | - | Color theme | | className | `string` | - | Additional CSS classes | | style | `React.CSSProperties` | - | Inline styles | | children | `React.ReactNode` | - | Button content | | confirmSignOut | `boolean` | `false` | Whether to show confirmation dialog on sign out | | confirmMessage | `string` | `"Are you sure you want to sign out?"` | Custom confirmation message for sign out | | redirectTo | `string` | - | URL to redirect after sign out | | onSignOut | `() => void` | - | Callback fired after successful sign out | | showClearInfo | `boolean` | `false` | Whether to show detailed info about what happens on sign out | ## Basic Usage ```tsx import { AuthButton } from 'bigblocks'; export default function SignInPage() { return ( Sign In with Bitcoin ); } ``` ## Authentication Modes AuthButton automatically handles different authentication flows based on the `mode` prop: ```tsx // Sign-in mode - triggers existing user authentication Sign In // Sign-up mode - triggers new user registration flow Create Account // Sign-out mode - shows sign out button when authenticated Sign Out ``` ## Sign Out Customization AuthButton provides several options for customizing the sign out experience: ```tsx // Basic sign out with confirmation Sign Out // Custom confirmation message Log Out // Show detailed info and redirect after sign out console.log('User signed out')} > Sign Out Securely ``` ## Integration with Auth Provider AuthButton automatically integrates with [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) context: ```tsx import { AuthButton, BitcoinAuthProvider } from 'bigblocks'; export default function App() { return (
Connect Wallet
); } ``` For styling options (size, variant, color, etc.), see the [Radix Button documentation](https://www.radix-ui.com/themes/docs/components/button). ## Related Components * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - Authentication context provider * [LoginForm](/docs/components/login-form) - Complete authentication form * [AuthCard](/docs/components/auth-card) - Card layout for auth flows # AuthCard URL: /docs/components/authentication/auth-card Flexible card component designed for authentication forms and flows *** title: AuthCard description: Flexible card component designed for authentication forms and flows category: layouts ----------------- import { AuthCardDemo } from '@/components/docs/demos/AuthCardDemo'; A flexible card component designed specifically for authentication forms and flows. It provides a consistent structure with optional header, content area, and footer sections, making it ideal for login forms, signup flows, and other authentication-related UI. ## Installation ```bash npx bigblocks add auth-card ``` ## Import ```typescript import { AuthCard } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | --------- | --------------------------------------- | -------- | ----------- | ----------------------- | | children | `ReactNode` | Yes | - | Card content | | title | `string` | No | - | Optional card title | | subtitle | `string` | No | - | Optional card subtitle | | footer | `ReactNode` | No | - | Optional footer content | | variant | `'default' \| 'outlined' \| 'elevated'` | No | `'default'` | Card style variant | | className | `string` | No | - | Additional CSS classes | ## Basic Usage ```tsx import { AuthCard } from 'bigblocks'; export default function Example() { return (
); } ``` ## Advanced Usage ### With Footer ```tsx import { AuthCard } from 'bigblocks'; import { Text, Link } from '@radix-ui/themes'; export default function LoginCard() { return ( Don't have an account? Sign up } variant="elevated" > console.log('Logged in:', user)} /> ); } ``` ### Different Variants ```tsx import { AuthCard } from 'bigblocks'; export default function VariantExamples() { return (
{/* Default variant */}

Standard surface card with subtle background

{/* Outlined variant */}

Classic card with border

{/* Elevated variant */}

Surface card with shadow for emphasis

); } ``` ### Multi-Step Form ```tsx import { AuthCard } from 'bigblocks'; import { useState } from 'react'; export default function MultiStepAuth() { const [currentStep, setCurrentStep] = useState(1); const totalSteps = 3; return ( {currentStep === 1 && setCurrentStep(2)} />} {currentStep === 2 && setCurrentStep(3)} />} {currentStep === 3 && console.log('Done!')} />} ); } ``` ## Common Patterns ### Login Form ```tsx import { AuthCard, LoginForm } from 'bigblocks'; import { Link } from '@radix-ui/themes'; export function LoginPage() { return ( Forgot password? } > ); } ``` ### Error State ```tsx import { AuthCard, ErrorDisplay } from 'bigblocks'; export function AuthWithError({ error }) { return ( ); } ``` ### Loading State ```tsx import { AuthCard } from 'bigblocks'; import { Spinner } from '@radix-ui/themes'; export function LoadingAuth() { return (
); } ``` ### Custom Styling ```tsx import { AuthCard } from 'bigblocks'; export function StyledAuthCard() { return (

This card has custom background styling

); } ``` ## Styling AuthCard uses Radix Themes design tokens for consistent styling: * **Spacing**: Uses `--space-6` for consistent padding * **Colors**: Automatically adapts to the current theme * **Typography**: Uses Radix heading and text components * **Shadows**: `--shadow-6` for elevated variant ### Variant Styles * **default**: Standard surface card with subtle background * **outlined**: Classic card with border styling * **elevated**: Surface card with shadow for emphasis and depth ## Accessibility * Uses semantic HTML structure with proper heading hierarchy * Maintains keyboard navigation support * Compatible with screen readers * Proper ARIA attributes when needed ## Best Practices 1. **Title Hierarchy**: Use title for main heading, subtitle for supporting text 2. **Footer Content**: Ideal for secondary actions, links, or disclaimers 3. **Variant Selection**: * Use `default` for most authentication forms * Use `outlined` for secondary forms or nested cards * Use `elevated` for primary actions or important forms 4. **Responsive Design**: Card adapts to container width automatically 5. **Content Spacing**: Use consistent spacing within card content ## Troubleshooting ### Card Not Centered * Wrap AuthCard in a CenteredLayout component for page-level centering * Check parent container width and centering styles ### Styling Not Applied * Ensure Radix Themes CSS is imported * Check that BitcoinThemeProvider is wrapping your app * Verify custom classes don't conflict with Radix styles ### Content Overflow * AuthCard handles responsive sizing automatically * For very long content, consider pagination or scrollable areas * Test on various screen sizes ## Related Components * [AuthLayout](/docs/components/auth-layout) - Full-page authentication layout * [CenteredLayout](/docs/components/centered-layout) - Center content on page * [LoginForm](/docs/components/login-form) - Complete login form * [SignupFlow](/docs/components/signup-flow) - Multi-step signup process * [ErrorDisplay](/docs/components/error-display) - Error message display ## API Reference ### Variant Types * `'default'` - Standard surface styling * `'outlined'` - Border-based styling * `'elevated'` - Shadow-enhanced styling ### Layout Structure The AuthCard component creates the following structure: * Card container with variant styling * Optional header with title/subtitle * Main content area (children) * Optional footer section ## Integration Works seamlessly with other BigBlocks components: * Contains forms like `LoginForm`, `SignupFlow` * Pairs with `AuthLayout` for full-page layouts * Compatible with all authentication components * Integrates with theme system automatically # AuthFlowOrchestrator URL: /docs/components/authentication/auth-flow-orchestrator Unified authentication flow manager for intelligent routing through sign in, sign up, or wallet restoration *** title: AuthFlowOrchestrator description: Unified authentication flow manager for intelligent routing through sign in, sign up, or wallet restoration category: authentication ------------------------ A comprehensive authentication flow manager that intelligently routes users through sign in, sign up, OAuth restoration, device linking, or file import flows. This component provides a unified entry point for all authentication scenarios with automatic flow detection and seamless transitions. ## Installation ```bash npx bigblocks add auth-flow-orchestrator ``` ## Import ```typescript import { AuthFlowOrchestrator } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | -------------------- | ----------------------------------------------- | -------- | ------------ | ----------------------------------- | | flowType | `AuthFlowType` | No | `'unified'` | Initial flow type | | initialStep | `AuthStep` | No | `'initial'` | Starting step in the flow | | enableOAuth | `boolean` | No | `true` | Enable OAuth provider options | | enableDeviceLink | `boolean` | No | `true` | Enable device linking flow | | enableFileImport | `boolean` | No | `true` | Enable file import for backups | | enableLocalBackup | `boolean` | No | `true` | Enable local backup storage | | enableProfileSync | `boolean` | No | `false` | Enable profile synchronization | | maxDiscoveryAttempts | `number` | No | `3` | Max attempts for profile discovery | | oauthProviders | `OAuthProvider[]` | No | - | Custom OAuth provider configuration | | onSuccess | `(user: {id: string, address: string}) => void` | No | - | Success callback | | onError | `(error: string) => void` | No | - | Error callback | | onFlowChange | `(flow: AuthFlowType) => void` | No | - | Flow change callback | | onStepChange | `(step: AuthStep) => void` | No | - | Step change callback | | title | `string` | No | - | Custom title | | subtitle | `string` | No | - | Custom subtitle | | showHeader | `boolean` | No | `true` | Show header section | | showFooter | `boolean` | No | `true` | Show footer section | | className | `string` | No | - | Additional CSS classes | | layout | `'centered' \| 'full' \| 'custom'` | No | `'centered'` | Layout style | | customLayout | `React.ComponentType` | No | - | Custom layout component | | autoDetectFlow | `boolean` | No | `true` | Auto-detect best flow | | persistFlow | `boolean` | No | `true` | Persist flow state | | debug | `boolean` | No | `false` | Enable debug mode | ## Flow Types ```typescript type AuthFlowType = | 'unified' // Auto-detect best flow | 'signin' // Direct sign in | 'signup' // New account creation | 'oauth-restore' // Restore via OAuth | 'device-link' // Link new device | 'import' // Import backup file | 'custom'; // Custom flow ``` ## Auth Steps ```typescript type AuthStep = | 'initial' // Starting point | 'signin' // Sign in form | 'signup' // Sign up form | 'password' // Password entry | 'confirm-password' // Password confirmation | 'backup-display' // Show backup | 'backup-download' // Download backup | 'oauth-link' // Link OAuth provider | 'oauth-restore' // Restore from OAuth | 'import-backup' // Import backup file | 'success'; // Success state ``` ## Basic Usage ```tsx import { AuthFlowOrchestrator, BitcoinAuthProvider } from 'bigblocks'; import { useRouter } from 'next/navigation'; export default function AuthPage() { const router = useRouter(); return ( { console.log('Auth successful:', user); router.push('/dashboard'); }} onError={(error) => { console.error('Auth failed:', error); }} /> ); } ``` ## Advanced Usage ### Specific Flow Type ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; export default function SignUpOnly() { return ( { console.log('New user created:', user); }} /> ); } ``` ### Custom OAuth Providers ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; import { FaGoogle, FaGithub } from 'react-icons/fa'; export default function CustomOAuth() { const customProviders = [ { id: 'google', name: 'Google', icon: }, { id: 'github', name: 'GitHub', icon: } ]; return ( { console.log('OAuth auth successful'); }} /> ); } ``` ### Track Flow Progress ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; import { useState } from 'react'; export default function TrackedAuth() { const [currentFlow, setCurrentFlow] = useState('unified'); const [currentStep, setCurrentStep] = useState('initial'); return (

Current Flow: {currentFlow}

Current Step: {currentStep}

{ analytics.track('auth_completed', { flow: currentFlow, userId: user.id }); }} />
); } ``` ### Custom Layout ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; const CustomAuthLayout = ({ children }) => (
Logo
{children}
); export default function CustomLayoutAuth() { return ( { console.log('Auth completed'); }} /> ); } ``` ### Debug Mode ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; export default function DebugAuth() { return ( { console.log('Debug auth successful:', user); }} onError={(error) => { console.error('Debug auth error:', error); }} /> ); } ``` ## Common Patterns ### With Loading State ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; import { useEffect, useState } from 'react'; export function SmartAuth() { const [hasExistingBackup, setHasExistingBackup] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { // Check for existing backup const backup = localStorage.getItem('encryptedBackup'); setHasExistingBackup(!!backup); setLoading(false); }, []); if (loading) { return
Loading...
; } return ( { console.log('Auth successful'); }} /> ); } ``` ### In Modal ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; import { Modal } from '@radix-ui/themes'; export function AuthModal({ isOpen, onClose }) { return ( { console.log('Modal auth successful'); onClose(); }} /> ); } ``` ### Profile Sync Enabled ```tsx import { AuthFlowOrchestrator } from 'bigblocks'; export function ProfileSyncAuth() { return ( { console.log('Auth with profile sync completed'); }} /> ); } ``` ## Flow Behavior ### Unified Flow (Default) * Detects if user has existing backup * Routes to appropriate flow automatically * Seamless transitions between states ### Sign In Flow 1. Password entry 2. Backup decryption 3. Identity verification 4. Success ### Sign Up Flow 1. Identity generation 2. Password creation 3. Backup creation 4. Download/save backup 5. Optional OAuth linking 6. Success ### OAuth Restore Flow 1. Select OAuth provider 2. Authenticate with provider 3. Retrieve encrypted backup 4. Decrypt with password 5. Success ### Device Link Flow 1. Generate device link code 2. Scan QR or enter code 3. Authorize on primary device 4. Sync backup to new device 5. Success ## Troubleshooting ### Flow Not Auto-Detecting * Check that `autoDetectFlow` is enabled * Verify local storage is accessible * Ensure BitcoinAuthProvider is properly configured ### OAuth Not Working * Verify OAuth providers are configured in your backend * Check that `enableOAuth` is true * Ensure callback URLs are properly set ### Custom Layout Issues * Layout component must accept `children` prop * Ensure proper CSS/styling is applied * Check that `layout` prop is set to `'custom'` ## Related Components * [LoginForm](/docs/components/login-form) - Standalone login form * [SignupFlow](/docs/components/signup-flow) - Signup flow component * [OAuthRestoreFlow](/docs/components/oauth-restore-flow) - OAuth restoration * [BackupImport](/docs/components/backup-import) - File import component * [DeviceLinkQR](/docs/components/device-link-qr) - Device linking QR ## API Reference ### Success Callback The `onSuccess` callback receives a user object: ```typescript { id: string; // User's BAP ID address: string; // Bitcoin address } ``` ### Error Handling Errors are passed as strings to the `onError` callback. Common error types: * `'USER_EXISTS'` - Account already exists * `'INVALID_PASSWORD'` - Incorrect password * `'INVALID_BACKUP'` - Corrupted backup file * `'OAUTH_FAILED'` - OAuth authentication failed * `'DEVICE_LINK_FAILED'` - Device linking failed ### Flow State The component manages internal state including: * Current flow type * Current step * Form data * Error states * Loading states ## Notes for Improvement **Implementation Note**: The prompt described props like `mode`, `allowModeSwitch`, `showOAuthProviders`, and `customSteps` which don't exist in the actual implementation. The actual component uses `flowType`, `enableOAuth`, and other boolean flags for configuration. The component is more feature-rich than the prompt suggested, with support for device linking, profile sync, and debug mode. # AuthLayout URL: /docs/components/authentication/auth-layout Full-page layout component for authentication screens with progress tracking *** title: AuthLayout description: Full-page layout component for authentication screens with progress tracking category: layouts ----------------- A full-page layout component designed specifically for authentication screens. It provides a consistent structure with optional header, progress indicator, and centered content area, making it perfect for login pages, signup flows, and password reset screens. ## Installation ```bash npx bigblocks add auth-layout ``` ## Import ```typescript import { AuthLayout } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | ------------ | ----------- | -------- | ------- | ----------------------- | | children | `ReactNode` | Yes | - | Main content to display | | title | `string` | No | - | Optional page title | | subtitle | `string` | No | - | Optional page subtitle | | showProgress | `boolean` | No | `false` | Show progress indicator | | progressStep | `number` | No | `1` | Current step number | | totalSteps | `number` | No | `3` | Total number of steps | | className | `string` | No | - | Additional CSS classes | ## Basic Usage ```tsx import { AuthLayout, LoginForm } from 'bigblocks'; export default function LoginPage() { return ( console.log('Logged in:', user)} /> ); } ``` ## Advanced Usage ### Multi-Step Registration ```tsx import { AuthLayout } from 'bigblocks'; import { useState } from 'react'; export default function SignupPage() { const [currentStep, setCurrentStep] = useState(1); const totalSteps = 4; return ( {currentStep === 1 && setCurrentStep(2)} />} {currentStep === 2 && setCurrentStep(3)} />} {currentStep === 3 && setCurrentStep(4)} />} {currentStep === 4 && console.log('Done!')} />} ); } ``` ### With Custom Styling ```tsx import { AuthLayout } from 'bigblocks'; export default function StyledAuthPage() { return ( ); } ``` ### Password Reset Flow ```tsx import { AuthLayout } from 'bigblocks'; export default function PasswordResetPage() { return (
); } ``` ## Common Patterns ### Dynamic Progress Tracking ```tsx import { AuthLayout } from 'bigblocks'; import { useState } from 'react'; export function OnboardingFlow() { const [step, setStep] = useState(1); const steps = [ { title: "Account Info", component: AccountInfo }, { title: "Security Setup", component: SecuritySetup }, { title: "Backup Creation", component: BackupCreation }, { title: "Verification", component: Verification } ]; const CurrentStepComponent = steps[step - 1].component; return ( setStep(step + 1)} onBack={() => setStep(step - 1)} /> ); } ``` ### With Error Handling ```tsx import { AuthLayout, ErrorDisplay } from 'bigblocks'; import { useState } from 'react'; export function AuthWithErrors() { const [error, setError] = useState(null); return ( {error && } setError(err.message)} onSuccess={(user) => { setError(null); console.log('Success!'); }} /> ); } ``` ### Conditional Content ```tsx import { AuthLayout } from 'bigblocks'; export function ConditionalAuthPage({ isNewUser }) { return ( {isNewUser ? : } ); } ``` ## Layout Structure The AuthLayout component creates a full-height page with the following structure: ``` ┌─────────────────────────────────┐ │ Header Section │ │ Title & Subtitle Text │ ├─────────────────────────────────┤ │ │ │ Progress Bar (if enabled) │ │ [===========------] 60% │ │ │ │ ┌─────────────────────────┐ │ │ │ │ │ │ │ Centered Content │ │ │ │ (440px max width) │ │ │ │ │ │ │ └─────────────────────────┘ │ │ │ └─────────────────────────────────┘ ``` ## Features ### Full Height Layout * Automatically fills viewport height * Ensures content is always centered * No scrolling for standard auth forms ### Progress Tracking * Visual progress bar for multi-step flows * Percentage display for accessibility * Smooth animations between steps ### Responsive Design * Adapts to all screen sizes * Maintains readability on mobile * Consistent padding and spacing ### Theme Integration * Follows active theme colors * Supports dark/light modes * Consistent with BigBlocks design system ## Styling AuthLayout uses Radix Themes design tokens: * **Background**: `var(--color-background)` * **Text Color**: `var(--gray-12)` for titles * **Spacing**: `var(--space-4)` padding * **Container**: 440px maximum width for content * **Progress Bar**: Theme accent color ## Best Practices 1. **Title Usage**: Keep titles concise and action-oriented (e.g., "Sign In", "Create Account") 2. **Progress Steps**: Use progress tracking for flows with 3 or more steps 3. **Content Width**: Content is limited to 440px for optimal readability 4. **Spacing**: The layout maintains consistent padding across all screen sizes 5. **Subtitle**: Use subtitles to provide helpful context or instructions ## Accessibility * Uses semantic HTML structure with proper heading hierarchy * Progress indicator includes percentage text for screen readers * Maintains focus management during step transitions * Fully keyboard navigable * Supports reduced motion preferences ## Troubleshooting ### Content Not Centering * Ensure parent container doesn't have conflicting styles * Check that the layout is at the root of your page component * Verify no global CSS is overriding flexbox properties ### Progress Bar Not Showing * Confirm `showProgress` prop is set to `true` * Verify `progressStep` and `totalSteps` are valid numbers * Check that `progressStep` is between 1 and `totalSteps` ### Layout Height Issues * AuthLayout uses `min-h-screen` - ensure no parent has `height` constraints * Check for conflicting global styles on `html` or `body` elements ## Related Components * [AuthCard](/docs/components/auth-card) - Card-based container for auth forms * [CenteredLayout](/docs/components/centered-layout) - Generic centered layout wrapper * [LoginForm](/docs/components/login-form) - Common child component for sign-in * [SignupFlow](/docs/components/signup-flow) - Multi-step registration component * [LoadingLayout](/docs/components/loading-layout) - Loading state layout * [ErrorLayout](/docs/components/error-layout) - Error state layout * [SuccessLayout](/docs/components/success-layout) - Success state layout ## API Reference ### Progress Calculation The progress bar percentage is calculated as: ```typescript percentage = (progressStep / totalSteps) * 100 ``` ### Layout Sizing * **Content Max Width**: 440px * **Vertical Spacing**: Flexible, centers content * **Horizontal Padding**: Responsive (16px mobile, 24px desktop) # AuthManager URL: /docs/components/authentication/auth-manager Core authentication manager class for Bitcoin-based authentication and session management *** title: AuthManager description: Core authentication manager class for Bitcoin-based authentication and session management categories: \[authentication, core, session-management] ------------------------------------------------------- import { ComponentBadges } from '@/components/docs/ComponentBadges'; import { AuthManagerDemo } from '@/components/docs/demos/AuthManagerDemo'; Core authentication manager class that handles Bitcoin-based authentication, session management, backup operations, and user state. It provides a comprehensive API for managing Bitcoin identity authentication with support for multiple backup formats and OAuth integration. ## Demo ## API Reference This component extends [BitcoinAuthConfig](/docs/components/bitcoin-auth-provider) for configuration and uses [StorageAdapter](/docs/components/storage-adapter) for persistent storage. ## Overview The `AuthManager` is the core engine behind BigBlocks authentication. It manages the complete authentication lifecycle, from account creation and sign-in to backup management and session handling. It supports multiple backup formats (BAP Master, BAP Member, OneSat) and provides OAuth integration for cloud backup storage. ## Key Features * **Multi-format Backup Support**: BAP Master, BAP Member, OneSat, WIF formats * **Encrypted Storage**: AES-256 encryption for local backup storage * **OAuth Integration**: Link Google, GitHub, and custom providers for cloud backups * **Session Management**: Secure session creation and management * **Event System**: Subscribe to authentication state changes * **Wallet Integration**: Check for and integrate with browser wallet extensions * **Type-safe API**: Full TypeScript support with comprehensive type definitions ## Configuration ```typescript interface BitcoinAuthConfig { apiUrl?: string; // API base URL (default: '/api') oauthProviders?: OAuthProvider[]; // OAuth providers to enable customOAuthProviders?: CustomOAuthProvider[]; // Custom OAuth configurations backupTypes?: BackupTypeConfig; // Allowed backup formats storage?: StorageAdapter; // Storage implementation storageNamespace?: string; // Storage key namespace theme?: ThemeConfig; // UI theme configuration redirects?: RedirectConfig; // OAuth redirect URLs onSuccess?: (user: AuthUser) => void; // Success callback onError?: (error: AuthError) => void; // Error callback } ``` ## Basic Usage ### Creating an AuthManager ```typescript import { AuthManager, createAuthManager } from 'bigblocks'; // Using factory function (recommended) const authManager = createAuthManager({ apiUrl: 'https://api.bigblocks.io', oauthProviders: ['google', 'github'], storage: customStorageAdapter, // Optional custom storage }); // Direct instantiation const authManager = new AuthManager({ apiUrl: '/api', backupTypes: { enabled: ['bap-master', 'bap-member'] } }); ``` ### Authentication Flow ```typescript // Sign up new user async function handleSignUp(password: string) { try { await authManager.signUp(password); console.log('Account created successfully'); } catch (error) { console.error('Sign up failed:', error); } } // Sign in existing user async function handleSignIn(password: string) { try { await authManager.signIn(password); console.log('Signed in successfully'); } catch (error) { console.error('Sign in failed:', error); } } // Sign out current user async function handleSignOut() { await authManager.signOut(); console.log('Signed out'); } ``` ## Core Methods ### Authentication Methods ```typescript class AuthManager { // Create new account with password async signUp(password: string): Promise<{ success: boolean; error?: AuthError }> // Sign in with existing backup async signIn(password: string): Promise<{ success: boolean; error?: AuthError }> // Sign out current user async signOut(): Promise // Validate password against stored backup async validatePassword(password: string): Promise } ``` ### Backup Management ```typescript class AuthManager { // Generate backup for current user generateBackup(): BapMasterBackup // Import backup from file async importBackup(file: File): Promise // Get current backup status getBackupStatus(): BackupStatus } ``` ### OAuth Integration ```typescript class AuthManager { // Link OAuth provider for cloud backup async linkOAuth(provider: OAuthProvider): Promise // Handle OAuth callback after authorization async handleOAuthCallback(provider: OAuthProvider, success: boolean): Promise // Get linked OAuth providers getLinkedProviders(): OAuthProvider[] } ``` ### State Management ```typescript class AuthManager { // Get current authentication state getState(): AuthState // Subscribe to state changes subscribe(listener: (event: AuthEvent) => void): () => void // Get action functions for UI integration getActions(): AuthActions } ``` ## State Management ### Authentication State ```typescript interface AuthState { user: AuthUser | null; // Current authenticated user isAuthenticated: boolean; // Authentication status isLoading: boolean; // Loading state error: AuthError | null; // Current error currentStep: AuthStep; // Current flow step mode: 'signin' | 'signup'; // Current mode hasLocalBackup: boolean; // Local backup exists backupStatus: BackupStatus; // Detailed backup status isImportedBackup: boolean; // Backup was imported hasWalletCapabilities: boolean; // Wallet extension available linkedProviders: OAuthProvider[]; // Linked OAuth providers pendingOAuthProvider: OAuthProvider | null; // Pending OAuth link } ``` ### Event System ```typescript type AuthEvent = | { type: 'AUTH_STARTED' } | { type: 'AUTH_SUCCESS'; user: AuthUser } | { type: 'AUTH_FAILED'; error: AuthError } | { type: 'OAUTH_STARTED'; provider: OAuthProvider } | { type: 'OAUTH_LINKED'; provider: OAuthProvider } | { type: 'BACKUP_IMPORTED'; backupType: string } | { type: 'BACKUP_EXPORTED' } | { type: 'SESSION_EXPIRED' }; ``` ## Advanced Usage ### State Subscription with React ```tsx import { createAuthManager } from 'bigblocks'; import { useEffect, useState } from 'react'; export function AuthStateManager() { const [authManager] = useState(() => createAuthManager({ apiUrl: '/api', onSuccess: (user) => console.log('Auth success:', user), onError: (error) => console.error('Auth error:', error) })); const [authState, setAuthState] = useState(authManager.getState()); useEffect(() => { const unsubscribe = authManager.subscribe((event) => { console.log('Auth event:', event); setAuthState(authManager.getState()); // Handle specific events switch (event.type) { case 'AUTH_SUCCESS': // Redirect to dashboard window.location.href = '/dashboard'; break; case 'AUTH_FAILED': // Show error message alert(event.error.message); break; case 'OAUTH_LINKED': // Show success message console.log(`${event.provider} linked successfully`); break; } }); return unsubscribe; }, [authManager]); return (

Authentication Status

Authenticated: {authState.isAuthenticated ? 'Yes' : 'No'}

User: {authState.user?.paymail || 'None'}

Current Step: {authState.currentStep}

Has Local Backup: {authState.hasLocalBackup ? 'Yes' : 'No'}

Linked Providers: {authState.linkedProviders.join(', ') || 'None'}

{authState.error && (
Error: {authState.error.message}
)}
); } ``` ### Backup Import with Validation ```tsx import { createAuthManager } from 'bigblocks'; export function BackupImporter() { const authManager = createAuthManager({ apiUrl: '/api' }); const [importing, setImporting] = useState(false); const handleFileSelect = async (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (!file) return; setImporting(true); try { await authManager.importBackup(file); console.log('Backup imported successfully'); // Check backup status const state = authManager.getState(); if (state.hasLocalBackup) { console.log('Local backup is now available'); } } catch (error) { console.error('Import failed:', error); if (error.code === 'INVALID_BACKUP_FORMAT') { alert('Invalid backup file format'); } else if (error.code === 'UNSUPPORTED_BACKUP_TYPE') { alert('This backup type is not supported'); } } finally { setImporting(false); } }; return (
{importing &&

Importing backup...

}
); } ``` ### OAuth Integration ```tsx import { createAuthManager } from 'bigblocks'; export function OAuthLinker() { const authManager = createAuthManager({ apiUrl: '/api', oauthProviders: ['google', 'github'], redirects: { success: '/dashboard', error: '/auth/error' } }); const handleLinkProvider = async (provider: 'google' | 'github') => { try { await authManager.linkOAuth(provider); // User will be redirected to OAuth provider } catch (error) { console.error('OAuth linking failed:', error); } }; const handleOAuthCallback = async (provider: 'google' | 'github', success: boolean) => { await authManager.handleOAuthCallback(provider, success); const state = authManager.getState(); if (state.linkedProviders.includes(provider)) { console.log(`${provider} linked successfully`); } }; return (
); } ``` ### Custom Storage Adapter ```typescript import { StorageAdapter } from 'bigblocks'; // Custom storage adapter for server-side rendering const serverStorageAdapter: StorageAdapter = { async get(key: string): Promise { // Implement server-side storage retrieval return await db.get(`auth:${key}`); }, async set(key: string, value: string): Promise { // Implement server-side storage await db.set(`auth:${key}`, value); }, async remove(key: string): Promise { // Implement server-side storage removal await db.delete(`auth:${key}`); } }; const authManager = createAuthManager({ apiUrl: '/api', storage: serverStorageAdapter }); ``` ## Error Handling The AuthManager provides detailed error information: ```typescript interface AuthError { code: 'BACKUP_NOT_FOUND' | 'INVALID_PASSWORD' | 'NETWORK_ERROR' | 'INVALID_BACKUP_FORMAT' | 'UNSUPPORTED_BACKUP_TYPE' | 'OAUTH_ERROR' | 'SESSION_EXPIRED' | 'UNKNOWN_ERROR'; message: string; details?: Record; } // Handle specific error types try { await authManager.signIn(password); } catch (error: AuthError) { switch (error.code) { case 'BACKUP_NOT_FOUND': // Show sign-up flow break; case 'INVALID_PASSWORD': // Show password reset option break; case 'NETWORK_ERROR': // Show retry option break; default: // Show generic error break; } } ``` ## Supported Backup Formats * **BAP Master**: Complete identity with private keys and attestations * **BAP Member**: Member-only backup with limited capabilities * **OneSat**: Simple backup format with basic identity * **WIF**: Wallet Import Format for single private key ## Security Features * **AES-256 Encryption**: All local backups are encrypted with user password * **Secure Session Management**: Sessions are managed securely with proper cleanup * **OAuth Security**: Secure OAuth flow with state verification * **Storage Security**: Sensitive data is never stored in plain text ## Installation ```bash npm install bigblocks ``` ## Related Components * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - Authentication context provider * [useBitcoinAuth](/docs/components/use-bitcoin-auth) - Authentication hook * [AuthButton](/docs/components/auth-button) - Authentication UI components * [BackupDownload](/docs/components/backup-download) - Backup management * [BackupImport](/docs/components/backup-import) - Backup import functionality # createAuthManager URL: /docs/components/authentication/create-auth-manager Factory function for creating pre-configured AuthManager instances *** title: createAuthManager description: Factory function for creating pre-configured AuthManager instances category: route-helpers ----------------------- A factory function that creates and configures AuthManager instances for Bitcoin authentication. Provides a comprehensive API for managing authentication state, sessions, and wallet operations. ## Installation ```bash npx bigblocks add create-auth-manager ``` ## Import ```typescript import { createAuthManager } from 'bigblocks'; ``` ## Basic Usage ```tsx import { createAuthManager } from 'bigblocks'; // Create auth manager instance const authManager = createAuthManager({ apiUrl: '/api' }); // Use in your application async function handleSignIn(password: string) { try { await authManager.signIn(password); console.log('Signed in successfully'); } catch (error) { console.error('Sign in failed:', error); } } ``` ## Configuration ```typescript interface BitcoinAuthConfig { apiUrl: string; // API endpoint URL debug?: boolean; // Enable debug logging backupTypes?: string[]; // Supported backup types } ``` ## API Methods The AuthManager instance provides these methods: ### Authentication ```typescript // Sign in with password await authManager.signIn(password: string); // Sign up with new account await authManager.signUp(password: string); // Sign out await authManager.signOut(); // Validate password const isValid = await authManager.validatePassword(password: string); ``` ### State Management ```typescript // Get current state const state = authManager.getState(); // Returns: { isAuthenticated, isLoading, user, error } // Subscribe to state changes const unsubscribe = authManager.subscribe((event) => { console.log('Auth event:', event.type, event.data); }); // Cleanup unsubscribe(); ``` ### Backup Operations ```typescript // Generate backup const backup = authManager.generateBackup(); // Import backup from file await authManager.importBackup(file: File); ``` ### OAuth Integration ```typescript // Link OAuth provider await authManager.linkOAuth('google'); // Handle OAuth callback await authManager.handleOAuthCallback('google', true); ``` ### Wallet Features ```typescript // Get wallet extension (if user has wallet capabilities) const walletExt = await authManager.getWalletExtension(); ``` ### Actions Helper ```typescript // Get all actions as a convenient object const actions = authManager.getActions(); // Includes: signIn, signUp, signOut, importBackup, linkOAuth, etc. ``` ## Advanced Usage ### With React Hook ```tsx import { createAuthManager } from 'bigblocks'; import { useState, useEffect, useCallback } from 'react'; function useAuthManager(config) { const [authManager] = useState(() => createAuthManager(config)); const [state, setState] = useState(authManager.getState()); useEffect(() => { const unsubscribe = authManager.subscribe((event) => { setState(authManager.getState()); }); return unsubscribe; }, [authManager]); const signIn = useCallback(async (password) => { await authManager.signIn(password); }, [authManager]); const signOut = useCallback(async () => { await authManager.signOut(); }, [authManager]); return { ...state, signIn, signOut, authManager }; } // Usage function LoginComponent() { const { isAuthenticated, user, signIn, signOut } = useAuthManager({ apiUrl: '/api' }); if (isAuthenticated) { return (

Welcome, {user.name}!

); } return (
{ e.preventDefault(); const password = e.target.password.value; await signIn(password); }}>
); } ``` ### With Error Handling ```tsx import { createAuthManager } from 'bigblocks'; const authManager = createAuthManager({ apiUrl: '/api', debug: true }); // Subscribe to all events authManager.subscribe((event) => { switch (event.type) { case 'AUTH_ERROR': console.error('Auth error:', event.data.error); showErrorNotification(event.data.error.message); break; case 'STATE_CHANGE': console.log('State changed:', event.data); break; case 'SESSION_CREATED': console.log('Session created for:', event.data.user.name); trackLogin(event.data.user); break; case 'SESSION_DESTROYED': console.log('Session destroyed'); trackLogout(); break; } }); ``` ### With Backup Management ```tsx import { createAuthManager } from 'bigblocks'; const authManager = createAuthManager({ apiUrl: '/api', backupTypes: ['BapMasterBackup', 'OneSatBackup', 'WifBackup'] }); // Export backup function exportBackup() { const backup = authManager.generateBackup(); const blob = new Blob([JSON.stringify(backup)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'bitcoin-wallet-backup.json'; a.click(); } // Import backup async function importBackup(file) { try { await authManager.importBackup(file); console.log('Backup imported successfully'); } catch (error) { console.error('Import failed:', error); } } ``` ### With OAuth Flow ```tsx import { createAuthManager } from 'bigblocks'; const authManager = createAuthManager({ apiUrl: '/api' }); // OAuth link button function OAuthLinkButton({ provider }) { const handleLink = async () => { try { await authManager.linkOAuth(provider); // This will redirect to OAuth provider } catch (error) { console.error('OAuth link failed:', error); } }; return ( ); } // OAuth callback handler async function handleOAuthReturn() { const params = new URLSearchParams(window.location.search); const provider = params.get('provider'); const success = params.get('success') === 'true'; if (provider) { await authManager.handleOAuthCallback(provider, success); } } ``` ## Event Types The AuthManager emits these events: ```typescript type AuthEvent = | { type: 'STATE_CHANGE'; data: AuthState } | { type: 'AUTH_ERROR'; data: { error: Error } } | { type: 'SESSION_CREATED'; data: { user: AuthUser } } | { type: 'SESSION_DESTROYED'; data: null } | { type: 'BACKUP_IMPORTED'; data: { type: string } } | { type: 'OAUTH_LINKED'; data: { provider: string } }; ``` ## State Structure ```typescript interface AuthState { isAuthenticated: boolean; isLoading: boolean; user: AuthUser | null; error: Error | null; } interface AuthUser { bapId: string; name?: string; address?: string; hasWalletCapabilities?: boolean; createdAt?: Date; // ... other user properties } ``` ## Common Patterns ### Protected Routes ```tsx function ProtectedRoute({ children }) { const authManager = createAuthManager({ apiUrl: '/api' }); const [state, setState] = useState(authManager.getState()); useEffect(() => { const unsubscribe = authManager.subscribe(() => { setState(authManager.getState()); }); return unsubscribe; }, []); if (!state.isAuthenticated) { return ; } return children; } ``` ### Session Persistence ```tsx function PersistentAuth() { const authManager = createAuthManager({ apiUrl: '/api' }); useEffect(() => { // Check for existing session on mount const checkSession = async () => { const encryptedBackup = localStorage.getItem('encryptedBackup'); if (encryptedBackup) { // Session exists, validate it const state = authManager.getState(); if (!state.isAuthenticated) { // Re-authenticate if needed console.log('Session expired, please sign in again'); } } }; checkSession(); }, []); } ``` ### Multi-Provider Support ```tsx function MultiProviderAuth() { const authManager = createAuthManager({ apiUrl: '/api', backupTypes: ['BapMasterBackup', 'OneSatBackup', 'WifBackup'] }); const handleImport = async (file) => { try { await authManager.importBackup(file); // Check which type was imported const state = authManager.getState(); console.log('Imported user:', state.user); } catch (error) { if (error.message.includes('password')) { // Prompt for password const password = prompt('Enter backup password:'); // Retry import with password } } }; } ``` ## Error Handling ```typescript authManager.subscribe((event) => { if (event.type === 'AUTH_ERROR') { const error = event.data.error; switch (error.code) { case 'INVALID_PASSWORD': showError('Invalid password'); break; case 'NETWORK_ERROR': showError('Network connection failed'); break; case 'SESSION_EXPIRED': showError('Session expired, please sign in again'); break; case 'BACKUP_CORRUPTED': showError('Backup file is corrupted'); break; default: showError('Authentication failed'); } } }); ``` ## Best Practices 1. **Single Instance**: Create one AuthManager instance per app 2. **Error Handling**: Always handle authentication errors 3. **State Subscription**: Subscribe to state changes for reactive UI 4. **Cleanup**: Unsubscribe from events when components unmount 5. **Security**: Never log sensitive data like passwords or private keys ## Troubleshooting ### State Not Updating ```typescript // Ensure you're subscribing to changes const unsubscribe = authManager.subscribe((event) => { // Update your UI state here updateUIState(authManager.getState()); }); // Don't forget to cleanup return () => unsubscribe(); ``` ### Import Failing ```typescript // Check supported backup types console.log('Supported types:', authManager.options?.backupTypes); // Validate file before import if (!file.type.match(/json|text/)) { throw new Error('Invalid file type'); } ``` ## Related Components * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - React provider wrapper * [createBigBlocksAuth](/docs/components/create-bigblocks-auth) - Lower-level auth core * [LoginForm](/docs/components/login-form) - Pre-built login UI * [SignupFlow](/docs/components/signup-flow) - Complete signup flow ## API Reference ### AuthManager Class The AuthManager provides a complete authentication system with: * Password-based authentication * Backup import/export * OAuth provider linking * Session management * Event-driven state updates * Wallet integration support All methods are async and return promises for easy integration with modern JavaScript applications. # createBigBlocksAuth URL: /docs/components/authentication/create-bigblocks-auth Framework-agnostic authentication core for Bitcoin-based authentication *** title: createBigBlocksAuth description: Framework-agnostic authentication core for Bitcoin-based authentication category: route-helpers ----------------------- A framework-agnostic authentication core that provides Bitcoin-based authentication primitives for any JavaScript framework. Creates a low-level auth instance with a universal handler pattern for maximum flexibility. ## Installation ```bash npx bigblocks add create-bigblocks-auth ``` ## Import ```typescript import { createBigBlocksAuth } from 'bigblocks'; ``` ## Basic Usage ```tsx import { createBigBlocksAuth } from 'bigblocks'; // Create authentication instance const auth = createBigBlocksAuth({ verifySignatures: true, timeWindow: 600000, // 10 minutes basePath: '/api/auth' }); // Use the universal handler const response = await auth.handler(request); ``` ## Configuration ```typescript interface BigBlocksAuthOptions { verifySignatures?: boolean; // Verify Bitcoin signatures (default: true) timeWindow?: number; // Signature validity window in ms (default: 600000) bodyEncoding?: 'hex' | 'base64' | 'utf8'; // Request body encoding (default: 'utf8') basePath?: string; // Base API path (default: '/api/auth') storage?: StorageAdapter; // Storage adapter storageNamespace?: string; // Storage key prefix backupTypes?: string[]; // Supported backup types } ``` ## Core API The auth instance provides: ### Universal Handler ```typescript // Handle any authentication request const response = await auth.handler(request); ``` ### API Methods ```typescript // Verify authentication const result = await auth.api.verifyAuth({ address: 'bitcoin-address', idKey: 'bap-id-key', authToken: 'signed-message', requestPath: '/api/protected', body: 'request-body' }); // Get session from headers const session = await auth.api.getSession(headers); // Generate backup const backup = auth.api.generateBackup(); // Encrypt backup const encrypted = await auth.api.encryptBackup(backup, password); // Decrypt backup const decrypted = await auth.api.decryptBackup(encrypted, password); ``` ## Framework Integrations ### Next.js App Router ```typescript // app/api/auth/[...auth]/route.ts import { createBigBlocksAuth } from 'bigblocks'; const auth = createBigBlocksAuth({ basePath: '/api/auth' }); export async function GET(request: Request) { return auth.handler(request); } export async function POST(request: Request) { return auth.handler(request); } ``` ### Express.js ```typescript import express from 'express'; import { createBigBlocksAuth } from 'bigblocks'; const app = express(); const auth = createBigBlocksAuth(); // Convert Express request to standard Request app.use('/api/auth/*', async (req, res) => { const url = `http://localhost${req.originalUrl}`; const request = new Request(url, { method: req.method, headers: req.headers, body: req.method !== 'GET' ? JSON.stringify(req.body) : undefined }); const response = await auth.handler(request); const body = await response.text(); res.status(response.status).send(body); }); ``` ### Fastify ```typescript import fastify from 'fastify'; import { createBigBlocksAuth } from 'bigblocks'; const app = fastify(); const auth = createBigBlocksAuth(); app.all('/api/auth/*', async (request, reply) => { const standardRequest = new Request(request.url, { method: request.method, headers: request.headers, body: request.body ? JSON.stringify(request.body) : undefined }); const response = await auth.handler(standardRequest); const body = await response.text(); reply.code(response.status).send(body); }); ``` ### Hono ```typescript import { Hono } from 'hono'; import { createBigBlocksAuth } from 'bigblocks'; const app = new Hono(); const auth = createBigBlocksAuth(); app.all('/api/auth/*', async (c) => { const response = await auth.handler(c.req.raw); return response; }); ``` ## Advanced Usage ### Custom Storage Adapter ```typescript import { createBigBlocksAuth } from 'bigblocks'; class RedisStorageAdapter { async get(key: string): Promise { return redis.get(key); } async set(key: string, value: string): Promise { await redis.set(key, value); } async delete(key: string): Promise { await redis.del(key); } } const auth = createBigBlocksAuth({ storage: new RedisStorageAdapter(), storageNamespace: 'bigblocks:auth:' }); ``` ### Custom Verification ```typescript const auth = createBigBlocksAuth({ verifySignatures: true, timeWindow: 300000, // 5 minutes for stricter security bodyEncoding: 'base64' // For binary data }); // Manual verification async function verifyRequest(req: Request) { const authHeader = req.headers.get('X-Auth-Token'); if (!authHeader) { return { success: false, error: 'Missing auth token' }; } const [address, idKey, signature] = authHeader.split(':'); return auth.api.verifyAuth({ address, idKey, authToken: signature, requestPath: new URL(req.url).pathname, body: await req.text() }); } ``` ### Session Management ```typescript const auth = createBigBlocksAuth(); // Middleware to attach session async function sessionMiddleware(req: Request): Promise { const session = await auth.api.getSession(req.headers); if (session) { // Attach session to request (req as any).session = session; } return req; } // Protected route handler async function protectedHandler(req: Request) { const session = (req as any).session; if (!session) { return new Response('Unauthorized', { status: 401 }); } return new Response(JSON.stringify({ message: 'Protected data', user: session.user })); } ``` ### Backup Operations ```typescript const auth = createBigBlocksAuth({ backupTypes: ['BapMasterBackup', 'OneSatBackup', 'WifBackup'] }); // Generate and encrypt backup async function exportBackup(password: string) { const backup = auth.api.generateBackup(); const encrypted = await auth.api.encryptBackup(backup, password); // Save to file const blob = new Blob([encrypted], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'wallet-backup.txt'; a.click(); } // Import and decrypt backup async function importBackup(file: File, password: string) { const encrypted = await file.text(); const backup = await auth.api.decryptBackup(encrypted, password); // Process backup console.log('Imported backup:', backup); return backup; } ``` ## Authentication Flow ### Client-Side ```typescript // Sign authentication request async function authenticatedFetch(url: string, options?: RequestInit) { const { address, idKey, privateKey } = getWalletInfo(); // Create message to sign const timestamp = Date.now(); const body = options?.body || ''; const message = `${url}:${body}:${timestamp}`; // Sign with Bitcoin private key const signature = await signMessage(message, privateKey); // Create auth token const authToken = `${address}:${idKey}:${signature}:${timestamp}`; return fetch(url, { ...options, headers: { ...options?.headers, 'X-Auth-Token': authToken } }); } ``` ### Server-Side Verification ```typescript const auth = createBigBlocksAuth(); async function handleProtectedRoute(request: Request) { // Auth handler automatically verifies the signature const authResponse = await auth.handler(request); if (!authResponse.ok) { return authResponse; // Return error response } // Get verified session const session = await auth.api.getSession(request.headers); // Process authenticated request return new Response(JSON.stringify({ message: 'Success', user: session?.user })); } ``` ## Route Patterns The universal handler supports these routes: * `POST /signin` - Sign in with Bitcoin signature * `POST /signout` - Sign out and clear session * `GET /session` - Get current session * `POST /verify` - Verify authentication token * `POST /backup/generate` - Generate wallet backup * `POST /backup/encrypt` - Encrypt backup * `POST /backup/decrypt` - Decrypt backup ## Error Handling ```typescript const auth = createBigBlocksAuth(); async function handleAuthError(request: Request) { try { const response = await auth.handler(request); return response; } catch (error) { console.error('Auth error:', error); if (error.message.includes('signature')) { return new Response('Invalid signature', { status: 401 }); } if (error.message.includes('expired')) { return new Response('Token expired', { status: 401 }); } return new Response('Authentication failed', { status: 500 }); } } ``` ## Best Practices 1. **Security**: Always use HTTPS in production 2. **Time Window**: Set appropriate signature expiry time 3. **Storage**: Use persistent storage for production 4. **Error Handling**: Provide clear error messages 5. **Logging**: Log authentication events for security ## Types ```typescript interface BigBlocksAuthPayload { address: string; // Bitcoin address idKey: string; // BAP identity key authToken: string; // Signed message requestPath: string; // API path body: string; // Request body timestamp?: string; // Optional timestamp } interface BigBlocksAuthResult { success: boolean; user?: AuthUser; error?: string; } interface BigBlocksSession { user: AuthUser; sessionId: string; expiresAt: Date; } ``` ## Troubleshooting ### Signature Verification Failed ```typescript // Check time synchronization const auth = createBigBlocksAuth({ timeWindow: 1200000 // 20 minutes for testing }); // Log verification details auth.api.verifyAuth(payload).catch(error => { console.error('Verification failed:', error); console.log('Payload:', payload); }); ``` ### Session Not Persisting ```typescript // Ensure storage is configured const auth = createBigBlocksAuth({ storage: new PersistentStorageAdapter(), storageNamespace: 'myapp:auth:' }); ``` ## Related Components * [createAuthManager](/docs/components/create-auth-manager) - Higher-level auth manager * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - React provider * [AuthButton](/docs/components/auth-button) - Pre-built auth UI * Framework adapters for Next.js, Express, Astro ## Notes for Improvement **Simplified Implementation**: The actual component is a universal handler pattern following the Better Auth approach. It's more focused on: * Universal request/response handling * Bitcoin signature verification * Session management via headers * Backup encryption/decryption utilities The prompt described a more complex client-side focused API, while the actual implementation is server-oriented with a clean handler pattern for easy framework integration. # IdentityGeneration URL: /docs/components/authentication/identity-generation Component for generating new Bitcoin identities or importing existing ones *** title: IdentityGeneration description: Component for generating new Bitcoin identities or importing existing ones category: backup-recovery ------------------------- import { IdentityGenerationDemo } from '@/components/docs/demos/IdentityGenerationDemo'; A streamlined component that provides options to generate a new Bitcoin identity or import an existing backup. It offers a simple interface with two primary actions, perfect for onboarding flows. ## Installation ```bash npx bigblocks add identity-generation ``` ## Import ```typescript import { IdentityGeneration } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | ---------- | ---------------------- | -------- | ------- | --------------------------------------- | | onGenerate | `() => void` | Yes | - | Handler when generate button is clicked | | onImport | `(file: File) => void` | Yes | - | Handler when import file is selected | | loading | `boolean` | No | `false` | Show loading state | | error | `string` | No | - | Error message to display | | className | `string` | No | - | Additional CSS classes | ## Basic Usage ```tsx import { IdentityGeneration } from 'bigblocks'; import { useRouter } from 'next/navigation'; export default function OnboardingPage() { const router = useRouter(); const handleGenerate = () => { // Navigate to identity creation flow router.push('/create-identity'); }; const handleImport = (file: File) => { // Process the imported file console.log('Importing backup file:', file.name); // Navigate to import flow router.push('/import-backup'); }; return ( ); } ``` ## Advanced Usage ### With Loading State ```tsx import { IdentityGeneration } from 'bigblocks'; import { useState } from 'react'; export default function LoadingExample() { const [loading, setLoading] = useState(false); const handleGenerate = async () => { setLoading(true); try { // Simulate async operation await new Promise(resolve => setTimeout(resolve, 2000)); // Navigate or process } finally { setLoading(false); } }; return ( console.log(file)} loading={loading} /> ); } ``` ### With Error Handling ```tsx import { IdentityGeneration } from 'bigblocks'; import { useState } from 'react'; export default function ErrorHandlingExample() { const [error, setError] = useState(); const handleImport = (file: File) => { setError(undefined); // Validate file if (!file.name.match(/\.(txt|json|enc)$/)) { setError('Invalid file type. Please select a backup file.'); return; } if (file.size > 10 * 1024 * 1024) { setError('File too large. Maximum size is 10MB.'); return; } // Process file processBackupFile(file); }; return ( console.log('Generate clicked')} onImport={handleImport} error={error} /> ); } ``` ### Custom Styling ```tsx import { IdentityGeneration } from 'bigblocks'; export default function StyledExample() { return (

Get Started

console.log('Generate')} onImport={(file) => console.log('Import', file)} className="max-w-md mx-auto" />
); } ``` ## Common Patterns ### In Onboarding Flow ```tsx import { IdentityGeneration } from 'bigblocks'; import { useState } from 'react'; export function OnboardingFlow() { const [step, setStep] = useState<'choice' | 'generate' | 'import'>('choice'); return (
{step === 'choice' && (

Welcome to BigBlocks

setStep('generate')} onImport={(file) => { // Store file for processing sessionStorage.setItem('importFile', file.name); setStep('import'); }} />
)} {step === 'generate' && (

Generate New Identity

{/* Identity creation component */}
)} {step === 'import' && (

Import Backup

{/* Backup import component */}
)}
); } ``` ### With File Processing ```tsx import { IdentityGeneration } from 'bigblocks'; export function ProcessingExample() { const processFile = async (file: File) => { const content = await file.text(); // Detect format if (content.startsWith('U2FsdGVkX1')) { console.log('Processing encrypted backup'); // Handle encrypted backup } else if (content.startsWith('{')) { console.log('Processing JSON backup'); // Handle JSON backup } else { console.log('Processing WIF backup'); // Handle WIF format } }; return ( { console.log('Creating new identity'); }} onImport={processFile} /> ); } ``` ### With Navigation ```tsx import { IdentityGeneration } from 'bigblocks'; import { useRouter } from 'next/navigation'; export function NavigationExample() { const router = useRouter(); return ( { router.push('/auth/create-identity'); }} onImport={(file) => { // Store file reference const fileUrl = URL.createObjectURL(file); sessionStorage.setItem('importFileUrl', fileUrl); router.push('/auth/import-backup'); }} /> ); } ``` ### In Modal Dialog ```tsx import { IdentityGeneration } from 'bigblocks'; import { useState } from 'react'; export function ModalExample() { const [showModal, setShowModal] = useState(true); return ( <> {showModal && (

Get Started

{ setShowModal(false); // Start generation flow }} onImport={(file) => { setShowModal(false); // Start import flow }} />
)} ); } ``` ## File Handling The component uses a hidden file input that accepts common backup formats: ```tsx // Internal file input configuration { const file = e.target.files?.[0]; if (file) onImport(file); }} /> ``` ## Styling The component uses Radix Themes Button components and can be customized with the className prop: ```css /* Default button arrangement */ .identity-generation { display: flex; flex-direction: column; gap: 1rem; } /* Custom styling example */ .custom-identity-generation { max-width: 400px; margin: 0 auto; } ``` ## Best Practices 1. **Clear Actions**: The two buttons clearly indicate the available options 2. **Error Feedback**: Always provide error messages for invalid files 3. **Loading States**: Show loading state during async operations 4. **File Validation**: Validate file type and size before processing 5. **Navigation**: Handle navigation after user selection ## Accessibility * Both buttons are keyboard accessible * Clear visual feedback for hover and focus states * Error messages are announced to screen readers * File input is properly labeled ## Troubleshooting ### Import Not Working * Check that onImport handler is defined * Verify file types are accepted * Ensure file input isn't blocked by browser ### Generate Not Triggering * Verify onGenerate handler is provided * Check for JavaScript errors in console * Ensure component isn't disabled via loading state ### Styling Issues * Check className is applied correctly * Verify Radix Themes is properly configured * Inspect for CSS conflicts ## Related Components * [BackupImport](/docs/components/backup-import) - Detailed backup import * [MnemonicDisplay](/docs/components/mnemonic-display) - Display recovery phrases * [BackupDownload](/docs/components/backup-download) - Download backups * [SignupFlow](/docs/components/signup-flow) - Complete signup process ## API Reference This component provides a simple interface for choosing between generating a new Bitcoin identity or importing an existing backup. ### Handler Types ```typescript type GenerateHandler = () => void; type ImportHandler = (file: File) => void; ``` ### File Object The File object passed to onImport contains: ```typescript interface File { name: string; size: number; type: string; lastModified: number; text(): Promise; arrayBuffer(): Promise; } ``` ## Notes for Improvement **Simplified Implementation**: The actual component is much simpler than the prompt described. It lacks: * Built-in identity generation logic (just triggers a callback) * Multiple generation modes (mnemonic vs random) * Direct identity/backup object handling * showImport prop to hide import option * generateMode prop for different generation methods The actual implementation is a basic choice component with two buttons that delegate all logic to the parent component via callbacks. # LoginForm URL: /docs/components/authentication/login-form Complete Bitcoin wallet login form with multiple authentication modes *** title: LoginForm description: Complete Bitcoin wallet login form with multiple authentication modes category: authentication ------------------------ import { LoginFormDemo } from '@/components/docs/demos/LoginFormDemo' Complete authentication form supporting Bitcoin wallet sign-in, sign-up, and restoration flows. LoginForm combines multiple [Radix Themes components](https://www.radix-ui.com/themes/docs/components) with Bitcoin-specific authentication logic, providing a complete user experience for wallet-based authentication including keypair generation, backup management, and session handling. ## Installation ```bash npx bigblocks add login-form ``` ## Import ```tsx import { LoginForm } from 'bigblocks'; ``` ## API Reference This component uses [Radix Themes components](https://www.radix-ui.com/themes/docs/components) for UI elements. | Prop | Type | Default | Description | | -------------------- | ----------------------------------- | ---------- | ---------------------------------------- | | mode | `'signin' \| 'signup' \| 'restore'` | `'signin'` | Authentication flow mode | | onSuccess | `(user: AuthUser) => void` | - | Callback when authentication succeeds | | onError | `(error: AuthError) => void` | - | Callback when authentication fails | | enableProfileSync | `boolean` | `false` | Enable automatic profile synchronization | | maxDiscoveryAttempts | `number` | `3` | Max attempts for profile discovery | | className | `string` | - | Additional CSS classes | | style | `React.CSSProperties` | - | Inline styles | | cardProps | `object` | - | Props for card container styling | | buttonProps | `object` | - | Props for button styling | ## Basic Usage ```tsx import { LoginForm, BitcoinAuthProvider } from 'bigblocks'; export default function LoginPage() { return ( { console.log('Login successful:', user); router.push('/dashboard'); }} onError={(error) => { console.error('Login failed:', error); }} /> ); } ``` ## Authentication Modes LoginForm supports three distinct authentication flows: ```tsx // Sign-in mode - authenticate existing users router.push('/dashboard')} /> // Sign-up mode - create new Bitcoin identity router.push('/onboarding')} /> // Restore mode - recover from backup file router.push('/dashboard')} /> ``` ## Profile Synchronization Enable automatic profile discovery and synchronization: ```tsx { console.log('User profiles synced:', user.profiles); }} /> ``` ## Custom Styling Customize the form appearance using cardProps and buttonProps: ```tsx ``` ## Authentication Flow LoginForm automatically handles the complete authentication process: 1. **Sign-in**: Password entry → Backup decryption → Session creation 2. **Sign-up**: Password creation → Backup generation → Download → Account creation 3. **Restore**: File import → Password entry → Backup decryption → Session restoration For styling customization, see the [Radix Themes documentation](https://www.radix-ui.com/themes/docs/components). ## Related Components * [AuthButton](/docs/components/auth-button) - Simple authentication button * [BitcoinAuthProvider](/docs/components/bitcoin-auth-provider) - Authentication context provider * [BackupDownload](/docs/components/backup-download) - Backup file management # OAuthProviders URL: /docs/components/authentication/oauth-providers OAuth provider selection component for linking cloud backup storage *** title: OAuthProviders description: OAuth provider selection component for linking cloud backup storage category: wallet-integrations ----------------------------- import { OAuthProvidersDemo } from '@/components/docs/demos/OAuthProvidersDemo'; A component for displaying and managing OAuth provider connections for cloud backup storage. Supports multiple providers with official brand colors and flexible configuration. ## Installation ```bash npx bigblocks add oauth-providers ``` ## Import ```typescript import { OAuthProviders } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | --------------- | -------------------------------- | -------- | ----------------- | ----------------------------- | | providers | `OAuthProvider[]` | No | Default providers | Custom provider configuration | | action | `'signin' \| 'signup' \| 'link'` | No | `'link'` | Action context | | callbackUrl | `string` | No | - | OAuth callback URL | | linkedProviders | `string[]` | No | `[]` | Already linked provider IDs | | onProviderClick | `(provider: string) => void` | No | - | Provider click handler | | disabled | `boolean` | No | `false` | Disable all providers | | loading | `boolean` | No | `false` | Loading state | | className | `string` | No | - | Additional CSS classes | | size | `'1' \| '2' \| '3'` | No | `'2'` | Button size | ## Types ```typescript interface OAuthProvider { id: string; name: string; icon: React.ReactNode; enabled?: boolean; } ``` ## Basic Usage ```tsx import { OAuthProviders } from 'bigblocks'; export default function BackupSettings() { const handleProviderClick = (provider: string) => { console.log('Selected provider:', provider); // Initiate OAuth flow window.location.href = `/api/auth/link?provider=${provider}`; }; return ( ); } ``` ## Advanced Usage ### With Custom Providers ```tsx import { OAuthProviders } from 'bigblocks'; const customProviders = [ { id: 'google', name: 'Google', icon: , enabled: true, }, { id: 'github', name: 'GitHub', icon: , enabled: true, }, { id: 'microsoft', name: 'Microsoft', icon: , enabled: false, // Disabled }, ]; export default function CustomProviders() { return ( { console.log('Clicked:', provider); }} /> ); } ``` ### With Linked Status ```tsx import { OAuthProviders } from 'bigblocks'; import { useConnectedAccounts } from '@/hooks/useConnectedAccounts'; export default function LinkedProviders() { const { data: accounts } = useConnectedAccounts(); const linkedProviders = accounts?.map(a => a.provider) || []; return ( { if (linkedProviders.includes(provider)) { // Already linked - maybe unlink? console.log('Already linked:', provider); } else { // Link new provider window.location.href = `/api/auth/link?provider=${provider}`; } }} /> ); } ``` ### Different Actions ```tsx import { OAuthProviders } from 'bigblocks'; export default function ActionExamples() { return (
{/* Sign in with OAuth */} { window.location.href = `/api/auth/signin?provider=${provider}`; }} /> {/* Sign up with OAuth */} { window.location.href = `/api/auth/signup?provider=${provider}`; }} /> {/* Link for backup */} { window.location.href = `/api/auth/link?provider=${provider}`; }} />
); } ``` ### With Loading State ```tsx import { OAuthProviders } from 'bigblocks'; import { useState } from 'react'; export default function LoadingExample() { const [isLoading, setIsLoading] = useState(false); const handleProviderClick = async (provider: string) => { setIsLoading(true); try { await linkProvider(provider); } finally { setIsLoading(false); } }; return ( ); } ``` ### Custom Sizing ```tsx import { OAuthProviders } from 'bigblocks'; export default function SizingExample() { return (
); } ``` ## Brand Colors The component exports official brand colors for OAuth providers: ```tsx import { OAUTH_BRAND_COLORS } from 'bigblocks'; // Access brand colors const googleBlue = OAUTH_BRAND_COLORS.google.blue; // #4285F4 const githubDark = OAUTH_BRAND_COLORS.github; // #24292e const twitterBlue = OAUTH_BRAND_COLORS.twitter; // #1DA1F2 const handcashGreen = OAUTH_BRAND_COLORS.handcash; // #38CB7C const discordPurple = OAUTH_BRAND_COLORS.discord; // #5865F2 const facebookBlue = OAUTH_BRAND_COLORS.facebook; // #1877F2 const microsoftBlue = OAUTH_BRAND_COLORS.microsoft; // #00BCF2 ``` ## Common Patterns ### In Settings Page ```tsx import { OAuthProviders } from 'bigblocks'; export function SecuritySettings() { const { data: user } = useAuth(); const linkedProviders = user?.connectedAccounts || []; return (

Cloud Backup Providers

Link providers to backup your wallet

{ if (linkedProviders.includes(provider)) { if (confirm(`Unlink ${provider}?`)) { unlinkProvider(provider); } } else { linkProvider(provider); } }} />
{linkedProviders.length === 0 && (

No providers linked yet

)} {linkedProviders.length > 0 && (

Linked: {linkedProviders.join(', ')}

)}
); } ``` ### In Signup Flow ```tsx import { OAuthProviders } from 'bigblocks'; export function SignupStep() { const [step, setStep] = useState('create'); return (
{step === 'create' && (

Create Your Account

setStep('backup')} />
)} {step === 'backup' && (

Backup Your Wallet

Link a cloud provider for automatic backups

{ // Store provider choice sessionStorage.setItem('backupProvider', provider); // Redirect to OAuth window.location.href = `/api/auth/link?provider=${provider}`; }} />
)}
); } ``` ### With Custom Styling ```tsx import { OAuthProviders } from 'bigblocks'; export function StyledProviders() { return (
{ console.log('Selected:', provider); }} />
); } ``` ## Provider Setup Each provider requires OAuth app configuration: ### Google 1. Visit [Google Cloud Console](https://console.cloud.google.com) 2. Create OAuth 2.0 credentials 3. Add redirect URI: `https://yourdomain.com/api/auth/callback/google` 4. Enable Google Drive API for backup storage ### GitHub 1. Visit [GitHub Developer Settings](https://github.com/settings/developers) 2. Create OAuth App 3. Add redirect URI: `https://yourdomain.com/api/auth/callback/github` 4. Request `gist` scope for backup storage ### Twitter 1. Visit [Twitter Developer Portal](https://developer.twitter.com) 2. Create OAuth 2.0 app 3. Add redirect URI: `https://yourdomain.com/api/auth/callback/twitter` ### HandCash 1. Visit [HandCash Developer Portal](https://developer.handcash.io) 2. Create app 3. Add redirect URI: `https://yourdomain.com/api/auth/callback/handcash` ## Styling The component uses Radix Themes buttons and can be customized: ```css /* Custom provider button styles */ .oauth-providers { display: flex; gap: 1rem; flex-wrap: wrap; } .oauth-provider-button { min-width: 120px; } .oauth-provider-button[data-linked="true"] { opacity: 0.7; position: relative; } .oauth-provider-button[data-linked="true"]::after { content: "✓"; position: absolute; top: 0; right: 0; background: green; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; } ``` ## Best Practices 1. **Clear Action Context**: Use appropriate `action` prop for context 2. **Loading States**: Show loading feedback during OAuth flows 3. **Error Handling**: Handle OAuth failures gracefully 4. **Security**: Always validate OAuth responses server-side 5. **Accessibility**: Ensure keyboard navigation works ## Troubleshooting ### Providers Not Showing * Check that providers array is properly configured * Ensure `enabled` is true for each provider * Verify component is wrapped in theme provider ### Click Handler Not Working * Ensure `onProviderClick` is properly defined * Check for event propagation issues * Verify buttons aren't disabled ### OAuth Flow Issues * Verify redirect URIs match exactly * Check OAuth app permissions/scopes * Ensure callback handlers are implemented ## Related Components * [SignupFlow](/docs/components/signup-flow) - Uses during registration * [LoginForm](/docs/components/login-form) - OAuth sign-in option * [CloudBackupManager](/docs/components/cloud-backup-manager) - Manages backups * [OAuthRestoreFlow](/docs/components/oauth-restore-flow) - Restore from OAuth ## API Reference ### Default Providers The component includes these providers by default: * Google (id: 'google') * GitHub (id: 'github') * Twitter (id: 'twitter') * HandCash (id: 'handcash') Each can be customized or filtered using the `providers` prop. ## Notes for Improvement **Enhanced Implementation**: The actual component is more sophisticated than the prompt suggested: * Supports custom provider configurations * Includes brand color constants * Has size variants for different contexts * More flexible action contexts (signin/signup/link) * Better TypeScript support with proper interfaces # SignOutButton URL: /docs/components/authentication/sign-out-button Secure sign-out button with confirmation dialog and session cleanup *** title: SignOutButton description: Secure sign-out button with confirmation dialog and session cleanup category: authentication ------------------------ A secure sign-out button component that handles session cleanup while preserving encrypted backups. It features optional confirmation dialogs, loading states, and customizable appearance to fit various UI contexts. ## Installation ```bash npx bigblocks add sign-out-button ``` ## Import ```typescript import { SignOutButton } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | -------------- | -------------------------------------------------- | -------- | -------------------------------------- | ------------------------------ | | redirectTo | `string` | No | `'/'` | URL to redirect after sign out | | confirmSignOut | `boolean` | No | `false` | Show confirmation dialog | | confirmMessage | `string` | No | `'Are you sure you want to sign out?'` | Custom confirmation message | | variant | `'solid' \| 'soft' \| 'outline' \| 'ghost'` | No | `'soft'` | Button style variant | | color | `'gray' \| 'red' \| 'orange' \| 'blue' \| 'green'` | No | `'gray'` | Button color | | size | `'1' \| '2' \| '3' \| '4'` | No | `'3'` | Button size (Radix scale) | | showIcon | `boolean` | No | `true` | Show exit icon | | children | `React.ReactNode` | No | `'Sign Out'` | Custom button text | | className | `string` | No | - | Additional CSS classes | | onSignOut | `() => void` | No | - | Callback after sign out | | showClearInfo | `boolean` | No | `false` | Show what will be cleared | ## Basic Usage ```tsx import { SignOutButton } from 'bigblocks'; export default function Header() { return ( ); } ``` ## Advanced Usage ### With Confirmation Dialog ```tsx import { SignOutButton } from 'bigblocks'; export default function SecuritySettings() { return ( ); } ``` ### Custom Sign Out Handler ```tsx import { SignOutButton } from 'bigblocks'; export default function ProfileMenu() { const handleSignOut = async () => { // Clean up app-specific data await clearLocalCache(); // Track analytics analytics.track('user_signed_out', { location: 'profile_menu', timestamp: Date.now() }); // Show toast notification toast.success('Signed out successfully'); }; return ( ); } ``` ### With Clear Info Display ```tsx import { SignOutButton } from 'bigblocks'; export default function DetailedSignOut() { return ( ); } ``` ### In Dropdown Menu ```tsx import { SignOutButton } from 'bigblocks'; import { DropdownMenu } from '@radix-ui/themes'; export function UserMenu() { return ( Profile Settings ); } ``` ## Common Patterns ### Header Integration ```tsx import { SignOutButton } from 'bigblocks'; import { useAuth } from '@/hooks/useAuth'; export function AppHeader() { const { isAuthenticated } = useAuth(); return (

My App

{isAuthenticated && ( )}
); } ``` ### Mobile Responsive ```tsx import { SignOutButton } from 'bigblocks'; export function ResponsiveSignOut() { return ( Sign Out ); } ``` ### Settings Page ```tsx import { SignOutButton } from 'bigblocks'; export function AccountSettings() { return (

Account

Sign Out

Sign out of your account. Your encrypted backup will be preserved.

); } ``` ## Data Management ### What Gets Cleared When signing out, the following data is cleared: 1. **Session Storage** * Decrypted backup data * Temporary authentication tokens * Active session information 2. **Authentication State** * User context * Authentication status * Active profile 3. **Server Session** * NextAuth session cookies * Server-side session data 4. **Cache** * React Query cache * API response cache ### What Gets Preserved The following data remains after sign out: 1. **Encrypted Backup** * Stored in localStorage * Password-protected * Ready for next sign in 2. **OAuth Links** * Connected provider information * OAuth backup references 3. **User Preferences** * Theme settings * UI preferences * Language settings ## Confirmation Dialog When `confirmSignOut` is enabled, the component shows a modal with: * Custom confirmation message * Clear information (if enabled) * Cancel button * Confirm button Example dialog content: ``` Are you sure you want to sign out? This will clear: • Current session • Temporary data Your encrypted backup will remain safe. [Cancel] [Sign Out] ``` ## Styling The button uses Radix Themes styling system: ```tsx // Different variants // Filled background // Subtle background // Border only // Minimal styling // Different colors // Default // Danger/warning // Caution // Info // Success // Different sizes // Extra small // Small // Medium (default) // Large ``` ## Best Practices 1. **Confirmation for Important Flows**: Enable confirmation when signing out would interrupt important work 2. **Color Coding**: Use red color for emphasis in security contexts 3. **Placement**: Common locations include headers, profile menus, and settings pages 4. **Clear Information**: Show what will be cleared in sensitive applications 5. **Loading States**: The button shows a spinner during the sign-out process ## Accessibility * **Auto-hide**: Only renders when user is authenticated * **Keyboard Navigation**: Fully keyboard accessible * **Screen Readers**: Proper ARIA labels and announcements * **Focus Management**: Proper focus handling in confirmation dialog ## Security Considerations 1. **Client-Side Cleanup**: Ensures all sensitive session data is cleared 2. **Server Coordination**: Properly invalidates server sessions 3. **Backup Protection**: Never touches encrypted backup data 4. **No Data Loss**: Preserves all persistent user data ## Troubleshooting ### Button Not Showing * Verify user is authenticated * Check that component is inside `BitcoinAuthProvider` * Ensure proper React Query setup ### Sign Out Not Working * Check console for errors * Verify API endpoints are accessible * Ensure proper session configuration ### Redirect Not Working * For Next.js apps, ensure router is properly configured * Check that redirect URL is valid * Verify no middleware is blocking navigation ## Related Components * [LoginForm](/docs/components/login-form) - Sign in form * [AuthButton](/docs/components/auth-button) - Generic auth button * [ProfileDropdownMenu](/docs/components/profile-dropdown-menu) - Profile menu with sign out * [AuthFlowOrchestrator](/docs/components/auth-flow-orchestrator) - Complete auth flows ## API Reference ### Internal Behavior The component internally: 1. Checks authentication status 2. Clears session storage 3. Calls sign out API 4. Clears authentication context 5. Redirects (if specified) 6. Calls onSignOut callback ### Session Cleanup The sign-out process: ```typescript 1. Clear sessionStorage 2. Clear authentication state 3. Invalidate server session 4. Clear React Query cache 5. Preserve encrypted backup 6. Redirect to specified URL ``` # SignupFlow URL: /docs/components/authentication/signup-flow Multi-step signup process for creating new Bitcoin wallets *** title: SignupFlow description: Multi-step signup process for creating new Bitcoin wallets category: authentication ------------------------ A comprehensive multi-step signup component for creating new Bitcoin wallets with built-in identity generation, password setup, and backup management. It provides a complete onboarding experience with proper error handling and state management. ## Installation ```bash npx bigblocks add signup-flow ``` ## Import ```typescript import { SignupFlow } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | --------- | ---------------------------- | -------- | ------- | ----------------------------- | | onSuccess | `(user: AuthUser) => void` | No | - | Callback when signup succeeds | | onError | `(error: AuthError) => void` | No | - | Callback for error handling | | className | `string` | No | - | Additional CSS classes | ## Basic Usage ```tsx import { SignupFlow, BitcoinAuthProvider } from 'bigblocks'; import { useRouter } from 'next/navigation'; export default function SignupPage() { const router = useRouter(); const handleSuccess = (user) => { console.log('Signup successful:', user); router.push('/dashboard'); }; const handleError = (error) => { console.error('Signup failed:', error); }; return ( ); } ``` ## Advanced Usage ### With Custom Error Handling ```tsx import { SignupFlow } from 'bigblocks'; import { toast } from 'sonner'; export default function SignupWithErrorHandling() { return ( { toast.success('Account created successfully!'); router.push('/onboarding'); }} onError={(error) => { // Handle specific error types switch (error.code) { case 'USER_EXISTS': toast.error('An account already exists. Please sign in.'); router.push('/signin'); break; case 'NETWORK_ERROR': toast.error('Network error. Please check your connection.'); break; case 'INVALID_PASSWORD': toast.error('Password does not meet requirements.'); break; default: toast.error(error.message || 'Signup failed. Please try again.'); } }} /> ); } ``` ### With Analytics Tracking ```tsx import { SignupFlow } from 'bigblocks'; import { analytics } from '@/lib/analytics'; export default function TrackedSignup() { const startTime = Date.now(); return ( { const duration = Date.now() - startTime; analytics.track('signup_completed', { userId: user.id, duration: duration, profileCount: user.profiles.length, hasMultipleProfiles: user.profiles.length > 1 }); // Set user for future analytics analytics.identify(user.id, { address: user.address, createdAt: new Date().toISOString() }); router.push('/welcome'); }} onError={(error) => { analytics.track('signup_failed', { error: error.code, duration: Date.now() - startTime }); }} /> ); } ``` ### With Custom Styling ```tsx import { SignupFlow } from 'bigblocks'; export default function StyledSignup() { return (
{ router.push('/dashboard'); }} />
); } ``` ### In Modal ```tsx import { SignupFlow } from 'bigblocks'; import { Modal } from '@radix-ui/themes'; export function SignupModal({ isOpen, onClose }) { return ( Create Your Bitcoin Wallet { console.log('Signup completed:', user); onClose(); router.push('/dashboard'); }} onError={(error) => { if (error.code !== 'USER_CANCELLED') { toast.error('Signup failed'); } }} /> ); } ``` ## Signup Flow Steps The SignupFlow component guides users through these steps: ### 1. Welcome Step * Introduction to Bitcoin wallet creation * Terms of service acceptance (if configured) * Clear value proposition ### 2. Identity Generation * Automatic Bitcoin keypair generation * Visual feedback during generation * Secure client-side process ### 3. Password Setup * Password creation for encryption * Password strength indicator * Confirmation field * Requirements display ### 4. Backup Creation * Encrypted backup generation * Download prompt * Security instructions * Verification checkbox ### 5. Success Confirmation * Account creation confirmation * Next steps guidance * Navigation to dashboard ## Common Patterns ### Full Page Signup ```tsx import { SignupFlow } from 'bigblocks'; export function SignupPage() { return (

Create Account

{ router.push('/onboarding'); }} />
); } ``` ### With Navigation Options ```tsx import { SignupFlow } from 'bigblocks'; import Link from 'next/link'; export function SignupWithNav() { return (
{ router.push('/dashboard'); }} />

Already have an account?{' '} Sign in

); } ``` ### With Loading Overlay ```tsx import { SignupFlow } from 'bigblocks'; import { useState } from 'react'; export function SignupWithLoading() { const [isProcessing, setIsProcessing] = useState(false); return ( <> {isProcessing && (

Setting up your account...

)} { setIsProcessing(true); try { // Additional setup await setupUserProfile(user); await createDefaultSettings(user.id); router.push('/welcome'); } finally { setIsProcessing(false); } }} /> ); } ``` ## Security Features 1. **Client-Side Key Generation**: All cryptographic operations happen in the browser 2. **Password Encryption**: Private keys are encrypted before any storage 3. **No Password Transmission**: Passwords never leave the client 4. **Secure Backup Format**: Industry-standard encryption for backups 5. **Session Management**: Secure session creation after signup ## Error Types ```typescript interface AuthError { code: | 'USER_EXISTS' // Account already exists | 'NETWORK_ERROR' // Network connectivity issues | 'INVALID_PASSWORD' // Password requirements not met | 'GENERATION_FAILED' // Key generation failed | 'BACKUP_FAILED' // Backup creation failed | 'SESSION_FAILED' // Session creation failed | 'USER_CANCELLED'; // User cancelled the flow message: string; } ``` ## Styling The SignupFlow uses Radix Themes and respects the BitcoinThemeProvider: ```css /* Component structure */ .signup-flow-container { /* Inherits theme styles */ } .signup-step { /* Individual step styling */ } .signup-navigation { /* Step navigation buttons */ } ``` ## State Management The component internally manages: * Current step tracking * Form data across steps * Loading states * Error states * Validation state * Backup generation status ## Best Practices 1. **Error Handling**: Always implement onError to handle failures gracefully 2. **Success Routing**: Navigate users appropriately after signup 3. **Loading States**: Show feedback during async operations 4. **Backup Emphasis**: Ensure users understand backup importance 5. **Mobile Optimization**: Test on mobile devices for touch interactions ## Troubleshooting ### Component Not Rendering * Ensure wrapped in `BitcoinAuthProvider` * Check that React Query is properly configured * Verify API endpoints are accessible ### Key Generation Failing * Check browser crypto API support * Ensure sufficient entropy available * Verify no browser extensions blocking crypto ### Backup Download Issues * Check browser download permissions * Ensure popup blockers aren't interfering * Verify file download API compatibility ## Related Components * [LoginForm](/docs/components/login-form) - Sign in existing users * [AuthFlowOrchestrator](/docs/components/auth-flow-orchestrator) - Unified auth flows * [BackupDownload](/docs/components/backup-download) - Backup management * [IdentityGeneration](/docs/components/identity-generation) - Key generation * [OAuthProviders](/docs/components/oauth-providers) - OAuth integration ## API Reference ### AuthUser Type ```typescript interface AuthUser { id: string; // User's BAP ID address: string; // Bitcoin address idKey: string; // Identity key profiles: ProfileInfo[]; // User profiles activeProfileId: string; // Current profile } ``` ### Internal Flow 1. Generate Bitcoin keypair 2. Create password 3. Encrypt private key 4. Generate backup file 5. Store encrypted backup 6. Create server session 7. Return authenticated user ## Notes for Improvement **Implementation Differences**: The actual component is simpler than the prompt described: * No `onCancel` callback * No `showBackupStep` or `showOAuthStep` props to control flow * No configurable steps * OAuth linking is not part of the current implementation * The flow is more streamlined with fewer customization options # BackupDownload URL: /docs/components/backup/backup-download Component for downloading encrypted wallet backups with security features *** title: BackupDownload description: Component for downloading encrypted wallet backups with security features categories: \['backup-recovery', 'security', 'wallet'] providers: \['BitcoinAuthProvider'] ----------------------------------- import { BackupDownloadDemo } from '@/components/docs/demos/BackupDownloadDemo' import { ComponentBadges } from '@/components/docs/ComponentBadges' BackupDownload combines the [Radix Button primitive](https://www.radix-ui.com/themes/docs/components/button) with Bitcoin backup generation, providing secure encrypted wallet backup downloads with user guidance and safety instructions. ## Installation ```bash npx bigblocks add backup-download ``` ## Import ```typescript import { BackupDownload } from 'bigblocks'; ``` This component extends the [Button primitive](https://www.radix-ui.com/themes/docs/components/button) and inherits all its props. ## Props | Prop | Type | Required | Default | Description | | --------------- | ----------------- | -------- | ------- | -------------------------------------------------- | | backup | `BapMasterBackup` | Yes | - | The backup data to download | | password | `string` | No | - | Password for encryption (if not already encrypted) | | onDownloaded | `() => void` | No | - | Callback when download is complete | | requireDownload | `boolean` | No | `false` | Whether download is required before proceeding | | className | `string` | No | - | Additional CSS classes | ## Basic Usage ```tsx import { BackupDownload } from 'bigblocks'; export default function BackupExample() { const backup = { // BapMasterBackup data idKey: 'L1...', derivationScheme: 'master', profiles: [], bitcoin: {} }; return ( { console.log('Backup downloaded successfully'); }} /> ); } ``` ## Advanced Usage ### Required Download ```tsx import { BackupDownload } from 'bigblocks'; import { useState } from 'react'; export default function RequiredBackupFlow() { const [downloadComplete, setDownloadComplete] = useState(false); const backup = generateBackup(); // Your backup generation logic return (

Step 2: Download Your Backup

You must download your backup before continuing.

{ setDownloadComplete(true); }} />
); } ``` ### With Custom Styling ```tsx import { BackupDownload } from 'bigblocks'; export default function StyledBackupDownload() { const backup = getUserBackup(); return ( { toast.success('Backup saved successfully!'); }} /> ); } ``` ### In Registration Flow ```tsx import { BackupDownload } from 'bigblocks'; import { useAuth } from '@/hooks/useAuth'; export default function RegistrationBackupStep() { const { backup, password } = useAuth(); const [downloaded, setDownloaded] = useState(false); return (

Save Your Backup

This backup file is the only way to recover your account. Download and store it safely.

{ setDownloaded(true); analytics.track('backup_downloaded'); }} /> {downloaded && (
✓ Backup downloaded successfully
)}
); } ``` ## Common Patterns ### Backup Settings Page ```tsx import { BackupDownload } from 'bigblocks'; import { useWallet } from '@/hooks/useWallet'; export function BackupSettings() { const { backup } = useWallet(); const [password, setPassword] = useState(''); const [showBackup, setShowBackup] = useState(false); const handlePasswordSubmit = (e) => { e.preventDefault(); // Validate password setShowBackup(true); }; return (

Download Backup

{!showBackup ? (
setPassword(e.target.value)} required />
) : ( { console.log('New backup downloaded'); setShowBackup(false); setPassword(''); }} /> )}
); } ``` ### With Progress Tracking ```tsx import { BackupDownload } from 'bigblocks'; export function BackupWithProgress() { const [step, setStep] = useState(1); const backup = generateBackup(); return (
{step === 1 && (

Create Password

setStep(2)} />
)} {step === 2 && (

Download Backup

setStep(3)} />
)} {step === 3 && (

Backup Complete!

Your wallet is now safely backed up.

)}
); } ``` ### Error Handling ```tsx import { BackupDownload } from 'bigblocks'; export function BackupWithErrorHandling() { const backup = getUserBackup(); const [error, setError] = useState(null); if (!backup) { return
No backup available
; } return (
{error && (
{error}
)} { try { // Additional validation or tracking validateBackupDownload(); console.log('Backup downloaded successfully'); } catch (err) { setError('Failed to validate backup download'); } }} />
); } ``` ## File Format The downloaded backup file is encrypted and contains: ```typescript // Encrypted backup format (after decryption) interface BapMasterBackup { idKey: string; // Master private key derivationScheme: string; // Key derivation scheme profiles: ProfileInfo[]; // User profiles bitcoin: { // Bitcoin-specific data mnemonic?: string; // Optional seed phrase network?: string; // Bitcoin network }; } ``` The file is saved with a timestamp-based filename: * Format: `bitcoin-backup-{timestamp}.txt` * Content: Base64 encoded encrypted data ## Security Considerations 1. **Encryption**: Backups are encrypted using AES-256-GCM 2. **Password**: Never stored, only used for encryption 3. **Client-side**: All encryption happens in the browser 4. **No Network**: Download doesn't require network requests 5. **User Responsibility**: Users must safely store their backups ## Styling The component uses Radix Themes and can be styled with: ```css /* Custom styling example */ .backup-download-container { background: var(--orange-2); border: 1px solid var(--orange-6); border-radius: var(--radius-3); padding: var(--space-4); } ``` ## Best Practices 1. **Password Strength**: Encourage strong passwords for encryption 2. **Multiple Copies**: Advise users to make multiple backup copies 3. **Offline Storage**: Recommend offline storage (USB, paper) 4. **Test Recovery**: Suggest testing backup restoration 5. **Regular Updates**: Remind users to update backups after profile changes ## Troubleshooting ### Download Not Working * Check that backup data is valid BapMasterBackup format * Ensure browser allows file downloads * Verify password is provided if encryption is needed ### File Not Encrypted * Confirm password prop is provided * Check that backup isn't already encrypted * Verify encryption library is loaded ### Callback Not Firing * Ensure onDownloaded prop is a valid function * Check browser console for errors * Verify download completes successfully ## Related Components * [BackupImport](/docs/components/backup-import) - Import backup files * [FileImport](/docs/components/file-import) - General file import * [MemberExport](/docs/components/member-export) - Export member backups * [QRCodeRenderer](/docs/components/qr-code-renderer) - QR code backups ## API Reference ### BapMasterBackup Type The backup data structure expected by the component: ```typescript interface BapMasterBackup { idKey: string; derivationScheme: string; profiles: Array<{ idKey: string; name?: string; // ... other profile data }>; bitcoin: { mnemonic?: string; network?: string; }; } ``` ### File Generation The component handles: 1. Encryption of backup data (if password provided) 2. Base64 encoding 3. File blob creation 4. Download trigger 5. Cleanup ## Notes for Improvement **Major Discrepancy**: The prompt describes a much more feature-rich component than what's actually implemented. The actual component is simpler with: * No variant prop (button vs card) * No size options * No preview functionality * No progress tracking * No error callback * No custom filename support * No instruction display options * No backend integration The actual implementation focuses solely on downloading an encrypted backup file with minimal UI. # BackupImport URL: /docs/components/backup/backup-import Component for importing Bitcoin wallet backups from various formats *** title: BackupImport description: Component for importing Bitcoin wallet backups from various formats categories: \['backup-recovery', 'onboarding', 'security'] providers: \[] -------------- import { BackupImportDemo } from '@/components/docs/demos/BackupImportDemo' import { ComponentBadges } from '@/components/docs/ComponentBadges' BackupImport combines native HTML file input with Bitcoin backup processing, providing a streamlined interface for importing encrypted wallet backups with validation, profile synchronization, and secure file handling. ## Installation ```bash npx bigblocks add backup-import ``` ## Import ```typescript import { BackupImport } from 'bigblocks'; ``` This component extends native HTML file input functionality with Bitcoin-specific backup processing. ## Props | Prop | Type | Required | Default | Description | | -------------------- | --------------------------------------- | -------- | ------- | ---------------------------------- | | onImport | `(file: File) => Promise \| void` | Yes | - | Handler for file import | | disabled | `boolean` | No | `false` | Disable the import button | | className | `string` | No | - | Additional CSS classes | | showLabel | `boolean` | No | `true` | Show the label text | | enableProfileSync | `boolean` | No | `false` | Enable profile synchronization | | maxDiscoveryAttempts | `number` | No | `3` | Max attempts for profile discovery | | onImportSuccess | `() => void` | No | - | Callback when import succeeds | ## Basic Usage ```tsx import { BackupImport } from 'bigblocks'; export default function RestorePage() { const handleImport = async (file: File) => { try { // Process the backup file const content = await file.text(); // Your backup processing logic await processBackup(content); console.log('Backup imported successfully'); } catch (error) { console.error('Import failed:', error); throw error; // Re-throw to show error in UI } }; return ( { console.log('Import completed!'); }} /> ); } ``` ## Advanced Usage ### With Authentication Manager ```tsx import { BackupImport } from 'bigblocks'; import { useAuthManager } from '@/hooks/useAuthManager'; export default function AuthBackupImport() { const authManager = useAuthManager(); return ( { await authManager.importBackup(file); }} onImportSuccess={() => { router.push('/dashboard'); }} /> ); } ``` ### With Profile Sync ```tsx import { BackupImport } from 'bigblocks'; export default function ProfileSyncImport() { return ( { toast.success('Backup imported with profile sync'); }} /> ); } ``` ### Disabled State ```tsx import { BackupImport } from 'bigblocks'; import { useState } from 'react'; export default function ConditionalImport() { const [isProcessing, setIsProcessing] = useState(false); return ( { setIsProcessing(true); try { await processBackupFile(file); } finally { setIsProcessing(false); } }} disabled={isProcessing} showLabel={!isProcessing} /> ); } ``` ### Custom Styling ```tsx import { BackupImport } from 'bigblocks'; export default function StyledImport() { return ( ); } ``` ## Common Patterns ### In Restore Flow ```tsx import { BackupImport } from 'bigblocks'; import { useState } from 'react'; export function RestoreFlow() { const [step, setStep] = useState<'import' | 'password' | 'complete'>('import'); const [backupFile, setBackupFile] = useState(null); return (
{step === 'import' && (

Import Your Backup

{ setBackupFile(file); setStep('password'); }} />
)} {step === 'password' && backupFile && (

Enter Password

{ await decryptAndImport(backupFile, password); setStep('complete'); }} />
)} {step === 'complete' && (

Import Complete!

)}
); } ``` ### With Error Handling ```tsx import { BackupImport } from 'bigblocks'; import { useState } from 'react'; export function ImportWithErrors() { const [error, setError] = useState(null); return (
{error && (
{error}
)} { setError(null); try { // Validate file if (!file.name.match(/\.(txt|json|enc)$/)) { throw new Error('Invalid file type. Please select a backup file.'); } if (file.size > 10 * 1024 * 1024) { throw new Error('File too large. Maximum size is 10MB.'); } await processBackup(file); } catch (err) { setError(err.message); throw err; // Re-throw for component error handling } }} onImportSuccess={() => { setError(null); toast.success('Backup imported successfully'); }} />
); } ``` ### Multiple Import Options ```tsx import { BackupImport } from 'bigblocks'; export function ImportOptions() { return (

Import from File

{ console.log('File import complete'); }} />
OR

Import from Cloud

); } ``` ## File Handling The component accepts various backup file formats: ```typescript async function handleImport(file: File) { const content = await file.text(); // Detect format if (content.startsWith('U2FsdGVkX1')) { // Encrypted backup const password = await promptForPassword(); const decrypted = decrypt(content, password); await restoreFromBackup(decrypted); } else if (content.startsWith('{')) { // JSON backup const backup = JSON.parse(content); await restoreFromBackup(backup); } else if (content.match(/^[KL5][1-9A-HJ-NP-Za-km-z]{50,51}$/)) { // WIF format await restoreFromWIF(content); } else { throw new Error('Unknown backup format'); } } ``` ## Styling The component uses Radix Themes and can be customized: ```css /* Default structure */ .backup-import-container { /* Button styling from Radix */ } .backup-import-input { /* Hidden file input */ display: none; } ``` ## Best Practices 1. **Validation**: Always validate file format and size before processing 2. **Error Handling**: Provide clear error messages for common issues 3. **Progress Feedback**: Show loading state during import 4. **Success Confirmation**: Always confirm successful import 5. **Security**: Never log or expose sensitive backup data ## Security Considerations 1. **Client-Side Processing**: Handle backup data only in the browser 2. **File Validation**: Check file size and format before processing 3. **Password Protection**: Prompt for passwords for encrypted backups 4. **Memory Cleanup**: Clear sensitive data from memory after use 5. **Error Messages**: Don't expose sensitive information in errors ## Troubleshooting ### Import Button Not Working * Check that onImport handler is properly defined * Ensure component isn't disabled * Verify file input isn't blocked by browser ### File Not Processing * Check file format is supported * Verify file isn't corrupted * Ensure async operations are properly handled ### Success Callback Not Firing * Make sure onImport doesn't throw errors * Verify onImportSuccess prop is passed * Check that import process completes successfully ## Related Components * [BackupDownload](/docs/components/backup-download) - Download backups * [FileImport](/docs/components/file-import) - Generic file import * [IdentityGeneration](/docs/components/identity-generation) - Create new identity * [LoginForm](/docs/components/login-form) - Sign in with existing backup ## API Reference ### File Processing The onImport handler receives a File object: ```typescript interface File { name: string; size: number; type: string; lastModified: number; text(): Promise; arrayBuffer(): Promise; } ``` ### Error Handling Errors thrown in onImport will be caught and displayed by the component. Return or throw errors to show them to users. ## Notes for Improvement **Major Simplification**: The actual component is much simpler than the prompt described. It lacks: * Multiple format support options * Built-in validation * Progress tracking * Format detection * The extensive backend API integration described * Drag and drop functionality * Conflict resolution * Preview capabilities The actual implementation is a basic file input button that delegates all processing to the onImport handler. # CloudBackupManager URL: /docs/components/backup/cloud-backup-manager Component for managing encrypted cloud backups stored with OAuth providers *** title: CloudBackupManager description: Component for managing encrypted cloud backups stored with OAuth providers category: backup-recovery ------------------------- import { CloudBackupManagerDemo } from '@/components/docs/demos/CloudBackupManagerDemo'; A streamlined component for managing cloud-stored wallet backups via OAuth providers. It provides status checking, update capabilities, and automatic synchronization of encrypted backups. ## Installation ```bash npx bigblocks add cloud-backup-manager ``` ## Import ```typescript import { CloudBackupManager } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | ----------------- | ------------------------------------- | -------- | ------- | ------------------------------- | | checkBackupStatus | `() => Promise` | No | - | Function to check backup status | | updateCloudBackup | `() => Promise` | No | - | Function to update cloud backup | | onStatusChange | `(status: CloudBackupStatus) => void` | No | - | Callback when status changes | | className | `string` | No | - | Additional CSS classes | ## Types ```typescript interface CloudBackupStatus { hasCloudBackup: boolean; isOutdated?: boolean; lastUpdated?: number; provider?: string; } ``` ## Basic Usage ```tsx import { CloudBackupManager } from 'bigblocks'; export default function BackupSettings() { const checkStatus = async () => { // Check backup status from your backend const response = await fetch('/api/backup/status'); return response.json(); }; const updateBackup = async () => { // Update cloud backup await fetch('/api/backup/sync', { method: 'POST' }); }; return ( { console.log('Backup status:', status); }} /> ); } ``` ## Advanced Usage ### With Authentication Context ```tsx import { CloudBackupManager } from 'bigblocks'; import { useAuth } from '@/hooks/useAuth'; export default function AuthenticatedBackup() { const { user, backup } = useAuth(); const checkBackupStatus = async () => { if (!user) throw new Error('Not authenticated'); const response = await fetch('/api/backup/status', { headers: { 'X-Auth-Token': user.authToken, }, }); return response.json(); }; const updateCloudBackup = async () => { if (!backup) throw new Error('No backup available'); await fetch('/api/backup/sync', { method: 'POST', headers: { 'X-Auth-Token': user.authToken, 'Content-Type': 'application/json', }, body: JSON.stringify({ backup }), }); }; return ( { if (status.isOutdated) { console.log('Backup is outdated, consider updating'); } }} /> ); } ``` ### With Custom Status Handling ```tsx import { CloudBackupManager } from 'bigblocks'; import { useState, useEffect } from 'react'; export default function CustomStatusHandling() { const [lastSync, setLastSync] = useState(null); const [provider, setProvider] = useState(null); const handleStatusChange = (status: CloudBackupStatus) => { if (status.lastUpdated) { setLastSync(new Date(status.lastUpdated)); } if (status.provider) { setProvider(status.provider); } }; return (
{lastSync && (

Last synced: {lastSync.toLocaleString()}

)} {provider && (

Backed up with: {provider}

)}
); } ``` ### Auto-sync Implementation ```tsx import { CloudBackupManager } from 'bigblocks'; import { useEffect, useRef } from 'react'; export default function AutoSyncBackup() { const intervalRef = useRef(null); const checkBackupStatus = async () => { const response = await fetch('/api/backup/status'); const status = await response.json(); // Auto-update if backup is outdated by more than 24 hours if (status.lastUpdated) { const hoursSinceUpdate = (Date.now() - status.lastUpdated) / (1000 * 60 * 60); if (hoursSinceUpdate > 24) { status.isOutdated = true; } } return status; }; useEffect(() => { // Check status every 5 minutes intervalRef.current = setInterval(() => { checkBackupStatus(); }, 5 * 60 * 1000); return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } }; }, []); return ( { if (status.isOutdated) { // Trigger notification showNotification('Your backup is outdated'); } }} /> ); } ``` ### With Error Handling ```tsx import { CloudBackupManager } from 'bigblocks'; import { useState } from 'react'; export default function ErrorHandlingExample() { const [error, setError] = useState(null); const checkBackupStatus = async () => { try { setError(null); const response = await fetch('/api/backup/status'); if (!response.ok) { throw new Error('Failed to check backup status'); } return response.json(); } catch (err) { setError(err.message); throw err; } }; const updateCloudBackup = async () => { try { setError(null); const response = await fetch('/api/backup/sync', { method: 'POST', }); if (!response.ok) { throw new Error('Failed to update backup'); } } catch (err) { setError(err.message); throw err; } }; return (
{error && (
{error}
)}
); } ``` ## Common Patterns ### In Settings Page ```tsx import { CloudBackupManager } from 'bigblocks'; export function BackupSettingsSection() { return (

Backup Management

Keep your wallet backup synchronized with your cloud provider

Backup Tips

  • • Keep your backup password secure
  • • Update your backup after profile changes
  • • Backups are end-to-end encrypted
); } ``` ### With Multiple Providers ```tsx import { CloudBackupManager } from 'bigblocks'; import { useState } from 'react'; export function MultiProviderBackup() { const [activeProvider, setActiveProvider] = useState(null); const checkBackupStatus = async () => { // Check status across multiple providers const providers = ['google', 'github', 'dropbox']; for (const provider of providers) { const response = await fetch(`/api/backup/status?provider=${provider}`); const status = await response.json(); if (status.hasCloudBackup) { setActiveProvider(provider); return status; } } return { hasCloudBackup: false }; }; return (
{activeProvider && (

Active provider: {activeProvider}

)}
); } ``` ### In Dashboard Widget ```tsx import { CloudBackupManager } from 'bigblocks'; export function DashboardBackupWidget() { return (

Cloud Backup

Auto-sync enabled
{ // Update dashboard metrics updateDashboardMetrics({ backupStatus: status.hasCloudBackup ? 'active' : 'none', lastSync: status.lastUpdated, }); }} />
); } ``` ## API Reference This component provides cloud backup management functionality with configurable status checking and update capabilities. ## API Integration ### Status Check Endpoint ```typescript // GET /api/backup/status interface BackupStatusResponse { hasCloudBackup: boolean; isOutdated?: boolean; lastUpdated?: number; provider?: string; size?: number; profileCount?: number; } ``` ### Sync Endpoint ```typescript // POST /api/backup/sync interface BackupSyncRequest { backup?: string; // Optional encrypted backup data forceUpdate?: boolean; } interface BackupSyncResponse { success: boolean; provider: string; timestamp: number; backupId: string; } ``` ## Features * **Status Monitoring**: Real-time backup status checking * **Automatic Updates**: Detect and update outdated backups * **Provider Display**: Show which OAuth provider stores the backup * **Last Update Time**: Display when backup was last synchronized * **Status Callbacks**: React to backup status changes * **Error Handling**: Graceful error handling with user feedback ## Styling The component uses Radix Themes and can be customized: ```css /* Custom styling */ .cloud-backup-manager { padding: 1rem; border: 1px solid var(--gray-5); border-radius: var(--radius-3); } .backup-status { display: flex; align-items: center; gap: 0.5rem; } .update-button { margin-top: 0.5rem; } ``` ## Best Practices 1. **Regular Checks**: Implement periodic status checks 2. **Error Handling**: Always handle API errors gracefully 3. **User Feedback**: Show clear status messages 4. **Auto-sync**: Consider implementing automatic synchronization 5. **Security**: Ensure all backups are encrypted before cloud storage ## Security Considerations 1. **Encryption**: All backups are encrypted client-side 2. **OAuth Only**: Uses OAuth providers as storage, not authentication 3. **No Credentials**: Never store provider credentials 4. **Token Handling**: Secure handling of auth tokens 5. **HTTPS Only**: Always use secure connections ## Troubleshooting ### Status Not Updating * Verify checkBackupStatus returns correct format * Check network connectivity * Ensure proper authentication headers ### Update Failing * Verify updateCloudBackup is properly implemented * Check OAuth provider permissions * Ensure backup data is properly formatted ### Provider Not Showing * Confirm provider field is returned from status check * Verify OAuth connection is active * Check provider permissions ## Related Components * [BackupDownload](/docs/components/backup-download) - Download local backups * [BackupImport](/docs/components/backup-import) - Import backup files * [OAuthProviders](/docs/components/oauth-providers) - OAuth provider management * [IdentityGeneration](/docs/components/identity-generation) - Create new identities ## Notes for Improvement **Simplified Implementation**: The actual component is more focused than the prompt suggested: * No multi-provider UI management (handled by callbacks) * No built-in auto-sync configuration * No direct provider linking/unlinking * Delegates all API operations to parent component * Focus on status display and update triggering The actual implementation provides a clean interface for backup status management while leaving the complex provider and sync logic to the implementing application. # MnemonicDisplay URL: /docs/components/backup/mnemonic-display Component for displaying, verifying, or importing mnemonic seed phrases *** title: MnemonicDisplay description: Component for displaying, verifying, or importing mnemonic seed phrases category: backup-recovery ------------------------- import { MnemonicDisplayDemo } from '@/components/docs/demos/MnemonicDisplayDemo'; A versatile component for handling mnemonic seed phrases with three modes: viewing, verifying, and importing. It provides a secure interface for displaying recovery phrases with optional verification and import capabilities. ## Installation ```bash npx bigblocks add mnemonic-display ``` ## Import ```typescript import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | -------------------- | ---------------------------------- | -------- | -------- | -------------------------------------------------- | | mnemonic | `string` | No | - | Mnemonic phrase to display (for view/verify modes) | | mode | `MnemonicMode` | No | `'view'` | Display mode: 'view', 'verify', or 'import' | | onResult | `(result: MnemonicResult) => void` | No | - | Callback with operation result | | onContinue | `() => void` | No | - | Handler for continue action | | onBack | `() => void` | No | - | Handler for back action | | showCopyButton | `boolean` | No | `true` | Show copy to clipboard button | | requireVerification | `boolean` | No | `false` | Require verification in view mode | | wordCount | `12 \| 24` | No | `12` | Expected word count for import | | autoCompleteLastWord | `boolean` | No | `false` | Auto-complete the last word | | className | `string` | No | - | Additional CSS classes | ## Modes ### View Mode Display a mnemonic phrase securely with optional copy functionality: ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export default function ViewMnemonic() { const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; return ( { console.log('User acknowledged'); }} showCopyButton={true} /> ); } ``` ### Verify Mode Test user's backup by requiring them to confirm specific words: ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export default function VerifyMnemonic() { const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; return ( { if (result.verified) { console.log('Verification successful'); } else { console.log('Verification failed'); } }} /> ); } ``` ### Import Mode Allow users to enter their own mnemonic phrase: ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export default function ImportMnemonic() { return ( { if (result.importedMnemonic) { console.log('Imported:', result.importedMnemonic); } }} /> ); } ``` ## Result Types ```typescript type MnemonicResult = { verified?: boolean; // For verify mode importedMnemonic?: string; // For import mode words?: string[]; // Word array for processing }; ``` ## Advanced Usage ### Complete Backup Flow ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; import { useState } from 'react'; export function BackupFlow() { const [step, setStep] = useState<'view' | 'verify' | 'complete'>('view'); const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; return (
{step === 'view' && (

Your Recovery Phrase

setStep('verify')} showCopyButton={true} />
)} {step === 'verify' && (

Verify Your Backup

{ if (result.verified) { setStep('complete'); } else { alert('Please try again'); } }} onBack={() => setStep('view')} />
)} {step === 'complete' && (

Backup Complete!

Your recovery phrase has been verified.

)}
); } ``` ### Import with Validation ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; import { validateMnemonic } from '@bsv/sdk'; export function ImportWithValidation() { const handleImport = async (result: MnemonicResult) => { if (!result.importedMnemonic) return; try { // Validate mnemonic const isValid = validateMnemonic(result.importedMnemonic); if (!isValid) { throw new Error('Invalid mnemonic phrase'); } // Process valid mnemonic await processImport(result.importedMnemonic); } catch (error) { console.error('Import failed:', error); } }; return ( window.history.back()} /> ); } ``` ### View with Custom Styling ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export function StyledMnemonicView() { return (

Recovery Phrase

{ console.log('Proceeding to next step'); }} />
⚠️ Never share these words with anyone
); } ``` ### Conditional Copy Button ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; import { useState } from 'react'; export function ConditionalCopy() { const [allowCopy, setAllowCopy] = useState(false); return (
console.log('Continue')} />
); } ``` ## Common Patterns ### In SignupFlow ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export function SignupMnemonicStep({ mnemonic, onComplete }) { const [verified, setVerified] = useState(false); return (
{!verified ? ( setVerified(true)} /> ) : ( { if (result.verified) { onComplete(); } }} /> )}
); } ``` ### Recovery Flow ```tsx import { MnemonicDisplay, MnemonicMode } from 'bigblocks'; export function RecoveryFlow() { const [mnemonic, setMnemonic] = useState(null); return (

Recover Your Wallet

{ if (result.importedMnemonic) { setMnemonic(result.importedMnemonic); // Proceed with recovery recoverWallet(result.importedMnemonic); } }} />
); } ``` ## Features by Mode ### View Mode Features * Grid display of numbered words * Optional copy to clipboard * Security warnings * Verification requirement option * Continue button ### Verify Mode Features * Random word verification * Input validation * Error feedback * Back navigation * Success/failure callbacks ### Import Mode Features * Word count selection (12 or 24) * Auto-completion for last word * BIP39 word list validation * Paste support * Progress tracking ## Styling The component uses Radix Themes and supports custom styling: ```css /* Word grid styling */ .mnemonic-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.5rem; } /* Word item styling */ .mnemonic-word { padding: 0.5rem; background: var(--gray-2); border-radius: var(--radius-2); font-family: monospace; } ``` ## Best Practices 1. **Security First**: Always show security warnings in view mode 2. **Verification**: Require verification for new wallet creation 3. **Copy Protection**: Consider disabling copy for sensitive contexts 4. **Clear Instructions**: Provide mode-specific guidance 5. **Error Handling**: Validate mnemonics before processing ## Accessibility * Keyboard navigation for all interactive elements * Screen reader announcements for verification * Clear focus indicators * Semantic HTML structure ## Troubleshooting ### Verification Failing * Ensure correct mnemonic is passed * Check for extra spaces or formatting * Verify word indices are correct ### Import Not Working * Validate BIP39 word list compatibility * Check word count matches expected * Ensure proper whitespace handling ### Copy Not Working * Check browser clipboard permissions * Verify showCopyButton prop * Test in different browsers ## Related Components * [IdentityGeneration](/docs/components/identity-generation) - Generate new identities * [BackupDownload](/docs/components/backup-download) - Download encrypted backups * [SignupFlow](/docs/components/signup-flow) - Complete signup with mnemonic * [BackupImport](/docs/components/backup-import) - Import from various formats ## API Reference This component provides secure mnemonic phrase handling with three distinct modes for viewing, verifying, and importing seed phrases. ### MnemonicMode Enum ```typescript enum MnemonicMode { View = "view", Verify = "verify", Import = "import" } ``` ### MnemonicResult Type ```typescript type MnemonicResult = { verified?: boolean; // Verification success (verify mode) importedMnemonic?: string; // Imported phrase (import mode) words?: string[]; // Word array for processing }; ``` ## Notes for Improvement **Mode-Based Implementation**: The actual component is more sophisticated than the prompt suggested, with three distinct modes: * View mode for displaying phrases * Verify mode for testing user knowledge * Import mode for entering phrases The prompt described mainly view mode features, while the actual implementation provides a complete mnemonic handling solution with verification and import capabilities. # ArtifactDisplay URL: /docs/components/developer/artifact-display Universal content renderer for blockchain artifacts (ordinals, inscriptions, files) *** title: ArtifactDisplay description: Universal content renderer for blockchain artifacts (ordinals, inscriptions, files) categories: \[blockchain, content, display, media] -------------------------------------------------- import { ComponentBadges } from '@/components/docs/ComponentBadges'; import { ArtifactDisplayDemo } from '@/components/docs/demos/ArtifactDisplayDemo'; A universal content renderer for blockchain artifacts including ordinals, inscriptions, and files. This component supports a wide variety of content types including images, videos, audio, HTML, text, JSON, SVG, PDF, and 3D models. It uses the bitcoin-image library for blockchain URL processing. ## Demo ## API Reference This component is a custom implementation that handles various content types and media formats. For specific media types, consider using: * Native HTML elements (`img`, `video`, `audio`) * [SVG elements](https://developer.mozilla.org/en-US/docs/Web/SVG) for vector graphics * [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) for interactive content ## Installation ```bash npx bigblocks add artifact-display ``` ## Import ```typescript import { ArtifactDisplay, ArtifactType } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | ------------ | ---------------------------------- | -------- | ------- | ------------------------------------------------------- | | artifact | `ArtifactData` | Yes | - | The artifact data object containing source and metadata | | size | `number` | No | - | Display size in pixels | | maxWidth | `number` | No | - | Maximum width constraint | | showControls | `boolean` | No | `false` | Whether to show controls/footer | | allowZoom | `boolean` | No | `false` | Whether to allow zooming on the artifact | | showMetadata | `boolean` | No | `false` | Whether to show artifact metadata | | loading | `boolean` | No | `false` | Loading state indicator | | error | `string` | No | - | Error message to display | | className | `string` | No | - | Custom CSS classes | | onClick | `(artifact: ArtifactData) => void` | No | - | Click handler for the artifact | | onDownload | `(artifact: ArtifactData) => void` | No | - | Download handler | | onShare | `(artifact: ArtifactData) => void` | No | - | Share handler | | fallback | `React.ReactNode` | No | - | Custom fallback component for unsupported types | ## ArtifactData Interface ```typescript interface ArtifactData { /** The URL or blockchain reference to the artifact */ src: string; /** Content type (MIME type) */ contentType?: string; /** Artifact type (auto-detected if not provided) */ type?: ArtifactType; /** Size in bytes */ size?: number; /** Display name */ name?: string; /** Description */ description?: string; /** Transaction ID (for blockchain artifacts) */ txid?: string; /** Output index */ vout?: number; /** Inscription number */ number?: string | number; /** Additional metadata */ metadata?: Record; } ``` ## Artifact Types ```typescript enum ArtifactType { Image = "image", Video = "video", Audio = "audio", HTML = "html", Text = "text", JSON = "json", SVG = "svg", PDF = "pdf", Model = "model", Unknown = "unknown" } ``` ## Basic Usage ```tsx import { ArtifactDisplay } from 'bigblocks'; export default function Example() { const artifact = { src: "https://ordfs.network/abc123_0", contentType: "image/png", name: "My NFT", txid: "abc123", vout: 0 }; return ( ); } ``` ## Advanced Usage ### With Event Handlers ```tsx import { ArtifactDisplay, ArtifactData } from 'bigblocks'; export default function InteractiveArtifact() { const handleClick = (artifact: ArtifactData) => { console.log('Artifact clicked:', artifact.name); }; const handleDownload = (artifact: ArtifactData) => { // Custom download logic console.log('Downloading:', artifact.src); }; const handleShare = (artifact: ArtifactData) => { // Share functionality navigator.share({ title: artifact.name, url: artifact.src }); }; const artifact = { src: "ordfs://abc123_0", contentType: "video/mp4", name: "Bitcoin Documentary", description: "A short documentary about Bitcoin", size: 5242880, // 5MB txid: "abc123", vout: 0, metadata: { duration: "2:30", creator: "Satoshi" } }; return ( ); } ``` ### With Custom Fallback ```tsx import { ArtifactDisplay } from 'bigblocks'; export default function ArtifactWithFallback() { const artifact = { src: "blockchain://unknown-format", type: ArtifactType.Unknown, name: "Unknown Artifact" }; const customFallback = (

This artifact type is not supported

Download Raw File
); return ( ); } ``` ## Common Patterns ### Gallery Display ```tsx import { ArtifactDisplay } from 'bigblocks'; export function ArtifactGallery({ artifacts }) { return (
{artifacts.map((artifact) => ( openLightbox(art)} /> ))}
); } ``` ### Loading States ```tsx import { ArtifactDisplay } from 'bigblocks'; import { useState, useEffect } from 'react'; export function AsyncArtifact({ txid }) { const [artifact, setArtifact] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetchArtifact(txid) .then(setArtifact) .catch(err => setError(err.message)) .finally(() => setLoading(false)); }, [txid]); return ( ); } ``` ## Troubleshooting ### Artifact Not Displaying * Ensure the `src` URL is accessible * Check that the `contentType` is correctly set or can be auto-detected * Verify blockchain URLs are properly formatted (e.g., `ordfs://txid_vout`) ### Performance Issues * Use the `size` prop to constrain large images/videos * Implement lazy loading for galleries with many artifacts * Consider thumbnails for initial display ### CORS Errors * Blockchain URLs may require proxy configuration * Ensure your bitcoin-image library is properly configured * Check browser console for specific CORS error messages ## Related Components * [BitcoinImage](/docs/components/bitcoin-image) - Optimized image display for blockchain sources * [FileImport](/docs/components/file-import) - Import files to create artifacts * [QRCodeRenderer](/docs/components/qr-code-renderer) - Display artifact URLs as QR codes ## API Reference ### ArtifactType Enum The component exports an `ArtifactType` enum for type-safe artifact type specification. ### Type Detection If `type` is not provided in the artifact data, the component will attempt to auto-detect based on: 1. The `contentType` MIME type 2. File extension in the `src` URL 3. Blockchain metadata ## Notes for Improvement **Discrepancy Alert**: The original prompt for this component incorrectly described it as displaying Bitcoin transactions, blocks, and scripts. The actual implementation is a media/content renderer for blockchain artifacts. If transaction/block/script display functionality is needed, consider creating separate components like `TransactionDisplay`, `BlockDisplay`, and `ScriptDisplay`. # DataPushButton URL: /docs/components/developer/data-push-button Push structured data to the Bitcoin blockchain using predefined protocol templates *** title: DataPushButton description: Push structured data to the Bitcoin blockchain using predefined protocol templates category: droplit ----------------- A powerful component for pushing structured data to the Bitcoin blockchain using predefined protocol templates. Unlike traditional OP\_RETURN data storage, this component uses the droplit protocol for zero-cost data transactions while maintaining blockchain permanence. [View Component Preview →](/component-preview/data-push-button) ## Installation ```bash npx bigblocks add data-push-button ``` ## Import ```typescript import { DataPushButton } from 'bigblocks'; ``` ## Props | Prop | Type | Required | Default | Description | | -------------------- | ---------------------------------------------------------------------- | -------- | -------------- | -------------------------------------------- | | onSuccess | `(result: { txid: string; data: string[]; template: string }) => void` | No | - | Callback when data is successfully pushed | | onError | `(error: Error) => void` | No | - | Error callback | | data | `string[]` | No | - | Custom data array to push (disables form UI) | | template | `DataTemplate` | No | First template | Pre-selected protocol template | | buttonText | `string` | No | `'Push Data'` | Custom button text | | variant | `'solid' \| 'soft' \| 'outline' \| 'ghost'` | No | `'solid'` | Button variant style | | size | `'1' \| '2' \| '3' \| '4'` | No | `'2'` | Button size | | showTemplateSelector | `boolean` | No | `true` | Show protocol template selector | | showPreview | `boolean` | No | `true` | Show data preview before pushing | | className | `string` | No | - | Additional CSS classes | | color | `'blue' \| 'green' \| 'orange' \| 'red' \| 'purple' \| 'gray'` | No | `'orange'` | Button color theme | | requireAuth | `boolean` | No | `false` | Require authentication | | disabled | `boolean` | No | `false` | Disable the button | ## Basic Usage ```tsx import { DataPushButton } from 'bigblocks'; function MyComponent() { return ( { console.log('Data pushed:', result.txid); console.log('Template used:', result.template); console.log('Data array:', result.data); }} onError={(error) => { console.error('Push failed:', error); }} /> ); } ``` ## Advanced Usage ### With Custom Template Selection ```tsx { alert(`Posted! TX ID: ${result.txid}`); }} /> ``` ### Button-Only Mode with Custom Data ```tsx { console.log('Market listing created:', result.txid); }} /> ``` ## Common Patterns ### Social Media Integration ```tsx function SocialPostForm() { const [content, setContent] = useState(''); return (