# Fireblocks TypeScript SDK The Fireblocks TypeScript SDK (`@fireblocks/ts-sdk`) is an official client library that enables developers to integrate with the Fireblocks platform for secure digital asset management and blockchain operations. Built on top of the Fireblocks REST API (OpenAPI v1.6.2), this SDK provides type-safe TypeScript interfaces for managing vault accounts, executing transactions, handling NFTs, staking operations, webhooks, and comprehensive compliance workflows. The SDK uses Axios for HTTP communication and supports JWT-based authentication with API key and secret key credentials. The core functionality revolves around the `Fireblocks` client class which provides access to over 40 specialized API modules including vaults, transactions, assets, NFTs, staking, webhooks, external wallets, and various beta features. The SDK supports multiple deployment environments (Sandbox, US, EU, EU2) and offers idempotency support for safe request retries. All API responses are wrapped in `FireblocksResponse` objects that include the data payload, HTTP status code, and response headers. --- ## SDK Initialization Initialize the Fireblocks SDK using environment variables or direct configuration to authenticate with the Fireblocks API. ```typescript import { readFileSync } from 'fs'; import { Fireblocks, BasePath } from '@fireblocks/ts-sdk'; // Option 1: Using environment variables process.env.FIREBLOCKS_BASE_PATH = BasePath.Sandbox; process.env.FIREBLOCKS_API_KEY = "my-api-key"; process.env.FIREBLOCKS_SECRET_KEY = readFileSync("./fireblocks_secret.key", "utf8"); const fireblocks = new Fireblocks(); // Option 2: Direct configuration const fireblocksWithConfig = new Fireblocks({ apiKey: "my-api-key", basePath: BasePath.US, // Production US: 'https://api.fireblocks.io/v1' secretKey: readFileSync("./fireblocks_secret.key", "utf8"), additionalOptions: { userAgent: "MyApp/1.0.0", isAnonymousPlatform: false } }); // Available base paths: // BasePath.Sandbox = 'https://sandbox-api.fireblocks.io/v1' // BasePath.US = 'https://api.fireblocks.io/v1' // BasePath.EU = 'https://eu-api.fireblocks.io/v1' // BasePath.EU2 = 'https://eu2-api.fireblocks.io/v1' ``` --- ## Create Vault Account Create a new vault account to store and manage digital assets within the Fireblocks platform. ```typescript import { Fireblocks, BasePath } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, VaultAccount } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function createVault() { try { const response: FireblocksResponse = await fireblocks.vaults.createVaultAccount({ createVaultAccountRequest: { name: 'My First Vault Account', hiddenOnUI: false, autoFuel: false } }); console.log('Vault created:', response.data); console.log('Vault ID:', response.data.id); console.log('Status Code:', response.statusCode); // Output: { id: "123", name: "My First Vault Account", hiddenOnUI: false, autoFuel: false, assets: [] } } catch (error) { console.error('Error creating vault:', error); } } ``` --- ## List Vault Accounts (Paginated) Retrieve a paginated list of vault accounts with optional filtering and sorting. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, VaultAccountsPagedResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getPagedVaultAccounts() { const response: FireblocksResponse = await fireblocks.vaults.getPagedVaultAccounts({ limit: 20, orderBy: 'ASC', minAmountThreshold: 0 }); console.log('Accounts:', response.data.accounts); console.log('Paging:', response.data.paging); // Output: { accounts: [...], paging: { before: "cursor", after: "cursor" } } // Paginate through results if (response.data.paging?.after) { const nextPage = await fireblocks.vaults.getPagedVaultAccounts({ after: response.data.paging.after, limit: 20 }); } } ``` --- ## Get Vault Account by ID Retrieve details of a specific vault account by its unique identifier. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, VaultAccount } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getVaultAccount(vaultAccountId: string) { const response: FireblocksResponse = await fireblocks.vaults.getVaultAccount({ vaultAccountId: vaultAccountId }); console.log('Vault Account:', response.data); console.log('Name:', response.data.name); console.log('Assets:', response.data.assets); // Output: { id: "123", name: "Treasury", assets: [{ id: "BTC", total: "1.5", ... }] } } // Use 'default' for the default vault account getVaultAccount('default'); getVaultAccount('123'); ``` --- ## Create Vault Account Asset (Wallet) Create a new wallet for a specific asset within a vault account. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, CreateVaultAssetResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function createVaultAsset(vaultAccountId: string, assetId: string) { const response: FireblocksResponse = await fireblocks.vaults.createVaultAccountAsset({ vaultAccountId: vaultAccountId, assetId: assetId, // e.g., 'BTC', 'ETH', 'USDC' idempotencyKey: `create-asset-${Date.now()}` // Optional: prevent duplicate creation }); console.log('Asset created:', response.data); console.log('Address:', response.data.address); // Output: { id: "ETH", address: "0x...", tag: null, ... } } createVaultAsset('123', 'ETH'); createVaultAsset('123', 'BTC'); ``` --- ## Create Transaction Create and submit a new blockchain transaction between vault accounts or external addresses. ```typescript import { Fireblocks, TransferPeerPathType } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, CreateTransactionResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function createTransaction(assetId: string, amount: string, srcId: string, destId: string) { const response: FireblocksResponse = await fireblocks.transactions.createTransaction({ transactionRequest: { assetId: assetId, amount: amount, source: { type: TransferPeerPathType.VaultAccount, id: srcId }, destination: { type: TransferPeerPathType.VaultAccount, id: destId }, note: "Payment transfer", // Optional: specify fee level feeLevel: "MEDIUM" // LOW, MEDIUM, HIGH }, idempotencyKey: `tx-${Date.now()}` }); console.log('Transaction ID:', response.data.id); console.log('Status:', response.data.status); // Output: { id: "abc123", status: "SUBMITTED" } } // Transfer to external wallet async function transferToExternal(assetId: string, amount: string, srcId: string, address: string) { const response = await fireblocks.transactions.createTransaction({ transactionRequest: { assetId: assetId, amount: amount, source: { type: TransferPeerPathType.VaultAccount, id: srcId }, destination: { type: TransferPeerPathType.OneTimeAddress, oneTimeAddress: { address: address } } } }); return response.data; } ``` --- ## Get Transaction by ID Retrieve details of a specific transaction by its Fireblocks transaction ID. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, TransactionResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getTransaction(txId: string) { const response: FireblocksResponse = await fireblocks.transactions.getTransaction({ txId: txId }); console.log('Transaction:', response.data); console.log('Status:', response.data.status); console.log('Amount:', response.data.amount); console.log('Fee:', response.data.fee); console.log('TxHash:', response.data.txHash); // Output: { id: "abc", status: "COMPLETED", amount: 1.5, txHash: "0x...", ... } } // Get transaction by external ID async function getTransactionByExternalId(externalTxId: string) { const response = await fireblocks.transactions.getTransactionByExternalId({ externalTxId: externalTxId }); return response.data; } ``` --- ## List Transactions Retrieve transaction history with filtering options for status, time range, and assets. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, GetTransactionsResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getTransactions() { const response: FireblocksResponse = await fireblocks.transactions.getTransactions({ limit: 50, orderBy: 'createdAt', // Optional filters: status: 'COMPLETED', sourceType: 'VAULT_ACCOUNT', sourceId: '123', assets: 'BTC,ETH', after: '2024-01-01T00:00:00Z' }); response.data.forEach(tx => { console.log(`TX ${tx.id}: ${tx.status} - ${tx.amount} ${tx.assetId}`); }); } // Poll for transaction status async function waitForCompletion(txId: string, maxAttempts = 30) { for (let i = 0; i < maxAttempts; i++) { const response = await fireblocks.transactions.getTransaction({ txId }); const status = response.data.status; if (status === 'COMPLETED' || status === 'FAILED' || status === 'CANCELLED') { return response.data; } await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error('Transaction timeout'); } ``` --- ## Cancel Transaction Cancel a pending transaction that has not yet been signed or broadcast. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, CancelTransactionResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function cancelTransaction(txId: string) { const response: FireblocksResponse = await fireblocks.transactions.cancelTransaction({ txId: txId }); console.log('Cancellation result:', response.data); console.log('Success:', response.data.success); // Output: { success: true } } ``` --- ## Estimate Transaction Fee Estimate the network fee for a transaction before submitting it. ```typescript import { Fireblocks, TransferPeerPathType } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, EstimatedTransactionFeeResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function estimateFee(assetId: string, amount: string, srcId: string, destAddress: string) { const response: FireblocksResponse = await fireblocks.transactions.estimateTransactionFee({ transactionRequest: { assetId: assetId, amount: amount, source: { type: TransferPeerPathType.VaultAccount, id: srcId }, destination: { type: TransferPeerPathType.OneTimeAddress, oneTimeAddress: { address: destAddress } } } }); console.log('Low fee:', response.data.low); console.log('Medium fee:', response.data.medium); console.log('High fee:', response.data.high); // Output: { low: { networkFee: "0.0001" }, medium: { networkFee: "0.0002" }, high: { networkFee: "0.0005" } } } // Estimate network fee for an asset async function estimateNetworkFee(assetId: string) { const response = await fireblocks.transactions.estimateNetworkFee({ assetId: assetId }); return response.data; } ``` --- ## Create External Wallet Create an external wallet to whitelist external addresses for transfers. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, UnmanagedWallet, ExternalWalletAsset } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function createExternalWallet(name: string) { const response: FireblocksResponse = await fireblocks.externalWallets.createExternalWallet({ createWalletRequest: { name: name, customerRefId: 'customer-123' // Optional: AML reference } }); console.log('External wallet created:', response.data.id); return response.data; } async function addAssetToExternalWallet(walletId: string, assetId: string, address: string) { const response: FireblocksResponse = await fireblocks.externalWallets.addAssetToExternalWallet({ walletId: walletId, assetId: assetId, addAssetToExternalWalletRequest: { address: address, tag: null // For assets like XRP that require a tag } }); console.log('Asset added:', response.data); // Output: { id: "ETH", status: "WAITING_FOR_APPROVAL", address: "0x...", ... } } // Full workflow async function setupExternalWallet() { const wallet = await createExternalWallet('Partner Treasury'); await addAssetToExternalWallet(wallet.id!, 'ETH', '0x742d35Cc6634C0532925a3b844Bc9e7595f...'); await addAssetToExternalWallet(wallet.id!, 'BTC', 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh'); } ``` --- ## Get NFT Token Data Retrieve metadata and ownership information for NFT tokens. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, TokenResponse, GetNFTsResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getNFT(tokenId: string) { const response: FireblocksResponse = await fireblocks.nfts.getNFT({ id: tokenId // e.g., 'NFT-abcdefabcdefabcdefabcdefabcdefabcdefabcd' }); console.log('NFT:', response.data); console.log('Collection:', response.data.collection); console.log('Metadata:', response.data.metadata); } // Get multiple NFTs by IDs async function getNFTs(tokenIds: string[]) { const response: FireblocksResponse = await fireblocks.nfts.getNFTs({ ids: tokenIds.join(',') // Up to 100 IDs }); return response.data; } // List owned NFTs (paginated) async function listOwnedNFTs() { const response = await fireblocks.nfts.getOwnershipTokens({ blockchainDescriptor: 'ETH', vaultAccountIds: '123,456', limit: 50 }); response.data.data?.forEach(token => { console.log(`Token: ${token.id} - ${token.collection?.name}`); }); } ``` --- ## Staking Operations Stake, unstake, and manage staking positions across supported blockchains. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, StakeResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); // Approve staking provider terms (required first time) async function approveStakingTerms() { await fireblocks.staking.approveTermsOfServiceByProviderId({ providerId: 'kiln' }); } // Stake assets async function stake(chainDescriptor: string, vaultId: string, providerId: string, amount: string) { const response: FireblocksResponse = await fireblocks.staking.stake({ chainDescriptor: chainDescriptor, // e.g., 'ETH', 'SOL' stakeRequest: { vaultAccountId: vaultId, providerId: providerId, stakeAmount: amount } }); console.log('Stake initiated:', response.data); } // Get staking positions async function getStakingPositions() { const response = await fireblocks.staking.getAllDelegations({}); response.data.data?.forEach(position => { console.log(`Position: ${position.id} - ${position.amount} ${position.chainDescriptor}`); console.log(`Status: ${position.status}`); }); } // Unstake async function unstake(chainDescriptor: string, positionId: string, amount: string) { const response = await fireblocks.staking.unstake({ chainDescriptor: chainDescriptor, unstakeRequest: { id: positionId, amount: amount } }); return response.data; } // Claim rewards async function claimRewards(chainDescriptor: string, positionId: string) { await fireblocks.staking.claimRewards({ chainDescriptor: chainDescriptor, claimRewardsRequest: { id: positionId } }); } ``` --- ## Webhooks Management Configure and manage webhook notifications for transaction and account events. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; import type { FireblocksResponse, Webhook, ResendWebhooksResponse } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); // Create a webhook (v2 API) async function createWebhook(url: string, events: string[]) { const response: FireblocksResponse = await fireblocks.webhooksV2.createWebhook({ createWebhookRequest: { url: url, events: events // e.g., ['transaction.created', 'transaction.status.updated'] } }); console.log('Webhook created:', response.data.id); return response.data; } // List webhooks async function listWebhooks() { const response = await fireblocks.webhooksV2.getWebhooks({}); response.data.data?.forEach(webhook => { console.log(`Webhook: ${webhook.id} - ${webhook.url}`); console.log(`Events: ${webhook.events?.join(', ')}`); }); } // Resend failed webhooks async function resendFailedWebhooks() { const response: FireblocksResponse = await fireblocks.webhooks.resendWebhooks({}); console.log('Messages resent:', response.data.messagesCount); } // Resend webhooks for specific transaction async function resendTransactionWebhooks(txId: string) { const response = await fireblocks.webhooks.resendTransactionWebhooks({ txId: txId, resendTransactionWebhooksRequest: { resendCreated: true, resendStatusUpdated: true } }); return response.data; } ``` --- ## Supported Blockchains and Assets Query supported blockchains and assets on the Fireblocks platform. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); // List supported assets async function listAssets() { const response = await fireblocks.blockchainsAssets.listAssets({ scope: 'Global', // or 'Local' for workspace-specific deprecated: false }); response.data.assets?.forEach(asset => { console.log(`${asset.id}: ${asset.name} (${asset.type})`); }); } // List blockchains async function listBlockchains() { const response = await fireblocks.blockchainsAssets.listBlockchains({}); response.data.blockchains?.forEach(chain => { console.log(`${chain.id}: ${chain.name}`); }); } // Get specific asset info async function getAsset(assetId: string) { const response = await fireblocks.blockchainsAssets.getAsset({ id: assetId }); console.log('Asset:', response.data); console.log('Decimals:', response.data.onchain?.decimals); } ``` --- ## Error Handling Handle API errors using the FireblocksError class with detailed response information. ```typescript import { Fireblocks, FireblocksError } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function safeApiCall() { try { const response = await fireblocks.vaults.getVaultAccount({ vaultAccountId: 'non-existent-id' }); return response.data; } catch (error) { if (error instanceof FireblocksError) { console.error('API Error:', error.message); console.error('Status Code:', error.response?.statusCode); console.error('Response Headers:', error.response?.headers); console.error('Request ID:', error.response?.headers['x-request-id']); // Handle specific error codes if (error.response?.statusCode === 404) { console.log('Vault account not found'); } else if (error.response?.statusCode === 401) { console.log('Authentication failed - check API credentials'); } else if (error.response?.statusCode === 429) { console.log('Rate limited - retry after delay'); } } else { console.error('Unexpected error:', error); } throw error; } } // Retry with exponential backoff async function retryWithBackoff(fn: () => Promise, maxRetries = 3): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (error) { if (error instanceof FireblocksError && error.response?.statusCode === 429) { const delay = Math.pow(2, attempt) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } throw new Error('Max retries exceeded'); } ``` --- ## Audit Logs Retrieve audit logs for workspace activity monitoring and compliance. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); async function getAuditLogs() { const response = await fireblocks.auditLogs.getAuditLogs({ timePeriod: 'DAY', // DAY, WEEK, MONTH // Optional filters: // cursor: 'pagination-cursor', // limit: 50 }); response.data.data?.forEach(log => { console.log(`[${log.timestamp}] ${log.user}: ${log.event}`); console.log(' Subject:', log.subject); }); // Paginate if (response.data.cursor) { const nextPage = await fireblocks.auditLogs.getAuditLogs({ cursor: response.data.cursor }); } } ``` --- ## Bulk Operations Perform bulk operations for creating multiple vault accounts or wallets efficiently. ```typescript import { Fireblocks } from '@fireblocks/ts-sdk'; const fireblocks = new Fireblocks(); // Bulk create vault accounts async function bulkCreateVaults(count: number, prefix: string) { const response = await fireblocks.vaults.createMultipleAccounts({ createMultipleAccountsRequest: { count: count, asset: 'ETH', vaultNamePrefix: prefix, autoFuel: false } }); console.log('Job created:', response.data.jobId); return response.data.jobId; } // Check bulk job status async function checkBulkJobStatus(jobId: string) { const response = await fireblocks.vaults.getCreateMultipleVaultAccountsJobStatus({ jobId: jobId }); console.log('Job status:', response.data.status); console.log('Progress:', response.data.completedTasksCount, '/', response.data.totalTasksCount); return response.data; } // Bulk create wallets for existing vault async function bulkCreateAssets(vaultAccountId: string, assetIds: string[]) { const response = await fireblocks.assets.createAssetsBulk({ createAssetsBulkRequest: { vaultAccountId: vaultAccountId, assetIds: assetIds } }); return response.data.jobId; } ``` --- ## Summary The Fireblocks TypeScript SDK provides a comprehensive interface for building secure digital asset applications. Core use cases include treasury management (vault accounts, asset wallets, balance tracking), transaction processing (transfers between vaults, external payments, fee estimation), compliance workflows (external wallet whitelisting, AML reference IDs, audit logs), and advanced operations (NFT management, staking, webhooks). The SDK's type-safe design ensures compile-time validation of API parameters and responses. Integration patterns typically involve initializing the SDK with environment-specific credentials, then accessing API modules through the `Fireblocks` client instance (e.g., `fireblocks.vaults`, `fireblocks.transactions`). All API calls return `FireblocksResponse` objects containing the typed response data, HTTP status code, and headers. For production deployments, implement proper error handling with `FireblocksError`, use idempotency keys for critical operations, and leverage webhooks for real-time transaction status updates rather than polling. The SDK supports both promise-based and async/await patterns for flexible integration with existing codebases.