configuration - saltict/Demo-Docs GitHub Wiki

Configuration Guide

Comprehensive guide for configuring the SubWallet Services SDK for different environments and use cases.

📖 Navigation


Table of Contents

Basic Configuration

Default Configuration

The SDK comes with sensible defaults that work out of the box:

import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

// Default configuration values
console.log('Default settings:', {
  version: subwalletApiSdk.version,        // "0.1.3-beta.5"
  headers: subwalletApiSdk.headers         // Platform and version headers
});

SDK Configuration Interface

interface SDKOption {
  baseUrl?: string;                        // API endpoint URL
  platform: 'extension' | 'mobile' | 'webapp';  // Platform type
  chainListVersion?: string;               // Chain list version
}

interface SDKConfig extends SDKOption {
  sdkVersion: string;                      // SDK version (read-only)
}

Basic Configuration Update

// Update SDK configuration
subwalletApiSdk.updateConfig({
  platform: 'webapp',
  baseUrl: 'https://sw-services.subwallet.app',
  chainListVersion: '0.2.108'
});

// Verify configuration is applied
console.log('Updated headers:', subwalletApiSdk.headers);

Platform-Specific Configuration

Browser Extension Configuration

Optimized for browser extension environments with appropriate headers and security settings.

// Extension-specific configuration
subwalletApiSdk.updateConfig({
  platform: 'extension'
});

// Headers generated for extension platform:
// {
//   'SW-SDK-ChainList-Version': '0.2.108',
//   'SW-SDK-Platform': 'extension',
//   'SW-SDK-Version': '0.1.3-beta.5'
// }

Extension Manifest Configuration:

{
  "manifest_version": 3,
  "host_permissions": [
    "https://sw-services.subwallet.app/*"
  ],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; connect-src https://sw-services.subwallet.app"
  }
}

Mobile Application Configuration

Optimized for mobile environments with appropriate timeouts and retry logic.

// Mobile-specific configuration
subwalletApiSdk.updateConfig({
  platform: 'mobile'
});

// Additional mobile-specific settings
const mobileConfig = {
  timeout: 30000,        // Longer timeout for mobile networks
  retryAttempts: 3,      // Retry failed requests
  cacheEnabled: true     // Enable response caching
};

React Native Setup:

// App.tsx
import { useEffect } from 'react';
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

export default function App() {
  useEffect(() => {
    // Configure for mobile on app start
    subwalletApiSdk.updateConfig({
      platform: 'mobile'
    });
  }, []);

  return (
    // Your app components
  );
}

Web Application Configuration

Standard configuration for web applications with CORS and performance optimizations.

// Web application configuration
subwalletApiSdk.updateConfig({
  platform: 'webapp'
});

// Development vs Production configuration
const isDevelopment = process.env.NODE_ENV === 'development';

subwalletApiSdk.updateConfig({
  platform: 'webapp',
  baseUrl: isDevelopment 
    ? 'http://localhost:3001/api'  // Local proxy
    : 'https://sw-services.subwallet.app'
});

Environment Configuration

Development Environment

// Development configuration
if (process.env.NODE_ENV === 'development') {
  subwalletApiSdk.updateConfig({
    platform: 'webapp',
    baseUrl: 'https://dev-api.subwallet.app',
    chainListVersion: '0.2.108-dev'
  });
  
  // Enable debug logging in development
  console.log('Development mode - SDK configured for dev environment');
}

Staging Environment

// Staging configuration
if (process.env.NODE_ENV === 'staging') {
  subwalletApiSdk.updateConfig({
    platform: 'webapp',
    baseUrl: 'https://staging-api.subwallet.app',
    chainListVersion: '0.2.108-staging'
  });
}

Production Environment

// Production configuration
if (process.env.NODE_ENV === 'production') {
  subwalletApiSdk.updateConfig({
    platform: 'webapp',
    baseUrl: 'https://sw-services.subwallet.app',
    chainListVersion: '0.2.108'
  });
}

Environment Variables

