installation - saltict/Demo-Docs GitHub Wiki

Installation Guide

Complete guide for installing and setting up the SubWallet Services SDK in your project.

📖 Navigation


Table of Contents

Package Installation

Using npm

npm install @subwallet-monorepos/subwallet-services-sdk

Using yarn

yarn add @subwallet-monorepos/subwallet-services-sdk

Using pnpm

pnpm add @subwallet-monorepos/subwallet-services-sdk

Package Information

  • Package Name: @subwallet-monorepos/subwallet-services-sdk
  • Current Version: 0.1.3-beta.5
  • License: MIT
  • Module System: ES Modules with CommonJS compatibility

Platform-Specific Setup

Browser Extensions (Manifest V3)

manifest.json Configuration

{
  "manifest_version": 3,
  "name": "Your Extension",
  "version": "1.0.0",
  "permissions": [
    "activeTab",
    "storage"
  ],
  "host_permissions": [
    "https://sw-services.subwallet.app/*"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'"
  }
}

Background Script (background.js)

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

// Configure for extension environment
subwalletApiSdk.updateConfig({
  platform: 'extension'
});

// Use in background script
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.action === 'getPriceHistory') {
    try {
      const prices = await subwalletApiSdk.priceHistoryApi.getPriceHistory(
        request.token, 
        request.timeframe
      );
      sendResponse({ success: true, data: prices });
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }
});

Mobile Applications (React Native)

Installation with React Native

# Install the SDK
npm install @subwallet-monorepos/subwallet-services-sdk

# Install required polyfills for React Native
npm install react-native-polyfill-globals

# For iOS (if using CocoaPods)
cd ios && pod install

React Native Setup

// index.js or App.tsx
import 'react-native-polyfill-globals/auto';
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

// Configure for mobile environment
subwalletApiSdk.updateConfig({
  platform: 'mobile'
});

// Usage in React Native component
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';

const PriceDisplay = ({ token }) => {
  const [price, setPrice] = useState(null);
  
  useEffect(() => {
    const fetchPrice = async () => {
      try {
        const priceData = await subwalletApiSdk.priceHistoryApi.getPriceHistory(token, '1D');
        setPrice(priceData.history[priceData.history.length - 1]?.value);
      } catch (error) {
        console.error('Failed to fetch price:', error);
      }
    };
    
    fetchPrice();
  }, [token]);
  
  return (
    <View>
      <Text>Current Price: ${price}</Text>
    </View>
  );
};

Web Applications

Standard Web Application

// main.ts or index.ts
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

// Configure for web application
subwalletApiSdk.updateConfig({
  platform: 'webapp'
});

// Usage in web application
async function displayTokenBalance() {
  try {
    const balances = await subwalletApiSdk.balanceDetectionApi.getBalances({
      addresses: ['your-wallet-address'],
      chains: ['polkadot']
    });
    
    console.log('Token balances:', balances);
  } catch (error) {
    console.error('Failed to fetch balances:', error);
  }
}

Next.js Application

// pages/_app.tsx or app/layout.tsx
import { useEffect } from 'react';
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

export default function App({ Component, pageProps }) {
  useEffect(() => {
    // Configure SDK on client side only
    if (typeof window !== 'undefined') {
      subwalletApiSdk.updateConfig({
        platform: 'webapp'
      });
    }
  }, []);

  return <Component {...pageProps} />;
}

// pages/api/prices.ts (API route)
import { NextApiRequest, NextApiResponse } from 'next';
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    const { token, timeframe } = req.query;
    
    const priceHistory = await subwalletApiSdk.priceHistoryApi.getPriceHistory(
      token as string, 
      timeframe as string
    );
    
    res.status(200).json(priceHistory);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch price history' });
  }
}

Node.js Backend Applications

Express.js Integration

// server.ts
import express from 'express';
import subwalletApiSdk from '@subwallet-monorepos/subwallet-services-sdk';

const app = express();

// Configure SDK for server environment
subwalletApiSdk.updateConfig({
  platform: 'webapp', // or create a 'server' platform
  baseUrl: process.env.SUBWALLET_API_URL || 'https://sw-services.subwallet.app'
});

