W3MSG SDK Migration Guide
Comprehensive guide for migrating between W3MSG SDK versions and handling protocol upgrades seamlessly.
Overview
The W3MSG SDK includes an advanced migration system that automatically detects and handles protocol version changes, SDK updates, and data migrations. This ensures smooth transitions without data loss or service interruption.
Migration System Architecture
Automatic Migration Detection
The SDK automatically checks for migrations when connecting to a wallet:
import { W3MSGSDK } from '@w3msg/sdk';
const w3msg = new W3MSGSDK({
environment: 'production',
enableLogging: true
});
// Migration check happens automatically during connection
await w3msg.connect(signer);
Migration Events
Listen to migration events for UI updates and user notifications:
// Migration available - user action may be required
w3msg.on('migration:available', (data) => {
if (data.notification) {
// Show user notification for breaking changes
showMigrationNotification(data.notification);
}
});
// Migration progress updates
w3msg.on('migration:progress', (data) => {
console.log(`Migration ${data.planId}: ${data.progress}% complete`);
});
// Migration completed successfully
w3msg.on('migration:completed', (execution) => {
console.log('Migration completed successfully');
});
// Migration failed - may require user intervention
w3msg.on('migration:failed', (execution) => {
console.error('Migration failed:', execution.error);
// Handle rollback or retry logic
});
Protocol-Specific Migrations
XMTP Protocol Migrations
XMTP v2 to v3 Migration
What Changes:
- Conversation addressing: Peer addresses → Inbox IDs
- Message format updates
- Enhanced group chat support
- Local database integration
Migration Process:
- Automatic Detection: SDK detects XMTP v2 data in local storage
- Conversation Migration: Converts peer addresses to inbox IDs
- Message History: Migrates existing conversations and messages
- Configuration Update: Updates client configuration for v3 compatibility
Code Example:
// Migration happens automatically, but you can monitor progress
w3msg.on('migration:started', (data) => {
if (data.plan.protocol === 'xmtp') {
console.log(`XMTP migration started: ${data.plan.fromVersion} → ${data.plan.toVersion}`);
}
});
// Access migrated data
const conversations = await w3msg.getConversations();
// Conversations now use inbox IDs instead of peer addresses
Breaking Changes:
- Conversation IDs change from peer addresses to inbox IDs
- Some v2-specific methods are deprecated
- Group conversation handling is different
Rollback Support:
// If migration fails, automatic rollback preserves v2 data
w3msg.on('migration:rollback', (data) => {
console.log(`Migration rolled back: ${data.reason}`);
// Continue using v2 functionality
});
Push Protocol Migrations
Push Protocol v1 to v2 Migration
What Changes:
- Channel subscription model updates
- Enhanced notification payload structure
- Improved spam protection
Migration Process:
- Channel Migration: Updates channel subscription format
- Notification History: Converts old notification format
- Settings Migration: Updates user preferences and settings
SDK Version Migrations
From v1.x to v2.x
The v2.x release introduces breaking changes for improved developer experience.
Breaking Changes
-
Constructor Changes
// ❌ v1.x
const w3msg = new W3MSGSDK(signer, options);
// ✅ v2.x
const w3msg = new W3MSGSDK({ signer, ...options }); -
Method Signature Updates
// ❌ v1.x
await w3msg.send(recipientAddress, message, options);
// ✅ v2.x
await w3msg.send({ to: recipientAddress, content: message, ...options }); -
Event System Changes
// ❌ v1.x
w3msg.on('message', (msg) => console.log(msg));
// ✅ v2.x
w3msg.on('messageReceived', (msg) => console.log(msg)); -
Configuration Structure
// ❌ v1.x
const config = {
xmtpEnv: 'production',
pushEnv: 'prod',
vcEnabled: true
};
// ✅ v2.x
const config = {
xmtpConfig: { env: 'production' },
pushConfig: { env: 'prod' },
vcConfig: { enableVerification: true }
};
Migration Steps
-
Update Dependencies
npm install @w3msg/sdk@^2.0.0 -
Update Imports and Configuration
// Update constructor calls
const w3msg = new W3MSGSDK({
environment: 'production',
vcConfig: {
enableVerification: true,
verificationMode: 'lenient'
}
}); -
Update Event Handlers
// Update event names
w3msg.on('messageReceived', handleMessage);
w3msg.on('migration:available', handleMigrationNotification); -
Test Thoroughly
- Test wallet connection
- Verify message sending/receiving
- Check VC verification functionality
- Validate migration handling
Manual Migration Management
Executing Specific Migrations
// Get available migrations
const activeMigrations = w3msg.getActiveMigrations();
// Execute a specific migration manually
try {
const execution = await w3msg.executeMigration(migrationPlan);
console.log('Migration executed:', execution.status);
} catch (error) {
console.error('Migration failed:', error);
}
Migration Configuration
const w3msg = new W3MSGSDK({
// Migration-related configuration
enableLogging: true, // Enable migration logging
retryAttempts: 3, // Retry failed migrations
timeoutMs: 30000, // Migration timeout
});
Data Backup and Recovery
Automatic Backups
The migration system automatically creates backups before major changes:
// Backups are created automatically for breaking changes
w3msg.on('migration:started', (data) => {
if (data.plan.breakingChanges.length > 0) {
console.log('Backup created before breaking migration');
}
});
Manual Backup Creation
// Create manual backup before custom migrations
const migrationManager = w3msg.migrationManager;
const backupId = await migrationManager.createBackup('xmtp', userData);
console.log(`Backup created: ${backupId}`);
// Restore from backup if needed
try {
const restoredData = await migrationManager.restoreBackup(backupId);
console.log('Data restored successfully');
} catch (error) {
console.error('Backup restoration failed:', error);
}
Best Practices
1. Monitor Migration Events
Always listen to migration events in production applications:
const setupMigrationHandling = (w3msg) => {
w3msg.on('migration:available', (data) => {
// Show user notification for required migrations
if (data.plan.requiresUserConfirmation) {
showUserConfirmationDialog(data.plan, data.notification);
}
});
w3msg.on('migration:failed', (execution) => {
// Log migration failures for debugging
console.error('Migration failed:', execution);
// Show user-friendly error message
showErrorNotification('Migration failed. Please try again.');
});
};
2. Handle Breaking Changes Gracefully
const handleBreakingMigration = async (plan) => {
// Warn users about breaking changes
if (plan.breakingChanges.length > 0) {
const confirmed = await showBreakingChangeWarning(plan.breakingChanges);
if (!confirmed) {
console.log('User cancelled breaking migration');
return;
}
}
// Execute migration with progress tracking
try {
const execution = await w3msg.executeMigration(plan);
showMigrationSuccess();
} catch (error) {
showMigrationError(error);
}
};
3. Test Migration Scenarios
// Test migration scenarios in development
const testMigration = async () => {
// Simulate v2 to v3 migration
const mockPlan = {
protocol: 'xmtp',
fromVersion: '2.5.0',
toVersion: '3.0.0',
breakingChanges: ['Conversation ID format changed'],
requiresUserConfirmation: true
};
// Test migration execution
const result = await w3msg.executeMigration(mockPlan);
console.log('Test migration result:', result);
};
4. Version Compatibility
// Check version compatibility before operations
const checkCompatibility = async () => {
const state = w3msg.getState();
if (!state.isInitialized) {
throw new Error('SDK not initialized');
}
// Check if migrations are in progress
const activeMigrations = w3msg.getActiveMigrations();
if (activeMigrations.length > 0) {
console.log('Migrations in progress, waiting...');
// Wait for migrations to complete
await waitForMigrations(w3msg);
}
};
Troubleshooting
Common Migration Issues
-
Migration Stuck in Progress
// Clear stuck migrations
w3msg.clearActiveMigrations();
// Restart migration check
await w3msg.checkAndExecuteMigrations(); -
Version Detection Failed
// Manual version check
const migrationManager = w3msg.migrationManager;
const xmtpVersion = await migrationManager.getStoredVersion('xmtp');
console.log('Stored XMTP version:', xmtpVersion); -
Rollback Issues
// Check rollback status
w3msg.on('migration:rollback', (data) => {
console.log(`Rollback completed for: ${data.planId}`);
// Verify data integrity after rollback
});
Debug Migration Issues
// Enable detailed migration logging
const w3msg = new W3MSGSDK({
enableLogging: true,
logLevel: 'debug' // Enable debug logs
});
// Monitor all migration events
const events = [
'migration:available',
'migration:started',
'migration:progress',
'migration:completed',
'migration:failed',
'migration:rollback'
];
events.forEach(event => {
w3msg.on(event, (data) => {
console.log(`[${event}]`, data);
});
});
Migration Notifications
User-Friendly Notifications
const createMigrationNotification = (plan, notification) => {
return {
id: notification.id,
type: notification.type, // 'info', 'warning', 'critical'
title: notification.title,
message: notification.message,
actions: notification.actions.map(action => ({
label: action.label,
primary: action.primary,
onClick: () => handleMigrationAction(action.action, plan)
})),
dismissible: notification.dismissible,
persistent: notification.persistent
};
};
const handleMigrationAction = async (action, plan) => {
switch (action) {
case 'migrate':
await w3msg.executeMigration(plan);
break;
case 'defer':
// Remind user later
scheduleReminderNotification(plan);
break;
case 'learn_more':
// Open documentation
window.open('/docs/migration-guide');
break;
case 'backup':
// Create backup before migration
await w3msg.migrationManager.createBackup(plan.protocol, userData);
break;
}
};
Advanced Migration Features
Custom Migration Steps
// Register custom migration step
const customStep = {
id: 'custom-data-migration',
name: 'Migrate Custom Data',
description: 'Migrate application-specific data',
fromVersion: '1.x',
toVersion: '2.x',
required: false,
async: true,
rollbackSupported: true,
migrate: async (context) => {
// Custom migration logic
const result = await migrateCustomData(context.userData);
return {
success: true,
message: 'Custom data migrated successfully',
data: result
};
},
rollback: async (context) => {
// Custom rollback logic
await rollbackCustomData(context.rollbackData);
return { success: true, message: 'Rollback completed' };
}
};
w3msg.migrationManager.registerMigrationStep(customStep);
Migration Analytics
// Track migration metrics
w3msg.on('migration:completed', (execution) => {
const metrics = {
protocol: execution.protocol,
fromVersion: execution.fromVersion,
toVersion: execution.toVersion,
duration: execution.endTime - execution.startTime,
stepsCompleted: execution.completedSteps.length,
warnings: execution.warnings.length
};
// Send to analytics service
analytics.track('migration_completed', metrics);
});
Migration API Reference
MigrationManager Methods
interface MigrationManager {
// Check if migration is needed
checkMigrationNeeded(protocol: string, version: string): Promise<MigrationCheckResult>;
// Execute migration plan
executeMigration(plan: MigrationPlan): Promise<MigrationExecution>;
// Create backup
createBackup(protocol: string, data: any): Promise<string>;
// Restore from backup
restoreBackup(backupId: string): Promise<any>;
// Generate user notification
generateMigrationNotification(plan: MigrationPlan): MigrationNotification;
// Register custom migration step
registerMigrationStep(step: MigrationStep): void;
}
Migration Event Types
interface MigrationEvents {
'migration:available': (data: { plan: MigrationPlan; notification?: MigrationNotification }) => void;
'migration:started': (data: { planId: string; plan: MigrationPlan }) => void;
'migration:progress': (data: { planId: string; progress: number }) => void;
'migration:completed': (execution: MigrationExecution) => void;
'migration:failed': (data: { planId: string; error: string; execution: MigrationExecution }) => void;
'migration:rollback': (data: { planId: string; reason: string }) => void;
}
For more detailed examples and API documentation, see the API Reference.
Support
If you encounter migration issues:
- Check the troubleshooting section above
- Enable debug logging for detailed information
- Create a backup before attempting manual fixes
- Contact support with migration logs and error details
The migration system is designed to be robust and handle edge cases gracefully, but complex scenarios may require manual intervention.