# .env file
REACT_APP_SUBWALLET_API_URL=https://sw-services.subwallet.app
REACT_APP_SUBWALLET_PLATFORM=webapp
REACT_APP_SUBWALLET_CHAIN_LIST_VERSION=0.2.108
REACT_APP_SUBWALLET_DEBUG=false
// Environment-based configuration
const config = {
  baseUrl: process.env.REACT_APP_SUBWALLET_API_URL || 'https://sw-services.subwallet.app',
  platform: (process.env.REACT_APP_SUBWALLET_PLATFORM || 'webapp') as 'extension' | 'mobile' | 'webapp',
  chainListVersion: process.env.REACT_APP_SUBWALLET_CHAIN_LIST_VERSION || '0.2.108'
};

subwalletApiSdk.updateConfig(config);

Advanced Configuration

Custom Headers Configuration

// The SDK automatically generates headers based on configuration
// You cannot directly set custom headers, but you can influence them through config

subwalletApiSdk.updateConfig({
  platform: 'webapp',
  chainListVersion: '0.2.109'  // This will update the chain list version header
});

// Generated headers will include:
// {
//   'SW-SDK-ChainList-Version': '0.2.109',
//   'SW-SDK-Platform': 'webapp',
//   'SW-SDK-Version': '0.1.3-beta.5'
// }

Custom API Endpoint Configuration

// Configure custom API endpoint
subwalletApiSdk.updateConfig({
  baseUrl: 'https://your-custom-api.example.com'
});

// For proxy setup
subwalletApiSdk.updateConfig({
  baseUrl: '/api/proxy'  // Will be resolved relative to current origin
});

// For local development with proxy
subwalletApiSdk.updateConfig({
  baseUrl: 'http://localhost:3001/subwallet-api'
});

Service-Specific Configuration

While the SDK doesn't expose per-service configuration, you can create wrapper functions for service-specific behavior:

// Create service wrapper with custom behavior
class CustomPriceHistoryService {
  constructor(private sdk: typeof subwalletApiSdk) {}

  async getPriceHistoryWithCache(token: string, timeframe: string) {
    const cacheKey = `price-${token}-${timeframe}`;
    
    // Check cache first
    const cached = localStorage.getItem(cacheKey);
    if (cached) {
      const { data, timestamp } = JSON.parse(cached);
      if (Date.now() - timestamp < 60000) { // 1 minute cache
        return data;
      }
    }

    // Fetch fresh data
    const data = await this.sdk.priceHistoryApi.getPriceHistory(token, timeframe);
    
    // Cache the result
    localStorage.setItem(cacheKey, JSON.stringify({
      data,
      timestamp: Date.now()
    }));

    return data;
  }
}

const customPriceService = new CustomPriceHistoryService(subwalletApiSdk);

Configuration Validation

Configuration Validator

interface ConfigValidationResult {
  isValid: boolean;
  errors: string[];
}

