api reference - saltict/Demo-Docs GitHub Wiki

API Reference

Complete API reference for the SubWallet Services SDK with detailed method signatures, parameters, and response types.

📖 Navigation


Table of Contents

SDK Core API

SubWalletServiceSDK

The main SDK class implementing the singleton pattern for centralized service management.

getInstance()

Gets the singleton instance of the SDK.

static getInstance(): SubWalletServiceSDK

Returns: SubWalletServiceSDK - The singleton SDK instance

Example:

import { SubWalletServiceSDK } from '@subwallet-monorepos/subwallet-services-sdk';

const sdk = SubWalletServiceSDK.getInstance();
console.log('SDK Version:', sdk.version);

updateConfig()

Updates the SDK configuration dynamically.

updateConfig(newConfig: Partial<SDKOption>): void

Parameters:

  • newConfig - Partial configuration object containing settings to update

Example:

sdk.updateConfig({
  platform: 'mobile',
  baseUrl: 'https://staging-api.subwallet.app'
});

Properties

version
readonly version: string

Returns the current SDK version.

headers
readonly headers: Record<string, string>

Returns the current HTTP headers used for API requests.

Generated Headers:

{
  'SW-SDK-ChainList-Version': string;  // Chain list version
  'SW-SDK-Platform': string;           // Platform type
  'SW-SDK-Version': string;            // SDK version
}
Service API Instances
readonly balanceDetectionApi: BalanceDetectionApi;
readonly priceHistoryApi: PriceHistoryApi;
readonly swapApi: SwapApi;
readonly xcmApi: XcmApi;
readonly cardanoApi: CardanoApi;

Price History API

PriceHistoryApi

Provides historical and real-time price data for various timeframes.

getPriceHistory()

Retrieves historical price data for a specified token and timeframe.

async getPriceHistory(token: string, type: Timeframe): Promise<HistoryTokenPriceJSON>

Parameters:

  • token (string) - Token symbol (e.g., 'DOT', 'KSM', 'ACA')
  • type (Timeframe) - Time period for price data

Timeframe Options:

  • '1D' - 1 Day
  • '1W' - 1 Week
  • '1M' - 1 Month
  • '3M' - 3 Months
  • 'YTD' - Year to Date
  • '1Y' - 1 Year
  • 'ALL' - All available data

Returns: Promise<HistoryTokenPriceJSON>

Response Structure:

interface HistoryTokenPriceJSON {
  history: PriceChartPoint[];
}

interface PriceChartPoint {
  time: number;    // Unix timestamp
  value: number;   // Price value in USD
}

Example:

// Get weekly price history for DOT
const priceData = await sdk.priceHistoryApi.getPriceHistory('DOT', '1W');

console.log('Data points:', priceData.history.length);
console.log('Latest price:', priceData.history[priceData.history.length - 1]);

// Calculate price change
const latest = priceData.history[priceData.history.length - 1].value;
const earliest = priceData.history[0].value;
const change = ((latest - earliest) / earliest) * 100;
console.log('Price change:', change.toFixed(2) + '%');

Error Cases:

  • Invalid token symbol
  • Network connectivity issues
  • API rate limiting
  • Unsupported timeframe

Balance Detection API

BalanceDetectionApi

Detects token balances and provides token discovery for wallet addresses.

getEvmTokenBalanceSlug()

Retrieves token slugs for detected tokens in an EVM address.

async getEvmTokenBalanceSlug(address: string): Promise<string[]>

Parameters:

  • address (string) - EVM wallet address (0x prefixed hex string)

Returns: Promise<string[]> - Array of token slug identifiers

Example:

const address = '0x742d35Cc6565C0532F3E4db7c5F804E5D5eDeF94';
const tokenSlugs = await sdk.balanceDetectionApi.getEvmTokenBalanceSlug(address);

console.log('Detected tokens:', tokenSlugs);
console.log('Token count:', tokenSlugs.length);

// Process each token slug
tokenSlugs.forEach((slug, index) => {
  console.log(`Token ${index + 1}: ${slug}`);
});

Address Requirements:

  • Must be a valid EVM address (42 characters, 0x prefixed)
  • Supports Ethereum, BSC, Polygon, and other EVM-compatible networks
  • Address must have transaction history for accurate detection

Error Cases:

  • Invalid address format
  • Network not supported
  • Address with no transaction history
  • API service unavailable

XCM API

XcmApi

Handles Cross-Consensus Message Passing for parachain interoperability within the Polkadot ecosystem.

fetchXcmData()

Builds XCM transfer data for cross-chain asset transfers.

async fetchXcmData(XcmRequest: XcmRequest): Promise<XcmApiResponse>

Parameters:

  • XcmRequest (XcmRequest) - XCM transfer request configuration

XcmRequest Interface:

