;
+```
+
+### Error Handling
+
+#### Standardized Error Types
+
+```typescript
+import {
+ ServiceError,
+ ValidationError,
+ AuthenticationError,
+ NotFoundError,
+ RateLimitError,
+ createErrorHandler
+} from "@thirdweb-dev/service-utils";
+
+// Create custom errors
+throw new ValidationError("Invalid wallet address format");
+throw new AuthenticationError("JWT token expired");
+throw new NotFoundError("Contract not found");
+throw new RateLimitError("Rate limit exceeded", { retryAfter: 60 });
+
+// Generic service error
+throw new ServiceError("Database connection failed", {
+ code: "DB_CONNECTION_ERROR",
+ statusCode: 500,
+ context: { host: "db.example.com", port: 5432 },
+});
+
+// Error handler middleware
+const errorHandler = createErrorHandler({
+ logger: console,
+ includeStackTrace: process.env.NODE_ENV === "development",
+ sanitizeErrors: true,
+});
+
+// Express.js usage
+app.use(errorHandler);
+```
+
+#### Error Response Formatting
+
+```typescript
+import {
+ formatErrorResponse,
+ isServiceError,
+ sanitizeError
+} from "@thirdweb-dev/service-utils";
+
+function handleError(error: unknown) {
+ if (isServiceError(error)) {
+ // Handle known service errors
+ return formatErrorResponse({
+ error: error.message,
+ code: error.code,
+ statusCode: error.statusCode,
+ context: error.context,
+ });
+ }
+
+ // Handle unknown errors
+ const sanitized = sanitizeError(error);
+ return formatErrorResponse({
+ error: "Internal server error",
+ code: "INTERNAL_ERROR",
+ statusCode: 500,
+ details: process.env.NODE_ENV === "development" ? sanitized : undefined,
+ });
+}
+```
+
+### Logging Utilities
+
+#### Structured Logging
+
+```typescript
+import {
+ createLogger,
+ LogLevel,
+ createRequestLogger
+} from "@thirdweb-dev/service-utils";
+
+// Create structured logger
+const logger = createLogger({
+ service: "contract-service",
+ level: LogLevel.INFO,
+ format: "json", // or "text"
+ outputs: ["console", "file"],
+ metadata: {
+ version: "1.0.0",
+ environment: process.env.NODE_ENV,
+ },
+});
+
+// Log with context
+logger.info("Contract deployed", {
+ contractAddress: "0x...",
+ chainId: 1,
+ deployerAddress: "0x...",
+ transactionHash: "0x...",
+});
+
+logger.error("Deployment failed", {
+ error: error.message,
+ contractType: "ERC721",
+ chainId: 1,
+});
+
+// Request logging middleware
+const requestLogger = createRequestLogger({
+ logger,
+ includeBody: false,
+ includeHeaders: ["user-agent", "x-forwarded-for"],
+ excludePaths: ["/health", "/metrics"],
+});
+
+// Express.js usage
+app.use(requestLogger);
+```
+
+#### Performance Monitoring
+
+```typescript
+import {
+ createPerformanceTimer,
+ trackMetric,
+ createMetricsCollector
+} from "@thirdweb-dev/service-utils";
+
+// Performance timing
+const timer = createPerformanceTimer();
+timer.start("database-query");
+
+// ... perform database query
+const result = await queryDatabase();
+
+timer.end("database-query");
+const duration = timer.getDuration("database-query");
+
+logger.info("Database query completed", {
+ duration: `${duration}ms`,
+ resultCount: result.length,
+});
+
+// Metrics tracking
+trackMetric("contracts.deployed", 1, {
+ chainId: "1",
+ contractType: "ERC721",
+});
+
+trackMetric("api.response_time", duration, {
+ endpoint: "/api/contracts",
+ status: "success",
+});
+
+// Metrics collector
+const metricsCollector = createMetricsCollector({
+ prefix: "thirdweb_service",
+ labels: {
+ service: "contract-api",
+ version: "1.0.0",
+ },
+});
+
+metricsCollector.incrementCounter("requests_total", {
+ method: "POST",
+ endpoint: "/deploy",
+});
+```
+
+### Caching Utilities
+
+#### Redis Caching
+
+```typescript
+import {
+ createRedisCache,
+ createMemoryCache,
+ CacheConfig
+} from "@thirdweb-dev/service-utils";
+
+// Redis cache configuration
+const redisCache = createRedisCache({
+ host: "localhost",
+ port: 6379,
+ password: "redis-password",
+ db: 0,
+ keyPrefix: "thirdweb:",
+ defaultTTL: 300, // 5 minutes
+});
+
+// Set cache value
+await redisCache.set("contract:0x123", {
+ name: "My Contract",
+ symbol: "MC",
+ totalSupply: "1000",
+}, { ttl: 600 }); // 10 minutes
+
+// Get cache value
+const cached = await redisCache.get("contract:0x123");
+console.log("Cached data:", cached);
+
+// Cache with automatic serialization
+await redisCache.setJSON("user:123:profile", {
+ walletAddress: "0x...",
+ preferences: { theme: "dark" },
+});
+
+const profile = await redisCache.getJSON("user:123:profile");
+
+// Batch operations
+await redisCache.mset({
+ "contract:0x123": contractData,
+ "contract:0x456": anotherContract,
+});
+
+const contracts = await redisCache.mget(["contract:0x123", "contract:0x456"]);
+```
+
+#### Memory Caching
+
+```typescript
+import { createMemoryCache } from "@thirdweb-dev/service-utils";
+
+// In-memory cache for development or small-scale usage
+const memoryCache = createMemoryCache({
+ maxSize: 1000, // Maximum number of items
+ defaultTTL: 300, // 5 minutes
+ cleanupInterval: 60, // Cleanup every minute
+});
+
+// Same API as Redis cache
+await memoryCache.set("key", "value", { ttl: 120 });
+const value = await memoryCache.get("key");
+
+// Memory usage monitoring
+const stats = memoryCache.getStats();
+console.log("Cache stats:", {
+ size: stats.size,
+ hitRate: stats.hitRate,
+ memoryUsage: stats.memoryUsage,
+});
+```
+
+### Queue Management
+
+#### Job Queue Utilities
+
+```typescript
+import {
+ createJobQueue,
+ JobProcessor,
+ JobConfig
+} from "@thirdweb-dev/service-utils";
+
+// Define job processor
+const contractDeploymentProcessor: JobProcessor<{
+ contractType: string;
+ metadata: any;
+ chainId: number;
+}> = async (job) => {
+ logger.info("Processing contract deployment", {
+ jobId: job.id,
+ contractType: job.data.contractType,
+ chainId: job.data.chainId,
+ });
+
+ try {
+ // Simulate contract deployment
+ const result = await deployContract(job.data);
+
+ return {
+ success: true,
+ contractAddress: result.address,
+ transactionHash: result.txHash,
+ };
+ } catch (error) {
+ logger.error("Contract deployment failed", {
+ jobId: job.id,
+ error: error.message,
+ });
+ throw error;
+ }
+};
+
+// Create job queue
+const deploymentQueue = createJobQueue({
+ name: "contract-deployment",
+ processor: contractDeploymentProcessor,
+ config: {
+ concurrency: 5, // Process 5 jobs concurrently
+ retries: 3,
+ backoff: "exponential",
+ removeOnComplete: 100, // Keep last 100 completed jobs
+ removeOnFail: 50, // Keep last 50 failed jobs
+ },
+ redis: {
+ host: "localhost",
+ port: 6379,
+ },
+});
+
+// Add job to queue
+const job = await deploymentQueue.add("deploy-nft-collection", {
+ contractType: "ERC721",
+ metadata: {
+ name: "My Collection",
+ symbol: "MC",
+ },
+ chainId: 1,
+}, {
+ delay: 5000, // Delay processing by 5 seconds
+ priority: 1, // Higher priority
+});
+
+console.log("Job added:", job.id);
+
+// Monitor queue events
+deploymentQueue.on("completed", (job, result) => {
+ logger.info("Job completed", {
+ jobId: job.id,
+ result,
+ });
+});
+
+deploymentQueue.on("failed", (job, error) => {
+ logger.error("Job failed", {
+ jobId: job.id,
+ error: error.message,
+ });
+});
+```
+
+### Cryptographic Utilities
+
+#### Hashing and Encryption
+
+```typescript
+import {
+ hashData,
+ verifyHash,
+ encryptData,
+ decryptData,
+ generateSecureToken
+} from "@thirdweb-dev/service-utils";
+
+// Secure hashing
+const hashedPassword = await hashData("user-password", {
+ algorithm: "argon2", // or "bcrypt", "scrypt"
+ saltLength: 32,
+});
+
+const isValidPassword = await verifyHash("user-password", hashedPassword);
+console.log("Password valid:", isValidPassword);
+
+// Data encryption
+const encryptedData = await encryptData({
+ message: "sensitive information",
+ key: "encryption-key-32-bytes-long!",
+ algorithm: "aes-256-gcm",
+});
+
+const decryptedData = await decryptData({
+ encryptedMessage: encryptedData.encryptedData,
+ key: "encryption-key-32-bytes-long!",
+ iv: encryptedData.iv,
+ tag: encryptedData.tag,
+ algorithm: "aes-256-gcm",
+});
+
+console.log("Decrypted:", decryptedData);
+
+// Secure token generation
+const apiKey = generateSecureToken(64); // 64 bytes = 128 hex characters
+const sessionId = generateSecureToken(32); // 32 bytes = 64 hex characters
+
+console.log("API Key:", apiKey);
+console.log("Session ID:", sessionId);
+```
+
+### Rate Limiting
+
+#### Request Rate Limiting
+
+```typescript
+import {
+ createRateLimiter,
+ RateLimitConfig,
+ createRateLimitMiddleware
+} from "@thirdweb-dev/service-utils";
+
+// Create rate limiter
+const rateLimiter = createRateLimiter({
+ windowMs: 60 * 1000, // 1 minute window
+ max: 100, // Maximum 100 requests per window
+ keyGenerator: (req) => req.ip, // Rate limit by IP
+ skipSuccessfulRequests: false,
+ skipFailedRequests: false,
+ store: "redis", // or "memory"
+ redis: {
+ host: "localhost",
+ port: 6379,
+ },
+});
+
+// Rate limit middleware for Express.js
+const rateLimitMiddleware = createRateLimitMiddleware(rateLimiter);
+app.use("/api", rateLimitMiddleware);
+
+// Custom rate limiting
+app.post("/api/deploy", async (req, res) => {
+ const identifier = `deploy:${req.user.id}`;
+
+ const result = await rateLimiter.consume(identifier, 1);
+
+ if (!result.allowed) {
+ return res.status(429).json({
+ error: "Rate limit exceeded",
+ retryAfter: result.retryAfter,
+ resetTime: result.resetTime,
+ });
+ }
+
+ // Process deployment request
+ const deployment = await processDeployment(req.body);
+ res.json(deployment);
+});
+
+// Different rate limits for different endpoints
+const deploymentRateLimit = createRateLimiter({
+ windowMs: 60 * 1000, // 1 minute
+ max: 5, // 5 deployments per minute
+});
+
+const readRateLimit = createRateLimiter({
+ windowMs: 60 * 1000, // 1 minute
+ max: 1000, // 1000 reads per minute
+});
+```
+
+## Configuration Management
+
+### Environment Configuration
+
+```typescript
+import {
+ loadConfig,
+ validateConfig,
+ ConfigSchema
+} from "@thirdweb-dev/service-utils";
+import { z } from "zod";
+
+// Define configuration schema
+const ServiceConfigSchema = z.object({
+ port: z.number().default(3000),
+ database: z.object({
+ host: z.string(),
+ port: z.number().default(5432),
+ name: z.string(),
+ username: z.string(),
+ password: z.string(),
+ }),
+ redis: z.object({
+ host: z.string().default("localhost"),
+ port: z.number().default(6379),
+ password: z.string().optional(),
+ }),
+ jwt: z.object({
+ secret: z.string().min(32),
+ expiresIn: z.string().default("1h"),
+ }),
+ logging: z.object({
+ level: z.enum(["debug", "info", "warn", "error"]).default("info"),
+ format: z.enum(["json", "text"]).default("json"),
+ }),
+});
+
+// Load and validate configuration
+const config = loadConfig(ServiceConfigSchema, {
+ envPrefix: "THIRDWEB_",
+ configFiles: ["config.json", "config.local.json"],
+ overrides: {
+ port: process.env.PORT ? parseInt(process.env.PORT) : undefined,
+ },
+});
+
+console.log("Service configuration:", config);
+
+// Type-safe configuration access
+const dbConfig = config.database;
+const jwtSecret = config.jwt.secret;
+```
+
+## API Reference
+
+### Authentication
+
+- `generateJWT(payload, secret, options?)` - Generate JWT token
+- `verifyJWT(token, secret)` - Verify JWT token
+- `refreshJWT(token, secret, options)` - Refresh JWT token
+- `verifySignature(options)` - Verify message signature
+- `verifyEIP712Signature(options)` - Verify EIP-712 signature
+
+### Validation
+
+- `createAPISchema(schema)` - Create API endpoint schema
+- `validateAddress(address)` - Validate Ethereum address
+- `validateChainId(chainId)` - Validate chain ID
+- `createPaginatedResponse(schema)` - Create paginated response schema
+
+### Error Handling
+
+- `ServiceError` - Base service error class
+- `ValidationError` - Data validation error
+- `AuthenticationError` - Authentication error
+- `NotFoundError` - Resource not found error
+- `RateLimitError` - Rate limit exceeded error
+
+### Logging
+
+- `createLogger(config)` - Create structured logger
+- `createRequestLogger(config)` - Create request logging middleware
+- `createPerformanceTimer()` - Create performance timer
+- `trackMetric(name, value, labels?)` - Track application metrics
+
+### Caching
+
+- `createRedisCache(config)` - Create Redis cache instance
+- `createMemoryCache(config)` - Create in-memory cache instance
+- `cache.set(key, value, options?)` - Set cache value
+- `cache.get(key)` - Get cache value
+- `cache.del(key)` - Delete cache value
+
+### Queue Management
+
+- `createJobQueue(config)` - Create job queue
+- `queue.add(name, data, options?)` - Add job to queue
+- `queue.process(processor)` - Process jobs
+- `queue.on(event, handler)` - Listen to queue events
+
+### Cryptography
+
+- `hashData(data, options)` - Hash data securely
+- `verifyHash(data, hash)` - Verify hashed data
+- `encryptData(options)` - Encrypt data
+- `decryptData(options)` - Decrypt data
+- `generateSecureToken(bytes)` - Generate secure random token
+
+### Rate Limiting
+
+- `createRateLimiter(config)` - Create rate limiter
+- `createRateLimitMiddleware(limiter)` - Create Express middleware
+- `limiter.consume(key, tokens)` - Consume rate limit tokens
+
+## Examples
+
+### Complete Service Setup
+
+```typescript
+import {
+ createLogger,
+ createRedisCache,
+ createRateLimiter,
+ createJobQueue,
+ createAPISchema,
+ ServiceError,
+ loadConfig,
+} from "@thirdweb-dev/service-utils";
+import { z } from "zod";
+
+class ContractService {
+ private logger;
+ private cache;
+ private rateLimiter;
+ private deploymentQueue;
+
+ constructor(config: any) {
+ // Initialize logger
+ this.logger = createLogger({
+ service: "contract-service",
+ level: config.logging.level,
+ format: config.logging.format,
+ });
+
+ // Initialize cache
+ this.cache = createRedisCache({
+ host: config.redis.host,
+ port: config.redis.port,
+ password: config.redis.password,
+ keyPrefix: "contracts:",
+ defaultTTL: 300,
+ });
+
+ // Initialize rate limiter
+ this.rateLimiter = createRateLimiter({
+ windowMs: 60 * 1000,
+ max: 10, // 10 deployments per minute
+ store: "redis",
+ redis: config.redis,
+ });
+
+ // Initialize job queue
+ this.deploymentQueue = createJobQueue({
+ name: "contract-deployment",
+ processor: this.processDeployment.bind(this),
+ config: {
+ concurrency: 3,
+ retries: 3,
+ backoff: "exponential",
+ },
+ redis: config.redis,
+ });
+
+ this.setupEventHandlers();
+ }
+
+ async deployContract(userId: string, contractData: any) {
+ // Check rate limit
+ const rateLimitResult = await this.rateLimiter.consume(
+ `deploy:${userId}`,
+ 1
+ );
+
+ if (!rateLimitResult.allowed) {
+ throw new ServiceError("Rate limit exceeded", {
+ code: "RATE_LIMIT_EXCEEDED",
+ statusCode: 429,
+ context: { retryAfter: rateLimitResult.retryAfter },
+ });
+ }
+
+ // Check cache for existing deployment
+ const cacheKey = `deployment:${userId}:${JSON.stringify(contractData)}`;
+ const cached = await this.cache.get(cacheKey);
+
+ if (cached) {
+ this.logger.info("Returning cached deployment", {
+ userId,
+ cacheKey,
+ });
+ return cached;
+ }
+
+ // Queue deployment job
+ const job = await this.deploymentQueue.add("deploy", {
+ userId,
+ contractData,
+ timestamp: Date.now(),
+ });
+
+ this.logger.info("Contract deployment queued", {
+ userId,
+ jobId: job.id,
+ contractType: contractData.type,
+ });
+
+ return {
+ jobId: job.id,
+ status: "queued",
+ estimatedCompletion: Date.now() + 60000, // 1 minute
+ };
+ }
+
+ private async processDeployment(job: any) {
+ const { userId, contractData } = job.data;
+
+ this.logger.info("Processing contract deployment", {
+ jobId: job.id,
+ userId,
+ contractType: contractData.type,
+ });
+
+ try {
+ // Simulate deployment process
+ await new Promise(resolve => setTimeout(resolve, 5000));
+
+ const result = {
+ contractAddress: "0x" + Math.random().toString(16).substr(2, 40),
+ transactionHash: "0x" + Math.random().toString(16).substr(2, 64),
+ blockNumber: Math.floor(Math.random() * 1000000),
+ deployedAt: new Date().toISOString(),
+ };
+
+ // Cache the result
+ const cacheKey = `deployment:${userId}:${JSON.stringify(contractData)}`;
+ await this.cache.set(cacheKey, result, { ttl: 3600 }); // 1 hour
+
+ this.logger.info("Contract deployment completed", {
+ jobId: job.id,
+ userId,
+ contractAddress: result.contractAddress,
+ });
+
+ return result;
+ } catch (error) {
+ this.logger.error("Contract deployment failed", {
+ jobId: job.id,
+ userId,
+ error: error.message,
+ });
+ throw error;
+ }
+ }
+
+ private setupEventHandlers() {
+ this.deploymentQueue.on("completed", (job, result) => {
+ this.logger.info("Deployment job completed", {
+ jobId: job.id,
+ contractAddress: result.contractAddress,
+ });
+ });
+
+ this.deploymentQueue.on("failed", (job, error) => {
+ this.logger.error("Deployment job failed", {
+ jobId: job.id,
+ error: error.message,
+ });
+ });
+ }
+
+ async getDeploymentStatus(jobId: string) {
+ const job = await this.deploymentQueue.getJob(jobId);
+
+ if (!job) {
+ throw new ServiceError("Job not found", {
+ code: "JOB_NOT_FOUND",
+ statusCode: 404,
+ });
+ }
+
+ return {
+ id: job.id,
+ status: await job.getState(),
+ progress: job.progress(),
+ result: job.returnvalue,
+ error: job.failedReason,
+ createdAt: new Date(job.timestamp),
+ processedAt: job.processedOn ? new Date(job.processedOn) : null,
+ finishedAt: job.finishedOn ? new Date(job.finishedOn) : null,
+ };
+ }
+}
+
+// Usage
+const config = loadConfig(ServiceConfigSchema);
+const contractService = new ContractService(config);
+
+// Deploy contract
+const deployment = await contractService.deployContract("user123", {
+ type: "ERC721",
+ name: "My NFT Collection",
+ symbol: "MNC",
+});
+
+console.log("Deployment queued:", deployment);
+```
+
+## References
+
+### Documentation
+- [Service Utils Guide](https://portal.thirdweb.com/infrastructure/service-utils) - Complete service utilities guide
+- [Authentication Utilities](https://portal.thirdweb.com/infrastructure/auth-utils) - Authentication helper documentation
+- [Caching Strategies](https://portal.thirdweb.com/infrastructure/caching) - Caching best practices
+
+### Platform-Specific Guides
+- [Cloudflare Workers Setup](https://portal.thirdweb.com/infrastructure/cloudflare-workers) - Using service-utils in Cloudflare Workers
+- [Node.js Integration](https://portal.thirdweb.com/infrastructure/nodejs) - Node.js specific utilities and patterns
+- [Docker Deployment](https://portal.thirdweb.com/infrastructure/docker) - Containerized service deployment
+
+### Integration Examples
+- [Service Utils Examples](https://github.com/thirdweb-example/service-utils-examples) - Example implementations
+- [Microservice Template](https://github.com/thirdweb-example/microservice-template) - Complete microservice template
+- [API Gateway Pattern](https://github.com/thirdweb-example/api-gateway) - API gateway implementation
+
+### Advanced Topics
+- [Error Handling Patterns](https://portal.thirdweb.com/infrastructure/error-handling) - Error handling best practices
+- [Logging and Monitoring](https://portal.thirdweb.com/infrastructure/logging) - Structured logging and monitoring
+- [Performance Optimization](https://portal.thirdweb.com/infrastructure/performance) - Service performance optimization
+
+### Related Packages
+- [Zod Documentation](https://zod.dev/) - Schema validation library
+- [Redis Documentation](https://redis.io/docs) - Redis caching and data structures
+- [Bull Queue](https://github.com/OptimalBits/bull) - Job queue processing
+
+### Community and Support
+- [Discord #infrastructure](https://discord.gg/thirdweb) - Infrastructure and backend help
+- [GitHub Issues](https://github.com/thirdweb-dev/js/issues) - Report service-utils issues
+- [Service Uptime](https://status.thirdweb.com/) - thirdweb services status and uptime
diff --git a/packages/thirdweb/README.md b/packages/thirdweb/README.md
index b959008f41f..8a1c2fc8324 100644
--- a/packages/thirdweb/README.md
+++ b/packages/thirdweb/README.md
@@ -8,7 +8,22 @@
-All-in-one web3 SDK for Browser, Node and Mobile apps
+
+## Description
+
+The **thirdweb** SDK is a comprehensive web3 development toolkit that provides everything you need to build decentralized applications. It offers type-safe APIs for smart contract interactions, embedded wallets with social login, account abstraction support, React hooks and UI components, and cross-platform compatibility for web, React Native, and Node.js applications.
+
+### Key Features
+
+- **Type-safe APIs**: Fully typed contract and wallet interactions
+- **Embedded Wallets**: Social login (Google, Facebook, etc.) and email authentication
+- **Account Abstraction**: ERC-4337 smart accounts with gas sponsorship
+- **React Integration**: Hooks and UI components for seamless frontend development
+- **React Native Support**: Cross-platform mobile app development
+- **Automatic ABI Resolution**: Smart contract ABIs resolved automatically
+- **IPFS Integration**: Built-in decentralized storage capabilities
+- **Multi-chain Support**: Connect to any EVM-compatible blockchain
+- **Auth System**: Sign-in with Ethereum (SIWE) support
## Installation
@@ -16,40 +31,376 @@
npm install thirdweb
```
-## Features
+### For TypeScript Projects
+```bash
+npm install thirdweb typescript
+```
+
+### For React Applications
+```bash
+npm install thirdweb react react-dom
+```
+
+### For React Native Applications
+```bash
+npm install thirdweb @thirdweb-dev/react-native-adapter
+# Additional React Native dependencies required - see React Native Adapter docs
+```
+
+## Usage
+
+### Basic Setup
+
+#### 1. Create a Thirdweb Client
+
+```typescript
+import { createThirdwebClient } from "thirdweb";
+
+const client = createThirdwebClient({
+ clientId: "YOUR_CLIENT_ID", // Get from thirdweb.com/dashboard
+});
+```
+
+#### 2. Connect to a Blockchain
+
+```typescript
+import { defineChain } from "thirdweb/chains";
+
+// Use a built-in chain
+import { ethereum, polygon } from "thirdweb/chains";
+
+// Or define a custom chain
+const customChain = defineChain({
+ id: 1234,
+ name: "My Custom Chain",
+ rpc: "https://my-rpc-url.com",
+});
+```
+
+### React Integration
+
+#### ThirdwebProvider Setup
+
+```tsx
+import { ThirdwebProvider } from "thirdweb/react";
+import { createThirdwebClient } from "thirdweb";
+
+const client = createThirdwebClient({
+ clientId: "YOUR_CLIENT_ID",
+});
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+#### Connect Wallet Button
+
+```tsx
+import { ConnectButton } from "thirdweb/react";
+import { createWallet } from "thirdweb/wallets";
+
+const wallets = [
+ createWallet("io.metamask"),
+ createWallet("com.coinbase.wallet"),
+ createWallet("walletConnect"),
+ createWallet("inApp", {
+ auth: {
+ options: ["email", "google", "apple", "facebook"],
+ },
+ }),
+];
+
+function MyComponent() {
+ return (
+
+ );
+}
+```
+
+### Smart Contract Interactions
+
+#### Reading from a Contract
+
+```typescript
+import { getContract } from "thirdweb";
+import { readContract } from "thirdweb";
+import { ethereum } from "thirdweb/chains";
+
+const contract = getContract({
+ client,
+ chain: ethereum,
+ address: "0x...",
+});
+
+// Read with automatic ABI resolution
+const result = await readContract({
+ contract,
+ method: "function balanceOf(address owner) view returns (uint256)",
+ params: ["0x..."],
+});
+```
+
+#### Writing to a Contract
+
+```typescript
+import { prepareContractCall, sendTransaction } from "thirdweb";
+import { useSendTransaction } from "thirdweb/react";
+
+// In a React component
+function TransferButton() {
+ const { mutate: sendTransaction } = useSendTransaction();
+
+ const handleTransfer = async () => {
+ const transaction = prepareContractCall({
+ contract,
+ method: "function transfer(address to, uint256 amount)",
+ params: ["0x...", 100n],
+ });
+
+ sendTransaction(transaction);
+ };
+
+ return ;
+}
+```
+
+### Embedded Wallets (In-App Wallets)
+
+```typescript
+import { createWallet } from "thirdweb/wallets";
+
+const embeddedWallet = createWallet("inApp", {
+ auth: {
+ options: ["email", "google", "apple", "facebook"],
+ },
+});
+
+// Connect with email
+await embeddedWallet.connect({
+ client,
+ strategy: "email",
+ email: "user@example.com",
+});
+```
+
+### Account Abstraction (Smart Accounts)
+
+```typescript
+import { createWallet } from "thirdweb/wallets";
+
+const smartWallet = createWallet("smart", {
+ chain: ethereum,
+ sponsorGas: true, // Enable gas sponsorship
+});
+
+const personalWallet = createWallet("inApp");
+await personalWallet.connect({ client, strategy: "email", email: "user@example.com" });
-| | thirdweb | Wagmi | Viem | Ethers@6 |
-| ----------------------------------------- | -------- | ------------------ | ------------------ | -------- |
-| Type safe contract API | β
| β
| β
| β
|
-| Type safe wallet API | β
| β
| β
| β
|
-| EVM utils | β
| β | β
| β
|
-| RPC for any EVM | β
Β | β οΈΒ public RPC only | β οΈΒ public RPC only | β |
-| Automatic ABI Resolution | β
| β | β | β |
-| IPFS Upload/Download | β
| β | β | β |
-| Embedded wallet (email/ social login) | β
| β οΈΒ via 3rd party | β | β |
-| Account abstraction (ERC4337) support | β
| β οΈΒ via 3rd party | β οΈΒ via 3rd party | β |
-| Web3 wallet connectors | β
| β
| β | β |
-| Local wallet creation | β
| β | β
| β
|
-| Auth (SIWE) | β
| β οΈΒ via 3rd party | β | β |
-| Extensions functions for common standards | β
| β | β | β |
-| React Hooks | β
| β
| β | β |
-| React UI components | β
| β | β | β |
-| React Native Hooks | β
| β | β | β |
-| React Native UI Components | β
| β | β | β |
+await smartWallet.connect({
+ client,
+ personalWallet,
+});
+```
+
+### Storage and IPFS
+
+```typescript
+import { upload, download } from "thirdweb/storage";
+
+// Upload to IPFS
+const file = new File(["content"], "example.txt");
+const uri = await upload({
+ client,
+ files: [file],
+});
+
+// Download from IPFS
+const response = await download({
+ client,
+ uri: "ipfs://...",
+});
+```
-## Documentation
+### Node.js Backend Usage
-Visit [the thirdweb developer portal](https://portal.thirdweb.com/typescript/v5?ref=github.com) to view the full documentation.
+```typescript
+import { createThirdwebClient } from "thirdweb";
+import { privateKeyToAccount } from "thirdweb/wallets";
+
+const client = createThirdwebClient({
+ secretKey: "YOUR_SECRET_KEY", // Use secret key for backend
+});
+
+const account = privateKeyToAccount({
+ client,
+ privateKey: "0x...",
+});
+
+// Send transactions from backend
+const transaction = prepareContractCall({
+ contract,
+ method: "function mint(address to, uint256 amount)",
+ params: [account.address, 100n],
+});
+
+const result = await sendTransaction({
+ transaction,
+ account,
+});
+```
+
+### CLI Usage
+
+The thirdweb package also includes a CLI for project scaffolding and contract deployment:
+
+```bash
+# Create a new project
+npx thirdweb create
+
+# Deploy contracts
+npx thirdweb deploy
+
+# Generate contract bindings
+npx thirdweb generate
+```
+
+## API Reference
+
+### Core Functions
+
+- `createThirdwebClient(options)` - Create a thirdweb client instance
+- `getContract(options)` - Get a contract instance for interactions
+- `readContract(options)` - Read data from a smart contract
+- `prepareContractCall(options)` - Prepare a contract transaction
+- `sendTransaction(options)` - Send a prepared transaction
+
+### React Hooks
+
+- `useActiveAccount()` - Get the currently connected account
+- `useActiveWallet()` - Get the currently connected wallet
+- `useReadContract(options)` - Read contract data with caching
+- `useSendTransaction()` - Send transactions with loading states
+- `useContractEvents(options)` - Listen to contract events
+
+### React Components
+
+- `` - Wallet connection button with modal
+- `` - Button that executes transactions
+- `` - Render NFT media (images, videos, etc.)
+- `` - Button that requires wallet connection
+
+### Wallet Types
+
+- `"io.metamask"` - MetaMask wallet
+- `"com.coinbase.wallet"` - Coinbase Wallet
+- `"walletConnect"` - WalletConnect protocol
+- `"inApp"` - Embedded wallet with social login
+- `"smart"` - Smart account with account abstraction
+
+## Examples
+
+### Complete DApp Example
+
+```tsx
+import { ThirdwebProvider, ConnectButton, useActiveAccount, useReadContract } from "thirdweb/react";
+import { createThirdwebClient, getContract } from "thirdweb";
+import { ethereum } from "thirdweb/chains";
+
+const client = createThirdwebClient({ clientId: "YOUR_CLIENT_ID" });
+
+const contract = getContract({
+ client,
+ chain: ethereum,
+ address: "0x...",
+});
+
+function TokenBalance() {
+ const account = useActiveAccount();
+ const { data: balance } = useReadContract({
+ contract,
+ method: "function balanceOf(address owner) view returns (uint256)",
+ params: [account?.address!],
+ queryOptions: { enabled: !!account },
+ });
+
+ return Balance: {balance?.toString()}
;
+}
+
+function App() {
+ return (
+
+
+
+
+ );
+}
+```
+
+### NFT Minting Example
+
+```tsx
+import { prepareContractCall, sendTransaction } from "thirdweb";
+import { upload } from "thirdweb/storage";
+
+async function mintNFT() {
+ // Upload metadata to IPFS
+ const metadata = {
+ name: "My NFT",
+ description: "An awesome NFT",
+ image: file, // File object
+ };
+
+ const uri = await upload({
+ client,
+ files: [metadata],
+ });
+
+ // Mint NFT
+ const transaction = prepareContractCall({
+ contract,
+ method: "function mint(address to, string uri)",
+ params: [account.address, uri],
+ });
+
+ await sendTransaction({ transaction, account });
+}
+```
-## Migrating from previous versions
+## References
-Follow the [migration guide](https://portal.thirdweb.com/typescript/v5/migrate?ref=github.com) to learn how to progrssively upgrade to the unified thirdweb SDK from previous versions.
+### Documentation
+- [Main Documentation](https://portal.thirdweb.com/typescript/v5) - Complete SDK documentation
+- [React Documentation](https://portal.thirdweb.com/typescript/v5/react) - React-specific guides
+- [Getting Started Guide](https://portal.thirdweb.com/typescript/v5/getting-started) - Step-by-step setup
+- [Migration Guide](https://portal.thirdweb.com/typescript/v5/migrate) - Upgrading from v4
-## Starter kits
+### Examples and Templates
+- [Starter Templates](https://thirdweb.com/templates) - Ready-to-use project templates
+- [Next.js Starter](https://github.com/thirdweb-example/next-starter) - Next.js template
+- [Vite Starter](https://github.com/thirdweb-example/vite-starter) - Vite template
+- [Code Examples](https://github.com/thirdweb-example) - Example repositories
-- [Next.js starter](https://github.com/thirdweb-example/next-starter)
-- [Vite starter](https://github.com/thirdweb-example/vite-starter)
+### Tools and Services
+- [thirdweb Dashboard](https://thirdweb.com/dashboard) - Manage your projects and API keys
+- [Contracts Hub](https://thirdweb.com/explore) - Pre-built smart contracts
+- [Chain List](https://thirdweb.com/chainlist) - Supported blockchain networks
-## Contributing
+### Community and Support
+- [Discord Community](https://discord.gg/thirdweb) - Join the community
+- [GitHub Issues](https://github.com/thirdweb-dev/js/issues) - Report bugs and feature requests
+- [Support Center](https://thirdweb.com/support) - Get help and support
+- [YouTube Channel](https://www.youtube.com/c/thirdweb) - Video tutorials and guides
-We welcome contributions from all developers, regardless of experience level. If you are interested in contributing, please read our [Contributing Guide](https://github.com/thirdweb-dev/js/blob/main/.github/contributing.md) where you'll learn how the repo works, how to test your changes, and how to submit a pull request.
+### Additional Resources
+- [Blog](https://blog.thirdweb.com/) - Latest news and tutorials
+- [Twitter](https://twitter.com/thirdweb) - Follow for updates
+- [Changelog](https://portal.thirdweb.com/changelog) - Latest features and fixes
diff --git a/packages/vault-sdk/README.md b/packages/vault-sdk/README.md
index 610166b5fb5..0f41b6e2e17 100644
--- a/packages/vault-sdk/README.md
+++ b/packages/vault-sdk/README.md
@@ -1,5 +1,637 @@
# Vault SDK
-This package contains utilities to interact with Vault, thirdweb's key management servive.
+## Description
-[View documentation](https://portal.thirdweb.com/vault)
+The **@thirdweb-dev/vault-sdk** package provides a TypeScript SDK for interacting with thirdweb's Vault service, a secure key management solution for web3 applications. Vault offers enterprise-grade security for managing private keys, signing transactions, and handling sensitive cryptographic operations without exposing private keys to your application code.
+
+### Key Features
+
+- **Secure Key Management**: Store and manage private keys in a secure, isolated environment
+- **Multi-Signature Support**: Configure multi-signature wallets for enhanced security
+- **Hardware Security Modules (HSM)**: Integration with hardware-based security modules
+- **Key Derivation**: Hierarchical deterministic (HD) wallet support with BIP-32/BIP-44
+- **Transaction Signing**: Sign transactions without exposing private keys
+- **Access Control**: Role-based access control and permission management
+- **Audit Logging**: Complete audit trail of all cryptographic operations
+- **Cross-Platform**: Works in Node.js, browser, and React Native environments
+
+## Installation
+
+```bash
+npm install @thirdweb-dev/vault-sdk
+```
+
+### Prerequisites
+
+To use the Vault SDK, you need:
+
+1. **Vault Service Access**: Access to a thirdweb Vault instance
+2. **Authentication Credentials**: Valid JWT tokens or API keys
+3. **Vault Configuration**: Properly configured vault policies and access permissions
+
+## Usage
+
+### Basic Setup
+
+#### 1. Initialize Vault Client
+
+```typescript
+import { createVaultClient } from "@thirdweb-dev/vault-sdk";
+
+const vaultClient = createVaultClient({
+ vaultUrl: "https://vault.thirdweb.com", // Your Vault instance URL
+ accessToken: "your-jwt-token", // JWT token for authentication
+});
+```
+
+#### 2. Alternative Setup with API Key
+
+```typescript
+import { createVaultClient } from "@thirdweb-dev/vault-sdk";
+
+const vaultClient = createVaultClient({
+ vaultUrl: "https://vault.thirdweb.com",
+ apiKey: "your-api-key",
+ organizationId: "your-org-id",
+});
+```
+
+### Key Management
+
+#### Create New Wallet
+
+```typescript
+import { generateWallet } from "@thirdweb-dev/vault-sdk";
+
+const wallet = await generateWallet(vaultClient, {
+ name: "My Secure Wallet",
+ description: "Primary wallet for production use",
+ keyType: "secp256k1", // or "ed25519"
+ metadata: {
+ environment: "production",
+ purpose: "primary-signer",
+ },
+});
+
+console.log("Wallet created:", {
+ id: wallet.id,
+ address: wallet.address,
+ publicKey: wallet.publicKey,
+});
+```
+
+#### Import Existing Wallet
+
+```typescript
+import { importWallet } from "@thirdweb-dev/vault-sdk";
+
+const importedWallet = await importWallet(vaultClient, {
+ name: "Imported Wallet",
+ privateKey: "0x...", // Private key to import
+ encryptionKey: "your-encryption-key", // Optional additional encryption
+});
+```
+
+#### List Wallets
+
+```typescript
+import { listWallets } from "@thirdweb-dev/vault-sdk";
+
+const wallets = await listWallets(vaultClient, {
+ limit: 50,
+ offset: 0,
+ filter: {
+ keyType: "secp256k1",
+ status: "active",
+ },
+});
+
+console.log("Available wallets:", wallets);
+```
+
+### Transaction Signing
+
+#### Sign Transaction
+
+```typescript
+import { signTransaction } from "@thirdweb-dev/vault-sdk";
+
+const signature = await signTransaction(vaultClient, {
+ walletId: "wallet-id-123",
+ transaction: {
+ to: "0x742d35Cc06C94a2E0b2dE76D63CB8d35e3Ae1B1a",
+ value: "1000000000000000000", // 1 ETH in wei
+ data: "0x", // Contract call data
+ gasLimit: "21000",
+ gasPrice: "20000000000", // 20 gwei
+ nonce: 42,
+ chainId: 1, // Ethereum mainnet
+ },
+ approvalType: "automatic", // or "manual" for multi-sig
+});
+
+console.log("Transaction signed:", signature);
+```
+
+#### Sign Message
+
+```typescript
+import { signMessage } from "@thirdweb-dev/vault-sdk";
+
+const messageSignature = await signMessage(vaultClient, {
+ walletId: "wallet-id-123",
+ message: "Hello, Web3!",
+ encoding: "utf8", // or "hex"
+});
+
+console.log("Message signature:", messageSignature);
+```
+
+#### Sign Typed Data (EIP-712)
+
+```typescript
+import { signTypedData } from "@thirdweb-dev/vault-sdk";
+
+const typedDataSignature = await signTypedData(vaultClient, {
+ walletId: "wallet-id-123",
+ domain: {
+ name: "MyDApp",
+ version: "1",
+ chainId: 1,
+ verifyingContract: "0x...",
+ },
+ types: {
+ Transfer: [
+ { name: "from", type: "address" },
+ { name: "to", type: "address" },
+ { name: "amount", type: "uint256" },
+ ],
+ },
+ value: {
+ from: "0x...",
+ to: "0x...",
+ amount: "1000000000000000000",
+ },
+});
+```
+
+### Multi-Signature Wallets
+
+#### Create Multi-Sig Wallet
+
+```typescript
+import { createMultiSigWallet } from "@thirdweb-dev/vault-sdk";
+
+const multiSigWallet = await createMultiSigWallet(vaultClient, {
+ name: "Treasury Multi-Sig",
+ signers: [
+ { address: "0x...", weight: 1 },
+ { address: "0x...", weight: 1 },
+ { address: "0x...", weight: 2 }, // Higher weight for admin
+ ],
+ threshold: 2, // Require 2 signatures
+ policy: {
+ requireAllForHighValue: true,
+ highValueThreshold: "10000000000000000000", // 10 ETH
+ },
+});
+```
+
+#### Submit Transaction for Approval
+
+```typescript
+import { submitTransactionProposal } from "@thirdweb-dev/vault-sdk";
+
+const proposal = await submitTransactionProposal(vaultClient, {
+ multiSigWalletId: "multisig-wallet-id",
+ transaction: {
+ to: "0x...",
+ value: "5000000000000000000", // 5 ETH
+ data: "0x",
+ },
+ description: "Treasury payout for Q4 operations",
+ executionDeadline: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days
+});
+
+console.log("Proposal submitted:", proposal.id);
+```
+
+#### Approve Transaction
+
+```typescript
+import { approveTransaction } from "@thirdweb-dev/vault-sdk";
+
+await approveTransaction(vaultClient, {
+ proposalId: "proposal-id-123",
+ signature: "optional-signature-if-required",
+ comment: "Approved for Q4 operations",
+});
+```
+
+### HD Wallet Support
+
+#### Create HD Wallet
+
+```typescript
+import { createHDWallet } from "@thirdweb-dev/vault-sdk";
+
+const hdWallet = await createHDWallet(vaultClient, {
+ name: "HD Master Wallet",
+ entropy: "high", // Security level
+ derivationPath: "m/44'/60'/0'/0", // Ethereum standard path
+ seedPhraseBackup: {
+ enabled: true,
+ encryptionKey: "backup-encryption-key",
+ },
+});
+```
+
+#### Derive Child Wallet
+
+```typescript
+import { deriveChildWallet } from "@thirdweb-dev/vault-sdk";
+
+const childWallet = await deriveChildWallet(vaultClient, {
+ parentWalletId: "hd-master-wallet-id",
+ derivationPath: "m/44'/60'/0'/0/5", // 6th account
+ name: "User Account 5",
+});
+```
+
+### Access Control and Policies
+
+#### Create Access Policy
+
+```typescript
+import { createAccessPolicy } from "@thirdweb-dev/vault-sdk";
+
+const policy = await createAccessPolicy(vaultClient, {
+ name: "Production Signing Policy",
+ rules: [
+ {
+ resource: "wallet:*",
+ actions: ["read", "sign"],
+ conditions: {
+ ipAllowlist: ["192.168.1.0/24"],
+ timeWindow: {
+ start: "09:00",
+ end: "17:00",
+ timezone: "UTC",
+ },
+ },
+ },
+ {
+ resource: "wallet:high-value-*",
+ actions: ["sign"],
+ conditions: {
+ requireMultiApproval: true,
+ maxTransactionValue: "1000000000000000000", // 1 ETH
+ },
+ },
+ ],
+});
+```
+
+#### Assign Policy to User
+
+```typescript
+import { assignPolicy } from "@thirdweb-dev/vault-sdk";
+
+await assignPolicy(vaultClient, {
+ userId: "user-123",
+ policyId: policy.id,
+ validUntil: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
+});
+```
+
+### Audit and Monitoring
+
+#### Get Audit Logs
+
+```typescript
+import { getAuditLogs } from "@thirdweb-dev/vault-sdk";
+
+const auditLogs = await getAuditLogs(vaultClient, {
+ startTime: Date.now() - 24 * 60 * 60 * 1000, // Last 24 hours
+ endTime: Date.now(),
+ walletId: "wallet-id-123", // Optional filter
+ action: "sign", // Optional filter
+ limit: 100,
+});
+
+console.log("Recent signing activities:", auditLogs);
+```
+
+#### Set Up Monitoring Alerts
+
+```typescript
+import { createAlert } from "@thirdweb-dev/vault-sdk";
+
+const alert = await createAlert(vaultClient, {
+ name: "High Value Transaction Alert",
+ conditions: {
+ transactionValue: {
+ greaterThan: "5000000000000000000", // > 5 ETH
+ },
+ frequency: {
+ threshold: 5,
+ timeWindow: "1h", // 5 transactions in 1 hour
+ },
+ },
+ notifications: [
+ {
+ type: "email",
+ recipients: ["security@company.com"],
+ },
+ {
+ type: "webhook",
+ url: "https://api.company.com/vault-alerts",
+ },
+ ],
+});
+```
+
+## Configuration Options
+
+### Client Configuration
+
+```typescript
+import { createVaultClient } from "@thirdweb-dev/vault-sdk";
+
+const client = createVaultClient({
+ vaultUrl: "https://vault.thirdweb.com",
+ accessToken: "jwt-token",
+
+ // Optional configuration
+ timeout: 30000, // Request timeout
+ retries: 3, // Number of retries
+ retryDelay: 1000, // Delay between retries
+
+ // TLS configuration for self-hosted instances
+ tls: {
+ rejectUnauthorized: true,
+ certificatePath: "/path/to/cert.pem",
+ },
+
+ // Logging configuration
+ logging: {
+ level: "info", // debug, info, warn, error
+ redactSensitiveData: true,
+ },
+});
+```
+
+### Security Configuration
+
+```typescript
+const secureClient = createVaultClient({
+ vaultUrl: "https://vault.thirdweb.com",
+ accessToken: "jwt-token",
+
+ // Enhanced security options
+ security: {
+ encryptionAtRest: true,
+ encryptionInTransit: true,
+ keyRotationInterval: "30d",
+ sessionTimeout: "15m",
+
+ // Hardware security module settings
+ hsm: {
+ enabled: true,
+ provider: "aws-cloudhsm", // or "azure-keyvault"
+ keyId: "hsm-key-id",
+ },
+ },
+});
+```
+
+## API Reference
+
+### Core Functions
+
+- `createVaultClient(config)` - Initialize Vault client
+- `generateWallet(client, options)` - Create new wallet
+- `importWallet(client, options)` - Import existing wallet
+- `listWallets(client, options)` - List available wallets
+- `deleteWallet(client, walletId)` - Securely delete wallet
+
+### Signing Functions
+
+- `signTransaction(client, options)` - Sign blockchain transaction
+- `signMessage(client, options)` - Sign arbitrary message
+- `signTypedData(client, options)` - Sign EIP-712 typed data
+- `batchSign(client, operations)` - Sign multiple operations atomically
+
+### Multi-Signature Functions
+
+- `createMultiSigWallet(client, options)` - Create multi-sig wallet
+- `submitTransactionProposal(client, options)` - Submit transaction for approval
+- `approveTransaction(client, options)` - Approve pending transaction
+- `rejectTransaction(client, options)` - Reject pending transaction
+
+### HD Wallet Functions
+
+- `createHDWallet(client, options)` - Create HD master wallet
+- `deriveChildWallet(client, options)` - Derive child wallet
+- `getDerivationPath(client, walletId)` - Get wallet derivation path
+
+### Access Control Functions
+
+- `createAccessPolicy(client, policy)` - Create access policy
+- `assignPolicy(client, assignment)` - Assign policy to user
+- `revokePolicy(client, assignment)` - Revoke policy assignment
+
+## Examples
+
+### Enterprise Wallet Service
+
+```typescript
+import {
+ createVaultClient,
+ generateWallet,
+ signTransaction,
+ createAccessPolicy
+} from "@thirdweb-dev/vault-sdk";
+
+class EnterpriseWalletService {
+ private vaultClient;
+
+ constructor(vaultUrl: string, accessToken: string) {
+ this.vaultClient = createVaultClient({
+ vaultUrl,
+ accessToken,
+ security: {
+ encryptionAtRest: true,
+ sessionTimeout: "15m",
+ },
+ });
+ }
+
+ async createUserWallet(userId: string, userRole: string) {
+ // Create wallet for user
+ const wallet = await generateWallet(this.vaultClient, {
+ name: `Wallet for ${userId}`,
+ metadata: {
+ userId,
+ userRole,
+ createdAt: new Date().toISOString(),
+ },
+ });
+
+ // Create appropriate access policy
+ const policy = await createAccessPolicy(this.vaultClient, {
+ name: `${userRole} Policy for ${userId}`,
+ rules: this.getPolicyRulesForRole(userRole),
+ });
+
+ // Assign policy to user
+ await assignPolicy(this.vaultClient, {
+ userId,
+ policyId: policy.id,
+ });
+
+ return wallet;
+ }
+
+ async executeSecureTransaction(walletId: string, transaction: any) {
+ try {
+ const signature = await signTransaction(this.vaultClient, {
+ walletId,
+ transaction,
+ approvalType: "automatic",
+ });
+
+ return {
+ success: true,
+ signature,
+ timestamp: new Date().toISOString(),
+ };
+ } catch (error) {
+ console.error("Transaction signing failed:", error);
+ throw error;
+ }
+ }
+
+ private getPolicyRulesForRole(role: string) {
+ const baseRules = [
+ {
+ resource: "wallet:own",
+ actions: ["read", "sign"],
+ conditions: {
+ maxTransactionValue: "1000000000000000000", // 1 ETH
+ },
+ },
+ ];
+
+ if (role === "admin") {
+ baseRules.push({
+ resource: "wallet:*",
+ actions: ["read", "sign", "manage"],
+ conditions: {
+ requireMultiApproval: true,
+ },
+ });
+ }
+
+ return baseRules;
+ }
+}
+```
+
+### DeFi Integration with Multi-Sig
+
+```typescript
+import {
+ createMultiSigWallet,
+ submitTransactionProposal,
+ approveTransaction
+} from "@thirdweb-dev/vault-sdk";
+
+class DeFiMultiSigManager {
+ private vaultClient;
+ private treasuryWalletId: string;
+
+ constructor(vaultClient: any) {
+ this.vaultClient = vaultClient;
+ }
+
+ async initializeTreasury() {
+ const treasuryWallet = await createMultiSigWallet(this.vaultClient, {
+ name: "DeFi Treasury",
+ signers: [
+ { address: "0x...", weight: 1, role: "cto" },
+ { address: "0x...", weight: 1, role: "cfo" },
+ { address: "0x...", weight: 2, role: "ceo" },
+ ],
+ threshold: 2,
+ policy: {
+ requireAllForHighValue: true,
+ highValueThreshold: "50000000000000000000", // 50 ETH
+ dailyLimit: "10000000000000000000", // 10 ETH per day
+ },
+ });
+
+ this.treasuryWalletId = treasuryWallet.id;
+ return treasuryWallet;
+ }
+
+ async proposeYieldFarmingInvestment(
+ protocolAddress: string,
+ amount: string,
+ description: string
+ ) {
+ const proposal = await submitTransactionProposal(this.vaultClient, {
+ multiSigWalletId: this.treasuryWalletId,
+ transaction: {
+ to: protocolAddress,
+ value: "0",
+ data: this.encodeStakeTransaction(amount),
+ },
+ description: `Yield farming investment: ${description}`,
+ category: "defi-investment",
+ riskLevel: "medium",
+ executionDeadline: Date.now() + 48 * 60 * 60 * 1000, // 48 hours
+ });
+
+ return proposal;
+ }
+
+ private encodeStakeTransaction(amount: string): string {
+ // Encode the staking transaction data
+ // This would typically use a library like ethers.js
+ return "0x..."; // Encoded transaction data
+ }
+}
+```
+
+## References
+
+### Documentation
+- [Vault Documentation](https://portal.thirdweb.com/vault) - Complete Vault guide
+- [Key Management Best Practices](https://portal.thirdweb.com/vault/security) - Security guidelines
+- [Multi-Signature Setup](https://portal.thirdweb.com/vault/multisig) - Multi-sig configuration
+
+### Security Resources
+- [Vault Security Model](https://portal.thirdweb.com/vault/security-model) - Understanding Vault's security architecture
+- [Access Control Guide](https://portal.thirdweb.com/vault/access-control) - Setting up permissions and policies
+- [Audit Logging](https://portal.thirdweb.com/vault/audit-logs) - Monitoring and compliance
+
+### Integration Examples
+- [Vault Examples](https://github.com/thirdweb-example/vault-examples) - Example implementations
+- [Enterprise Integration](https://github.com/thirdweb-example/vault-enterprise) - Enterprise use cases
+- [DeFi Integration](https://github.com/thirdweb-example/vault-defi) - DeFi protocol integration
+
+### Advanced Topics
+- [Hardware Security Modules](https://portal.thirdweb.com/vault/hsm) - HSM integration
+- [Key Derivation](https://portal.thirdweb.com/vault/hd-wallets) - HD wallet implementation
+- [Disaster Recovery](https://portal.thirdweb.com/vault/disaster-recovery) - Backup and recovery procedures
+
+### API References
+- [Vault API Reference](https://vault-api.thirdweb.com/docs) - Complete API documentation
+- [Authentication Guide](https://portal.thirdweb.com/vault/authentication) - Authentication methods
+- [Webhook Integration](https://portal.thirdweb.com/vault/webhooks) - Real-time notifications
+
+### Community and Support
+- [Discord #vault](https://discord.gg/thirdweb) - Vault specific help
+- [GitHub Issues](https://github.com/thirdweb-dev/js/issues) - Report Vault SDK issues
+- [Security Disclosures](mailto:security@thirdweb.com) - Report security vulnerabilities
diff --git a/packages/wagmi-adapter/README.md b/packages/wagmi-adapter/README.md
index 9b513578fbf..50b87385159 100644
--- a/packages/wagmi-adapter/README.md
+++ b/packages/wagmi-adapter/README.md
@@ -1,3 +1,579 @@
# Wagmi Adapter
-This package enables the use of thirdweb's in-app wallets with wagmi.
+## Description
+
+The **@thirdweb-dev/wagmi-adapter** package provides a seamless integration layer that enables you to use thirdweb's powerful in-app wallets and smart account features within the wagmi ecosystem. This adapter allows developers to leverage thirdweb's embedded wallets, social login capabilities, and account abstraction while maintaining compatibility with the extensive wagmi tooling and ecosystem.
+
+### Key Features
+
+- **Wagmi Integration**: Use thirdweb wallets as wagmi connectors
+- **In-App Wallets**: Social login (Google, Facebook, Apple) and email authentication in wagmi apps
+- **Smart Accounts**: Account abstraction (ERC-4337) support with gas sponsorship
+- **Type Safety**: Full TypeScript support with wagmi's type system
+- **Ecosystem Compatibility**: Works with all wagmi-compatible tools and libraries
+- **Seamless Migration**: Easy integration into existing wagmi applications
+
+## Installation
+
+```bash
+npm install @thirdweb-dev/wagmi-adapter @wagmi/core thirdweb
+```
+
+### Peer Dependencies
+
+The wagmi adapter requires these peer dependencies:
+
+```bash
+npm install @wagmi/core@^2.16.0 thirdweb@^5.85.0
+```
+
+For React applications, also install:
+
+```bash
+npm install wagmi @tanstack/react-query
+```
+
+## Usage
+
+### Basic Setup
+
+#### 1. Configure Wagmi with Thirdweb Wallets
+
+```typescript
+import { createConfig, http } from '@wagmi/core'
+import { mainnet, polygon } from '@wagmi/core/chains'
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+
+// Create thirdweb client
+import { createThirdwebClient } from 'thirdweb'
+
+const thirdwebClient = createThirdwebClient({
+ clientId: 'YOUR_CLIENT_ID',
+})
+
+// Configure wagmi with thirdweb wallets
+const config = createConfig({
+ chains: [mainnet, polygon],
+ connectors: [
+ // Add thirdweb in-app wallet as wagmi connector
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: {
+ options: ['email', 'google', 'apple', 'facebook'],
+ },
+ }),
+ // Add smart wallet connector
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'smart',
+ sponsorGas: true,
+ }),
+ ],
+ transports: {
+ [mainnet.id]: http(),
+ [polygon.id]: http(),
+ },
+})
+```
+
+#### 2. React Integration
+
+```tsx
+import { WagmiProvider } from 'wagmi'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { config } from './wagmi-config'
+
+const queryClient = new QueryClient()
+
+function App() {
+ return (
+
+
+
+
+
+ )
+}
+```
+
+### Wallet Connection Examples
+
+#### In-App Wallet with Social Login
+
+```typescript
+import { connect } from '@wagmi/core'
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+
+const inAppConnector = thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: {
+ options: ['email', 'google', 'apple', 'facebook'],
+ },
+})
+
+// Connect with email
+await connect(config, {
+ connector: inAppConnector,
+ authOptions: {
+ strategy: 'email',
+ email: 'user@example.com',
+ },
+})
+
+// Connect with Google
+await connect(config, {
+ connector: inAppConnector,
+ authOptions: {
+ strategy: 'google',
+ },
+})
+```
+
+#### Smart Account Setup
+
+```typescript
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+
+const smartAccountConnector = thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'smart',
+ sponsorGas: true, // Enable gas sponsorship
+ factoryAddress: '0x...', // Optional: custom factory
+ accountSalt: 'unique-salt', // Optional: deterministic addresses
+})
+
+await connect(config, {
+ connector: smartAccountConnector,
+ personalWallet: inAppConnector, // Use in-app wallet as signer
+})
+```
+
+### React Hooks Usage
+
+#### Connection Management
+
+```tsx
+import { useConnect, useDisconnect, useAccount } from 'wagmi'
+
+function WalletConnection() {
+ const { connectors, connect } = useConnect()
+ const { disconnect } = useDisconnect()
+ const { address, isConnected } = useAccount()
+
+ const thirdwebConnectors = connectors.filter(
+ connector => connector.id.startsWith('thirdweb')
+ )
+
+ return (
+
+ {isConnected ? (
+
+
Connected: {address}
+
+
+ ) : (
+
+ {thirdwebConnectors.map((connector) => (
+
+ ))}
+
+ )}
+
+ )
+}
+```
+
+#### Contract Interactions
+
+```tsx
+import { useReadContract, useWriteContract } from 'wagmi'
+import { parseEther } from 'viem'
+
+const contractConfig = {
+ address: '0x...',
+ abi: [
+ {
+ name: 'balanceOf',
+ type: 'function',
+ stateMutability: 'view',
+ inputs: [{ name: 'owner', type: 'address' }],
+ outputs: [{ name: '', type: 'uint256' }],
+ },
+ {
+ name: 'transfer',
+ type: 'function',
+ stateMutability: 'nonpayable',
+ inputs: [
+ { name: 'to', type: 'address' },
+ { name: 'amount', type: 'uint256' },
+ ],
+ outputs: [{ name: '', type: 'bool' }],
+ },
+ ],
+} as const
+
+function TokenInteraction() {
+ const { address } = useAccount()
+
+ const { data: balance } = useReadContract({
+ ...contractConfig,
+ functionName: 'balanceOf',
+ args: [address!],
+ query: { enabled: !!address },
+ })
+
+ const { writeContract, isPending } = useWriteContract()
+
+ const handleTransfer = () => {
+ writeContract({
+ ...contractConfig,
+ functionName: 'transfer',
+ args: ['0x...', parseEther('1')],
+ })
+ }
+
+ return (
+
+
Balance: {balance?.toString()}
+
+
+ )
+}
+```
+
+### Advanced Configuration
+
+#### Custom Connector Configuration
+
+```typescript
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+
+const customConnector = thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: {
+ options: ['email', 'google'],
+ // Custom auth configuration
+ redirectUrl: 'https://myapp.com/auth',
+ loginUrl: 'https://myapp.com/login',
+ },
+ // Wallet display options
+ metadata: {
+ name: 'My App Wallet',
+ description: 'Secure wallet for My App',
+ url: 'https://myapp.com',
+ icons: ['https://myapp.com/icon.png'],
+ },
+})
+```
+
+#### Multi-Chain Smart Accounts
+
+```typescript
+import { mainnet, polygon, arbitrum } from '@wagmi/core/chains'
+
+const createSmartAccountConnector = (chainId: number) =>
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'smart',
+ chain: chainId,
+ sponsorGas: true,
+ factoryAddress: getFactoryAddress(chainId),
+ })
+
+const config = createConfig({
+ chains: [mainnet, polygon, arbitrum],
+ connectors: [
+ // In-app wallet for signing
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: { options: ['email', 'google'] },
+ }),
+ // Smart accounts for each chain
+ createSmartAccountConnector(mainnet.id),
+ createSmartAccountConnector(polygon.id),
+ createSmartAccountConnector(arbitrum.id),
+ ],
+ transports: {
+ [mainnet.id]: http(),
+ [polygon.id]: http(),
+ [arbitrum.id]: http(),
+ },
+})
+```
+
+### Migration from Wagmi Connectors
+
+#### Replace Existing Connectors
+
+```typescript
+// Before: Standard wagmi connectors
+import { metaMask, walletConnect } from '@wagmi/connectors'
+
+const oldConfig = createConfig({
+ connectors: [
+ metaMask(),
+ walletConnect({ projectId: 'YOUR_PROJECT_ID' }),
+ ],
+})
+
+// After: Enhanced with thirdweb capabilities
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+
+const newConfig = createConfig({
+ connectors: [
+ metaMask(), // Keep existing connectors
+ walletConnect({ projectId: 'YOUR_PROJECT_ID' }),
+ // Add thirdweb enhanced wallets
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: { options: ['email', 'google', 'apple'] },
+ }),
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'smart',
+ sponsorGas: true,
+ }),
+ ],
+})
+```
+
+## API Reference
+
+### thirdwebWalletConnect
+
+Main function to create thirdweb wallet connectors for wagmi.
+
+```typescript
+function thirdwebWalletConnect(options: ThirdwebWalletOptions): Connector
+```
+
+#### Options
+
+```typescript
+interface ThirdwebWalletOptions {
+ client: ThirdwebClient
+ walletId: 'inApp' | 'smart' | string
+ chain?: number
+ auth?: {
+ options: AuthOption[]
+ redirectUrl?: string
+ loginUrl?: string
+ }
+ sponsorGas?: boolean
+ factoryAddress?: string
+ accountSalt?: string
+ metadata?: {
+ name: string
+ description?: string
+ url?: string
+ icons?: string[]
+ }
+}
+```
+
+#### Auth Options
+
+- `'email'` - Email-based authentication
+- `'google'` - Google OAuth
+- `'apple'` - Apple OAuth
+- `'facebook'` - Facebook OAuth
+- `'discord'` - Discord OAuth
+- `'twitter'` - Twitter OAuth
+
+### Connector Methods
+
+```typescript
+// Standard wagmi connector interface
+connector.connect(options?)
+connector.disconnect()
+connector.getAccount()
+connector.getChainId()
+connector.switchChain(chainId)
+```
+
+## Examples
+
+### Complete wagmi + thirdweb Application
+
+```tsx
+import { createConfig, http } from '@wagmi/core'
+import { mainnet, polygon } from '@wagmi/core/chains'
+import { WagmiProvider, useAccount, useConnect, useReadContract } from 'wagmi'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { thirdwebWalletConnect } from '@thirdweb-dev/wagmi-adapter'
+import { createThirdwebClient } from 'thirdweb'
+
+const thirdwebClient = createThirdwebClient({
+ clientId: 'YOUR_CLIENT_ID',
+})
+
+const config = createConfig({
+ chains: [mainnet, polygon],
+ connectors: [
+ thirdwebWalletConnect({
+ client: thirdwebClient,
+ walletId: 'inApp',
+ auth: {
+ options: ['email', 'google'],
+ },
+ }),
+ ],
+ transports: {
+ [mainnet.id]: http(),
+ [polygon.id]: http(),
+ },
+})
+
+const queryClient = new QueryClient()
+
+function WalletStatus() {
+ const { address, isConnected } = useAccount()
+ const { connect, connectors } = useConnect()
+
+ if (isConnected) {
+ return Connected: {address}
+ }
+
+ return (
+
+ {connectors.map((connector) => (
+
+ ))}
+
+ )
+}
+
+function TokenBalance() {
+ const { address } = useAccount()
+
+ const { data: balance } = useReadContract({
+ address: '0xA0b86a33E6441e13C7C95C5D6b55b7cE06eB6a9D', // USDC
+ abi: [
+ {
+ name: 'balanceOf',
+ type: 'function',
+ stateMutability: 'view',
+ inputs: [{ name: 'account', type: 'address' }],
+ outputs: [{ name: '', type: 'uint256' }],
+ },
+ ],
+ functionName: 'balanceOf',
+ args: [address!],
+ query: { enabled: !!address },
+ })
+
+ return USDC Balance: {balance?.toString()}
+}
+
+export default function App() {
+ return (
+
+
+
+
Wagmi + thirdweb Example
+
+
+
+
+
+ )
+}
+```
+
+### Smart Account with Gas Sponsorship
+
+```tsx
+import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi'
+
+function GaslessTransaction() {
+ const {
+ writeContract,
+ data: hash,
+ isPending
+ } = useWriteContract()
+
+ const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({
+ hash,
+ })
+
+ const handleMint = async () => {
+ // This transaction will be sponsored (no gas required)
+ writeContract({
+ address: '0x...',
+ abi: [
+ {
+ name: 'mint',
+ type: 'function',
+ inputs: [
+ { name: 'to', type: 'address' },
+ { name: 'amount', type: 'uint256' },
+ ],
+ },
+ ],
+ functionName: 'mint',
+ args: ['0x...', 1000000000000000000n], // 1 token
+ })
+ }
+
+ return (
+
+
+ {isSuccess &&
Transaction successful!
}
+
+ )
+}
+```
+
+## References
+
+### Documentation
+- [Wagmi Documentation](https://wagmi.sh/) - Official wagmi docs
+- [thirdweb wagmi Integration](https://portal.thirdweb.com/typescript/v5/wagmi) - Integration guide
+- [Wagmi Connectors Guide](https://wagmi.sh/core/api/connectors) - Understanding wagmi connectors
+
+### Examples and Templates
+- [wagmi + thirdweb Template](https://github.com/thirdweb-example/wagmi-starter) - Complete example
+- [Smart Account wagmi Example](https://github.com/thirdweb-example/smart-wallet-wagmi) - Account abstraction
+- [Multi-chain wagmi App](https://github.com/thirdweb-example/multi-chain-wagmi) - Cross-chain functionality
+
+### Related Libraries
+- [@wagmi/core](https://www.npmjs.com/package/@wagmi/core) - Core wagmi functionality
+- [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query) - Data fetching for React
+- [viem](https://www.npmjs.com/package/viem) - Low-level Ethereum library
+
+### Advanced Topics
+- [Custom Connectors](https://wagmi.sh/dev/creating-connectors) - Creating custom wagmi connectors
+- [Account Abstraction Guide](https://portal.thirdweb.com/wallet/smart-wallet) - Understanding smart accounts
+- [Gas Sponsorship Setup](https://portal.thirdweb.com/engine/features/gasless-transactions) - Configuring gasless transactions
+
+### Community and Support
+- [wagmi Discord](https://discord.gg/wagmi) - wagmi community support
+- [thirdweb Discord](https://discord.gg/thirdweb) - thirdweb specific help
+- [GitHub Issues](https://github.com/thirdweb-dev/js/issues) - Report integration issues