installation - saltict/Demo-Docs GitHub Wiki
Complete guide for installing and setting up the SubWallet Services SDK in your project.
📖 Navigation
- Package Installation
- Platform-Specific Setup
- Build Tools Configuration
- TypeScript Configuration
- Environment Variables
- Verification
npm install @subwallet-monorepos/subwallet-services-sdk
yarn add @subwallet-monorepos/subwallet-services-sdk
pnpm add @subwallet-monorepos/subwallet-services-sdk
-
Package Name:
@subwallet-monorepos/subwallet-services-sdk
-
Current Version:
0.1.3-beta.5
- License: MIT
- Module System: ES Modules with CommonJS compatibility
{
"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'"
}
}
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 });
}
}
});
# 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
// 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>
);
};
// 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);
}
}
// 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' });
}
}
// 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');
});
// 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.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
define: {
global: 'globalThis',
},
resolve: {
alias: {
buffer: 'buffer',
},
},
optimizeDeps: {
include: ['buffer'],
},
});
// 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']
};
{
"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"]
}
// 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;
}
# .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
// 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
});
// 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.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
};
}
}
-
Module Resolution Error:
# Install missing peer dependencies npm install --save-dev @types/node
-
Build Tool Compatibility:
# For older webpack versions npm install --save-dev crypto-browserify stream-browserify buffer
-
TypeScript Errors:
# Update TypeScript and types npm update typescript @types/node
-
Network Configuration:
// Configure custom endpoints subwalletApiSdk.updateConfig({ baseUrl: 'https://your-custom-endpoint.com' });
🔗 Related Documentation