interface XcmRequest {
  address: string;    // Sender address (SS58 format)
  from: string;       // Source chain identifier
  to: string;         // Destination chain identifier  
  recipient: string;  // Recipient address (SS58 format)
  value: string;      // Amount in smallest unit (string to handle large numbers)
}

Returns: Promise<XcmApiResponse>

XcmApiResponse Interface:

interface XcmApiResponse {
  sender: string;              // Confirmed sender address
  to: string;                  // Destination chain
  transferEncodedCall: string; // Encoded extrinsic call data
  value: string;               // Transfer amount
  metadata?: any;              // Additional transfer metadata (fees, etc.)
}

Example:

const xcmRequest = {
  address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
  from: 'polkadot',
  to: 'acala', 
  recipient: '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty',
  value: '10000000000000' // 10 DOT (10^13 smallest units)
};

const xcmData = await sdk.xcmApi.fetchXcmData(xcmRequest);

console.log('XCM Transfer Built:', {
  from: xcmData.sender,
  to: xcmData.to,
  amount: xcmData.value,
  callData: xcmData.transferEncodedCall
});

// Use the encoded call in a transaction
const extrinsic = api.tx(xcmData.transferEncodedCall);

Supported Chains:

  • Polkadot ecosystem parachains
  • Kusama ecosystem parachains
  • Relay chains (Polkadot, Kusama)

Common Chain Identifiers:

  • 'polkadot' - Polkadot relay chain
  • 'kusama' - Kusama relay chain
  • 'acala' - Acala parachain
  • 'moonbeam' - Moonbeam parachain
  • 'astar' - Astar parachain
  • 'parallel' - Parallel parachain

Error Cases:

  • Unsupported chain pairing
  • Invalid address format (must be SS58)
  • Insufficient balance for transfer + fees
  • Chain connectivity issues

Cardano API

CardanoApi

Handles Cardano-specific operations including transaction building and native token transfers.

fetchUnsignedPayload()

Builds unsigned transaction payload for Cardano transfers.

async fetchUnsignedPayload(buildCardanoTxRequest: BuildCardanoTxRequest): Promise<string>

Parameters:

  • buildCardanoTxRequest (BuildCardanoTxRequest) - Transaction build configuration

BuildCardanoTxRequest Interface:

interface BuildCardanoTxRequest {
  sender: string;    // Sender Cardano address (Bech32 format)
  receiver: string;  // Receiver Cardano address (Bech32 format)
  unit: string;      // Asset unit ('lovelace' for ADA, or native token identifier)
  quantity: string;  // Amount in smallest unit
}

Returns: Promise<string> - Unsigned transaction payload (CBOR hex string)

Example - ADA Transfer:

const adaTransfer = {
  sender: 'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj0vs2qd4a6gtmydwfqq5e8a0m',
  receiver: 'addr1qy93ktfeuwxm4k7k9u8xy6qxh0vlalq8a5q2kxj4rtj3v2ycu5d8ps7zex2k2xt3uqxgjqnnj0vs2qd4a6gtmydwfqq5dcd7',
  unit: 'lovelace',
  quantity: '2000000' // 2 ADA (1 ADA = 1,000,000 lovelace)
};

const unsignedTx = await sdk.cardanoApi.fetchUnsignedPayload(adaTransfer);

console.log('Unsigned transaction built');
console.log('Payload length:', unsignedTx.length);

// Sign with wallet and submit to blockchain
// const signedTx = await wallet.signTx(unsignedTx);

Example - Native Token Transfer:

const nativeTokenTransfer = {
  sender: 'addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj4rtj3v2ycu5d8ps7zex2k2xt3uqxgjqnnj0vs2qd4a6gtmydwfqq5e8a0m',
  receiver: 'addr1qy93ktfeuwxm4k7k9u8xy6qxh0vlalq8a5q2kxj4rtj3v2ycu5d8ps7zex2k2xt3uqxgjqnnj0vs2qd4a6gtmydwfqq5dcd7',
  unit: 'a0028f350aaabe0545fdcb56b039bfb08e4bb4d8c4d7c3c7d481c235.484f534b59', // Policy ID + Asset Name
  quantity: '1000'
};

const nativeTokenTx = await sdk.cardanoApi.fetchUnsignedPayload(nativeTokenTransfer);

Unit Formats:

  • ADA: 'lovelace' (1 ADA = 1,000,000 lovelace)
  • Native Tokens: '<policy_id>.<asset_name>' (hex encoded)

Address Requirements:

  • Must be valid Bech32 Cardano addresses
  • Supports both payment and stake addresses
  • Addresses must exist on the specified network (mainnet/testnet)

Error Cases:

  • Invalid address format
  • Insufficient funds (including fees)
  • Invalid native token identifier
  • Network connectivity issues

Swap API

SwapApi

Handles token swap operations and route optimization across decentralized exchanges.

Note: The Swap API interface is available but specific method implementations depend on the backend service configuration. The following represents the expected interface pattern.