function validateConfig(config: Partial<SDKOption>): ConfigValidationResult {
  const errors: string[] = [];

  // Validate platform
  if (config.platform && !['extension', 'mobile', 'webapp'].includes(config.platform)) {
    errors.push(`Invalid platform: ${config.platform}. Must be 'extension', 'mobile', or 'webapp'`);
  }

  // Validate baseUrl
  if (config.baseUrl) {
    try {
      new URL(config.baseUrl);
    } catch {
      errors.push(`Invalid baseUrl: ${config.baseUrl}. Must be a valid URL`);
    }
  }

  // Validate chainListVersion
  if (config.chainListVersion && !/^\d+\.\d+\.\d+/.test(config.chainListVersion)) {
    errors.push(`Invalid chainListVersion: ${config.chainListVersion}. Must follow semantic versioning`);
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

// Usage
const newConfig = {
  platform: 'webapp' as const,
  baseUrl: 'https://sw-services.subwallet.app'
};

const validation = validateConfig(newConfig);
if (validation.isValid) {
  subwalletApiSdk.updateConfig(newConfig);
} else {
  console.error('Configuration validation failed:', validation.errors);
}

Runtime Configuration Check

function checkConfiguration() {
  const diagnostics = {
    version: subwalletApiSdk.version,
    headers: subwalletApiSdk.headers,
    servicesAvailable: {
      balanceDetection: !!subwalletApiSdk.balanceDetectionApi,
      priceHistory: !!subwalletApiSdk.priceHistoryApi,
      swap: !!subwalletApiSdk.swapApi,
      xcm: !!subwalletApiSdk.xcmApi,
      cardano: !!subwalletApiSdk.cardanoApi
    },
    timestamp: new Date().toISOString()
  };

  console.log('SDK Configuration Diagnostics:', diagnostics);
  return diagnostics;
}

// Run configuration check
checkConfiguration();

Dynamic Configuration Updates

Runtime Configuration Updates

The SDK supports dynamic configuration updates that will affect all subsequent API calls:

// Initial configuration
subwalletApiSdk.updateConfig({
  platform: 'webapp',
  baseUrl: 'https://sw-services.subwallet.app'
});

// Later, update to use staging environment
subwalletApiSdk.updateConfig({
  baseUrl: 'https://staging-api.subwallet.app'
});

// Platform change (e.g., when detecting mobile environment)
if (window.innerWidth < 768) {
  subwalletApiSdk.updateConfig({
    platform: 'mobile'
  });
}

Configuration Update Listeners

While the SDK doesn't expose configuration change events, you can create a wrapper to track changes:

class ConfigurationManager {
  private listeners: ((config: SDKOption) => void)[] = [];
  private currentConfig: SDKOption;

  updateConfig(newConfig: Partial<SDKOption>) {
    const updatedConfig = { ...this.currentConfig, ...newConfig };
    
    // Update SDK
    subwalletApiSdk.updateConfig(newConfig);
    
    // Notify listeners
    this.listeners.forEach(listener => listener(updatedConfig));
    
    this.currentConfig = updatedConfig;
  }

  onConfigChange(listener: (config: SDKOption) => void) {
    this.listeners.push(listener);
    
    // Return unsubscribe function
    return () => {
      const index = this.listeners.indexOf(listener);
      if (index > -1) {
        this.listeners.splice(index, 1);
      }
    };
  }
}

const configManager = new ConfigurationManager();

// Listen for config changes
const unsubscribe = configManager.onConfigChange((config) => {
  console.log('Configuration updated:', config);
});

// Update configuration
configManager.updateConfig({ platform: 'mobile' });

// Later, unsubscribe
unsubscribe();

Conditional Configuration

// Configure based on environment detection
function configureBasedOnEnvironment() {
  // Detect environment
  const isExtension = typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.id;
  const isMobile = /Mobi|Android/i.test(navigator.userAgent);
  const isNode = typeof window === 'undefined';

  let platform: 'extension' | 'mobile' | 'webapp';
  
  if (isExtension) {
    platform = 'extension';
  } else if (isMobile) {
    platform = 'mobile';
  } else {
    platform = 'webapp';
  }

  // Configure accordingly
  subwalletApiSdk.updateConfig({
    platform,
    baseUrl: process.env.NODE_ENV === 'development' 
      ? 'https://dev-api.subwallet.app'
      : 'https://sw-services.subwallet.app'
  });

  console.log(`Configured for ${platform} platform`);
}

// Auto-configure on initialization
configureBasedOnEnvironment();

Configuration Persistence

// Save configuration to localStorage
function saveConfiguration(config: SDKOption) {
  localStorage.setItem('subwallet-sdk-config', JSON.stringify(config));
}

// Load configuration from localStorage
function loadConfiguration(): SDKOption | null {
  const saved = localStorage.getItem('subwallet-sdk-config');
  return saved ? JSON.parse(saved) : null;
}

// Initialize with saved configuration
const savedConfig = loadConfiguration();
if (savedConfig) {
  subwalletApiSdk.updateConfig(savedConfig);
}

// Save configuration on updates
function updateAndSaveConfig(config: Partial<SDKOption>) {
  subwalletApiSdk.updateConfig(config);
  
  // Get current headers to determine current config
  const currentConfig = {
    platform: subwalletApiSdk.headers['SW-SDK-Platform'] as 'extension' | 'mobile' | 'webapp',
    chainListVersion: subwalletApiSdk.headers['SW-SDK-ChainList-Version'],
    ...config
  };
  
  saveConfiguration(currentConfig);
}

🔗 Related Documentation

⚠️ **GitHub.com Fallback** ⚠️