app.get('/api/balance/:address', async (req, res) => {
  try {
    const { address } = req.params;
    const { chains } = req.query;
    
    const balances = await subwalletApiSdk.balanceDetectionApi.getBalances({
      addresses: [address],
      chains: chains ? (chains as string).split(',') : ['polkadot']
    });
    
    res.json(balances);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Build Tools Configuration

Webpack Configuration

// webpack.config.js
const path = require('path');

module.exports = {
  // ... other configuration
  resolve: {
    fallback: {
      "crypto": require.resolve("crypto-browserify"),
      "stream": require.resolve("stream-browserify"),
      "buffer": require.resolve("buffer")
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
      process: 'process/browser',
    }),
  ]
};

Vite Configuration

// vite.config.ts
import { defineConfig } from 'vite';

export default defineConfig({
  define: {
    global: 'globalThis',
  },
  resolve: {
    alias: {
      buffer: 'buffer',
    },
  },
  optimizeDeps: {
    include: ['buffer'],
  },
});

Rollup Configuration

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/index.ts',
  output: {
    dir: 'dist',
    format: 'es'
  },
  plugins: [
    resolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    typescript()
  ],
  external: ['@subwallet-monorepos/subwallet-services-sdk']
};

TypeScript Configuration

Basic TypeScript Setup

{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["ES2020", "DOM"],
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Type Declarations

// types/subwallet-sdk.d.ts
declare module '@subwallet-monorepos/subwallet-services-sdk' {
  export interface SDKOption {
    baseUrl?: string;
    platform: 'extension' | 'mobile' | 'webapp';
    chainListVersion?: string;
  }

  export class SubWalletServiceSDK {
    static getInstance(): SubWalletServiceSDK;
    updateConfig(config: Partial<SDKOption>): void;
    
    balanceDetectionApi: BalanceDetectionApi;
    priceHistoryApi: PriceHistoryApi;
    swapApi: SwapApi;
    xcmApi: XcmApi;
    cardanoApi: CardanoApi;
  }

  const sdk: SubWalletServiceSDK;
  export default sdk;
}

Environment Variables

Environment Configuration

# .env file
SUBWALLET_API_URL=https://sw-services.subwallet.app
SUBWALLET_API_KEY=your-api-key-if-required
SUBWALLET_PLATFORM=webapp
SUBWALLET_CHAIN_LIST_VERSION=0.2.108

Environment-based Configuration

// config.ts
const config = {
  apiUrl: process.env.SUBWALLET_API_URL || 'https://sw-services.subwallet.app',
  platform: (process.env.SUBWALLET_PLATFORM as 'extension' | 'mobile' | 'webapp') || 'webapp',
  chainListVersion: process.env.SUBWALLET_CHAIN_LIST_VERSION || '0.2.108'
};

// Apply configuration
subwalletApiSdk.updateConfig({
  baseUrl: config.apiUrl,
  platform: config.platform,
  chainListVersion: config.chainListVersion
});

Verification

Basic SDK Test

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

async function testSDK() {
  try {
    console.log('SDK Version:', subwalletApiSdk.version);
    
    // Test price history API
    const priceHistory = await subwalletApiSdk.priceHistoryApi.getPriceHistory('DOT', '1D');
    console.log('Price history retrieved:', priceHistory.history.length, 'data points');
    
    console.log('✅ SDK installation verified successfully');
  } catch (error) {
    console.error('❌ SDK installation verification failed:', error);
  }
}

testSDK();

Health Check Endpoint

// health-check.ts
export async function healthCheck() {
  const checks = {
    sdkLoaded: false,
    apiConnectivity: false,
    servicesAvailable: false
  };

  try {
    // Check if SDK is loaded
    checks.sdkLoaded = !!subwalletApiSdk.version;
    
    // Check API connectivity
    const testResponse = await subwalletApiSdk.priceHistoryApi.getPriceHistory('DOT', '1D');
    checks.apiConnectivity = !!testResponse;
    
    // Check if all services are available
    checks.servicesAvailable = !!(
      subwalletApiSdk.balanceDetectionApi &&
      subwalletApiSdk.priceHistoryApi &&
      subwalletApiSdk.swapApi &&
      subwalletApiSdk.xcmApi &&
      subwalletApiSdk.cardanoApi
    );
    
    return {
      status: 'healthy',
      checks,
      version: subwalletApiSdk.version
    };
  } catch (error) {
    return {
      status: 'unhealthy',
      checks,
      error: error.message
    };
  }
}

Installation Troubleshooting

Common Issues and Solutions

  1. Module Resolution Error:

    # Install missing peer dependencies
    npm install --save-dev @types/node
  2. Build Tool Compatibility:

    # For older webpack versions
    npm install --save-dev crypto-browserify stream-browserify buffer
  3. TypeScript Errors:

    # Update TypeScript and types
    npm update typescript @types/node
  4. Network Configuration:

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

🔗 Related Documentation

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