class SwapApi extends BaseApi {
  // Methods will depend on backend implementation
  // Common patterns include:
  
  async getQuote(params: SwapQuoteRequest): Promise<SwapQuote>;
  async buildSwapTransaction(params: SwapTransactionRequest): Promise<SwapTransaction>;
  async getRoutes(tokenIn: string, tokenOut: string): Promise<SwapRoute[]>;
}

Expected Interfaces:

interface SwapQuoteRequest {
  tokenIn: string;      // Input token symbol
  tokenOut: string;     // Output token symbol  
  amountIn: string;     // Input amount
  slippage?: string;    // Slippage tolerance (e.g., "0.5" for 0.5%)
  recipient?: string;   // Recipient address
}

interface SwapQuote {
  tokenIn: string;
  tokenOut: string;
  amountIn: string;
  amountOut: string;
  priceImpact: string;
  fee: string;
  route: SwapRoute[];
}

Types and Interfaces

Core Types

SDKOption

Configuration options for the SDK.

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

SDKConfig

Complete SDK configuration including read-only properties.

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

ApiConfig

Configuration passed to individual API services.

interface ApiConfig {
  baseUrl: string;                    // API base URL
  headers?: Record<string, string>;   // HTTP headers
}

Request/Response Types

RequestOptions

HTTP request configuration for API calls.

interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  path: string;                       // API endpoint path
  params?: Record<string, any>;       // Query parameters
  data?: any;                         // Request body data
  headers?: Record<string, string>;   // Additional headers
}

SWApiResponse

Standardized API response wrapper.

interface SWApiResponse<T> {
  status: 'error' | 'success' | 'fail';
  data: T;                            // Response data
  result: T;                          // Alternative data field
  error?: {
    message: string;
    code: number;
  };
  message?: string;
}

Utility Types

GetOptions & PostOptions

Simplified request option types for common HTTP methods.

type GetOptions = Pick<RequestOptions, 'path' | 'params' | 'headers'>;
type PostOptions = Pick<RequestOptions, 'path' | 'params' | 'headers' | 'data'>;

Timeframe

Valid timeframe values for price history requests.

type Timeframe = '1D' | '1W' | '1M' | '3M' | 'YTD' | '1Y' | 'ALL';

Error Handling

Error Types

SdkError

Base error class for SDK-specific errors.

class SdkError extends Error {
  constructor(
    message: string,
    options?: {
      code?: number;
      type?: ErrorType;
      originalError?: Error;
    }
  );
  
  code?: number;           // HTTP status code or error code
  type?: ErrorType;        // Error classification
  originalError?: Error;   // Original error if wrapped
}

ErrorType

Error classification enumeration.

enum ErrorType {
  NETWORK_ERROR = 'NETWORK_ERROR',
  REQUEST_ERROR = 'REQUEST_ERROR', 
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  API_ERROR = 'API_ERROR',
  CONFIG_ERROR = 'CONFIG_ERROR'
}

Error Handling Patterns

Basic Error Handling

try {
  const priceData = await sdk.priceHistoryApi.getPriceHistory('DOT', '1W');
  console.log('Success:', priceData);
} catch (error) {
  if (error instanceof SdkError) {
    console.error('SDK Error:', {
      message: error.message,
      code: error.code,
      type: error.type
    });
  } else {
    console.error('Unknown error:', error);
  }
}

Comprehensive Error Handling

async function handleApiCall<T>(apiCall: () => Promise<T>): Promise<T | null> {
  try {
    return await apiCall();
  } catch (error) {
    if (error instanceof SdkError) {
      switch (error.type) {
        case ErrorType.NETWORK_ERROR:
          console.error('Network issue - check connectivity');
          break;
        case ErrorType.REQUEST_ERROR:
          console.error('Request failed - check parameters');
          break;
        case ErrorType.VALIDATION_ERROR:
          console.error('Validation failed - check input data');
          break;
        case ErrorType.API_ERROR:
          console.error('API error - service may be unavailable');
          break;
        default:
          console.error('Unknown SDK error:', error.message);
      }
    } else {
      console.error('Unexpected error:', error);
    }
    return null;
  }
}

// Usage
const result = await handleApiCall(() => 
  sdk.priceHistoryApi.getPriceHistory('DOT', '1W')
);

HTTP Status Code Mapping

Common HTTP status codes and their meanings in the SDK context:

Status Code Error Type Description
400 VALIDATION_ERROR Bad request - invalid parameters
401 REQUEST_ERROR Unauthorized - authentication required
403 REQUEST_ERROR Forbidden - access denied
404 REQUEST_ERROR Not found - endpoint or resource missing
429 REQUEST_ERROR Too many requests - rate limit exceeded
500 API_ERROR Internal server error
502 NETWORK_ERROR Bad gateway - upstream server error
503 API_ERROR Service unavailable
504 NETWORK_ERROR Gateway timeout

🔗 Related Documentation

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