ποΈ Architecture Deep Dive
Explore the intricate details of SuperSafe Wallet's Professionally Standardized Service Worker architecture and understand how each component works together.
Executive Summaryβ
SuperSafe Wallet is a modern Ethereum-compatible browser extension wallet implementing a Professionally Standardized Service Worker architecture with Smart Native Connection for seamless multichain dApp integration. Built with React 18, ethers.js v6, and Chrome Extension Manifest V3.
Key Architectural Featuresβ
- β Professionally Standardized Architecture: Service worker as single source of truth
- β Smart Native Connection: Real chainIds only, zero compatibility hacks
- β Multichain Support: 7 active networks (SuperSeed, Optimism, Ethereum, Base, BSC, Arbitrum, Shardeum)
- β Stream-Based Communication: Native Chrome long-lived connections
- β Unified Vault System: Military-grade AES-256-GCM encryption
- β Thin Client Pattern: Frontend as lightweight presentation layer
- β Enterprise Signing System: Robust request management and recovery
- β Bebop Integration: Native swap support with partner fees
- β Relay.link Integration: Cross-chain swaps across 85+ blockchains
- β WalletConnect V2: Full Reown WalletKit implementation
- β Framework Detection: Automatic dApp framework identification
System Metricsβ
Total Project Files: 183 JavaScript/JSX files
Total Lines of Code: ~25,000 lines
Architecture Pattern: Professionally Standardized Service Worker
Security Level: Military-grade encryption
Supported Networks: 7 active networks
Response Time: <150ms average
Vault Encryption: AES-256-GCM + PBKDF2
System Architectureβ
High-Level Architecture Diagramβ
graph TB
subgraph "Chrome Browser Environment"
subgraph "Web Pages Context"
DAPP[π dApp Websites]
PROVIDER[π‘ EIP-1193 Provider]
CONTENT[π Content Script]
end
subgraph "Extension Context"
POPUP[π₯οΈ Popup UI - React]
BACKGROUND[βοΈ Background Service Worker]
end
subgraph "Storage Layer"
VAULT[π Unified Vault]
SESSION[πΎ Session Storage]
LOCAL[ποΈ Local Storage]
end
end
subgraph "External Services"
SUPERSEED[π SuperSeed RPC]
BEBOP[π Bebop Swap API]
RELAY[π Relay.link Cross-Chain]
WALLETCONNECT[π WalletConnect/Reown]
APIS[π Price & Token APIs]
end
%% Communication Flow
DAPP --> PROVIDER
PROVIDER --> CONTENT
CONTENT -.Stream.-> BACKGROUND
POPUP -.Stream.-> BACKGROUND
BACKGROUND --> VAULT
BACKGROUND --> SESSION
BACKGROUND --> LOCAL
BACKGROUND --> SUPERSEED
BACKGROUND --> BEBOP
BACKGROUND --> RELAY
BACKGROUND --> WALLETCONNECT
BACKGROUND --> APIS
style DAPP fill:#e1f5fe
style POPUP fill:#f3e5f5
style BACKGROUND fill:#fff3e0
style VAULT fill:#ffebee
Component Interaction Modelβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (Thin Client) β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββββββ β
β β React UI β β Adapters β β Stream Manager β β
β β Components ββββ (Frontend) ββββ (Long-lived ports) β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β Chrome Streams
β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Background Script (Single Source of Truth) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Stream Handlers β β
β β - Session - Provider - Swap - Send - Blockchain β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Core Controllers β β
β β - BackgroundSessionController (3,979 lines) β β
β β - BackgroundControllers (497 lines) β β
β β β’ TokenController β’ NetworkController β β
β β β’ TransactionController β’ NetworkSwitchService β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Enterprise Managers β β
β β - SigningRequestManager - PopupManager β β
β β - EIP1193EventsManager - AutoEscalationManager β β
β β - StreamPersistenceManager β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Handler Layer β β
β β - walletHandlers - contractHandlers β β
β β - providerHandlers - AllowListManager β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β External Integrations β β
β β - WalletConnect Manager - Bebop Integration β β
β β - Relay.link Integration - Cross-chain swaps β β
β β - Transaction History Service - Explorer Adapters β β
β β - SuperSeed API Wrapper - Secure API Client β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Storage Layer β
β ββββββββββββββββ ββββββββββββββββ βββββββββββββββββββββββββ β
β β Unified Vaultβ β Session β β Local β β
β β (Encrypted) β β Storage β β Storage β β
β ββββββββββββββββ ββββββββββββββββ βββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Core Design Principlesβ
1. Single Source of Truthβ
All state lives in the background service worker.
- Frontend components are purely presentational
- No direct storage access from frontend
- All mutations go through background controllers
- State synchronization via Chrome streams
Benefits:
- Eliminates race conditions
- Prevents storage context isolation issues
- Simplified state management
- Single point of control for security
2. Thin Client Patternβ
Frontend is a lightweight presentation layer.
// β WRONG: Frontend doing business logic
const wallet = await createWallet(privateKey);
await saveToStorage(wallet);
// β
CORRECT: Frontend delegates to background
const result = await FrontendSessionAdapter.createWallet(privateKey);
Frontend Responsibilities:
- Render UI components
- Handle user input
- Display data from background
- Route user actions to background
Background Responsibilities:
- State management
- Cryptographic operations
- Storage access
- Business logic
- External API calls
3. Stream-Based Communicationβ
Native Chrome long-lived connections for efficiency.
// Frontend creates persistent connection
const port = chrome.runtime.connect({ name: 'session' });
// Background listens on named channels
backgroundStreamManager.onMessage('session', async (message, port) => {
// Handle message
return { success: true, data: result };
});
Stream Channels:
session- Session and wallet operationsprovider- dApp provider requests (EIP-1193)swap- Swap quote and executionsend- Token transfer operationsblockchain- Blockchain queriesapi- External API calls
4. Zero Frontend Cryptoβ
All cryptographic operations isolated in background.
- Private keys never leave background context
- Vault encryption/decryption in background only
- Signing operations in background only
- Password handling in background only
Security Benefits:
- Reduced attack surface
- Memory isolation
- Audit-friendly architecture
- Simplified security model
5. Professionally Standardized Controllersβ
Modular controller pattern for separation of concerns.
BackgroundControllers {
tokenController // ERC20 token management
networkController // Network switching & configuration
transactionController // Transaction history & management
networkSwitchService // Centralized network switching
}
Each controller:
- Single responsibility
- Independent initialization
- Event-driven architecture
- Stateless where possible
Component Architectureβ
Background Script (3,220 lines)β
Location: src/background.js
Primary Responsibilities:
- Service worker initialization and lifecycle
- Stream handler registration
- Manager orchestration
- WalletConnect integration
- Global state coordination
Key Components:
// Core Controllers
backgroundSessionController // Session & wallet management
backgroundControllers // Token, network, transaction controllers
// Enterprise Managers
signingRequestManager // Signing request lifecycle
popupManager // Popup window management
eip1193EventsManager // EIP-1193 event broadcasting
autoEscalationManager // Auto-approval for trusted dApps
// External Integrations
walletConnectManager // WalletConnect v2 / Reown
secureApiClient // Secure external API calls
bebopTokenService // Bebop token list management
BackgroundSessionController (3,979 lines)β
Location: src/background/BackgroundSessionController.js
Core Functionality:
- Vault management (create, unlock, lock)
- Wallet management (create, import, remove)
- Session state management
- Auto-lock functionality
- Connected sites management
- Network switching coordination
Session State:
{
isUnlocked: boolean,
password: string (memory only),
vaultData: Object (decrypted),
decryptedWallets: Map<address, privateKey>,
connectedSites: Map<origin, siteData>,
currentNetworkKey: string
}
BackgroundControllers (497 lines)β
Location: src/background/BackgroundControllers.js
Architecture:
class BackgroundControllers {
tokenController // ERC20 operations
networkController // Network management
transactionController // Transaction history
networkSwitchService // Unified switching
async initialize(networkKey, provider, getPrivateKeyFn)
async handleTokenMessage(message)
async handleNetworkMessage(message)
async handleTransactionMessage(message)
}
Frontend Application (1,569 lines)β
Location: src/App.jsx
Main React Component:
- Screen routing logic
- Modal management
- Connection request handling
- Transaction confirmation
- Signing request UI
- Network switch consent
State Management:
// Wallet state (from background)
const {
currentWallet,
wallets,
network,
isUnlocked,
supportsSwap
} = useWalletProvider();
Swap Architecture (v2.0.0 - Refactored Nov 2025)β
Design Philosophy: Unified panel architecture for provider-agnostic swap interface.
Structure:
Swap.jsx (~115 lines) # Container/Orchestrator
ββ SwapProviderSelector # Tab selector (Bebop | Relay)
ββ SlippageControl # Shared slippage configuration
ββ Conditional Rendering:
ββ BebopSwapPanel.jsx (~1,400 lines) # Bebop JAM protocol
ββ RelaySwapPanel.jsx (~1,288 lines) # Relay.link cross-chain
Key Benefits:
- β Consistency: Both panels follow same architectural pattern
- β Maintainability: Each panel is self-contained and independently testable
- β Scalability: Easy to add new providers (Uniswap, 1inch, etc.)
- β
Separation of Concerns:
Swap.jsxonly handles routing, not implementation - β Reduced Complexity: From 2,206 lines monolith to 115-line orchestrator
BebopSwapPanel (~1,400 lines):
- Gasless MEV-protected swaps via Bebop JAM protocol
- Permit2 approvals (one-time per token)
- Internal components:
LoadingDots,PriceDeviationTooltip,SwapDetails - Uses
SwapAdapterfor all backend communication - NO ethers imports (architecture compliance)
RelaySwapPanel (~1,288 lines):
- Cross-chain swaps via Relay.link
- Network selection: Origin fixed (active network), Destination selectable
- Internal components:
UsdBalanceDisplay,formatTokenAmount - Uses
RelayAdapterfor all backend communication - Advanced features: Route visualization, gas estimation, bridge time
Stream Handlersβ
Location: src/background/handlers/streams/
| Handler | Purpose | Key Operations |
|---|---|---|
| SessionStreamHandler | Session operations | unlock, createWallet, switchWallet |
| ProviderStreamHandler | dApp requests | eth_requestAccounts, eth_sendTransaction |
| SwapStreamHandler | Bebop swaps | getQuote, signOrder, checkStatus |
| SendStreamHandler | Token transfers | estimateGas, sendTransaction |
| BlockchainStreamHandler | Blockchain queries | getBalance, getTokens, getNFTs |
| ApiStreamHandler | External APIs | price feeds, token lists |
Managersβ
Location: src/background/managers/
| Manager | Purpose | Key Features |
|---|---|---|
| SigningRequestManager | Signing request lifecycle | Timeout protection, request recovery |
| PopupManager | Popup window management | Mutual exclusion, priority system |
| EIP1193EventsManager | Event broadcasting | accountsChanged, chainChanged |
| AutoEscalationManager | Auto-approval system | Trusted dApp whitelist |
| WalletConnectManager | WalletConnect v2 | Session management, request handling |
Servicesβ
Location: src/background/services/
| Service | Purpose | Implementation |
|---|---|---|
| TokenMetadataService | Token metadata lookup | Multi-layer: Cache β BebopTokenService β RPC |
| BebopTokenService | Token list management | Local database, 2000+ tokens |
| NetworkSwitchService | Unified network switching | Bidirectional dApp-wallet sync |
Transaction Decoder Architectureβ
Overviewβ
SuperSafe Wallet implements a professional-grade transaction decoding system that transforms raw blockchain transactions into human-readable information. The system supports major DEX protocols (Uniswap V2/V3/V4, PancakeSwap Infinity, Velodrome, Aerodrome) across 7 EVM networks with a strict "no fallbacks" security policy.
Core Componentsβ
TransactionDecoder - Main orchestrator (src/background/decoders/TransactionDecoder.js)
- Routes transactions to specialized decoders based on function selector
- Manages token metadata resolution
- Enforces strict "no fallbacks" policy
UniversalRouterDecoder - Universal Router transactions (src/background/decoders/UniversalRouterDecoder.js)
- Decodes Uniswap and Velodrome Universal Router transactions
- Supports 11 command types (V2/V3/V4 swaps, wrap/unwrap, permit2)
- Context-aware opcode interpretation (detects Uniswap vs PancakeSwap)
UniversalRouterDecoderPancake - PancakeSwap Infinity (src/background/decoders/UniversalRouterDecoderPancake.js)
- Specialized decoder for PancakeSwap Infinity concentrated liquidity swaps
- Heuristic-based decoding for complex CL structures
- Handles both native (BNB) and ERC-20 inputs
TokenMetadataService - Token metadata management (src/background/services/TokenMetadataService.js)
- Multi-layer lookup: Cache β BebopTokenService β On-Chain RPC
- LRU cache with 1000 entry limit
- Strict validation with no fallbacks
- Request deduplication to prevent redundant RPC calls
Protocol Supportβ
| Protocol | Networks | Status |
|---|---|---|
| Uniswap V2/V3/V4 | ETH, OPT, BASE | β Full support |
| Universal Router | ETH, OPT, BASE, BSC | β Full support |
| PancakeSwap Infinity | BSC | β Heuristic decode |
| Velodrome | Optimism | β Full support |
| Aerodrome | Base | β Full support |
| ERC-20 Operations | All networks | β Full support |
| Permit2 | All networks | β Single/batch |
"No Fallbacks" Security Policyβ
Core Principle: Never use default or guessed values for critical transaction parameters.
Examples:
// β
CORRECT
const metadata = await tokenMetadataService.getTokenMetadata(address, chainId, provider);
if (!metadata) {
throw new Error(`Cannot fetch metadata for token ${address}`);
}
// β NEVER DO THIS
const decimals = metadata?.decimals || 18; // Dangerous!
Rationale:
- Better to show error than incorrect amounts/tokens
- Prevents user from signing wrong information
- Eliminates network mismatch risks
Signing System Architectureβ
Overviewβ
Unified signing system handling all signing request types (transactions, personal messages, typed data) with consistent request management, network validation, and security controls.
Core Componentsβ
SigningRequestManager (src/background/managers/SigningRequestManager.js)
- Centralized manager for all signing requests
- Request lifecycle management (created β pending β completed/rejected/expired)
- Timeout protection (5 minutes default)
- Request recovery on popup crash
SigningModalAdapter (src/background/adapters/SigningModalAdapter.js)
- Transforms raw RPC requests into user-friendly modal data
- Handles personal_sign hex-to-UTF8 decoding
- Parses eth_signTypedData_v4 structured data
- Detects Permit2 approvals for enhanced UI
Supported Signing Methodsβ
| Method | Status | Purpose |
|---|---|---|
personal_sign | β Active | SIWE, message authentication |
eth_signTypedData_v4 | β Active | Permit2, structured data |
eth_signTypedData_v3 | β Active | Legacy support |
eth_sign | β Disabled | Blind signing risk |
Snake_case Support: Both personal_sign and personalSign work (industry compatibility).
Request Lifecycleβ
1. createRequest() β Generate requestId, set timeout
2. buildModalRequestFromRpc() β Transform to modal format
3. createSigningPopup() β Show popup to user
4. User approves/rejects
5. handleResponse() β Process response
6. Complete/reject/expire β Cleanup
Security Validationβ
Network Validation:
validateSigningNetwork(chainId, supportedNetworks, origin)
- Prevents signing on unsupported networks
- Clear error messages
- Protects against replay attacks
eth_sign Disablement:
- Permanently disabled for security
- Returns error code 4200
- Users must use personal_sign or eth_signTypedData_v4
dApp Connection Architectureβ
PopupManager Mutual Exclusionβ
Purpose: Ensures extension UI and popup windows never coexist (Professionally Standardized UX).
Implementation:
- When popup opens β Extension closes
- When extension opens while popup active β Extension closes, popup gains focus
- Applies to ALL popup types
Popup Priority Order:
- Personal Sign
- Typed Data
- Transaction
- Network Switch
- Connection
- Unlock
Network Managementβ
Bidirectional Network Switching:
SuperSafe supports network switching initiated from both sides:
- Extension β dApp: User changes network in wallet β
eth_chainChangedevent propagated to all connected dApps - dApp β Wallet: dApp requests network switch via
wallet_switchEthereumChainβ Popup shown to user
Network Validation:
validateSigningNetwork(chainId, supportedNetworks, origin)
- Validates signing requests against dApp's supported networks
- Prevents cross-network signing attacks
- Shows clear error for unsupported networks
Stream Architectureβ
Long-Lived Connections:
SuperSafe uses native Chrome message ports for bidirectional communication:
// Content Script β Background
const port = chrome.runtime.connect({ name: 'provider-stream' });
// Background maintains open connections
providerStreams.set(origin, { port, metadata });
Stream Types:
- Provider Stream - dApp RPC requests (eth_sendTransaction, personal_sign, etc.)
- Session Stream - Extension UI communication
- WalletConnect Stream - Mobile wallet protocol
Lifecycle Management:
- Streams auto-reconnect on service worker restart
- Pending requests recovered from memory
- Disconnect cleanup removes stale connections
Service Worker Lifecycleβ
Manifest V3 Architectureβ
SuperSafe runs as Manifest V3 service worker with different lifecycle than traditional background pages.
Lifecycle States:
- Installing β Activated β Running β Idle (30s) β Terminated (5min)
- Wake-up events restart from Terminated to Running
Wakeup Mechanismβ
Problem: Service workers terminate after inactivity, breaking long-lived connections.
Solution: Proactive keep-alive ping system.
Implementation:
// Keep service worker alive with periodic ping
setInterval(() => {
chrome.runtime.getPlatformInfo(() => {
// Ping prevents termination
});
}, 20000); // Every 20 seconds
Benefits:
- Maintains stream connections
- Prevents timeout-related disconnections
- Ensures WalletConnect sessions stay alive
- Preserves in-memory session state
Persistence Strategyβ
- Critical State β Chrome Storage (encrypted vault, network selection)
- Session State β In-memory with auto-lock timeout
- Transient State β Streams with reconnection logic
Session Recoveryβ
Automatic Corruption Detection:
SuperSafe implements self-healing session restoration that automatically detects and cleans corrupted session data:
// checkPersistentSession() in BackgroundSessionController
const success = await this.restoreSessionWithLoginToken(loginToken, timeElapsed);
if (!success) {
// Auto-cleanup corrupted session data
await this.clearSessionState();
return false; // User sees login screen
}
Recovery Triggers:
- Decryption failure (OperationError)
- Invalid credentials (vault mismatch)
- Restoration exceptions
Benefits:
- β Prevents error loops on every extension open
- β Self-healing without user intervention
- β Maintains vault integrity (only clears session state)
Data Flow Patternsβ
Connection Request Flowβ
sequenceDiagram
participant D as dApp
participant C as Content Script
participant BG as Background
participant P as Popup
participant U as User
D->>C: window.ethereum.request({method: 'eth_requestAccounts'})
C->>BG: Chrome message (ETH_REQUEST_ACCOUNTS)
BG->>BG: Check allowlist & existing connection
alt Not Connected
BG->>P: Open popup with connection request
P->>U: Display connection request screen
U->>P: Approve/Reject
P->>BG: User decision
alt Approved
BG->>BG: Store connection in connectedSites
BG->>C: Return [address]
C->>D: Resolve with accounts array
BG->>D: Emit 'accountsChanged' event
else Rejected
BG->>C: Return error (4001 User Rejected)
C->>D: Reject promise
end
else Already Connected
BG->>C: Return [address] immediately
C->>D: Resolve with accounts array
end
Transaction Signing Flowβ
sequenceDiagram
participant D as dApp
participant BG as Background
participant SM as SigningRequestManager
participant PM as PopupManager
participant P as Popup
participant U as User
D->>BG: eth_sendTransaction
BG->>SM: Create signing request
SM->>SM: Generate requestId
SM->>PM: Request popup
PM->>P: Open signing popup
P->>BG: Request signing data
BG->>P: Return transaction details
P->>U: Display transaction confirmation
U->>P: Approve/Reject
alt Approved
P->>BG: User approved
BG->>BG: Sign transaction with private key
BG->>D: Return transaction hash
SM->>SM: Mark request complete
else Rejected
P->>BG: User rejected
BG->>D: Return error (4001)
SM->>SM: Mark request rejected
end
PM->>P: Close popup
Network Switch Flowβ
sequenceDiagram
participant D as dApp
participant BG as Background
participant NS as NetworkSwitchService
participant SC as SessionController
participant P as Popup
D->>BG: wallet_switchEthereumChain
BG->>NS: switchNetwork(chainId, 'dapp_request')
alt Network Supported
NS->>P: Show consent modal
P->>User: Request permission
alt User Approves
User->>NS: Approve
NS->>SC: Update current network
SC->>SC: Persist network change
NS->>BG: Broadcast networkChanged event
BG->>D: Return success
else User Rejects
User->>NS: Reject
NS->>D: Return error (4001)
end
else Network Not Supported
NS->>D: Return error (4902)
end
Technology Stackβ
Core Technologiesβ
| Technology | Version | Purpose |
|---|---|---|
| React | 18.2.0 | UI framework |
| ethers.js | 6.13.0 | Ethereum library |
| Vite | 6.3.6 | Build tool |
| TailwindCSS | 3.3.3 | Styling |
| Chrome Extension | Manifest V3 | Platform |
Key Dependenciesβ
{
"@reown/walletkit": "^1.2.8",
"@reservoir0x/relay-sdk": "^2.4.0",
"@metamask/eth-sig-util": "^8.2.0",
"ethereum-cryptography": "^3.2.0",
"buffer": "^6.0.3",
"idb": "^7.1.1",
"axios": "^1.12.0"
}
Build Configurationβ
Multiple Vite Configs:
vite.config.js- Frontend popup buildvite.config.worker.js- Background service workervite.config.content.js- Content script injection
Output Structure:
dist/
βββ index.html # Popup entry
βββ popup.js # Frontend bundle
βββ background.js # Service worker bundle
βββ content-script.js # Content script bundle
βββ provider.js # EIP-1193 provider
βββ manifest.json # Extension manifest
βββ assets/ # Static resources
Directory Structureβ
Backend Architectureβ
src/background/
βββ BackgroundSessionController.js # Session management (3,979 lines)
βββ BackgroundControllers.js # Controller orchestration (497 lines)
β
βββ handlers/ # Request handlers
β βββ streams/ # Stream-based handlers
β β βββ SessionStreamHandler.js # Session operations
β β βββ ProviderStreamHandler.js # dApp provider requests
β β βββ SwapStreamHandler.js # Bebop swap operations
β β βββ SendStreamHandler.js # Token transfers
β β βββ BlockchainStreamHandler.js # Blockchain queries
β β βββ ApiStreamHandler.js # External API calls
β β βββ GenericStreamHandlers.js # Generic utilities
β βββ walletHandlers.js # Wallet operations
β βββ contractHandlers.js # Smart contract calls
β βββ providerHandlers.js # Provider management
β
βββ managers/ # Enterprise managers
β βββ SigningRequestManager.js # Signing lifecycle
β βββ PopupManager.js # Popup orchestration
β βββ EIP1193EventsManager.js # Event broadcasting
β βββ AutoEscalationManager.js # Auto-approval logic
β βββ StreamPersistenceManager.js # Stream persistence
β βββ SigningRequestRecovery.js # Request recovery
β βββ SigningRequestDeduplicator.js # Duplicate prevention
β
βββ services/ # External services
β βββ NetworkSwitchService.js # Unified network switching
β βββ SecureApiClient.js # Secure HTTP client
β βββ SuperSeedApiWrapper.js # SuperSeed RPC wrapper
β
βββ adapters/ # Adapters
β βββ SigningModalAdapter.js # Modal communication
β
βββ decoders/ # Data decoders
β βββ TransactionDecoder.js # Transaction decoding
β
βββ policy/ # Security policies
β βββ AllowListManager.js # dApp allowlist
β
βββ security/ # Security modules
β βββ SimpleRateLimiter.js # Rate limiting
β βββ SimpleBlacklistManager.js # Blacklist management
β
βββ config/ # Configuration
β βββ apiConfig.js # API endpoints
β βββ bebopPartnerConfig.js # Bebop partner settings
β βββ walletConnectConfig.js # WalletConnect settings
β
βββ strategy/ # Strategy patterns
β βββ ConnectionStrategies.js # dApp connection strategies
β
βββ api/ # API layer
β βββ blockchainApi.js # Unified blockchain API
β
βββ utils/ # Utilities
βββ feeConfig.js # Fee configuration
Frontend Architectureβ
src/
βββ App.jsx # Main app component (1,569 lines)
βββ main.jsx # React entry point
β
βββ components/ # UI components
β βββ Dashboard.jsx # Portfolio view
β βββ Swap.jsx # Swap container/orchestrator (~115 lines)
β βββ SwapProviderSelector.jsx # Bebop/Relay provider selector
β βββ Settings.jsx # Settings panel
β βββ Ecosystem.jsx # Ecosystem explorer
β β
β βββ swap/ # Swap-specific components
β β βββ BebopSwapPanel.jsx # Bebop swap implementation (~1,400 lines)
β β βββ RelaySwapPanel.jsx # Relay swap implementation (~1,288 lines)
β β βββ CompactNetworkSelector.jsx # Compact network selector for cross-chain
β β βββ RouteVisualization.jsx # Visual swap route display
β β βββ BridgeTimeDisplay.jsx # Bridge time estimation
β β βββ GasEstimateDisplay.jsx # Gas cost estimation
β β βββ LoadingDots.jsx # Loading animation
β β
β βββ screens/ # Full-screen views
β β βββ ConnectionRequestScreen.jsx
β β βββ TransactionConfirmationScreen.jsx
β β βββ SigningConfirmationScreen.jsx
β β βββ TypedDataConfirmationScreen.jsx
β β βββ NetworkSwitchConfirmationScreen.jsx
β β βββ TransactionSuccessScreen.jsx
β β
β βββ modals/ # Modal dialogs
β β βββ UnlockWalletModal.jsx
β β βββ EditWalletModal.jsx
β β βββ NetworkConsentModal.jsx
β β βββ SignatureModal.jsx
β β βββ LoadingModal.jsx
β β βββ StyledModal.jsx
β β
β βββ settings/ # Settings sections
β β βββ SecuritySection.jsx
β β βββ WalletsSection.jsx
β β βββ NetworkSection.jsx
β β βββ TokensSection.jsx
β β βββ WalletConnectSection.jsx
β β βββ AppInfoSection.jsx
β β
β βββ common/ # Reusable components
β βββ Dashboard/
β β βββ PortfolioBalanceSection.jsx
β β βββ TokensList.jsx
β β βββ NFTsSection.jsx
β β βββ TokenCardDark.jsx
β βββ TokenImage.jsx
β βββ TokenLogo.jsx
β βββ NetworkIcon.jsx
β βββ TokenPriceChart.jsx
β
βββ contexts/ # React contexts
β βββ WalletProvider.jsx # Wallet state context
β βββ BalancesProvider.jsx # Balances context
β
βββ hooks/ # Custom hooks
β βββ useSessionWallet.js # Session management
β βββ useSwapLogic.js # Swap logic
β βββ useSwapQuote.js # Swap quote management
β βββ useTokenList.js # Token list management
β βββ usePortfolioData.js # Portfolio data aggregation
β βββ useUnifiedNetworkSwitch.js # Network switching
β βββ useNativeStreamConnection.js # Stream connection management
β βββ useAutoLock.js # Auto-lock functionality
β βββ useNotification.js # Notification system
β βββ useApiProxy.js # API proxy utilities
β
βββ utils/ # Frontend utilities
β βββ FrontendSessionAdapter.js # Session communication
β βββ FrontendControllerAdapter.js # Controller communication
β βββ SwapAdapter.js # Swap communication
β βββ SendAdapter.js # Send communication
β βββ NativeStreamManager.js # Stream management
β βββ provider.js # EIP-1193 provider
β βββ walletConnectManager.js # WalletConnect client
β βββ vaultManager.js # Vault operations
β βββ vaultStorage.js # Vault storage layer
β βββ crypto.js # Cryptography utilities
β βββ networks.js # Network configurations
β βββ ethereumUtils.js # Ethereum utilities
β βββ bebopTokenService.js # Bebop token list service
β βββ superseedApi.js # SuperSeed API client
β βββ apiProxy.js # API proxy layer
β βββ portfolioCalculator.js # Portfolio calculations
β βββ addressBook.js # Address book management
β βββ storage.js # Storage utilities
β βββ tokenConfig.js # Token configuration
β βββ swapConfig.js # Swap configuration
β βββ swapContracts.js # Swap contract addresses
β βββ curatedTokenLogos.js # Token logo mappings
β βββ feeConfigClient.js # Fee configuration client
β βββ dAppFrameworkDetector.js # dApp framework detection
β βββ networkMismatchDetector.js # Network mismatch detection
β
βββ controllers/ # Frontend controllers
β βββ TokenController.js # Token operations
β βββ NetworkController.js # Network management
β βββ TransactionController.js # Transaction history
β
βββ services/ # Frontend services
βββ NetworkSwitchService.js # Network switching service
Network Architectureβ
Supported Networksβ
Active Networks (7):
| Network | Chain ID | Swap Support | Relay Support | Status |
|---|---|---|---|---|
| SuperSeed | 5330 | β Bebop (JAM) | β Cross-chain | β Active |
| Optimism | 10 | β Bebop (JAM+RFQ) | β Cross-chain | β Active |
| Ethereum | 1 | β Bebop (JAM+RFQ) | β Cross-chain | β Active |
| Base | 8453 | β Bebop (JAM+RFQ) | β Cross-chain | β Active |
| BNB Chain | 56 | β Bebop (JAM+RFQ) | β Cross-chain | β Active |
| Arbitrum One | 42161 | β Bebop (JAM+RFQ) | β Cross-chain | β Active |
| Shardeum | 8118 | β Not supported | β Not supported | β Active |
Key Features:
- Bebop Support: 6 networks support Bebop swaps (JAM and/or RFQ)
- Relay.link Support: 6 networks support cross-chain swaps via Relay.link
- Network Tokens: Each network has wrapped native token (WETH, WBNB, etc.)
- Stable Tokens: USDC/USDT configured per network
- Explorer APIs: Moralis (ETH, OPT, BASE, BSC, ARB), Blockscout (SuperSeed)
Network Switching Architectureβ
graph LR
A[User/dApp Request] --> B{NetworkSwitchService}
B --> C[Validate Network]
C --> D{Requires Consent?}
D -->|Yes| E[Show Consent Modal]
D -->|No| F[Execute Switch]
E --> G{User Approves?}
G -->|Yes| F
G -->|No| H[Return Error]
F --> I[Update SessionController]
I --> J[Update Controllers]
J --> K[Broadcast Events]
K --> L[Update UI]
K --> M[Notify dApps]
Context-Aware Switching:
manual- User-initiated from UIdapp_request- dApp-requested via wallet_switchEthereumChainconnection- During dApp connectionautomatic- System-initiated
Pre-Switch Coordination Systemβ
Purpose: Ensures all components are ready before network switch completes, preventing race conditions and state inconsistencies.
Architecture: Promise-based coordination replaces fragile timing-based delays with deterministic handler execution.
// Pre-switch handler registration
preSwitchCoordinator.registerHandler(
'portfolio-data-lock',
async (targetNetworkKey) => {
// Prepare for network switch
isNetworkSwitchingRef.current = true;
pendingNetworkSwitchRef.current = targetNetworkKey;
},
{ name: 'Portfolio Lock', timeout: 500 }
);
// Coordinated execution during switch
await preSwitchCoordinator.executeHandlers(targetNetworkKey, {
context: 'manual',
abortOnError: true // Abort switch on handler failure
});
Key Features:
- Deterministic Execution: Waits for actual handler completion, not arbitrary delays
- Abort-on-Failure: Network switch aborts if any handler fails/times out
- Per-Handler Timeouts: Individual 2s timeout protection (configurable)
- Global Timeout: 5s safety net prevents infinite hangs
- Detailed Logging: Full visibility into handler execution and failures
- Cleanup Support: Automatic unregistration on component unmount
Security Benefits:
- Prevents showing one network while signing on another
- Eliminates race conditions in portfolio data fetching
- Ensures UI state consistency across network switches
- No silent failures - all errors surfaced to user
Performance Metricsβ
Response Timesβ
| Operation | Target | Actual | Status |
|---|---|---|---|
| Session unlock | <500ms | ~200ms | β Excellent |
| dApp response | <200ms | <150ms | β Excellent |
| Network switch | <1s | ~300ms | β Good |
| Swap quote | <2s | ~800ms | β Good |
| Transaction sign | <100ms | ~50ms | β Excellent |
Optimization Strategiesβ
- Stream Persistence: Long-lived connections eliminate handshake overhead
- Pre-decrypted Keys: Private keys cached in memory during session
- Controller Caching: Network state and tokens cached in memory
- Lazy Loading: Components loaded on-demand
- Event-Driven: Zero polling, all updates via events
Bundle Sizesβ
Frontend (popup.js): ~2.1 MB (includes React, ethers.js)
Background (background.js): ~1.8 MB (includes ethers.js, WalletConnect)
Content Script: ~150 KB (minimal injection)
Related Documentationβ
- Backend Architecture - Detailed backend architecture
- Frontend Architecture - React component architecture
- Security Overview - Security implementation
- Transaction Decoding - Transaction decoder system
- Signing System - Unified signing system
- Swap Integration - Bebop swap integration
- API Reference - Complete API documentation
Document Status: β
Current as of November 15, 2025
Code Version: v3.0.0+
Maintenance: Review quarterly or after major architecture changes