### CLI Quick Start - Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/skills/SKILL.md This snippet demonstrates how to quickly start using the Vultisig CLI for creating a fast vault and checking balances. It requires the Vultisig CLI to be installed globally via npm. The output is typically JSON, suitable for piping to other tools. ```bash npm install -g @vultisig/cli vultisig create fast --name "bot-wallet" --email "bot@example.com" --password "SecurePass123!" vultisig balance -o json ``` -------------------------------- ### Vultisig CLI: First-Time Setup Workflow Source: https://github.com/vultisig/vultisig-sdk/blob/main/skills/vultisig-cli/SKILL.md This workflow guides users through the initial setup of a Vultisig vault. It covers creating a new vault, enabling desired blockchain chains, retrieving wallet addresses, and checking account balances. This is a foundational step for using the Vultisig SDK. ```bash # 1. Create vault vultisig create fast --name "agent-wallet" --email "agent@example.com" --password "SecurePass123!" # Enter verification code # 2. Enable desired chains vultisig chains --add-all # 3. Get addresses vultisig addresses -o json # 4. Check balances vultisig balance -o json ``` -------------------------------- ### Initialize Rujira SDK Client Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/rujira/docs/EXAMPLES.md Demonstrates how to import necessary modules and initialize the RujiraClient. Includes both read-only configurations and full-signer setups using VultisigVault for transaction capabilities. ```typescript import { RujiraClient, VultisigRujiraProvider, EASY_ROUTES, ASSETS, RujiraError, RujiraErrorCode } from '@vultisig/rujira'; // Read-only const client = new RujiraClient({ debug: true }); await client.connect(); // With Signer import { VultisigVault } from '@vultisig/vault'; const vault = new VultisigVault(); const signer = new VultisigRujiraProvider(vault, { chainId: 'thorchain-1', addressPrefix: 'thor' }); const clientWithSigner = new RujiraClient({ signer, debug: false }); await clientWithSigner.connect(); ``` -------------------------------- ### Electron Main Process Setup with Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Initializes the Vultisig SDK in the Electron main process and exposes SDK functionalities (listVaults, getAddress, getBalance) via IPC handlers. This setup ensures that sensitive operations remain in the secure main process. ```typescript // main.ts - SDK runs here import { app, BrowserWindow, ipcMain } from 'electron' import { Vultisig, Chain } from '@vultisig/sdk' let sdk: Vultisig app.whenReady().then(async () => { // Initialize SDK in main process sdk = new Vultisig() // Uses FileStorage (~/.vultisig) await sdk.initialize() // Expose SDK operations via IPC ipcMain.handle('sdk:listVaults', () => sdk.listVaults()) ipcMain.handle('sdk:getAddress', async (_, chain) => { const vault = await sdk.getActiveVault() return vault?.address(chain) }) ipcMain.handle('sdk:getBalance', async (_, chain) => { const vault = await sdk.getActiveVault() return vault?.balance(chain) }) // Create window... }) ``` -------------------------------- ### Quick Start: Create and Verify a Fast Vault Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md A tutorial demonstrating the creation of a 'FastVault' using the Vultisig SDK. It includes initializing the SDK with password handling, creating the vault, verifying it with an email code, and deriving addresses. ```typescript import { Vultisig, Chain } from '@vultisig/sdk' // Step 1: Initialize SDK with configuration const sdk = new Vultisig({ // Password handling (recommended for production) onPasswordRequired: async (vaultId: string, vaultName: string) => { // Prompt user for password - implementation depends on platform return await promptUserForPassword(`Enter password for ${vaultName}`) }, passwordCache: { defaultTTL: 300000 // Cache password for 5 minutes } }) await sdk.initialize() // Step 2: Create a fast vault (server-assisted, always encrypted) // Returns the vaultId - vault is returned from verifyVault() const vaultId = await sdk.createFastVault({ name: "My Wallet", email: "user@example.com", password: "SecurePassword123!", onProgress: (step) => { console.log(`${step.message} (${step.progress}%)`) } }) // Step 3: Verify with email code and get the vault // The vault is saved to storage and returned after successful verification const code = await getVerificationCode() // Get code from user const vault = await sdk.verifyVault(vaultId, code) // Step 4: Now use the vault const btcAddress = await vault.address(Chain.Bitcoin) console.log('Bitcoin address:', btcAddress) // Step 5: Check balance const balance = await vault.balance(Chain.Bitcoin) console.log(`Balance: ${balance.amount} ${balance.symbol}`) // Step 6: Get balances across multiple chains const balances = await vault.balances([Chain.Bitcoin, Chain.Ethereum]) for (const [chain, balance] of Object.entries(balances)) { console.log(`${chain}: ${balance.amount} ${balance.symbol}`) } // Step 7: Clean up when done sdk.dispose() ``` -------------------------------- ### Prepare and Send Transactions with Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Guides through the process of preparing, signing, and broadcasting transactions on supported chains using the Vultisig SDK. It involves getting coin information, preparing the transaction payload, signing it (which may prompt for a password), and finally broadcasting the transaction. ```typescript import { AccountCoin, Chain } from 'vultisig-sdk' // Step 1: Get coin information const coin = new AccountCoin({ chain: Chain.Ethereum, ticker: 'ETH', address: await vault.address(Chain.Ethereum), decimals: 18, priceUSD: '3000.00', isNativeToken: true }) // Step 2: Prepare transaction const keysignPayload = await vault.prepareSendTx({ coin, receiver: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0', amount: '100000000000000000', // 0.1 ETH in wei memo: 'Payment for services', feeSettings: { gasPrice: '50000000000', // 50 gwei (optional, uses estimate if not provided) } }) // Step 3: Sign transaction (may trigger password prompt) const signature = await vault.sign(keysignPayload) // Step 4: Broadcast transaction const txHash = await vault.broadcastTx({ chain: Chain.Ethereum, keysignPayload, signature }) console.log('Transaction broadcast:', txHash) ``` -------------------------------- ### Implement Custom Storage Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Provides an example of implementing the Storage interface to create a custom persistence layer for the Vultisig SDK. ```typescript import { Vultisig, type VaultStorage } from '@vultisig/sdk' import * as fs from 'fs' import * as path from 'path' class CustomStorage implements Storage { constructor(private basePath: string) {} async get(key: string): Promise { try { return fs.readFileSync(path.join(this.basePath, key), 'utf-8') } catch { return null } } async set(key: string, value: string): Promise { fs.writeFileSync(path.join(this.basePath, key), value, 'utf-8') } async remove(key: string): Promise { fs.unlinkSync(path.join(this.basePath, key)) } async clear(): Promise { const files = fs.readdirSync(this.basePath) files.forEach(file => fs.unlinkSync(path.join(this.basePath, file))) } async list(prefix?: string): Promise { const files = fs.readdirSync(this.basePath) return prefix ? files.filter(f => f.startsWith(prefix)) : files } } const sdk = new Vultisig({ storage: new CustomStorage('./vaults') }) await sdk.initialize() sdk.dispose() ``` -------------------------------- ### Post Setup Message - HTTP Request Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Shares initial setup data for a key generation ceremony. This is an optional step that sends setup data to the server. It requires the session ID in the URL path and optionally a message ID in the header. ```http POST https://api.vultisig.com/router/setup-message/my-keygen-session-123 Content-Type: application/json message_id: setup-001 {setup data payload} ``` -------------------------------- ### Install and Initialize Vultisig CLI Source: https://github.com/vultisig/vultisig-sdk/blob/main/skills/vultisig-cli/SKILL.md Instructions for installing the CLI globally via npm or executing it directly using npx. This allows users to verify the installation or perform quick balance checks. ```bash npm install -g @vultisig/cli vultisig --version npx @vultisig/cli balance ethereum ``` -------------------------------- ### Initiate Server-Side Signing Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/VULTISERVER-API-USAGE.md Starts the two-step signing process by preparing the server for MPC coordination. This step does not return a signature directly. ```json { "public_key": "04a1b2c3...", "messages": ["abc123...", "def456..."], "session": "938124b5-7ddd-4bc7-9257-ec224962e7cb", "hex_encryption_key": "a1b2c3...", "derive_path": "m/44'/60'/0'/0/0", "is_ecdsa": true, "vault_password": "Password123!" } ``` -------------------------------- ### Check Asset Balances with Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Provides examples for checking cryptocurrency balances on single or multiple chains using the Vultisig SDK. It also shows how to include token balances and force a balance refresh, bypassing the cache. ```typescript // Single chain balance const balance = await vault.balance(Chain.Ethereum) console.log(`${balance.amount} ${balance.symbol}`) console.log(`Value: $${balance.fiatValue} ${balance.currency}`) // Multiple chain balances const balances = await vault.balances([Chain.Bitcoin, Chain.Ethereum]) for (const [chain, balance] of Object.entries(balances)) { console.log(`${chain}: ${balance.amount} ${balance.symbol} ($${balance.fiatValue})`) } // All configured chains (with tokens) const allBalances = await vault.balances(undefined, true) // includeTokens=true // Force refresh (bypass cache) await vault.updateBalance(Chain.Ethereum) await vault.updateBalances() // Refresh all chains ``` -------------------------------- ### Install Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/README.md Installs the Vultisig SDK package using npm. This is the first step to integrate the SDK into your project. ```bash npm install @vultisig/sdk ``` -------------------------------- ### Install Vultisig CLI from Source Source: https://github.com/vultisig/vultisig-sdk/blob/main/clients/cli/README.md Installs the Vultisig CLI by cloning the repository from GitHub and installing dependencies using yarn. This method is suitable for developers or those who need the latest code. ```bash # Clone the repository git clone https://github.com/vultisig/vultisig-sdk.git cd vultisig-sdk # Install dependencies yarn install # Run CLI yarn cli --help ``` -------------------------------- ### Setting Up Local Environment Variables for E2E Tests (Bash) Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/tests/e2e/SECURITY.md Provides bash commands to copy an example environment file and configure it for E2E tests. This includes setting vault paths, passwords, and enabling/disabling specific test types. ```bash cd packages/sdk/tests/e2e cp .env.example .env ``` -------------------------------- ### Install VultisigSDK via Package Manager Source: https://github.com/vultisig/vultisig-sdk/blob/main/README.md Commands to install the Vultisig SDK using common JavaScript package managers. ```bash npm install @vultisig/sdk # or yarn add @vultisig/sdk ``` -------------------------------- ### Install Vultisig CLI using npm Source: https://github.com/vultisig/vultisig-sdk/blob/main/clients/cli/README.md Installs the Vultisig CLI globally using npm, the Node Package Manager. After installation, you can verify the installation by checking the version. ```bash # Install globally npm install -g @vultisig/cli # Verify installation vultisig --version ``` -------------------------------- ### Join SecureVault Session - Fresh Keygen (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Demonstrates how multiple SDK instances can join a SecureVault creation session programmatically without QR scanning. This example shows joining a fresh key generation session where no seedphrase is initially provided. ```typescript // Device 1 initiates let qrPayload: string const promise1 = sdk1.createSecureVault({ name: 'Shared Vault', devices: 3, password: 'optional', onQRCodeReady: (qr) => { qrPayload = qr } }) // Device 2 joins (no mnemonic needed for keygen) const promise2 = sdk2.joinSecureVault(qrPayload, { devices: 3 }) // Device 3 joins const promise3 = sdk3.joinSecureVault(qrPayload, { devices: 3 }) // Wait for all to complete const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]) // All have matching vaultId but unique localPartyId ``` -------------------------------- ### Check TSS Start Status - HTTP Request Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Verifies if the TSS session has been marked as started. This GET request requires the session ID in the URL path and is used by participants to poll for the session's start status. ```http GET https://api.vultisig.com/router/start/my-keygen-session-123 ``` -------------------------------- ### GET /:sessionID Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Retrieves the current participant list for an existing TSS session. ```APIDOC ## GET /:sessionID ### Description Confirms session existence and retrieves the list of registered participants. ### Method GET ### Endpoint /:sessionID ### Parameters #### Path Parameters - **sessionID** (string) - Required - The session identifier ### Response #### Success Response (200) - **participants** (array) - List of participant IDs #### Response Example ["participant1", "participant2", "participant3"] ``` -------------------------------- ### Initialize and Use Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/skills/vultisig-sdk/SKILL.md Demonstrates initializing the SDK, creating a FastVault, and performing basic wallet operations like retrieving addresses and checking balances. ```typescript import { Vultisig, Chain } from '@vultisig/sdk' // Initialize SDK const sdk = new Vultisig({ onPasswordRequired: async (vaultId, vaultName) => { return process.env.VAULT_PASSWORD || '' }, passwordCache: { defaultTTL: 300000 } // 5 minutes }) await sdk.initialize() // Create a FastVault const vaultId = await sdk.createFastVault({ name: 'agent-wallet', email: 'agent@example.com', password: 'SecurePassword123!' }) // Verify with email code const vault = await sdk.verifyVault(vaultId, 'verification-code') // Get address const address = await vault.address(Chain.Ethereum) console.log('ETH address:', address) // Check balance const balance = await vault.balance(Chain.Ethereum) console.log(`Balance: ${balance.amount} ${balance.symbol}`) // Clean up sdk.dispose() ``` -------------------------------- ### GET /message/:sessionID/:participantID Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Retrieves messages addressed to a specific participant during a TSS ceremony. ```APIDOC ## GET /message/:sessionID/:participantID ### Description Retrieve messages addressed to a specific participant. Poll this endpoint regularly during the TSS ceremony. ### Method GET ### Endpoint /message/:sessionID/:participantID ### Parameters #### Path Parameters - **sessionID** (string) - Required - The session identifier - **participantID** (string) - Required - Your participant ID #### Query Parameters - **message_id** (string) - Optional - Filter by message ID ### Response #### Success Response (200) - **body** (array) - List of messages #### Response Example [ { "from": "participant2", "to": ["participant1"], "body": "encrypted_tss_response", "hash": "response_hash", "sequence_no": 2 } ] ``` -------------------------------- ### Vultisig SDK Integration Example Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/architecture/VAULTPLAN.md Demonstrates how to import and initialize the Vultisig SDK, create a new vault, verify email, retrieve address and balance, and sign a transaction using VultiServer. It includes progress updates for long-running operations. ```typescript import { Vultisig } from "vultisig-sdk"; const vultisig = new Vultisig(); const vault = await vultisig.createVault("My Vault", { password: "password", email: "user@example.com", onProgress: (step) => { console.log(`${step.step}: ${step.progress}% - ${step.message}`); }, }); await vault.verifyEmail("1234"); const ethAddress = await vault.address("ethereum"); const ethBalance = await vault.balance("ethereum"); const signature = await vault.sign({ transaction: { to: "0x...", value: "1000000000000000000" }, chain: "ethereum", onProgress: (step) => { console.log(`Signing: ${step.progress}% - ${step.message}`); }, }); console.log("Transaction signed:", signature.txHash); ``` -------------------------------- ### Vultisig SDK Configuration Example Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/README.md Demonstrates how to configure the Vultisig SDK instance with options such as automatic initialization, custom server URLs, and relay endpoints. This configuration is essential for setting up the SDK's communication channels and behavior. ```typescript const sdk = new Vultisig({ autoInit: true, // Automatically initialize WASM modules on creation serverUrl: "https://api.vultisig.com", // Custom VultiServer endpoint relayUrl: "https://relay.vultisig.com", // Custom relay endpoint }); ``` -------------------------------- ### Initialize SDK, Create and Verify Vault, Fetch Balance (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/skills/SKILL.md Demonstrates the basic workflow of the Vultisig SDK: initializing the SDK instance, creating a new fast vault with user details, verifying the vault using an email code, and fetching the balance for a specific blockchain chain. Requires the '@vultisig/sdk' package. ```typescript import { Vultisig, Chain } from '@vultisig/sdk' const sdk = new Vultisig() await sdk.initialize() const vaultId = await sdk.createFastVault({ name: 'bot-wallet', email: 'bot@example.com', password: 'SecurePass123!' }) const vault = await sdk.verifyVault(vaultId, 'email-code') const balance = await vault.balance(Chain.Ethereum) ``` -------------------------------- ### Initialize and Build SDK Environment Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/README.md Provides the shell commands necessary to clone the repository, install dependencies from the root, and build the SDK package using Yarn workspaces. ```bash # Clone the repository git clone https://github.com/vultisig/vultisig-sdk.git cd vultisig-sdk # IMPORTANT: Install from root (sets up all workspace packages) yarn install # Build the SDK (from root directory) yarn workspace @vultisig/sdk build ``` -------------------------------- ### Exporting Vaults with Password Encryption Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Exports a vault to an encrypted data format. Provides examples for saving the resulting data to a file in both Node.js and browser environments. ```typescript const { filename, data } = await vault.export('BackupPassword123!') // Save to file (Node.js) fs.writeFileSync(filename, data, 'utf-8') // Save to file (Browser) const blob = new Blob([data], { type: 'text/plain' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = filename link.click() URL.revokeObjectURL(url) ``` -------------------------------- ### Initialize and Manage Vultisig SDK Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/architecture/ARCHITECTURE.md Demonstrates the lifecycle of the Vultisig SDK, including initialization, fast vault creation, verification, and resource cleanup. This is the primary entry point for interacting with the SDK. ```typescript import { Vultisig, Chain } from "@vultisig/sdk"; const sdk = new Vultisig({ defaultChains: [Chain.Bitcoin, Chain.Ethereum], }); await sdk.initialize(); const vaultId = await sdk.createFastVault({ name: "My Vault", password: "secure-password", email: "user@example.com" }); const code = await getVerificationCode(); const vault = await sdk.verifyVault(vaultId, code); const address = await vault.address("Ethereum"); sdk.dispose(); ``` -------------------------------- ### Export Vault with Password (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Shows how to export a vault with or without encryption. It includes an example of creating an encrypted backup using a specified password and saving it to a file. ```typescript // Export with encryption const { filename, data } = await vault.export('BackupPassword123!') // Save to file (Node.js) fs.writeFileSync(filename, data, 'utf-8') console.log(`Encrypted backup saved to ${filename}`) // Export without encryption (not recommended for FastVault) const { filename, data } = await vault.export() ``` -------------------------------- ### Execute Simple Swaps Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/rujira/docs/EXAMPLES.md Demonstrates how to execute a swap using the 'easy swap' route, including transaction submission and awaiting confirmation. ```typescript const result = await client.swap.easySwap({ route: 'RUNE_TO_USDC', amount: '100000000', destination: 'thor1abc...', maxSlippagePercent: 1 }); try { const confirmed = await client.waitForTransaction(result.txHash); console.log(`Transaction confirmed in block ${confirmed.height}`); } catch (error) { console.error('Transaction failed:', error.message); } ``` -------------------------------- ### Configure Password Callback Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Configures the onPasswordRequired callback to handle secure vault decryption. Provides examples for integrating with browser-based UI modals and Node.js command-line prompts. ```typescript // Browser Example const sdk = new Vultisig({ storage: new MemoryStorage(), onPasswordRequired: async (vaultId: string, vaultName: string) => { return new Promise((resolve) => { const modal = createPasswordModal({ title: `Enter password for ${vaultName}`, onSubmit: (password) => { closeModal() resolve(password) } }) modal.show() }) } }) ``` ```typescript // Node.js Example const sdk = new Vultisig({ storage: new FileStorage(), onPasswordRequired: async (vaultId: string, vaultName: string) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) return new Promise((resolve) => { rl.question(`Enter password for ${vaultName}: `, (password) => { rl.close() resolve(password) }) }) } }) ``` -------------------------------- ### Verify Session - HTTP Request Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Confirms the existence of a TSS session and retrieves the list of participants by sending a GET request. Requires the session ID in the URL path. ```http GET https://api.vultisig.com/router/my-keygen-session-123 ``` -------------------------------- ### Manage SDK Caching Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Demonstrates how to interact with the address and balance caching system, including how to force cache refreshes. ```typescript // Address Caching const address = await vault.address(Chain.Ethereum) const cachedAddress = await vault.address(Chain.Ethereum) // Balance Caching const balance = await vault.balance(Chain.Ethereum) const cachedBalance = await vault.balance(Chain.Ethereum) // Force refresh await vault.updateBalance(Chain.Ethereum) await vault.updateBalances() ``` -------------------------------- ### Configure Password Caching (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Shows how to configure password caching for the Vultisig SDK using MemoryStorage. It includes examples of setting different Time-To-Live (TTL) values for the cache. ```typescript const sdk = new Vultisig({ storage: new MemoryStorage(), passwordCache: { defaultTTL: 300000 // Cache for 5 minutes (in milliseconds) } }) ``` ```typescript // Common TTL configurations: // 5 minutes (recommended for balance of security and UX) passwordCache: { defaultTTL: 300000 } // 15 minutes passwordCache: { defaultTTL: 900000 } // 1 hour passwordCache: { defaultTTL: 3600000 } // Session only (no expiry, cleared on app close) passwordCache: { defaultTTL: Infinity } ``` -------------------------------- ### Auto-lock Vault on Inactivity (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Provides an example of implementing an auto-lock mechanism for a vault based on user inactivity. It uses `setTimeout` to lock the vault after a specified period of no user interaction. ```typescript let inactivityTimer: NodeJS.Timeout | null = null function resetInactivityTimer(vault: VaultBase) { if (inactivityTimer) clearTimeout(inactivityTimer) // Lock after 10 minutes of inactivity inactivityTimer = setTimeout(async () => { await vault.lock() console.log('Vault locked due to inactivity') }, 600000) } // Call resetInactivityTimer() on user interactions document.addEventListener('click', () => resetInactivityTimer(vault)) document.addEventListener('keypress', () => resetInactivityTimer(vault)) ``` -------------------------------- ### Token Registry and Discovery with Vultisig SDK Source: https://context7.com/vultisig/vultisig-sdk/llms.txt This example illustrates how to use the Vultisig SDK for token registry and discovery. It covers looking up known tokens by chain, finding specific tokens by contract address, identifying native fee coins, discovering tokens with balances at a vault address, and resolving token metadata. ```typescript import { Vultisig, Chain, MemoryStorage } from '@vultisig/sdk' const sdk = new Vultisig({ storage: new MemoryStorage() }) await sdk.initialize() const vault = await sdk.importVault(vultContent, password) // Static methods (no vault needed) // Get all known tokens for a chain const tokens = Vultisig.getKnownTokens(Chain.Ethereum) tokens.forEach(t => console.log(`${t.ticker}: ${t.contractAddress}`)) // Look up specific token by contract address const usdc = Vultisig.getKnownToken(Chain.Ethereum, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48') if (usdc) console.log(`${usdc.ticker} - ${usdc.decimals} decimals`) // Get native fee coin (ETH, BTC, SOL, etc.) const feeCoin = Vultisig.getFeeCoin(Chain.Bitcoin) console.log(`${feeCoin.ticker} - ${feeCoin.decimals} decimals`) // Instance methods (require vault) // Discover tokens with balances at vault address const discoveredTokens = await vault.discoverTokens(Chain.Ethereum) discoveredTokens.forEach(t => console.log(`${t.ticker}: ${t.balance}`)) // Resolve token metadata by contract address const token = await vault.resolveToken(Chain.Ethereum, '0x6982508145454Ce325dDbE47a25d4ec3d2311933') console.log(`${token.ticker} - ${token.decimals} decimals`) ``` -------------------------------- ### Sync and Build SDK using Yarn Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SUBTREE-SYNC.md Commands to synchronize the latest code from vultisig-windows and then build the SDK. Assumes Yarn is installed and configured. ```bash # Sync latest code from vultisig-windows yarn sync-and-copy # Then build the SDK yarn workspace @vultisig/sdk build ``` -------------------------------- ### Subscribe to Swap Events Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Listen for swap-related events emitted by the SDK, such as 'swapQuoteReceived'. This allows for real-time updates on swap quote information, including the provider and estimated output. An example shows how to log quote details when received. ```typescript // Listen for swap quotes vault.on('swapQuoteReceived', ({ quote }) => { console.log(`Quote received from ${quote.provider}`) console.log(`Output: ${quote.estimatedOutput}`) }) // Get quote - event will fire automatically const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum }, toCoin: { chain: Chain.Bitcoin }, amount: 0.1 }) ``` -------------------------------- ### Start TSS Session - HTTP Request Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/SESSION-USAGE.md Signals the beginning of the TSS key generation ceremony. This POST request includes the session ID in the URL path and a JSON array of participating participant IDs in the request body. ```http POST https://api.vultisig.com/router/start/my-keygen-session-123 Content-Type: application/json ["participant1", "participant2", "participant3"] ``` -------------------------------- ### Configure Browser Environment Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Instructions for setting up the Vultisig SDK in a browser environment, including WASM file placement and SDK initialization using IndexedDB. ```bash cp node_modules/@vultisig/sdk/dist/*.wasm public/ ``` ```typescript import { Vultisig, Chain } from '@vultisig/sdk' const sdk = new Vultisig() await sdk.initialize() ``` -------------------------------- ### Swap Functionality in VaultBase (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Enables users to perform cryptocurrency swaps within the Vultisig ecosystem. Methods include getting swap quotes, preparing swap transactions, checking token allowances, and querying supported swap chains. ```typescript class VaultBase { // Swaps getSwapQuote(params: SwapQuoteParams): Promise prepareSwapTx(params: SwapTxParams): Promise getTokenAllowance(coin: AccountCoin, spender: string): Promise getSupportedSwapChains(): readonly Chain[] isSwapSupported(fromChain: Chain, toChain: Chain): boolean } ``` -------------------------------- ### Initialize Vultisig SDK Source: https://context7.com/vultisig/vultisig-sdk/llms.txt Configures and initializes the Vultisig SDK instance. It supports custom storage backends, default chain configurations, and password management callbacks. ```typescript import { Vultisig, Chain, MemoryStorage } from '@vultisig/sdk' const sdk = new Vultisig({ storage: new MemoryStorage(), // Optional - uses platform default defaultChains: [Chain.Bitcoin, Chain.Ethereum, Chain.Solana], defaultCurrency: 'USD', passwordCache: { defaultTTL: 300000 }, // 5 minutes onPasswordRequired: async (vaultId, vaultName) => { return await promptUserForPassword(`Enter password for ${vaultName}`) } }) await sdk.initialize() // ... use the SDK ... sdk.dispose() // Clean up resources when done ``` -------------------------------- ### Execute Full Swap Transaction Flow Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Complete the swap process by first getting a quote, then preparing the transaction. This includes handling ERC-20 approvals if necessary, signing the transaction, and broadcasting it. Dependencies include the vault object and Chain enum. ```typescript // Step 1: Get quote const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum }, toCoin: { chain: Chain.Bitcoin }, amount: 0.1 }) // Step 2: Prepare transaction const { keysignPayload, approvalPayload } = await vault.prepareSwapTx({ fromCoin: { chain: Chain.Ethereum }, toCoin: { chain: Chain.Bitcoin }, amount: 0.1, swapQuote: quote }) // Step 3: Handle approval if needed (ERC-20 tokens only) if (approvalPayload) { const approvalSignature = await vault.sign(approvalPayload) const approvalTxHash = await vault.broadcastTx({ chain: Chain.Ethereum, keysignPayload: approvalPayload, signature: approvalSignature }) console.log('Approval tx:', approvalTxHash) // Wait for approval confirmation before proceeding } // Step 4: Sign and broadcast swap const signature = await vault.sign(keysignPayload) const txHash = await vault.broadcastTx({ chain: Chain.Ethereum, keysignPayload, signature }) console.log('Swap tx:', txHash) ``` -------------------------------- ### Vultisig Constructor Configuration Options Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Illustrates the various optional configuration parameters available when initializing the Vultisig class. These include settings for storage, default chains and currency, cache behavior for balances and prices, password management, and custom server endpoints. ```typescript new Vultisig({ storage?: Storage, defaultChains?: Chain[], defaultCurrency?: string, cacheConfig?: { balanceTTL?: number, priceTTL?: number, maxMemoryCacheSize?: number }, passwordCache?: { defaultTTL: number }, onPasswordRequired?: (vaultId: string, vaultName: string) => Promise, serverEndpoints?: { fastVault?: string, messageRelay?: string } }) ``` -------------------------------- ### Get Swap Quote for ERC-20 Tokens Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Retrieve a swap quote for ERC-20 tokens by specifying the token contract address. This function can use a simplified token format or the full AccountCoin format, including address, ID, ticker, and decimals. ```typescript const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum, token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC }, toCoin: { chain: Chain.Ethereum }, // Native ETH amount: 100 // 100 USDC }) ``` ```typescript const ethAddress = await vault.address(Chain.Ethereum) const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum, address: ethAddress, id: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', ticker: 'USDC', decimals: 6 }, toCoin: { chain: Chain.Ethereum, address: ethAddress, ticker: 'ETH', decimals: 18 }, amount: 100 }) ``` -------------------------------- ### CLI Command to Create a Vultisig Vault Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Example of using the Vultisig CLI tool to create a new vault named 'My Wallet'. This vault will be stored in `~/.vultisig` and will be accessible by both the CLI and the Electron application if configured to use the same storage location. ```bash # Create vault with CLI vsig vault create --name "My Wallet" ``` -------------------------------- ### Initialize and Create Fast Vault Source: https://github.com/vultisig/vultisig-sdk/blob/main/README.md Demonstrates initializing the Vultisig SDK and creating a server-assisted 2-of-2 MPC vault. It includes vault verification and address derivation for supported blockchains. ```typescript import { Vultisig, MemoryStorage } from '@vultisig/sdk' // Initialize SDK const sdk = new Vultisig({ storage: new MemoryStorage() }) await sdk.initialize() // Create a fast vault (server-assisted 2-of-2) const vaultId = await sdk.createFastVault({ name: "My Wallet", email: "user@example.com", password: "secure-password", }); // Verify with email code const vault = await sdk.verifyVault(vaultId, "1234"); // Derive addresses const btcAddress = await vault.address("Bitcoin"); const ethAddress = await vault.address("Ethereum"); ``` -------------------------------- ### Vultisig Class Constructor and Initialization Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Initializes the Vultisig SDK. The constructor accepts an optional configuration object for storage, default chains, currency, password handling, caching, and server endpoints. The `initialize` method performs the necessary setup for the SDK to function. ```typescript class Vultisig { // Constructor - storage uses platform default if not provided constructor(config?: { storage?: Storage // Optional - uses FileStorage (Node) or BrowserStorage (browser) defaultChains?: Chain[] defaultCurrency?: string onPasswordRequired?: (vaultId: string, vaultName: string) => Promise passwordCache?: { defaultTTL: number } cacheConfig?: { balanceTTL?: number, priceTTL?: number, maxMemoryCacheSize?: number } serverEndpoints?: { fastVault?: string, messageRelay?: string } }) // Initialization initialize(): Promise // Cleanup (releases all resources) dispose(): void } ``` -------------------------------- ### Create Isolated SDK Instances Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/architecture/ARCHITECTURE.md Demonstrates how to create multiple, isolated Vultisig SDK instances. Each instance maintains its own storage and context, ensuring no shared state between independent SDK sessions. ```typescript const sdk1 = new Vultisig({ storage: storage1 }); const sdk2 = new Vultisig({ storage: storage2 }); await sdk1.initialize(); await sdk2.initialize(); sdk1.dispose(); sdk2.dispose(); ``` -------------------------------- ### Handle Swap Errors Gracefully Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Implement error handling for swap operations using a try-catch block. This example demonstrates how to identify and respond to specific swap errors, such as 'No swap route' or issues related to liquidity pools, by checking the error message. ```typescript try { const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum }, toCoin: { chain: Chain.Bitcoin }, amount: 0.001 // Very small amount }) } catch (error) { if (error.message.includes('No swap route')) { console.log('No swap route available for this pair/amount') } else if (error.message.includes('pool')) { console.log('Liquidity pool not available') } else { throw error } } ``` -------------------------------- ### Static Utility Methods Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/README.md Helper methods for token lookups, price fetching, and security scanning. ```APIDOC ## GET /Vultisig.getCoinPrices ### Description Fetches current token prices via CoinGecko. ### Method GET ### Parameters #### Query Parameters - **ids** (string[]) - Required - CoinGecko price provider IDs - **fiatCurrency** (string) - Optional - Currency code (default: 'usd') ### Response #### Success Response (200) - **prices** (Record) - Map of coin IDs to prices. --- ## GET /Vultisig.scanSite ### Description Scans a URL for malicious content using Blockaid. ### Method GET ### Parameters #### Query Parameters - **url** (string) - Required - The URL to scan ### Response #### Success Response (200) - **isMalicious** (boolean) - Flag indicating if site is malicious ``` -------------------------------- ### Getting Swap Quotes with Vultisig SDK (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Enables fetching a quote for a token swap before execution, providing details on the provider, estimated output, expiration, fees, balance, and whether an approval is needed for ERC-20 tokens. Requires the Chain enum and a vault instance. ```typescript // Simple format - just specify chains (native tokens) const quote = await vault.getSwapQuote({ fromCoin: { chain: Chain.Ethereum }, toCoin: { chain: Chain.Bitcoin }, amount: 0.1 // 0.1 ETH }) console.log(`Provider: ${quote.provider}`) // e.g., 'thorchain' console.log(`Output: ${quote.estimatedOutput} BTC`) // e.g., '0.00234 BTC' console.log(`Expires: ${new Date(quote.expiresAt)}`) console.log(`Fees: ${quote.fees.total}`) // Balance + max swappable amount (included automatically) console.log(`Balance: ${quote.balance}`) // Source coin balance in base units console.log(`Max swapable: ${quote.maxSwapable}`) // balance - network fee (native), or full balance (tokens) // Check if approval is needed (ERC-20 tokens) if (quote.requiresApproval) { console.log(`Approval needed for: ${quote.approvalInfo?.spender}`) } ``` -------------------------------- ### Create or Import a Vault Source: https://github.com/vultisig/vultisig-sdk/blob/main/clients/cli/README.md Provides example commands for creating a new vault with basic details or importing an existing vault from a file. These are necessary steps before performing most Vultisig operations. ```bash vultisig create fast --name "My Wallet" --password "mypassword" --email user@example.com # or vultisig import /path/to/vault.vult ``` -------------------------------- ### Step 5: Completion and Cleanup Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/FAST-SIGNING.md Optional endpoints for marking the signing process as complete and cleaning up the session resources. ```APIDOC ## POST /router/complete/{sessionId}/keysign ### Description Optionally marks the keysign process for the session as complete. Note: This endpoint is currently not implemented. ### Method POST ### Endpoint https://api.vultisig.com/router/complete/{sessionId}/keysign ### Parameters #### Path Parameters - **sessionId** (string) - Required - The UUID v4 session ID. ### Response #### Error Response (404) This endpoint is not yet implemented. #### Response Example (No response body expected, likely a 404 error) ``` ```APIDOC ## DELETE /router/{sessionId} ### Description Cleans up the session resources on the MessageRelay server. Sessions also expire automatically after approximately 5 minutes. ### Method DELETE ### Endpoint https://api.vultisig.com/router/{sessionId} ### Parameters #### Path Parameters - **sessionId** (string) - Required - The UUID v4 session ID to delete. ### Response #### Success Response (200) Indicates the session has been successfully deleted. #### Response Example (No response body expected on success) ``` -------------------------------- ### Portfolio Value Calculation with Vultisig SDK (TypeScript) Source: https://github.com/vultisig/vultisig-sdk/blob/main/docs/SDK-USERS-GUIDE.md Enables retrieval and management of total portfolio value in a specified fiat currency. It supports getting the overall value, specific asset values, forcing a refresh, and changing the preferred currency. Requires a vault instance. ```typescript // Get total value const totalValue = await vault.getTotalValue('USD') console.log(`Total portfolio value: $${totalValue}`) // Get value for specific asset const ethValue = await vault.getValue(Chain.Ethereum, null, 'USD') // Force refresh portfolio value await vault.updateTotalValue() // Change preferred currency await vault.setCurrency('EUR') const totalEur = await vault.getTotalValue() console.log(`Total portfolio value: €${totalEur}`) ``` -------------------------------- ### SDK Vault Workflow Source: https://github.com/vultisig/vultisig-sdk/blob/main/packages/sdk/src/server/VULTISERVER-API-USAGE.md Demonstrates the high-level SDK pattern for creating a fast vault, verifying the email, and retrieving the vault instance. ```typescript const { vaultId } = await sdk.createFastVault({ name: "TestVault", email: "user@example.com", password: "Password123!", }); await sdk.verifyVaultEmail(vaultId, "1234"); const vault = await sdk.getVault(vaultId, "Password123!"); ```