W3MSG SDK
Welcome to the W3MSG SDK - a next-generation Web3 messaging solution with comprehensive verifiable credentials integration. Built with modern ES6+ TypeScript, functional programming patterns, and production-ready security hardening.
🎉 NEW: Complete VC Verification Infrastructure
🆔 Identity & Credential Management
- Real identity wallet creation with secure DID generation
- W3C-compliant credential issuance and revocation systems
- ZK proof generation and verification using Polygon ID circuits
- Cross-chain credential verification across EVM networks
🔐 Enterprise Security
- Production security hardening with HSM/KMS key management
- Privacy-preserving ZK proofs with selective disclosure
- Challenge-response authentication with replay attack prevention
- Comprehensive monitoring and vulnerability management
📨 VC-Enhanced Messaging
- Credential attachment to XMTP v3 and Push Protocol messages
- Real-time verification of incoming message credentials
- Configurable verification modes (strict/lenient/off)
- Trust management with exempt senders and trusted issuers
- Pre/post-send verification hooks for custom business logic
- Event-driven verification UI with real-time status updates
🌐 Relay Service Infrastructure
- Cloudflare Workers-based verification endpoint with global edge distribution
- Intelligent caching with Cloudflare KV for performance optimization
- Rate limiting and API key management for production security
- Batch verification support for high-throughput scenarios
✨ Modern Architecture Highlights
🚀 Performance Optimized
- 6.58KB ESM bundle (2.48KB gzipped) - Tree-shakable modern bundle
- Advanced code splitting with protocol-specific lazy loading
- Real-time performance monitoring with telemetry and UX metrics
- Memory optimization through functional patterns and immutable operations
🔧 ES6+ TypeScript Excellence
- TypeScript 5.0+ with branded types and advanced utility types
- Functional programming with pure functions, monads, and immutable state
- Monadic error handling with
Result<T, E>andEither<L, R>patterns - Smart async patterns with timeout, retry, and resilience utilities
🌐 Cross-Platform Compatibility
- Modern browser support: Chrome 88+, Firefox 87+, Safari 14+, Edge 88+
- 6 major wallet integrations: MetaMask, Coinbase, Trust, Rainbow, Brave, WalletConnect
- Smart polyfill system with feature detection and conditional loading
- Browser compatibility scoring with automated testing
🚀 Quick Start
Installation
npm install @w3msg/sdk ethers
Modern TypeScript Usage
import { W3MSGSDK, Result, createWalletAddress, sdkPerformance } from '@w3msg/sdk';
import { ethers } from 'ethers';
// Initialize with functional configuration
const sdk = new W3MSGSDK({
apiKey: createAPIKey('your-api-key'),
environment: 'testnet' as const,
enableLogging: true,
retryConfig: {
maxAttempts: 3,
backoffFactor: 2,
jitter: true
}
});
// Modern event handling with type safety
sdk.on('connected', (address: string) => {
console.log('Connected to wallet:', address);
});
// Functional error handling with Result types
const connectWallet = async (): Promise<Result<string, Error>> => {
try {
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
await sdk.connect(signer);
return Result.success(sdk.getWalletAddress()!);
} catch (error) {
return Result.failure(error instanceof Error ? error : new Error(String(error)));
}
};
// Performance monitoring with telemetry
const result = await sdkPerformance.monitorWalletConnection(
() => connectWallet(),
'MetaMask'
);
result.fold(
(error) => console.error('Connection failed:', error.message),
(address) => console.log('Successfully connected:', address)
);
Advanced VC Verification Features
// Configure VC verification modes
await sdk.configureVCVerification({
mode: 'strict', // 'strict' | 'lenient' | 'off'
trustedIssuers: ['did:polygonid:polygon:mumbai:2qQpJqQpJqQpJqQpJqQpJq'],
exemptSenders: ['0x1234...'], // Addresses that bypass verification
requireCredentials: ['dao-member', 'token-holder']
});
// Set up verification hooks for custom business logic
sdk.addPreSendHook('custom-verification', async (context) => {
// Custom verification logic before sending
if (context.message.content.includes('sensitive')) {
return { action: 'block', reason: 'Sensitive content detected' };
}
return { action: 'allow' };
});
// Listen to verification events for UI updates
sdk.on('verification:started', (data) => {
console.log('Verification started for:', data.senderAddress);
});
sdk.on('verification:passed', (data) => {
console.log('Verification passed:', data.credentials);
});
Relay Service Integration
// Configure relay service for external verification
await sdk.configureRelayService({
endpoint: 'https://relay.w3msg.app/api/verify',
apiKey: 'your-api-key',
batchSize: 10, // Batch verification for performance
cacheTTL: 300 // 5 minutes cache
});
// Batch verify multiple credentials
const results = await sdk.batchVerifyCredentials([
{ type: 'dao-member', issuer: 'did:polygonid:...' },
{ type: 'token-holder', issuer: 'did:polygonid:...' }
]);
Advanced Features
// Browser compatibility testing
import { BrowserTestRunner } from '@w3msg/sdk';
const compatibilityReport = await BrowserTestRunner.runCompatibilityTest();
console.log('Browser score:', compatibilityReport.performance.overallScore);
// Functional async utilities with resilience
import { withTimeoutAndRetry } from '@w3msg/sdk';
const resilientOperation = await withTimeoutAndRetry(
() => sdk.verifyCredential(vcData),
{
timeout: 30000,
maxAttempts: 3,
backoffFactor: 2,
jitter: true
}
);
📊 Performance Metrics
| Metric | Value | Description |
|---|---|---|
| ESM Bundle | 6.58KB (2.48KB gzipped) | Tree-shakable modern bundle |
| CJS Bundle | 127.89KB (33.01KB gzipped) | Node.js compatibility |
| Build Time | ~4.4s | Including TypeScript compilation |
| Browser Coverage | 95%+ | Modern browsers with polyfill fallbacks |
| Wallet Support | 6 providers | Comprehensive wallet ecosystem |
| 🆕 VC Verification | ~50-200ms | Per credential verification |
| 🆕 Trust Management | ~10-50ms | Trust evaluation processing |
| 🆕 Relay Service | ~100-300ms | API response time |
🏆 Key Features
🚀 Modern Architecture
- Protocol Abstraction - Unified interface for XMTP and Push Protocol with functional composition
- Functional Programming - Pure functions, immutable state, and monadic error handling
- Performance Engineering - Real-time telemetry, bundle optimization, and memory profiling
- Type Safety - Comprehensive TypeScript with branded types and utility types
🛡️ Enterprise Ready
- Verifiable Credentials - Enhanced trust and spam protection with Polygon ID
- Circuit Breaker Patterns - Resilient protocol operations with automatic recovery
- Smart Error Handling - Protocol-specific error normalization with contextual recovery
- CI/CD Performance Pipeline - Automated regression testing and bundle analysis
🌐 Developer Experience
- Cross-Browser Compatibility - Smart polyfill loading with feature detection
- Intelligent Protocol Switching - Automatic failover with health monitoring
- Modern Build System - Vite optimization with code splitting and tree-shaking
- Comprehensive Testing - Browser compatibility and performance validation
🆕 VC Verification Infrastructure
- Configurable Verification Modes - Strict, lenient, or disabled verification
- Trust Management System - Exempt senders and trusted issuer management
- Verification Hooks - Pre/post-send custom business logic integration
- Event-Driven UI - Real-time verification status updates
- Relay Service - Cloudflare Workers-based verification endpoint
- Intelligent Caching - Performance optimization with Cloudflare KV
📚 Documentation
Getting Started
- Quick Start Guide - Modern setup and basic usage patterns
- Performance Guide - Optimization best practices and monitoring
- Browser Compatibility - Cross-browser support and testing
Core Architecture
- Functional Programming Guide - Architecture patterns and monadic types
- Protocol Abstraction Layer - Core design and implementation
- Error Handling Patterns - Result/Either types and recovery strategies
Advanced Features
- API Reference - Complete TypeScript API documentation
- Usage Examples - Real-world integration scenarios
- VC Verification Modes - Verifiable credentials integration
Development & Deployment
- Migration Guide - Upgrading to modern patterns
- Troubleshooting - Common issues and performance debugging
- Performance Guide - Build optimization and size monitoring
🏆 Technical Achievements
Our comprehensive ES6+ TypeScript modernization includes:
Functional Programming Excellence
- ✅ 6 major utilities refactored to functional programming patterns
- ✅ Pure functions with complete separation of state logic from side effects
- ✅ Immutable data structures using readonly types and spread operators
- ✅ Higher-order functions for cross-cutting concerns and behavior composition
Advanced Error Handling
- ✅ Monadic patterns with
Result<T, E>andEither<L, R>for composable error handling - ✅ Protocol-specific error normalization across XMTP, Push, and Ethers.js
- ✅ Circuit breaker patterns with configurable failure thresholds
- ✅ Retry mechanisms with exponential backoff and jitter
Performance Engineering
- ✅ Real-time telemetry with operation tracking and memory monitoring
- ✅ Bundle optimization with intelligent code splitting by functionality
- ✅ Tree-shaking with protocol-specific lazy loading
- ✅ Performance regression testing with automated CI thresholds
Browser Compatibility Framework
- ✅ 14 capability tests covering modern JavaScript features and Web APIs
- ✅ Smart polyfill loading with feature detection and parallel loading
- ✅ Wallet extension compatibility with comprehensive provider testing
- ✅ Cross-browser validation automated in CI pipeline
🆕 VC Verification Infrastructure
- ✅ Complete verification logic with configurable modes and trust management
- ✅ Event-driven verification UI with real-time status updates
- ✅ Pre/post-send verification hooks for custom business logic
- ✅ Relay service verification endpoint with Cloudflare Workers
- ✅ Intelligent caching system with Cloudflare KV for performance
- ✅ Batch verification support for high-throughput scenarios
🤝 Community & Support
- GitHub: w3msg/sdk - Source code and issues
- NPM: @w3msg/sdk - Package distribution
- Docs: docs.w3msg.dev - Comprehensive documentation
- Performance Dashboard: Real-time bundle analysis and compatibility metrics
Ready to build with modern Web3 messaging?
Check out our Usage Examples to see advanced functional programming patterns in action, or dive into the Performance Guide to optimize your integration!