UNPKG

@btc-stamps/tx-builder

Version:

Transaction builder for Bitcoin Stamps and SRC-20 tokens with advanced UTXO selection

1,526 lines (1,496 loc) 50.2 kB
import { T as TransactionBuilder, F as FeeEstimator } from './script-builder-BLrgaCPC.cjs'; export { c as EnhancedPSBTBuilder, a as PSBTBuilder, S as ScriptBuilder, d as createSrc20FeeCalculator } from './script-builder-BLrgaCPC.cjs'; export { B as BaseProvider, E as ElectrumXConfig, k as ElectrumXFeeEstimator, b as ElectrumXProvider, F as FeeEstimate } from './electrumx-fee-estimator-D567GEpl.cjs'; import { U as UTXO } from './provider.interface-53Rg30ZJ.cjs'; export { B as Balance, I as IUTXOProvider, T as Transaction } from './provider.interface-53Rg30ZJ.cjs'; import { B as BaseSelector } from './selector-factory-DVKbZKn-.cjs'; export { A as AccumulativeSelector, b as BlackjackSelector, a as BranchAndBoundSelector, K as KnapsackSelector, M as MockProtectionDetector, P as ProtectionAwareSelector, S as SelectorFactory, W as WasteOptimizedSelector } from './selector-factory-DVKbZKn-.cjs'; import { S as SelectionOptions, E as EnhancedSelectionResult, d as SelectorFactory } from './selector.interface-BqSIZhFv.cjs'; export { I as IUTXOSelector, a as SelectionResult } from './selector.interface-BqSIZhFv.cjs'; import { O as OrdinalsDetector, U as UTXO$1, I as InscriptionData, b as SRC20DeployData, c as SRC20MintData, d as SRC20TransferData, a as SRC20BuilderOptions, S as SRC20Options } from './src20.interface-4GEU42wj.cjs'; export { A as AggregationStrategy, D as DetectionStrategy, E as EncodingResult, H as HiroOrdinalsDetector, g as HiroOrdinalsDetectorOptions, k as IDataEncoder, M as MultiAssetProtectionDetector, h as MultiAssetProtectionDetectorOptions, f as OrdServerDetector, j as OrdServerDetectorOptions, e as OrdinalsMultiProviderDetector, i as OrdinalsMultiProviderDetectorOptions, l as SRC20Data, m as SRC20Operation } from './src20.interface-4GEU42wj.cjs'; import { I as IProtectionDetector, a as ProtectedAssetData } from './protection.interface-fY791gw8.cjs'; export { P as ProtectionDetectorConfig } from './protection.interface-fY791gw8.cjs'; import { BitcoinStampData } from './encoders/index.cjs'; export { BitcoinStampEncodingOptions, BitcoinStampsEncoder, CounterpartyIssuanceBuilder, P2WSHEncoder, SRC20Encoder, SRC20Helper } from './encoders/index.cjs'; import * as bitcoin from 'bitcoinjs-lib'; import { Psbt, Network } from 'bitcoinjs-lib'; export { Transaction as BTCTransaction, Network, Psbt, crypto, networks, opcodes, script } from 'bitcoinjs-lib'; import { Buffer } from 'node:buffer'; import { O as OutputType, D as DustThresholds } from './fee-normalizer-BGRDTCVR.cjs'; import 'ecpair'; /** * SRC-20 Token Builder Type Definitions * * Types for SRC-20 token transaction building */ /** * Token transfer transaction options */ interface TokenTransferOptions { /** Token ticker symbol */ tick: string; /** Amount to transfer */ amount: string; /** Sender address */ fromAddress: string; /** Recipient address */ toAddress: string; /** Fee rate in satoshis per byte */ feeRate?: number; /** Dust value for outputs */ dustValue?: number; /** Enable RBF */ enableRbf?: boolean; } /** * Token mint transaction options */ interface TokenMintOptions { /** Token ticker symbol */ tick: string; /** Amount to mint */ amount: string; /** Destination address for minted tokens */ mintingAddress: string; /** Fee rate in satoshis per byte */ feeRate?: number; /** Dust value for outputs */ dustValue?: number; /** Enable RBF */ enableRbf?: boolean; } /** * Token deployment options */ interface TokenDeployOptions { /** Token ticker symbol */ tick: string; /** Maximum supply */ max: string; /** Mint limit per transaction */ lim: string; /** Number of decimals */ dec?: number; /** Deploying address */ deployingAddress: string; /** Fee rate in satoshis per byte */ feeRate?: number; /** Dust value for outputs */ dustValue?: number; /** Enable RBF */ enableRbf?: boolean; /** Twitter/X handle */ x?: string; /** Token website */ web?: string; /** Email contact */ email?: string; /** Telegram link */ tg?: string; /** Token description */ description?: string; /** Token image URL */ img?: string; /** Token icon URL */ icon?: string; } /** * SRC-20 build result */ interface SRC20BuildResult { /** Built PSBT ready for signing */ psbt: Psbt; /** Total input value in satoshis */ totalInputValue: number; /** Total output value in satoshis */ totalOutputValue: number; /** Transaction fee in satoshis */ fee: number; /** Change amount in satoshis */ changeAmount: number; /** Data outputs */ dataOutputs: any[]; /** Estimated transaction size in bytes */ estimatedTxSize: number; /** Dust value used */ dustValue: number; } /** * Asset Validation Service * * Provides Bitcoin Stamp asset name validation and generation functionality. * Integrates with Counterparty API to check asset availability and generate * collision-free asset names. * * Based on BTCStampsExplorer/server/services/stamp/stampValidationService.ts */ /** * Configuration options for asset validation */ interface AssetValidationConfig { /** Maximum iterations when generating available asset names */ maxIterations?: number; /** Minimum asset ID for A-prefixed numeric assets */ minAssetId?: bigint; /** Maximum asset ID for A-prefixed numeric assets */ maxAssetId?: bigint; /** Timeout for API requests in milliseconds */ timeout?: number; /** Base URL for Counterparty API */ apiUrl?: string; /** Maximum number of retries for API requests */ maxRetries?: number; } /** * Result of asset validation operations */ interface AssetValidationResult { /** Whether the asset name format is valid */ isValid: boolean; /** Whether the asset is available for registration */ isAvailable: boolean; /** Normalized asset name */ normalizedName: string; /** List of validation errors */ errors: string[]; /** List of validation warnings */ warnings: string[]; } /** * Bitcoin Stamp Asset Validation Service * * Handles: * - Asset name format validation (A-prefixed numeric and alphabetic names) * - Asset availability checking via Counterparty API * - Available asset name generation with collision avoidance * - CPID format validation for Bitcoin Stamps */ declare class AssetValidationService { private readonly config; constructor(config?: AssetValidationConfig); /** * Validate and prepare an asset name for use * * @param assetName Optional asset name to validate, generates one if not provided * @returns Promise<string> Valid, available asset name * @throws Error if validation fails or no available asset can be generated */ validateAndPrepareAssetName(assetName?: string): Promise<string>; /** * Check if an asset is available for registration * * @param assetName Asset name to check * @returns Promise<boolean> True if asset is available */ checkAssetAvailability(assetName: string): Promise<boolean>; /** * Generate an available asset name * * @returns Promise<string> Available A-prefixed numeric asset name * @throws Error if no available asset can be generated within maxIterations */ generateAvailableAssetName(): Promise<string>; /** * Validate asset name format and availability * * @param assetName Asset name to validate * @returns Promise<AssetValidationResult> Validation result */ validateAssetName(assetName: string): Promise<AssetValidationResult>; /** * Get asset information for a specific asset name * Used for asset availability checking */ private getAssetInfo; /** * Call Counterparty API with retry logic and exponential backoff */ private callCounterpartyAPI; /** * Validate CPID format * * Supports: * - A-prefixed numeric assets: A95428956662000000 * - Alphabetic assets: MYTOKEN (max 13 characters) * - Sub-assets: A12345.SUBASSET * * @param value Asset name to validate * @returns boolean True if format is valid */ private isValidCPID; /** * Generate random BigInt in specified range * * @param min Minimum value (inclusive) * @param max Maximum value (exclusive) * @returns BigInt Random value in range */ private generateRandomBigInt; } /** * Ordinals Aware Selector * * UTXO selector that integrates with ordinals detection to avoid spending * UTXOs that contain valuable inscriptions or ordinals. */ /** * Options for OrdinalsAwareSelector configuration */ interface OrdinalsAwareSelectorOptions { /** Whether to cache detection results to improve performance */ cacheResults?: boolean; /** TTL for cache entries in milliseconds (default: 5 minutes) */ cacheTtl?: number; /** Whether to allow protected UTXOs as a last resort */ allowProtectedIfNecessary?: boolean; } /** * Ordinals-aware UTXO selector * * This selector wraps another selector and filters out UTXOs that contain * ordinals or inscriptions before performing selection. It provides: * * - Automatic ordinals detection and filtering * - Caching of detection results for performance * - Fallback strategies when protected UTXOs are the only option * - Clear reporting of when protected UTXOs are used */ declare class OrdinalsAwareSelector extends BaseSelector { private detector; private fallbackSelector; private cacheResults; private cacheTtl; private allowProtectedIfNecessary; private protectionCache; constructor(detector: OrdinalsDetector, fallbackSelector: BaseSelector, options?: OrdinalsAwareSelectorOptions); getName(): string; /** * Select UTXOs while avoiding ordinals/inscriptions */ select(utxos: UTXO[], options: SelectionOptions): EnhancedSelectionResult; /** * Pre-populate the protection cache for a set of UTXOs * This should be called before select() for optimal performance */ populateProtectionCache(utxos: UTXO[]): Promise<void>; /** * Clear the protection cache */ clearProtectionCache(): void; /** * Check if a UTXO is cached as protected */ private isCachedAsProtected; /** * Check if a cache entry is valid (exists and not expired) */ private isCacheValid; /** * Get protection summary for debugging */ getProtectionSummary(): { cacheSize: number; protectedCount: number; cacheEnabled: boolean; cacheTtl: number; }; /** * Get the underlying detector */ getDetector(): OrdinalsDetector; /** * Get the fallback selector */ getFallbackSelector(): BaseSelector; /** * Check if protected UTXOs are allowed as last resort */ isProtectedAllowed(): boolean; /** * Set whether to allow protected UTXOs as last resort */ setAllowProtected(allow: boolean): void; } /** * Counterparty API Detector * * Detects Counterparty tokens (SRC-20, Bitcoin Stamps, etc.) using the Counterparty API. * Provides fail-safe detection that returns false on any error. */ /** * Configuration options for CounterpartyDetector */ interface CounterpartyDetectorOptions { /** Base URL for Counterparty API (default: https://api.counterparty.io:4000) */ apiUrl?: string; /** Request timeout in milliseconds (default: 5000) */ timeout?: number; /** Maximum number of retries (default: 3) */ maxRetries?: number; } /** * Counterparty API detector implementation * * Integrates with the Counterparty API to detect: * - SRC-20 tokens * - Bitcoin Stamps * - Other Counterparty assets * * Features: * - Fail-safe operation (never throws, returns false on errors) * - Configurable timeout and retry logic * - Exponential backoff for rate limiting * - JSON-RPC 2.0 protocol support */ declare class CounterpartyDetector implements IProtectionDetector { private readonly apiUrl; private readonly timeout; private readonly maxRetries; constructor(options?: CounterpartyDetectorOptions); /** * Check if a UTXO contains protected Counterparty tokens */ isProtectedUtxo(utxo: UTXO$1): Promise<boolean>; /** * Get detailed asset data for a protected UTXO */ getAssetData(utxo: UTXO$1): Promise<ProtectedAssetData | null>; /** * Get balances for an address using Counterparty API */ private getBalances; /** * Fetch with retry logic and exponential backoff */ private fetchWithRetry; } /** * Mock Ordinals Detector * * Mock implementation of OrdinalsDetector for testing and development. * Allows manual configuration of protected UTXOs and inscription data. */ /** * Mock implementation of OrdinalsDetector for testing * * Allows pre-configuration of which UTXOs should be considered protected * and what inscription data they should return. */ declare class MockOrdinalsDetector implements OrdinalsDetector { private protectedUtxos; private inscriptionData; constructor(protectedUtxos?: string[], inscriptionData?: Map<string, InscriptionData>); /** * Check if a UTXO contains protected ordinals/inscriptions */ isProtectedUtxo(utxo: UTXO): Promise<boolean>; /** * Get inscription data for a UTXO if it contains an inscription */ getInscriptionData(utxo: UTXO): Promise<InscriptionData | null>; /** * Get asset data for a UTXO (combines protected status and inscription data) */ getAssetData(utxo: UTXO): Promise<ProtectedAssetData | null>; /** * Add a protected UTXO with optional inscription data */ addProtectedUtxo(utxoId: string, inscriptionData?: InscriptionData): void; /** * Remove a protected UTXO */ removeProtectedUtxo(utxoId: string): void; /** * Clear all protected UTXOs and inscription data */ clearProtectedUtxos(): void; /** * Get all protected UTXO IDs */ getProtectedUtxoIds(): string[]; /** * Get all inscription data */ getAllInscriptionData(): Map<string, InscriptionData>; /** * Set inscription data for a specific UTXO */ setInscriptionData(utxoId: string, data: InscriptionData): void; /** * Create a default inscription data object for testing */ static createDefaultInscriptionData(overrides?: Partial<InscriptionData>): InscriptionData; } /** * SRC-20 Token Transfer Builder * * Implements SRC-20 token transfer and minting transaction construction with proper UTXO management, * P2WSH encoding, and high-value UTXO protection. */ /** * SRC-20 transaction builder interface */ interface ISRC20TokenBuilder { /** * Build a DEPLOY transaction for creating a new SRC-20 token */ buildDeploy(deployData: SRC20DeployData): Promise<bitcoin.Transaction>; /** * Build a MINT transaction for minting SRC-20 tokens */ buildMint(mintData: SRC20MintData): Promise<bitcoin.Transaction>; /** * Build a TRANSFER transaction for sending SRC-20 tokens */ buildTransfer(transferData: SRC20TransferData): Promise<bitcoin.Transaction>; } /** * High-level builder for creating SRC-20 token transactions * * @remarks * SRC20TokenBuilder simplifies the creation of SRC-20 token transactions by handling: * - Token deployment, minting, and transfer operations * - Automatic encoding of SRC-20 protocol data * - Multi-signature output creation for data storage * - UTXO selection with asset protection * - Optimized fee calculation for token transactions * * Features: * - Support for all SRC-20 operations (DEPLOY, MINT, TRANSFER) * - Automatic data validation and encoding * - Built-in UTXO protection for special assets * - Configurable fee rates and selection algorithms * - Compatible with Stampchain protocol standards * * @example * ```typescript * const builder = new SRC20TokenBuilder({ * network: networks.bitcoin, * feeRate: 15 * }); * * // Deploy a new token * const deployResult = await builder.buildSRC20Transaction({ * encodedData: await encoder.encode({ * p: 'SRC-20', * op: 'DEPLOY', * tick: 'MYTOKEN', * max: '1000000', * lim: '1000' * }), * utxos: availableUTXOs, * changeAddress: 'bc1q...', * feeRate: 20 * }); * ``` */ declare class SRC20TokenBuilder extends TransactionBuilder implements ISRC20TokenBuilder { readonly network: bitcoin.networks.Network; readonly dustThreshold: number; readonly feeRate: number; readonly maxInputs: number; readonly enableRBF: boolean; readonly enableCPFP: boolean; private readonly encoder; private readonly selectorFactory; private readonly utxoProvider; private readonly logger; private readonly ordinalsDetector?; constructor(network: bitcoin.networks.Network, selectorFactory: SelectorFactory, options?: Partial<SRC20BuilderOptions>); /** * Build a DEPLOY transaction for creating a new SRC-20 token */ buildDeploy(deployData: SRC20DeployData): Promise<bitcoin.Transaction>; /** * Build a MINT transaction for minting SRC-20 tokens */ buildMint(mintData: SRC20MintData): Promise<bitcoin.Transaction>; /** * Build a TRANSFER transaction for sending SRC-20 tokens */ buildTransfer(transferData: SRC20TransferData): Promise<bitcoin.Transaction>; /** * Validate deploy data */ private validateDeployData; /** * Validate mint data */ private validateMintData; /** * Validate transfer data */ private validateTransferData; /** * Build a transaction from inputs and outputs */ private buildRawTransaction; /** * Get UTXOs for an address */ private getUTXOs; /** * Select UTXOs for a transaction using the configured selector */ protected selectUTXOs(utxos: UTXO[], targetValue: number, feeRate: number, dustThreshold: number): EnhancedSelectionResult; /** * Build a token transfer transaction */ buildTokenTransfer(utxos: UTXO[], options: TokenTransferOptions): Promise<SRC20BuildResult>; /** * Build a token mint transaction */ buildTokenMint(utxos: UTXO[], options: TokenMintOptions): Promise<SRC20BuildResult>; /** * Build a token deploy transaction */ buildTokenDeploy(utxos: UTXO[], options: TokenDeployOptions): Promise<SRC20BuildResult>; /** * Get SRC-20 dust value - instance method */ getSRC20DustValue(): number; /** * Get SRC-20 dust value - static method */ static getDustValue(): number; /** * Validate tick symbol - SRC-20 protocol enforces 5 character maximum */ validateTick(tick: string): boolean; /** * Validate amount string */ validateAmount(amount: any): boolean; /** * Estimate transaction cost */ estimateTransactionCost(numInputs: number, numDataOutputs: number, includeRecipient: boolean, feeRate: number): number; /** * Estimate transaction size for fee calculation */ protected estimateTransactionSize(numInputs: number, numOutputs: number): number; } /** * Logger interface for type-safe logging */ interface Logger { warn(message: string, context?: Record<string, unknown>): void; error(message: string, context?: Record<string, unknown>): void; info(message: string, context?: Record<string, unknown>): void; debug?(message: string, context?: Record<string, unknown>): void; } /** * Bitcoin Stamp Builder * * Implements Bitcoin Stamp transaction construction with proper UTXO management, * P2WSH encoding, and Counterparty protocol integration. Provides a high-level * builder interface similar to SRC20TokenBuilder for consistent developer experience. */ /** * Bitcoin Stamp Transaction Builder Configuration */ interface BitcoinStampBuilderConfig { network: bitcoin.networks.Network; feeRate: number; dustThreshold: number; maxInputs: number; enableRBF: boolean; enableCPFP?: boolean; utxoProvider: any; selectorFactory: SelectorFactory; assetValidationService?: any; logger?: Logger; } /** * Bitcoin Stamp Build Data */ interface BitcoinStampBuildData { data: Buffer; fromAddress: string; encoding?: 'gzip' | 'brotli' | 'base64'; cpid?: string; supply?: number; isLocked?: boolean; filename?: string; title?: string; description?: string; creator?: string; } /** * Simple issuance data (no image/file data) */ interface BitcoinStampIssuanceData { sourceAddress: string; cpid: string; quantity: number; divisible?: boolean; lock?: boolean; description?: string; imageData?: string; } /** * High-level builder for creating Bitcoin Stamp transactions * * @remarks * BitcoinStampBuilder simplifies the creation of Bitcoin Stamp transactions by handling: * - Image/file data encoding and compression * - Multi-signature output creation for data storage * - UTXO selection with protection for special assets * - Fee calculation optimized for stamp transactions * - Counterparty protocol integration * * Features: * - Automatic data compression (gzip/brotli) * - Base64 encoding for binary data * - CPID support for Counterparty assets * - Built-in UTXO protection (Ordinals, Stamps, etc.) * - Configurable fee rates and algorithms * * @example * ```typescript * const builder = new BitcoinStampBuilder(network, selectorFactory); * const result = await builder.buildStampTransaction(utxos, { * stampData: { * imageData: imageBuffer, * filename: 'art.png' * }, * fromAddress: 'bc1q...', * feeRate: 20 * }); * ``` */ declare class BitcoinStampBuilder extends TransactionBuilder { readonly network: bitcoin.networks.Network; readonly dustThreshold: number; readonly feeRate: number; readonly maxInputs: number; readonly enableRBF: boolean; readonly enableCPFP: boolean; private readonly encoder; private readonly selectorFactory; private readonly feeCalculator; private readonly assetValidationService?; private readonly utxoProvider; private readonly logger; constructor(config: BitcoinStampBuilderConfig); /** * Build a Bitcoin Stamp transaction */ buildStampTransaction(buildData: BitcoinStampBuildData): Promise<bitcoin.Transaction>; /** * Build a simple issuance transaction (for testing or simple asset creation) */ buildIssuance(issuanceData: BitcoinStampIssuanceData): Promise<bitcoin.Transaction>; /** * Validate description length to prevent OP_RETURN overflow */ private validateDescriptionLength; /** * Build a raw transaction from inputs and outputs */ private buildRawTransaction; /** * Validate build data */ private validateBuildData; /** * Get UTXOs for an address */ private getUTXOs; /** * Select UTXOs for a transaction using the configured selector */ protected selectUTXOs(utxos: UTXO[], targetValue: number, feeRate: number, dustThreshold: number, algorithm?: 'accumulative' | 'branch-and-bound' | 'blackjack' | 'knapsack'): EnhancedSelectionResult; /** * Estimate transaction size for fee calculation */ protected estimateTransactionSize(numInputs: number, numOutputs: number): number; } /** * Dynamic Dust Threshold Calculator * Implements Bitcoin Core's dust calculation logic with network-aware thresholds */ interface DustCalculatorOptions { minRelayFeeRate?: number; networkType?: 'mainnet' | 'testnet' | 'regtest'; enableSrc20Rules?: boolean; src20Options?: SRC20Options; } /** * Calculates dynamic dust thresholds based on network conditions and fee rates */ declare class DustCalculator { private options; static readonly NETWORK_MIN_RELAY_RATES: { mainnet: number; testnet: number; regtest: number; }; private static readonly SCRIPT_SIZES; private static readonly SPEND_INPUT_SIZES; private src20Options?; constructor(options?: DustCalculatorOptions); /** * Calculate dynamic dust threshold for a specific output type * Based on Bitcoin Core's GetDustThreshold function */ calculateDustThreshold(outputType: OutputType, scriptSize?: number, feeRate?: number): number; /** * Calculate all dust thresholds for current network conditions */ calculateAllThresholds(feeRate?: number): DustThresholds; /** * Check if a value is above dust threshold for specific output type */ isAboveDustThreshold(value: number, outputType: OutputType, scriptSize?: number, feeRate?: number): boolean; /** * Get output size in bytes */ private getOutputSize; /** * Get the size of input required to spend this output type */ private getSpendInputSize; /** * Get network-specific minimum dust threshold */ private getNetworkMinimum; /** * Calculate dust threshold for custom script */ calculateCustomScriptDust(scriptHex: string, feeRate?: number): number; /** * Get current fee rate from network */ getNetworkMinRelayFeeRate(): number; /** * Validate dust thresholds against Bitcoin Core reference values */ validateAgainstReference(): { isValid: boolean; differences: Array<{ outputType: OutputType; calculated: number; expected: number; diff: number; }>; }; } /** * Create a dust calculator with standard settings for Bitcoin transactions * * @param networkType - The Bitcoin network type ('mainnet', 'testnet', or 'regtest') * @param enableSrc20Rules - Whether to enable special SRC-20 dust rules * @param src20Options - Optional SRC-20 specific configuration * @returns A configured DustCalculator instance * * @example Basic dust calculation * ```typescript * const calculator = createDustCalculator(); * const dustAmount = calculator.getDustThreshold('p2wpkh'); * ``` * * @example With SRC-20 rules * ```typescript * const calculator = createDustCalculator('mainnet', true, { * minOutputValue: 10000 * }); * ``` */ declare function createDustCalculator(networkType?: 'mainnet' | 'testnet' | 'regtest', enableSrc20Rules?: boolean, src20Options?: SRC20Options): DustCalculator; /** * Data Processing Utilities for Bitcoin Stamps * * Bitcoin Stamps can store ANY data format on-chain. * This utility provides optional format detection for metadata purposes only. */ interface DataInfo { format: string; size: number; width?: number; height?: number; } /** * Data Processing Utilities */ declare class DataProcessor { /** * Detect common data format from binary data (optional - for metadata only) * Returns 'UNKNOWN' for unrecognized formats (which is perfectly valid for Stamps) */ static detectFormat(data: Buffer): string; /** * Simple heuristic to detect if data is likely text */ private static isProbablyText; /** * Create a data URL from binary data * Useful for preview/display purposes */ static createDataURL(data: Buffer, mimeType?: string): string; /** * Get data info for metadata purposes */ static getDataInfo(data: Buffer): DataInfo; /** * Check if data exceeds transaction size limit * This is the ONLY real constraint for Bitcoin Stamps */ static exceedsMaxSize(data: Buffer): boolean; } /** * SRC-20 Compression Utilities * * Provides zlib compression and msgpack encoding for SRC-20 data * to reduce transaction size and costs. Compatible with BTCStampsExplorer * decodeSrc20OlgaTx decoder which supports both compressed and uncompressed formats. */ interface SRC20CompressionOptions { /** Enable zlib compression (default: true for large data) */ useCompression?: boolean; /** Enable msgpack encoding (default: true when compression is used) */ useMsgpack?: boolean; /** Compression level 0-9 (default: 9 for maximum compression) */ compressionLevel?: number; /** Auto-compress if data exceeds this size (default: 100 bytes) */ compressionThreshold?: number; /** Force compression even for small data */ forceCompression?: boolean; } interface SRC20CompressionResult { /** Compressed/encoded data ready for P2WSH embedding */ data: Buffer; /** Original JSON string */ originalJson: string; /** Original size in bytes */ originalSize: number; /** Compressed size in bytes */ compressedSize: number; /** Compression ratio (0-1, higher is better) */ compressionRatio: number; /** Whether compression was applied */ compressed: boolean; /** Whether msgpack was used */ msgpacked: boolean; /** Estimated P2WSH outputs needed */ estimatedOutputs: number; /** Estimated transaction cost savings */ costSavings: { outputsReduced: number; satsSaved: number; }; } interface SRC20DecompressionResult { /** Decompressed JSON data */ data: any; /** JSON string representation */ jsonString: string; /** Whether data was compressed */ wasCompressed: boolean; /** Whether msgpack was used */ wasMsgpacked: boolean; /** Original compressed size */ compressedSize: number; /** Decompressed size */ decompressedSize: number; } /** * SRC-20 Compression Service * * Handles compression and decompression of SRC-20 JSON data * for efficient storage in Bitcoin transactions. */ declare class SRC20CompressionService { private static readonly STAMP_PREFIX; private static readonly CHUNK_SIZE; private static readonly DUST_VALUE; private static readonly DEFAULT_THRESHOLD; /** * Compress SRC-20 data for transaction embedding */ static compress(jsonData: string | object, options?: SRC20CompressionOptions): Promise<SRC20CompressionResult>; /** * Decompress SRC-20 data from transaction */ static decompress(data: Buffer | Uint8Array): Promise<SRC20DecompressionResult>; /** * Analyze compression benefits for SRC-20 data */ static analyzeCompressionBenefits(jsonData: string | object): { originalSize: number; estimatedCompressedSize: number; estimatedSavings: number; outputsOriginal: number; outputsCompressed: number; outputsSaved: number; satsSaved: number; recommendCompression: boolean; analysis: string[]; }; /** * Test compression round-trip */ static testCompressionRoundTrip(jsonData: string | object, options?: SRC20CompressionOptions): Promise<{ success: boolean; originalData: any; compressedSize: number; decompressedData: any; dataMatches: boolean; compressed?: SRC20CompressionResult; decompressed?: SRC20DecompressionResult; error?: string; }>; } /** * Advanced Fee Calculator for Bitcoin Stamps * Provides stamp-specific optimizations to achieve 10-20% cost reduction * Uses normalized satsPerVB for consistency with BTCStampsExplorer */ interface StampData$1 { data_size?: number; witness_script_size?: number; compression_ratio?: number; imageData?: Buffer; } interface Operation { type: 'stamp_creation' | 'stamp_transfer' | 'batch_mint' | 'src20_operation'; stamps?: StampData$1[]; input_count: number; output_count: number; data_outputs: number; witness_data_size?: number; priority: 'low' | 'medium' | 'high' | 'urgent'; } interface FeeBreakdown { base_fee: number; batch_savings: number; compression_savings: number; witness_optimization: number; dust_optimization: number; rbf_premium?: number; total_fee: number; original_fee_estimate: number; savings_percentage: number; } interface CompressionAnalysis { original_size: number; compressed_size: number; compression_ratio: number; estimated_savings: number; algorithm: 'gzip' | 'lz77' | 'huffman' | 'none'; applicable: boolean; } interface FeePrediction { operations: Operation[]; total_estimated_fee: number; fee_breakdown: FeeBreakdown; confidence: number; time_estimate: string; optimization_suggestions: Optimization[]; } interface Optimization { type: 'batch_consolidation' | 'witness_compression' | 'dust_management' | 'rbf_timing' | 'utxo_selection'; description: string; estimated_savings: number; estimated_savings_percentage: number; implementation_complexity: 'low' | 'medium' | 'high'; applicable_operations: string[]; } /** * Advanced fee calculator with stamp-specific optimizations */ declare class AdvancedFeeCalculator extends FeeEstimator { private _networkMempool; private compressionCache; private batchingThresholds; constructor(options?: { networkType?: 'mainnet' | 'testnet' | 'regtest'; }); /** * Calculate batch transaction fee with amortization using normalized satsPerVB * Achieves 5-15% savings through intelligent batching */ calculateBatchFee(stamps: StampData$1[], feeRateSatsPerVB: number): FeeBreakdown; /** * Analyze potential compression savings for witness data * Can achieve 2-8% savings on data-heavy stamp operations */ analyzeCompressionSavings(data: Buffer): CompressionAnalysis; /** * Calculate optimal dust threshold based on network conditions using normalized satsPerVB * Dynamically adjusts to current fee environment */ calculateOptimalDustThreshold(network: 'mainnet' | 'testnet', feeRate?: number): number; /** * Predict fees for multi-step stamp operations * Provides accurate cost estimates for complex workflows */ predictMultiStepFees(operations: Operation[]): FeePrediction; /** * Calculate RBF fee bump with stamp-specific considerations using normalized satsPerVB * Optimizes fee bumps for stamp transactions */ calculateRBFBump(originalFee: number, targetConfirmation: number, feeRates?: { low: number; medium: number; high: number; urgent?: number; }): number; /** * Suggest optimizations for given transaction * Provides actionable recommendations for cost reduction */ suggestOptimizations(transaction: bitcoin.Transaction): Optimization[]; private estimateIndividualStampFee; /** * Get current fee rates normalized to satsPerVB */ private getNormalizedCurrentFeeRates; private simulateCompression; private calculateEntropy; private hashBuffer; private estimateTransactionSize; private calculateOperationFee; private generateOperationOptimizations; private assessNetworkVolatility; private estimateConfirmationTime; private deduplicateOptimizations; private estimateWitnessDataSize; private identifyDustOutputs; private isBatchable; } /** * Create an advanced fee calculator with optimization features for complex transactions * * @param options - Optional configuration object * @param options.networkType - The Bitcoin network type ('mainnet', 'testnet', or 'regtest') * @returns A configured AdvancedFeeCalculator instance * * @example Basic usage * ```typescript * const calculator = createAdvancedFeeCalculator(); * const prediction = await calculator.predictFees(stampData, utxos, feeRate); * ``` * * @example For testnet * ```typescript * const calculator = createAdvancedFeeCalculator({ * networkType: 'testnet' * }); * const analysis = calculator.analyzeCompression(data); * ``` */ declare function createAdvancedFeeCalculator(options?: { networkType?: 'mainnet' | 'testnet' | 'regtest'; }): AdvancedFeeCalculator; /** * Script Optimizer Engine for Bitcoin Stamps * * Intelligent script optimization engine that reduces transaction costs through smart data handling. * Implements pattern recognition, compression, deduplication, and advanced chunking strategies. */ /** * Core interfaces for the Script Optimizer Engine */ interface PatternAnalysis { /** Detected patterns in the data */ patterns: DataPattern[]; /** Entropy level (0-1, higher = more random) */ entropy: number; /** Compression potential (0-1, higher = more compressible) */ compressionPotential: number; /** Recommended optimization strategies */ recommendedStrategies: string[]; /** Estimated size reduction percentage */ estimatedReduction: number; } interface DataPattern { /** Pattern type (e.g., 'repeated_bytes', 'color_palette', 'structure') */ type: string; /** Pattern description */ description: string; /** Frequency of occurrence */ frequency: number; /** Bytes saved if optimized */ potentialSavings: number; /** Pattern-specific data */ metadata: Record<string, any>; } interface OptimizedScript { /** Optimized witness script */ script: Buffer; /** Original script size */ originalSize: number; /** Optimized script size */ optimizedSize: number; /** Size reduction percentage */ reduction: number; /** Applied optimizations */ optimizations: string[]; /** Execution verification data */ verification: ScriptVerification; } interface ScriptVerification { /** Whether the script is still valid */ isValid: boolean; /** Execution cost (estimated op count) */ executionCost: number; /** Any warnings about the optimization */ warnings: string[]; } interface DeduplicationResult { /** Deduplicated data chunks */ chunks: DeduplicatedChunk[]; /** Original total size */ originalSize: number; /** Deduplicated total size */ deduplicatedSize: number; /** Size reduction from deduplication */ reduction: number; /** Mapping table for reconstruction */ mappingTable: Buffer; } interface DeduplicatedChunk { /** Chunk identifier hash */ id: string; /** Chunk data */ data: Buffer; /** Number of references to this chunk */ referenceCount: number; /** Original positions in the data */ positions: number[]; } interface MinimizedScript { /** Minimized script */ script: Buffer; /** Original size */ originalSize: number; /** Minimized size */ minimizedSize: number; /** Applied minimizations */ minimizations: ScriptMinimization[]; /** Execution equivalence verified */ verified: boolean; } interface ScriptMinimization { /** Type of minimization */ type: 'opcode_optimization' | 'stack_optimization' | 'constant_folding' | 'dead_code_removal'; /** Description of what was done */ description: string; /** Bytes saved */ bytesSaved: number; } interface ChunkingStrategy { /** Optimized data chunks */ chunks: OptimizedChunk[]; /** Chunking algorithm used */ algorithm: 'fixed_size' | 'content_aware' | 'entropy_based' | 'pattern_aware'; /** Total size after chunking */ totalSize: number; /** Overhead from chunking metadata */ overhead: number; /** Efficiency score (0-1) */ efficiency: number; } interface OptimizedChunk { /** Chunk index */ index: number; /** Chunk data */ data: Buffer; /** Compression applied to this chunk */ compression: string | null; /** Hash for integrity verification */ hash: string; } interface CompressedScript { /** Compressed witness script data */ compressedData: Buffer; /** Compression algorithm used */ algorithm: 'lz4' | 'gzip' | 'huffman' | 'rle' | 'custom'; /** Original size */ originalSize: number; /** Compressed size */ compressedSize: number; /** Compression ratio */ ratio: number; /** Decompression metadata */ metadata: Buffer; } interface OptimizedPath { /** Optimized execution path */ script: Buffer; /** Expected execution steps */ executionSteps: ExecutionStep[]; /** Gas/operation cost estimate */ estimatedCost: number; /** Critical path analysis */ criticalPath: boolean[]; /** Optimizations applied */ optimizations: PathOptimization[]; } interface ExecutionStep { /** Operation code */ opcode: number; /** Stack state before operation */ stackBefore: Buffer[]; /** Stack state after operation */ stackAfter: Buffer[]; /** Operation cost */ cost: number; } interface PathOptimization { /** Type of path optimization */ type: 'branch_elimination' | 'loop_unrolling' | 'constant_propagation' | 'instruction_reordering'; /** Description */ description: string; /** Operations saved */ operationsSaved: number; } interface StampData { /** Image data buffer */ imageData: Buffer; /** MIME type */ /** Metadata */ metadata?: Record<string, any>; } /** * Main Script Optimizer Engine Class */ declare class ScriptOptimizerEngine { private patternCache; private compressionCache; private deduplicationCache; private readonly network; constructor(network?: bitcoin.Network); /** * Analyze stamp data patterns for optimization opportunities * Uses entropy analysis, pattern detection, and statistical analysis */ analyzeDataPatterns(stampData: Buffer[]): PatternAnalysis; /** * Optimize P2WSH witness script construction * Focuses on minimizing script size while maintaining functionality */ optimizeWitnessScript(script: Buffer): OptimizedScript; /** * Implement data deduplication across multiple stamps * Identifies and eliminates duplicate data chunks across stamp collection */ deduplicateStampData(stamps: StampData[]): DeduplicationResult; /** * Automatic script size minimization * Applies comprehensive size reduction techniques */ minimizeScriptSize(script: Buffer): MinimizedScript; /** * Smart chunking algorithms for large stamp data * Optimizes chunk sizes based on data patterns and P2WSH constraints */ optimizeDataChunking(data: Buffer, maxChunkSize: number): ChunkingStrategy; /** * Witness script compression techniques * Applies specialized compression for P2WSH witness data */ compressWitnessScript(script: Buffer): CompressedScript; /** * Optimize script execution path * Analyzes and optimizes the execution flow for minimum operations */ optimizeExecutionPath(script: Buffer): OptimizedPath; private hashBuffers; private hashStampData; private calculateEntropy; private detectRepeatedBytes; private looksLikeImageData; private analyzeColorPatterns; private detectStructuralPatterns; private analyzeCrossBufferSimilarities; private calculateBufferSimilarity; private generateOptimizationRecommendations; private removeRedundantOpcodes; private optimizePushOperations; private foldConstants; private optimizeStackOperations; private verifyScriptOptimization; private minimizeStackOperations; private precomputeConstants; private removeDeadCode; private verifyScriptEquivalence; private optimizeOpcodes; private fixedSizeChunking; private contentAwareChunking; private entropyBasedChunking; private patternAwareChunking; private calculateChunkingEfficiency; private compressLZ4; private compressGzip; private compressHuffman; private compressRLE; private compressCustom; private simulateScriptExecution; private eliminateUnreachableBranches; private propagateConstants; private reorderInstructions; private identifyCriticalPath; private selectOptimalDeduplicationSet; private buildMappingTable; private calculateDeduplicationSavings; } /** * Minimal Stamp Validation Engine * * Bitcoin Stamps can store ANY data on-chain. * The only real constraint is the transaction size limit. */ interface StampValidationConfig { network?: Network; maxSize?: number; } interface ValidationResult { isValid: boolean; errors: ValidationError[]; warnings: ValidationWarning[]; details?: any; } interface ValidationError { severity: 'error'; code: string; message: string; field?: string; remediationSuggestion?: string; } interface ValidationWarning { severity: 'warning'; code: string; message: string; field?: string; remediationSuggestion?: string; } /** * Minimal validation for Bitcoin Stamps * Only validates what actually matters */ declare class StampValidationEngine { private readonly config; constructor(config?: StampValidationConfig); /** * Validate stamp data * Only checks the real constraint: transaction size */ validateStampData(data: BitcoinStampData): ValidationResult; /** * Simple helper to check if data is valid */ isValid(data: BitcoinStampData): boolean; } /** * Create a stamp validation engine for validating Bitcoin Stamps data * * @param config - Optional validation configuration * @returns A configured StampValidationEngine instance * * @example Basic validation * ```typescript * const validator = createStampValidationEngine(); * const result = await validator.validate(stampData); * if (!result.isValid) { * console.error(result.errors); * } * ``` * * @example With strict configuration * ```typescript * const validator = createStampValidationEngine({ * maxFileSize: 5000000, * strictMode: true * }); * ``` */ declare function createStampValidationEngine(config?: StampValidationConfig): StampValidationEngine; /** * Custom Error Classes */ declare class TransactionBuilderError extends Error { constructor(message: string); } declare class InsufficientFundsError extends TransactionBuilderError { required: number; available: number; constructor(required: number, available: number); } declare class InvalidAddressError extends TransactionBuilderError { address: string; constructor(address: string); } declare class InvalidTransactionError extends TransactionBuilderError { constructor(message: string); } declare class ProviderError extends TransactionBuilderError { provider?: string; constructor(message: string, provider?: string); } declare class NetworkMismatchError extends TransactionBuilderError { expected: string; actual: string; constructor(expected: string, actual: string); } declare class EncodingError extends TransactionBuilderError { constructor(message: string); } declare class SelectionError extends TransactionBuilderError { constructor(message: string); } declare class FeeEstimationError extends TransactionBuilderError { constructor(message: string); } /** * @module @btc-stamps/tx-builder * * Bitcoin Transaction Builder - A comprehensive library for building Bitcoin transactions * with support for Bitcoin Stamps, SRC-20 tokens, UTXO selection algorithms, and advanced * fee optimization. * * @example Basic transaction building * ```typescript * import { createTransactionBuilder } from '@btc-stamps/tx-builder'; * * const builder = createTransactionBuilder(); * const psbt = await builder.buildTransaction({ * inputs: [...], * outputs: [...], * feeRate: 10 * }); * ``` * * @example SRC-20 token transaction * ```typescript * import { SRC20TokenBuilder } from '@btc-stamps/tx-builder'; * * const tokenBuilder = new SRC20TokenBuilder({...}); * const result = await tokenBuilder.buildTransferTransaction({ * tick: 'STAMP', * amount: '1000', * recipient: 'bc1q...' * }); * ``` */ /** * Create a new transaction builder instance with default configuration * * @param network - The Bitcoin network to use (default: bitcoin mainnet) * @returns A configured TransactionBuilder instance * * @example Create builder for mainnet * ```typescript * const builder = createTransactionBuilder(); * ``` * * @example Create builder for testnet * ```typescript * import { networks } from 'bitcoinjs-lib'; * const builder = createTransactionBuilder(networks.testnet); * ``` */ declare function createTransactionBuilder(network?: Network): TransactionBuilder; export { AdvancedFeeCalculator, type AssetValidationConfig, type AssetValidationResult, AssetValidationService, type BitcoinStampBuildData, BitcoinStampBuilder, type BitcoinStampBuilderConfig, BitcoinStampData, type BitcoinStampIssuanceData, type ChunkingStrategy, type CompressedScript, type CompressionAnalysis, CounterpartyDetector, type CounterpartyDetectorOptions, type DataPattern, DataProcessor, type DeduplicatedChunk, type DeduplicationResult, EncodingError, type ExecutionStep, type FeeBreakdown, FeeEstimationError, FeeEstimator, type FeePrediction, IProtectionDetector, DataProcessor as ImageProcessor, InscriptionData, InsufficientFundsError, InvalidAddressError, InvalidTransactionError, type MinimizedScript, MockOrdinalsDetector, NetworkMismatchError, type Operation, type Optimization, type OptimizedChunk, type OptimizedPath, type OptimizedScript, type StampData as OptimizerStampData, OrdinalsAwareSelector, type OrdinalsAwareSelectorOptions, OrdinalsDetector, type PathOptimization, type PatternAnalysis, ProtectedAssetData, ProviderError, SRC20CompressionService, SRC20TokenBuilder, type ScriptMinimization, ScriptOptimizerEngine, type ScriptVerification, SelectionError, SelectionOptions, type StampData$1 as StampData, type StampValidationConfig, StampValidationEngine, TransactionBuilder, TransactionBuilde