BtcClient API Reference
Esta página aún no está disponible en tu idioma.
The BtcClient provides Bitcoin wallet management, transactions and fee information through a mempool.space-style (Esplora) API: mempool.space for mainnet, and the VerifiedX signet’s API for testnet.
Constructor
Section titled “Constructor”new btc.BtcClient(network, options?)
Section titled “new btc.BtcClient(network, options?)”Creates a new BtcClient instance.
Parameters:
network(‘mainnet’ | ‘testnet’): The Bitcoin network to connect to.'testnet'is the Bitcoin network the VerifiedX testnet follows: the VerifiedX signet.options(optional):{ dryRun?: boolean, apiBaseUrl?: string }.apiBaseUrloverrides the Esplora API origin, including/api. Defaults:https://mempool.space/apion mainnet; on testnethttps://signet.verifiedx.io/apifrom SDK 3.7.0. SDK 3.6.0 and earlier default testnet to Bitcoin testnet4, which the VerifiedX testnet no longer uses: pass{ apiBaseUrl: 'https://signet.verifiedx.io/api' }with those versions.
Example:
import { btc } from 'vfx-web-sdk';
const client = new btc.BtcClient('testnet');const mainnetClient = new btc.BtcClient('mainnet');
// SDK 3.6.0 and earlier: point testnet at the VerifiedX signetconst signetClient = new btc.BtcClient('testnet', { apiBaseUrl: 'https://signet.verifiedx.io/api' });Wallet Generation
Section titled “Wallet Generation”generatePrivateKey()
Section titled “generatePrivateKey()”Generates a new random Bitcoin wallet with all address types.
Returns: BtcKeypair - Complete keypair with multiple address formats
Response Object:
{ privateKey: string; publicKey: string; wif: string; address: string; // Default address (bech32) addresses: { p2pkh: string; // Legacy (starts with 1) p2sh: string; // Nested SegWit (starts with 3) bech32: string; // Native SegWit (starts with bc1/tb1) bech32m: string; // Taproot (starts with bc1p/tb1p) };}Example:
const keypair = client.generatePrivateKey();console.log('Default address:', keypair.address);console.log('Legacy address:', keypair.addresses.p2pkh);console.log('SegWit address:', keypair.addresses.bech32);console.log('Taproot address:', keypair.addresses.bech32m);generateMnemonic()
Section titled “generateMnemonic()”Generates a new wallet with BIP39 mnemonic phrase.
Returns: BtcMnemonicKeypair - Keypair with mnemonic for recovery
Response Object:
{ mnemonic: string; privateKey: string; publicKey: string; wif: string; address: string; addresses: { p2pkh: string; p2sh: string; bech32: string; bech32m: string; };}Example:
const wallet = client.generateMnemonic();console.log('Mnemonic:', wallet.mnemonic);console.log('Address:', wallet.address);privateKeyFromMnemonic(mnemonic, index)
Section titled “privateKeyFromMnemonic(mnemonic, index)”Derives a private key from a mnemonic phrase.
Parameters:
mnemonic(string): The BIP39 mnemonic phraseindex(number): The derivation index (typically 0)
Returns: BtcKeypair - Derived keypair
Example:
const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";const restoredWallet = client.privateKeyFromMnemonic(mnemonic, 0);console.log('Restored address:', restoredWallet.address);publicFromPrivate(privateKey)
Section titled “publicFromPrivate(privateKey)”Derives public key and addresses from a private key.
Parameters:
privateKey(string): The private key in hexadecimal format
Returns: BtcKeypair - Complete keypair derived from private key
Example:
const privateKey = "your-private-key-hex";const keypair = client.publicFromPrivate(privateKey);addressFromWif(wif)
Section titled “addressFromWif(wif)”Imports a wallet from Wallet Import Format (WIF).
Parameters:
wif(string): The WIF string
Returns: BtcKeypair - Keypair imported from WIF
Example:
const wif = "your-wif-string";const importedWallet = client.addressFromWif(wif);generateEmailKeypair(email, password, index)
Section titled “generateEmailKeypair(email, password, index)”Generates a deterministic wallet from email and password.
Parameters:
email(string): Email addresspassword(string): Passwordindex(number): Derivation index
Returns: BtcKeypair - Deterministic keypair
Example:
const emailWallet = client.generateEmailKeypair( "user@example.com", "secure-password", 0);Address Information
Section titled “Address Information”getAddressInfo(address)
Section titled “getAddressInfo(address)”Retrieves detailed information about a Bitcoin address.
Parameters:
address(string): The Bitcoin address to query
Returns: Promise<BtcAddressInfo> - Address information
Response Object:
{ address: string; balance: number; // Balance in satoshis totalRecieved: number; // Total received in satoshis totalSent: number; // Total sent in satoshis txCount: number; // Number of transactions}Example:
const addressInfo = await client.getAddressInfo("bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh");console.log(`Balance: ${addressInfo.balance} satoshis`);console.log(`BTC Balance: ${addressInfo.balance / 100000000} BTC`);getTransactions(address)
Section titled “getTransactions(address)”Retrieves transaction history for an address.
Parameters:
address(string): The Bitcoin address to query
Returns: Promise<BtcTransaction[]> - Array of transactions
Transaction Object:
{ txid: string; version: number; locktime: number; vin: Array<{ txid: string; vout: number; prevout?: { scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; }; scriptsig: string; scriptsig_asm: string; witness: string[]; is_coinbase: boolean; sequence: number; }>; vout: Array<{ scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; }>; size: number; weight: number; fee: number; status: { confirmed: boolean; block_height?: number; block_hash?: string; block_time?: number; };}Example:
const transactions = await client.getTransactions(address);transactions.forEach(tx => { console.log(`TX: ${tx.txid}`); console.log(`Confirmed: ${tx.status.confirmed}`); console.log(`Fee: ${tx.fee} satoshis`);});Transaction Operations
Section titled “Transaction Operations”sendBtc(wif, toAddress, amountSats, feeRate?)
Section titled “sendBtc(wif, toAddress, amountSats, feeRate?)”Sends Bitcoin to another address (simplified method).
Parameters:
wif(string): Sender’s Wallet Import Format keytoAddress(string): Recipient’s Bitcoin addressamountSats(number): Amount to send in satoshisfeeRate(number, optional): Fee rate in sat/vB (uses network estimate if not provided)
Returns: Promise<string> - Transaction ID
Example:
const txId = await client.sendBtc( wallet.wif, "bc1qrecipient...", 50000, // 0.0005 BTC 20 // 20 sat/vB fee rate);console.log('Transaction sent:', txId);createTransaction(wif, toAddress, amountSats, feeRate?)
Section titled “createTransaction(wif, toAddress, amountSats, feeRate?)”Creates a Bitcoin transaction without broadcasting.
Parameters:
wif(string): Sender’s WIFtoAddress(string): Recipient’s addressamountSats(number): Amount in satoshisfeeRate(number, optional): Fee rate in sat/vB
Returns: Promise<TransactionResult> - Transaction creation result
Response Object:
{ success: boolean; result?: string; // Raw transaction hex error?: string; // Error message if failed}Example:
const result = await client.createTransaction( wallet.wif, "bc1qrecipient...", 100000, 15);
if (result.success) { console.log('Transaction created:', result.result);} else { console.error('Failed:', result.error);}broadcastTransaction(rawTransaction)
Section titled “broadcastTransaction(rawTransaction)”Broadcasts a raw transaction to the Bitcoin network.
Parameters:
rawTransaction(string): Raw transaction hex
Returns: Promise<TransactionResult> - Broadcast result
Example:
const broadcastResult = await client.broadcastTransaction(rawTransaction);if (broadcastResult.success) { console.log('Transaction ID:', broadcastResult.result);}Network Information
Section titled “Network Information”getFeeRates()
Section titled “getFeeRates()”Retrieves current network fee rates.
Returns: Promise<BtcFeeRates | null> - Current fee rates or null if unavailable
Response Object:
{ fastestFee: number; // Fastest confirmation (sat/vB) halfHourFee: number; // ~30 minutes (sat/vB) hourFee: number; // ~1 hour (sat/vB) economyFee: number; // Economic rate (sat/vB) minimumFee: number; // Minimum fee (sat/vB)}Example:
const fees = await client.getFeeRates();if (fees) { console.log('Fast fee:', fees.fastestFee, 'sat/vB'); console.log('Standard fee:', fees.hourFee, 'sat/vB'); console.log('Economy fee:', fees.economyFee, 'sat/vB');}Message Signing
Section titled “Message Signing”getSignature(message, privateKey)
Section titled “getSignature(message, privateKey)”Signs a message with a private key.
Parameters:
message(string): The message to signprivateKey(string): The private key in hex format
Returns: string - Message signature
Example:
const signature = client.getSignature("Hello Bitcoin!", privateKey);console.log('Signature:', signature);getSignatureFromWif(message, wif)
Section titled “getSignatureFromWif(message, wif)”Signs a message using a WIF key.
Parameters:
message(string): The message to signwif(string): The WIF key
Returns: string - Message signature
Example:
const signature = client.getSignatureFromWif("Hello Bitcoin!", wallet.wif);BtcKeypair
Section titled “BtcKeypair”interface BtcKeypair { privateKey: string; publicKey: string; wif: string; address: string; addresses: { p2pkh: string; p2sh: string; bech32: string; bech32m: string; };}BtcMnemonicKeypair
Section titled “BtcMnemonicKeypair”interface BtcMnemonicKeypair extends BtcKeypair { mnemonic: string;}BtcAddressInfo
Section titled “BtcAddressInfo”interface BtcAddressInfo { address: string; balance: number; totalRecieved: number; totalSent: number; txCount: number;}TransactionResult
Section titled “TransactionResult”interface TransactionResult { success: boolean; result?: string; error?: string;}BtcFeeRates
Section titled “BtcFeeRates”interface BtcFeeRates { fastestFee: number; halfHourFee: number; hourFee: number; economyFee: number; minimumFee: number;}Error Handling
Section titled “Error Handling”Bitcoin operations can fail for various reasons. Always wrap async calls in try-catch blocks:
Insufficient Balance
Section titled “Insufficient Balance”try { await client.sendBtc(wif, toAddress, amount);} catch (error) { if (error.message.includes('insufficient')) { console.log('Not enough Bitcoin balance'); }}Invalid Address
Section titled “Invalid Address”try { await client.getAddressInfo(address);} catch (error) { if (error.message.includes('address')) { console.log('Invalid Bitcoin address format'); }}Network Errors
Section titled “Network Errors”try { const fees = await client.getFeeRates();} catch (error) { console.log('Network connectivity issue'); // Fallback to default fee rates}Best Practices
Section titled “Best Practices”Security
Section titled “Security”- Secure WIF storage: WIF keys provide full control over funds
- Validate addresses: Always verify recipient addresses before sending
- Use appropriate fee rates: Balance between speed and cost
Performance
Section titled “Performance”- Cache fee rates: Don’t fetch fees for every transaction
- Batch address lookups: Group multiple address queries when possible
- Handle rate limits: the mempool.space API has rate limiting
Address Types
Section titled “Address Types”- Use bech32 for new applications: Lower fees and better support
- Support multiple formats: For maximum compatibility
- Default to bech32: Unless specific requirements dictate otherwise
Constants
Section titled “Constants”Conversion Constants
Section titled “Conversion Constants”const BTC_TO_SATOSHI_MULTIPLIER = 100000000;const SATOSHI_TO_BTC_MULTIPLIER = 0.00000001;Networks
Section titled “Networks”The client automatically configures the correct Bitcoin network based on the constructor parameter:
'mainnet': Bitcoin mainnet'testnet': the VerifiedX signet, a private Bitcoin signet with 10-minute blocks andtb1…addresses (explorerhttps://signet.verifiedx.io). Test BTC comes from the testnet faucet (Signet BTC tab).
Examples
Section titled “Examples”Complete Bitcoin Wallet Implementation
Section titled “Complete Bitcoin Wallet Implementation”import { btc } from 'vfx-web-sdk';
class BitcoinWallet { private client: btc.BtcClient; private keypair: btc.BtcKeypair | null = null;
constructor(network: 'mainnet' | 'testnet' = 'testnet') { this.client = new btc.BtcClient(network); }
createWallet(): { mnemonic: string; address: string } { const wallet = this.client.generateMnemonic(); this.keypair = wallet;
return { mnemonic: wallet.mnemonic, address: wallet.address }; }
restoreWallet(mnemonic: string, index: number = 0): string { this.keypair = this.client.privateKeyFromMnemonic(mnemonic, index); return this.keypair.address; }
async getBalance(): Promise<number> { if (!this.keypair) throw new Error('Wallet not initialized');
const info = await this.client.getAddressInfo(this.keypair.address); return info.balance; }
async getBalanceBTC(): Promise<number> { const satoshis = await this.getBalance(); return satoshis / 100000000; }
async send(toAddress: string, amountSats: number, feeRate?: number): Promise<string> { if (!this.keypair) throw new Error('Wallet not initialized');
return await this.client.sendBtc( this.keypair.wif, toAddress, amountSats, feeRate ); }
async getTransactionHistory(): Promise<btc.BtcTransaction[]> { if (!this.keypair) throw new Error('Wallet not initialized');
return await this.client.getTransactions(this.keypair.address); }
signMessage(message: string): string { if (!this.keypair) throw new Error('Wallet not initialized');
return this.client.getSignatureFromWif(message, this.keypair.wif); }}Migration Notes
Section titled “Migration Notes”From Direct vfx-btc-js Usage
Section titled “From Direct vfx-btc-js Usage”If migrating from direct vfx-btc-js usage:
// Old wayimport BtcClient from 'vfx-btc-js';const client = new BtcClient('testnet');
// New wayimport { btc } from 'vfx-web-sdk';const client = new btc.BtcClient('testnet');API Compatibility
Section titled “API Compatibility”The BtcClient maintains full compatibility with the original vfx-btc-js API while being integrated into the unified SDK.
Integration with VFX
Section titled “Integration with VFX”For cross-chain applications combining Bitcoin and VFX functionality, see the Cross-Chain Integration Guide.