🚀 Sead SimpleSDK Web Integration Guide
The Complete Guide for Wallet Partners to Integrate Sead's Wallet Backup and Restore Solution
Overview & Philosophy
🎯 What is SimpleSDK?
SimpleSDK is Sead's production-ready, single-file JavaScript library that enables wallet partners to integrate Sead's wallet backup and restore functionality with just two functions: backup() and restore().
💡 Core Philosophy
Design Principles
- Simplicity First: Just 2 functions, 1 file
- Security by Default: Client-side crypto
- Production Ready: Battle-tested
Key Features
- Zero Dependencies: Self-contained
- API Integration: Quota management
- 1.1MB Bundle: Optimized size
🔐 How It Works
What You Get From Sead
📦 Your Integration Package
| Item | Description | Example |
|---|---|---|
| 1 JavaScript File | Complete SDK bundle | sead-simple-api-bundle.js |
| API Key | Your authentication credential | a1b2c3d4...xyz789.123abc...xyz890 |
| API Endpoint | Your backend URL | https://b2bapi.sead.world/api/v1 |
| Support | Direct technical support | support@sead.world |
🎁 What's Included in the Bundle
Architecture Overview
🏗️ High-Level Architecture
🔄 Data Flow
Important Security Note
Your seed phrase never leaves your device. All cryptographic operations happen locally in the browser. The API only handles quota management and never sees sensitive data.
Prerequisites
✅ Before You Start
1. Partner Account
- Contact Sead B2B team
- Receive your API credentials
- Get your integration package
2. Technical Requirements
- Modern web browser support
- HTTPS in production (required)
- JavaScript enabled
- ~2MB storage for SDK file
3. Planning Decisions
- User ID generation strategy
- Payment integration method
- Backup UI/UX design
- Share storage recommendations
🔑 User ID Strategy
Choose your approach for generating consistent User IDs:
Option 1: Wallet Address (Recommended)
function getUserId() {
return window.ethereum.selectedAddress; // "0x742d35Cc..."
}
Option 2: Hashed Email
function getUserId() {
const email = getCurrentUserEmail();
return sha256(email + 'your-salt-here');
}
Option 3: Deterministic from Seed
function getUserId() {
const seedHash = sha256(userSeedPhrase);
return `user_${seedHash.substring(0, 16)}`;
}
Important: Same user must always get the same ID for quota tracking to work correctly!
Integration Steps
Step 1: Add SDK to Your Project
<!DOCTYPE html>
<html>
<head>
<title>Your Wallet</title>
</head>
<body>
<!-- Your wallet UI -->
<!-- Add the SimpleSDK (just one file!) -->
<script src="./js/sead-simple-api-bundle.js"></script>
<!-- Your wallet code -->
<script src="./js/wallet.js"></script>
</body>
</html>
Step 2: Initialize the SDK
// wallet.js
// Your credentials from Sead
const SEAD_CONFIG = {
apiKey: 'your-api-key-here', // From Sead
apiUrl: 'https://b2bapi.sead.world/api/v1', // Production URL
};
// Initialize when needed (not globally)
function getSeadSDK(userId) {
return new SeadSimpleWithAPI({
apiUrl: SEAD_CONFIG.apiUrl,
apiKey: SEAD_CONFIG.apiKey,
userId: userId // Required - your user identifier
});
}
Step 3: Implement Backup
async function backupWallet() {
try {
// 1. Get seed phrase from your wallet
const seedPhrase = await getWalletSeedPhrase();
// 2. Get user ID (must be consistent!)
const userId = getUserId();
// 3. Initialize SDK
const sead = getSeadSDK(userId);
// 4. Perform backup
const result = await sead.backup({
seedPhrase: seedPhrase,
n: 3, // Total shares (default: 3)
m: 2, // Threshold (default: 2)
password: '', // Optional encryption
onPaymentRequired: handlePayment // If quota exhausted
});
// 5. Handle result
if (result.success) {
displayBackupShares(result.shares);
saveBackupMetadata(result.backupId);
} else {
handleBackupError(result.error);
}
} catch (error) {
console.error('Backup failed:', error);
showUserError('Backup failed. Please try again.');
}
}
Step 4: Implement Restore
async function restoreWallet() {
try {
// 1. Collect shares from user
const shares = await collectSharesFromUser();
// 2. Validate minimum shares
if (shares.length < 2) {
throw new Error('Need at least 2 shares');
}
// 3. Get password if needed
const password = document.getElementById('restore-password').value;
// 4. Initialize SDK
const userId = getUserId() || 'restore-temp';
const sead = getSeadSDK(userId);
// 5. Perform restore
const result = await sead.restore({
shareTexts: shares,
password: password || undefined
});
// 6. Handle result
if (result.success) {
await importSeedToWallet(result.seedPhrase);
showSuccess('Wallet restored successfully!');
} else {
handleRestoreError(result.error);
}
} catch (error) {
console.error('Restore failed:', error);
showUserError('Restore failed. Check your shares.');
}
}
Step 5: Handle Payments
// Called when user exceeds free quota
async function handlePayment(amount, currency) {
try {
// Show payment UI
const paymentModal = showPaymentModal({
amount: amount || 0.001,
currency: currency || 'SEAD',
description: 'Sead Backup Service Fee'
});
// Process payment (your implementation)
const payment = await processUserPayment({
amount: amount,
currency: currency
});
// Return proof for SDK
return {
transactionId: payment.txHash,
proof: payment.signature || payment.txHash
};
} catch (error) {
// User cancelled or payment failed
throw new Error('Payment cancelled');
}
}
Step 6: Add UI Components
<!-- Backup Section -->
<div id="backup-section">
<h2>Backup Your Wallet</h2>
<div class="backup-options">
<label>
Total Shares:
<select id="total-shares">
<option value="3" selected>3 (Recommended)</option>
<option value="5">5 (Higher Security)</option>
</select>
</label>
<label>
Minimum to Restore:
<select id="threshold">
<option value="2" selected>2 (Recommended)</option>
<option value="3">3 (Higher Security)</option>
</select>
</label>
<label>
Encryption Password (Optional):
<input type="password" id="backup-password" />
</label>
</div>
<button onclick="backupWallet()" class="primary-btn">
Create Backup
</button>
<div id="shares-container"></div>
</div>
<!-- Restore Section -->
<div id="restore-section">
<h2>Restore Your Wallet</h2>
<div class="restore-inputs">
<textarea id="share-input-1" placeholder="Enter share 1"></textarea>
<textarea id="share-input-2" placeholder="Enter share 2"></textarea>
<textarea id="share-input-3" placeholder="Enter share 3 (optional)"></textarea>
<input type="password" id="restore-password"
placeholder="Password (if encrypted)" />
</div>
<button onclick="restoreWallet()" class="primary-btn">
Restore Wallet
</button>
</div>
Reference Implementation Analysis
The reference implementation (test-simple-sdk.html) demonstrates best practices:
1. Configuration Management (Lines 563-576)
// Smart configuration
const SEAD_API_KEY = document.getElementById('apiKey').value;
const SEAD_API_URL = document.getElementById('baseUrl').value ||
'https://b2bapi.sead.world/api/v1';
const userId = document.getElementById('userId').value;
// Key validations
if (!apiKey.match(/^[a-f0-9]+\.[a-f0-9]+$/i)) {
showStatus('Invalid API key format', 'error');
return;
}
Best Practice: Always validate API key format and user ID presence.
2. Dynamic Share Input Creation (Lines 958-1017)
// Parse threshold from share
function parseShareThreshold() {
const shareText = document.getElementById('shareText1').value;
// Extract threshold from position 16
const thresholdChar = shareText.charAt(15);
const threshold = parseInt(thresholdChar, 16);
// Create dynamic inputs
for (let i = 2; i <= threshold; i++) {
createShareInput(i);
}
}
Best Practice: Dynamically adjust UI based on share requirements.
3. Payment Flow Integration (Lines 1116-1139)
onPaymentRequired: async (amount, currency) => {
if (document.getElementById('simulatePayment').checked) {
const transactionId = `tx_${Date.now()}`;
const proof = `proof_${Math.random().toString(36)}`;
return {
transactionId: transactionId,
proof: proof
};
} else {
throw new Error(`Payment of ${amount} ${currency} required`);
}
}
Best Practice: Implement clear payment flow with simulation for testing.
4. API Console Integration (Lines 762-932)
// API request interception
const originalFetch = window.fetch;
window.fetch = async function(...args) {
const [url, options = {}] = args;
// Log request
addApiLog('request', method, url, requestData);
try {
const response = await originalFetch.apply(this, args);
// Log response
addApiLog('response', method, url, responseData, response.status);
return response;
} catch (error) {
// Log error
addApiLog('error', method, url, error.message);
throw error;
}
};
Best Practice: Implement debugging console for development.
🎯 Key Patterns from Reference
Separation of Concerns
- • UI logic separated from SDK calls
- • Configuration management isolated
- • Error handling centralized
Progressive Enhancement
- • Basic functionality first
- • Advanced options hidden by default
- • Clear visual feedback
Error Recovery
- • Graceful degradation
- • Clear error messages
- • Retry mechanisms
User Guidance
- • Inline help text
- • Visual status indicators
- • Step-by-step flow
Security Considerations
🔒 Security Architecture
⚠️ Security Checklist
Client-Side
- Seed phrases processed locally only
- Shares generated on device
- Memory cleared after operations
- No sensitive data in logs
Network
- HTTPS required in production
- API key never in source code
- No seed data transmitted
- Rate limiting enforced
Storage
- Shares stored separately
- Encryption available
- No plaintext seeds saved
- Secure credential storage
🛡️ Best Practices
✅ GOOD: Security Best Practices
// Clear sensitive data
function clearSensitiveData() {
seedPhraseInput.value = '';
seedPhraseVariable = null;
shares.forEach(s => s.text = null);
}
// Validate before operations
function validateBeforeBackup(seedPhrase) {
if (!seedPhrase || seedPhrase.split(' ').length < 12) {
throw new Error('Invalid seed phrase');
}
}
// Secure configuration
const config = {
apiKey: process.env.SEAD_API_KEY || getFromSecureStorage('sead_key'),
apiUrl: 'https://b2bapi.sead.world/api/v1' // Always HTTPS
};
❌ BAD: Never Do This!
// Never hardcode API keys
const API_KEY = 'abc123...';
// Never store seeds in localStorage
localStorage.setItem('seed', seedPhrase);
// Never log sensitive data
console.log('Seed:', seedPhrase);
Production Deployment
🚀 Pre-Deployment Checklist
Configuration
- API key stored securely
- Production API URL configured
- HTTPS enforced on all pages
- Content Security Policy configured
Testing
- All test scenarios passed
- Payment flow tested
- Error handling verified
- Cross-browser compatibility checked
Security
- Security audit completed
- Penetration testing done
- Rate limiting configured
- Monitoring enabled
Documentation
- User guide prepared
- Support documentation ready
- Recovery procedures documented
- FAQ updated
📊 Monitoring & Analytics
// Track SDK usage
class SeadMetrics {
trackBackup(success, duration) {
analytics.track('sead_backup', {
success: success,
duration: duration,
timestamp: Date.now()
});
}
trackRestore(success, sharesUsed) {
analytics.track('sead_restore', {
success: success,
shares_used: sharesUsed,
timestamp: Date.now()
});
}
trackError(operation, error) {
analytics.track('sead_error', {
operation: operation,
error: error.message,
timestamp: Date.now()
});
}
}
🔄 Update Strategy
// Version checking
async function checkSDKVersion() {
const currentVersion = SeadSimpleWithAPI.VERSION;
const latestVersion = await fetchLatestVersion();
if (currentVersion < latestVersion) {
console.warn('SDK update available:', latestVersion);
// Notify operations team
}
}
Support & Resources
📚 Additional Documentation
🆘 Getting Help
Technical Support
Integration Support
🐛 Troubleshooting
API Key Invalid
- • Check format:
publicId.secret - • Verify not expired
- • Ensure correct environment
Quota Exhausted
- • Implement payment handler
- • Check free tier limits
- • Verify user ID consistency
Network Error
- • Check HTTPS requirement
- • Verify API URL
- • Check CORS settings
Invalid Shares
- • Verify share format
- • Check threshold requirements
- • Ensure same backup source
📈 Performance Tips
Lazy Load SDK
Load only when needed to improve initial page load
Cache API Responses
Reduce API calls by caching quota checks
Batch Operations
Group related calls to minimize network overhead
Optimize QR Display
Use virtual scrolling for many QR codes
Conclusion
SimpleSDK provides a complete, production-ready solution for integrating Sead's wallet backup and restore functionality into your wallet. With just one file and two functions, you can offer your users military-grade backup security.
happens locally
two functions
from day one
payment handling
by default