Dragon Wallets SDK Setup Guide
This guide walks you through the process of setting up and configuring the Dragon Wallets SDK in your application. Follow these steps to start integrating secure, high-performance wallet functionality.
Prerequisites
Before you begin, ensure you have the following:
- A DragonFire Developer account (register at Developer Portal)
- An API key with wallet permissions
- Node.js 16.x or higher (for npm/yarn installation)
- Basic understanding of async/await patterns
API Key Setup
To obtain an API key for the Dragon Wallets SDK:
- Log in to the Developer Portal
- Navigate to "API Keys" in your dashboard
- Select "Create New API Key"
- Enable the "Wallet Services" permission
- Copy your new API key and secret
Note: Store your API key securely and never expose it in client-side code.
Installation
Install the Dragon Wallets SDK using your preferred package manager:
npm install @dragonfire/client @dragonfire/wallet-client
yarn add @dragonfire/client @dragonfire/wallet-client
<script src="https://cdn.dragonfire.ai/sdk/dragonfire-client.min.js"></script>
<script src="https://cdn.dragonfire.ai/sdk/wallet-client.min.js"></script>
The SDK consists of two main packages:
@dragonfire/client
: Core DragonFire client for connecting to services@dragonfire/wallet-client
: Specialized wallet functionality
Client Initialization
Initialize the DragonFire client and wallet client:
import { DragonFireClient } from '@dragonfire/client';
import { WalletClient } from '@dragonfire/wallet-client';
// Step 1: Initialize the main DragonFire client
const dragonfire = new DragonFireClient({
apiKey: 'YOUR_API_KEY',
region: 'us-west', // Server region (us-west, us-east, eu, asia)
environment: 'production', // Environment (production, staging, development)
timeout: 30000, // Request timeout in milliseconds
retryConfig: { // Retry configuration
maxRetries: 3,
initialDelay: 100,
maxDelay: 3000
},
logging: { // Logging configuration
level: 'error', // Log level (debug, info, warn, error)
handler: console.log // Custom log handler
}
});
// Step 2: Connect to DragonFire services
await dragonfire.connect();
// Step 3: Initialize the wallet client
const wallet = new WalletClient(dragonfire, {
securityLevel: 'high', // Security level (standard, high, maximum)
vectorDimension: 7, // Vector space dimension (3-13, default: 7)
autoBackup: true, // Enable automatic wallet backups
identityVerification: true, // Enable advanced identity verification
defaultCurrency: 'USD', // Default currency
cacheStrategy: 'optimized', // Cache strategy (minimal, balanced, optimized)
performanceMode: 'balanced' // Performance mode (balanced, high-throughput, low-latency)
});
Configuration Options
Parameter | Type | Default | Description |
---|---|---|---|
securityLevel | string | 'standard' | Security level for wallet operations ('standard', 'high', 'maximum') |
vectorDimension | number | 7 | Vector space dimension for transactions (3-13) |
autoBackup | boolean | true | Enable automatic wallet backups |
identityVerification | boolean | false | Enable advanced identity verification |
defaultCurrency | string | 'USD' | Default currency for transactions |
cacheStrategy | string | 'balanced' | Cache strategy ('minimal', 'balanced', 'optimized') |
performanceMode | string | 'balanced' | Performance mode ('balanced', 'high-throughput', 'low-latency') |
Note: The initialization process establishes a secure connection to DragonFire services using RWT (Rotational WebSockets) protocol. This connection is used for all subsequent wallet operations.
Wallet Creation
After initializing the client, you can create a new wallet:
// Create a new wallet
const walletInfo = await wallet.createWallet({
name: 'Primary Wallet', // Wallet name
securityLevel: 'high', // Security level
backupMethod: 'cloud', // Backup method (cloud, local, none)
recoveryOptions: { // Recovery options
email: 'user@example.com',
phoneNumber: '+1234567890'
},
attributes: { // Custom attributes
purpose: 'personal',
limit: 1000
}
});
console.log('Wallet created successfully:');
console.log('Wallet ID:', walletInfo.id);
console.log('Creation time:', walletInfo.createdAt);
console.log('Status:', walletInfo.status);
Wallet Creation Options
Parameter | Type | Default | Description |
---|---|---|---|
name | string | 'Default Wallet' | Descriptive name for the wallet |
securityLevel | string | Client default | Security level for this wallet (overrides client default) |
backupMethod | string | 'cloud' | Wallet backup method ('cloud', 'local', 'none') |
recoveryOptions | object | {} | Recovery contact information |
attributes | object | {} | Custom wallet attributes |
Using an Existing Wallet
To use an existing wallet, load it by ID:
// Load an existing wallet
const existingWallet = await wallet.loadWallet('wallet_123456789');
// Check wallet status
console.log('Wallet status:', existingWallet.status);
console.log('Balance:', existingWallet.balance);
console.log('Last activity:', existingWallet.lastActivityTime);
Configuration Options
The Dragon Wallets SDK offers extensive configuration options to customize its behavior for your specific use case:
Performance Configuration
// Configure wallet performance settings
await wallet.configurePerformance({
concurrencyLevel: 'maximum', // Concurrency level (default, high, maximum)
vectorOptimization: true, // Enable vector path optimization
cacheIntegration: true, // Integrate with DragonFire Cache
precomputeRoutes: true, // Precompute common transaction routes
requestBatching: true, // Enable request batching
batchSize: 100, // Maximum batch size
processingPriority: 'high' // Processing priority (low, standard, high)
});
Security Configuration
// Configure wallet security settings
await wallet.configureSecurity({
tokenRotationInterval: 300000, // Token rotation interval (ms)
tokenRotationPattern: 'phi', // Token rotation pattern (phi, random, sequential)
verificationLevel: 'high', // Verification level (standard, high, maximum)
multiFactorAuth: true, // Enable multi-factor authentication
ipRestriction: true, // Enable IP restriction
allowedIPs: ['192.168.1.1'], // Allowed IP addresses
activityMonitoring: true, // Enable activity monitoring
suspiciousActivityDetection: true // Enable suspicious activity detection
});
Backup Configuration
// Configure wallet backup settings
await wallet.configureBackup({
autoBackupInterval: 3600000, // Auto-backup interval (ms)
backupEncryption: 'high', // Backup encryption level
redundancyLevel: 3, // Backup redundancy level
backupLocation: 'distributed', // Backup location (local, cloud, distributed)
backupNotification: true // Enable backup notifications
});
Transaction Configuration
// Configure transaction settings
await wallet.configureTransactions({
defaultFee: 'standard', // Default fee level (low, standard, high)
defaultTimeout: 30000, // Default transaction timeout (ms)
defaultVector: 'phi', // Default vector routing pattern
confirmationThreshold: 3, // Transaction confirmation threshold
autoRetry: true, // Enable automatic retry for failed transactions
maxRetries: 3, // Maximum retry attempts
receiptGeneration: true // Enable transaction receipt generation
});
Security Best Practices
Follow these security best practices when implementing the Dragon Wallets SDK:
API Key Protection
Never expose API keys in client-side code. Use server-side authentication to generate tokens for browser-based applications.
Secure Storage
Use secure storage mechanisms for wallet credentials. Consider using hardware security modules (HSMs) for high-value applications.
Activity Monitoring
Implement activity monitoring to detect suspicious patterns and implement automatic locking mechanisms for unusual activity.
Multi-Factor Authentication
Enable multi-factor authentication for sensitive wallet operations, especially for high-value transactions.
Sample Implementation
// Implementing enhanced security
// 1. Create a secure RWT token for authentication
const rwt = await wallet.createSecureToken({
purpose: 'wallet-operation',
permissions: ['read', 'transaction'],
expiresIn: 3600000, // 1 hour
rotationSettings: {
pattern: 'phi',
interval: 300000 // 5 minutes
}
});
// 2. Set up multi-factor authentication
await wallet.configureMultiFactorAuth({
methods: ['app', 'email'],
requireForAll: false,
highValueThreshold: 1000, // Require MFA for transactions over $1000
mfaTimeout: 300000 // MFA valid for 5 minutes
});
// 3. Configure IP restrictions
await wallet.configureIPRestriction({
enabled: true,
allowedIPs: ['192.168.1.0/24'],
alertOnNewIP: true
});
// 4. Set up activity monitoring
await wallet.configureActivityMonitoring({
enabled: true,
alertThreshold: 'medium',
lockThreshold: 'high',
notificationEmail: 'security@example.com'
});
// 5. Secure wallet storage
await wallet.configureSecureStorage({
method: 'encrypted',
encryptionLevel: 'AES-256',
useHardwareSecurity: true
});
Environment Setup
Different environments have different setup requirements. Follow these guidelines for your specific environment:
// Node.js server environment
// .env file
// DRAGONFIRE_API_KEY=your_api_key
// DRAGONFIRE_REGION=us-west
// Load environment variables
require('dotenv').config();
const { DragonFireClient } = require('@dragonfire/client');
const { WalletClient } = require('@dragonfire/wallet-client');
// Server-side implementation
async function initializeDragonFireServices() {
const dragonfire = new DragonFireClient({
apiKey: process.env.DRAGONFIRE_API_KEY,
region: process.env.DRAGONFIRE_REGION
});
await dragonfire.connect();
const wallet = new WalletClient(dragonfire, {
securityLevel: 'high',
vectorDimension: 7
});
return { dragonfire, wallet };
}
// Example Express implementation
const express = require('express');
const app = express();
app.use(express.json());
let services;
// Initialize services
(async () => {
services = await initializeDragonFireServices();
console.log('DragonFire services initialized');
})();
// API endpoint for wallet creation
app.post('/api/wallets', async (req, res) => {
try {
const walletInfo = await services.wallet.createWallet({
name: req.body.name,
attributes: req.body.attributes
});
res.json({ success: true, wallet: walletInfo });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
// Browser implementation
// IMPORTANT: Never expose API keys in browser code
// Use a server-side token generation mechanism
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dragon Wallets Demo</title>
<script src="https://cdn.dragonfire.ai/sdk/dragonfire-client.min.js"></script>
<script src="https://cdn.dragonfire.ai/sdk/wallet-client.min.js"></script>
</head>
<body>
<h1>Dragon Wallets Demo</h1>
<div id="wallet-status">Loading...</div>
<script>
// First, get a secured client token from your server
async function getClientToken() {
const response = await fetch('/api/auth/token');
const data = await response.json();
return data.token;
}
// Initialize using the server-provided token
async function initializeWallet() {
try {
const token = await getClientToken();
// Initialize with client token (not API key)
const dragonfire = new DragonFire.Client({
clientToken: token,
region: 'us-west'
});
await dragonfire.connect();
const wallet = new DragonFire.WalletClient(dragonfire);
// Load user wallet
const userWallet = await wallet.loadUserWallet();
// Update UI
document.getElementById('wallet-status').textContent =
`Wallet loaded: ${userWallet.name} (${userWallet.id})`;
return wallet;
} catch (error) {
document.getElementById('wallet-status').textContent =
`Error: ${error.message}`;
console.error(error);
}
}
// Initialize when page loads
window.addEventListener('DOMContentLoaded', initializeWallet);
</script>
</body>
</html>
// React implementation
import React, { useEffect, useState } from 'react';
import { DragonFireClient } from '@dragonfire/client';
import { WalletClient } from '@dragonfire/wallet-client';
// Create a context for wallet services
const WalletContext = React.createContext(null);
// Provider component
function WalletProvider({ children }) {
const [wallet, setWallet] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function initializeWallet() {
try {
// Get token from your secure backend
const response = await fetch('/api/auth/token');
const data = await response.json();
if (!data.token) {
throw new Error('Failed to get authentication token');
}
// Initialize with client token
const dragonfire = new DragonFireClient({
clientToken: data.token,
region: 'us-west'
});
await dragonfire.connect();
const walletClient = new WalletClient(dragonfire, {
securityLevel: 'high',
vectorDimension: 7
});
setWallet(walletClient);
} catch (err) {
setError(err.message);
console.error('Wallet initialization error:', err);
} finally {
setLoading(false);
}
}
initializeWallet();
}, []);
return (
<WalletContext.Provider value={{ wallet, loading, error }}>
{children}
</WalletContext.Provider>
);
}
// Hook for using the wallet context
function useWallet() {
const context = React.useContext(WalletContext);
if (!context) {
throw new Error('useWallet must be used within a WalletProvider');
}
return context;
}
// Example component using the wallet
function WalletBalance() {
const { wallet, loading, error } = useWallet();
const [balance, setBalance] = useState(null);
useEffect(() => {
async function fetchBalance() {
if (wallet) {
try {
const userWallet = await wallet.loadUserWallet();
setBalance(userWallet.balance);
} catch (err) {
console.error('Failed to fetch balance:', err);
}
}
}
fetchBalance();
}, [wallet]);
if (loading) return <div>Loading wallet...</div>;
if (error) return <div>Error: {error}</div>;
if (!balance) return <div>Loading balance...</div>;
return (
<div>
<h2>Wallet Balance</h2>
<p>{balance.amount} {balance.currency}</p>
</div>
);
}
// App component
function App() {
return (
<WalletProvider>
<div className="app">
<h1>Dragon Wallets Demo</h1>
<WalletBalance />
</div>
</WalletProvider>
);
}
export default App;
// React Native implementation
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DragonFireClient } from '@dragonfire/client/mobile';
import { WalletClient } from '@dragonfire/wallet-client/mobile';
// Secure token storage key
const TOKEN_STORAGE_KEY = 'dragonfire_auth_token';
function WalletScreen() {
const [wallet, setWallet] = useState(null);
const [walletInfo, setWalletInfo] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
initializeWallet();
}, []);
async function initializeWallet() {
try {
setLoading(true);
// First check if we have a stored token
let token = await AsyncStorage.getItem(TOKEN_STORAGE_KEY);
// If no token, fetch from server
if (!token) {
const response = await fetch('https://your-api.com/api/auth/token');
const data = await response.json();
token = data.token;
// Store token securely
await AsyncStorage.setItem(TOKEN_STORAGE_KEY, token);
}
// Initialize client with token
const dragonfire = new DragonFireClient({
clientToken: token,
region: 'us-west',
mobileConfig: {
offlineMode: true,
backgroundSync: true,
biometricAuth: true
}
});
await dragonfire.connect();
// Initialize wallet client
const walletClient = new WalletClient(dragonfire, {
securityLevel: 'high',
vectorDimension: 7,
mobileOptimized: true
});
// Load user wallet
const userWallet = await walletClient.loadUserWallet();
setWallet(walletClient);
setWalletInfo(userWallet);
setError(null);
} catch (err) {
console.error('Wallet initialization error:', err);
setError(err.message);
// If token expired, clear it and retry
if (err.code === 'TOKEN_EXPIRED') {
await AsyncStorage.removeItem(TOKEN_STORAGE_KEY);
initializeWallet();
}
} finally {
setLoading(false);
}
}
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#7f5af0" />
<Text style={styles.loadingText}>Loading wallet...</Text>
</View>
);
}
if (error) {
return (
<View style={styles.container}>
<Text style={styles.errorText}>Error: {error}</Text>
<Text style={styles.linkText} onPress={initializeWallet}>
Try Again
</Text>
</View>
);
}
return (
<View style={styles.container}>
<Text style={styles.title}>Dragon Wallet</Text>
{walletInfo && (
<View style={styles.walletCard}>
<Text style={styles.walletName}>{walletInfo.name}</Text>
<Text style={styles.walletId}>ID: {walletInfo.id}</Text>
<View style={styles.balanceContainer}>
<Text style={styles.balanceLabel}>Balance:</Text>
<Text style={styles.balanceAmount}>
{walletInfo.balance.amount} {walletInfo.balance.currency}
</Text>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
backgroundColor: '#10101a'
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#f0f0f0',
marginBottom: 24
},
loadingText: {
marginTop: 12,
color: '#f0f0f0',
fontSize: 16
},
errorText: {
color: '#e45a2d',
fontSize: 16,
marginBottom: 16
},
linkText: {
color: '#7f5af0',
fontSize: 16
},
walletCard: {
backgroundColor: '#1e1e2c',
borderRadius: 12,
padding: 20,
width: '100%',
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 5
},
walletName: {
fontSize: 20,
fontWeight: 'bold',
color: '#f0f0f0',
marginBottom: 8
},
walletId: {
fontSize: 14,
color: '#a0a0a0',
marginBottom: 16
},
balanceContainer: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 12
},
balanceLabel: {
fontSize: 16,
color: '#a0a0a0',
marginRight: 8
},
balanceAmount: {
fontSize: 22,
fontWeight: 'bold',
color: '#7f5af0'
}
});
export default WalletScreen;
Troubleshooting
Common issues and their solutions:
Connection Issues
Symptoms: Unable to connect to DragonFire services, timeout errors
Possible Causes:
- Invalid API key or token
- Network connectivity issues
- Region availability problems
Solutions:
- Verify your API key in the Developer Portal
- Check your network connection
- Try a different region
- Increase connection timeout
// Connection troubleshooting
const dragonfire = new DragonFireClient({
apiKey: 'YOUR_API_KEY',
region: 'us-west',
timeout: 60000, // Increase timeout to 60 seconds
debug: true // Enable debug mode
});
Authentication Errors
Symptoms: "Authentication failed" errors, "Invalid token" messages
Possible Causes:
- Expired API key or token
- Insufficient permissions
- Token rotation failures
Solutions:
- Generate a new API key with proper permissions
- Check token expiration and refresh if needed
- Verify wallet permissions in the Developer Portal
// Token refresh example
try {
await dragonfire.connect();
} catch (error) {
if (error.code === 'AUTH_FAILED' || error.code === 'TOKEN_EXPIRED') {
// Get a fresh token from your server
const newToken = await refreshToken();
// Reconnect with new token
dragonfire.updateClientToken(newToken);
await dragonfire.connect();
} else {
throw error;
}
}
Performance Issues
Symptoms: Slow transaction processing, high latency
Possible Causes:
- Inefficient configuration
- High network latency
- Resource constraints
Solutions:
- Optimize performance configuration
- Enable caching
- Use vector routing optimization
- Choose a closer region
// Performance optimization
await wallet.configurePerformance({
concurrencyLevel: 'maximum', // Maximum concurrency
vectorOptimization: true, // Enable vector optimization
cacheIntegration: true, // Integrate with cache
precomputeRoutes: true, // Precompute routes
requestBatching: true, // Enable batch processing
batchSize: 100 // Process in batches of 100
});
Transaction Failures
Symptoms: Failed transactions, timeout errors during transactions
Possible Causes:
- Insufficient balance
- Security restrictions
- Network issues during transaction
- Invalid transaction parameters
Solutions:
- Verify wallet balance before transaction
- Check transaction parameters
- Implement retry logic with exponential backoff
- Enable transaction logging for debugging
// Transaction with retry logic
async function executeTransaction(transactionDetails, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
// Check balance first
const walletInfo = await wallet.getWalletInfo();
if (walletInfo.balance < transactionDetails.amount) {
throw new Error('Insufficient balance');
}
// Execute transaction
const result = await wallet.createTransaction(transactionDetails);
return result;
} catch (error) {
attempt++;
// If last attempt, throw the error
if (attempt >= maxRetries) {
throw error;
}
// Log the error
console.warn(`Transaction attempt ${attempt} failed: ${error.message}`);
// Wait with exponential backoff before retry
const backoffMs = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, backoffMs));
}
}
}
Support Resources
If you encounter issues not covered in this guide, use these support resources: