UNPKG

@btc-stamps/tx-builder

Version:

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

667 lines (649 loc) 21.1 kB
import { Buffer } from 'node:buffer'; import { Network } from 'bitcoinjs-lib'; import { I as IProtectionDetector, P as ProtectionDetectorConfig, a as ProtectedAssetData } from './protection.interface-DWbXoL2W.js'; import { U as UTXO$1 } from './provider.interface-53Rg30ZJ.js'; /** * Data Encoder Interface * Defines the contract for encoding various data types into Bitcoin transactions */ interface EncodingResult { script: Buffer; outputs: TransactionOutput[]; estimatedSize: number; dataSize: number; } interface TransactionOutput { script: Buffer; value: number; } interface IDataEncoder { /** * Encode data into transaction outputs */ encode(data: P2WSHData | SRC20Data | StampData, options?: EncodingOptions): EncodingResult; /** * Decode data from transaction outputs */ decode(outputs: TransactionOutput[]): P2WSHData | SRC20Data | StampData; /** * Validate if data can be encoded */ validate(data: P2WSHData | SRC20Data | StampData): boolean; /** * Get maximum data size supported */ getMaxDataSize(): number; /** * Get encoder type/protocol name */ getType(): string; } interface EncodingOptions { network?: Network; compress?: boolean; chunkSize?: number; } interface StampData { base64: string; filename?: string; } interface P2WSHData { /** Raw binary data to embed */ data: Buffer; /** Optional content type identifier */ contentType?: string; /** Protocol identifier (e.g., 'SRC20', 'STAMP') */ protocol?: string; } /** * UTXO Type Definitions * * Core types for Unspent Transaction Output handling */ /** * Basic UTXO structure */ interface UTXO { /** Transaction ID */ txid: string; /** Output index */ vout: number; /** Value in satoshis */ value: number; /** ScriptPubKey */ scriptPubKey: string; /** Address (optional) */ address?: string; /** Number of confirmations */ confirmations?: number; /** Block height */ height?: number; /** Whether this UTXO is from a coinbase transaction */ coinbase?: boolean; /** Whether this UTXO is spendable */ spendable?: boolean; /** Whether this UTXO is safe to spend */ safe?: boolean; } /** * Multi-Asset Protection Detector * * Orchestrates multiple protection detectors for different asset types with * intelligent aggregation strategies. This detector combines results from * multiple IProtectionDetector implementations to provide comprehensive * asset protection detection across ordinals, stamps, SRC-20 tokens, and more. */ /** * Aggregation strategies for multi-detector operation */ type AggregationStrategy = 'any-positive' | 'all-positive' | 'majority'; /** * Configuration options for MultiAssetProtectionDetector */ interface MultiAssetProtectionDetectorOptions { /** Aggregation strategy to use (default: 'any-positive') */ strategy?: AggregationStrategy; /** Global timeout for all operations in milliseconds (default: 10000) */ timeout?: number; /** Maximum number of detectors to query concurrently (default: 3) */ maxConcurrency?: number; /** Whether to enable detailed logging (default: false) */ enableLogging?: boolean; /** Whether to continue on detector failures (default: true) */ continueOnFailure?: boolean; /** Global detector configuration override */ detectorConfig?: Partial<ProtectionDetectorConfig>; } /** * Multi-Asset Protection Detector implementation * * Orchestrates multiple protection detectors with intelligent aggregation strategies: * - 'any-positive': Return true if ANY detector finds protection * - 'all-positive': Return true only if ALL detectors find protection * - 'majority': Return true if majority of detectors find protection * * Features: * - Parallel execution for optimal performance * - Graceful error handling and recovery * - Detailed asset data aggregation * - Configurable concurrency limits * - Comprehensive logging and debugging * - Fail-safe operation (never throws on detector errors) */ declare class MultiAssetProtectionDetector implements IProtectionDetector { private readonly detectors; private readonly strategy; private readonly timeout; private readonly maxConcurrency; private readonly enableLogging; private readonly continueOnFailure; private readonly detectorConfig; constructor(detectors?: IProtectionDetector[], options?: MultiAssetProtectionDetectorOptions); /** * Check if a UTXO contains protected assets using multiple detectors */ isProtectedUtxo(utxo: UTXO): Promise<boolean>; /** * Get detailed asset data for a protected UTXO from all detectors */ getAssetData(utxo: UTXO): Promise<ProtectedAssetData | null>; /** * Execute detector operations in parallel with concurrency limits */ private executeDetectorOperations; /** * Aggregate protection results based on the configured strategy */ private aggregateProtectionResults; /** * Aggregate asset data from multiple detectors */ private aggregateAssetData; /** * Create a timeout promise that rejects after the specified duration */ private createTimeoutPromise; /** * Add a detector to the collection */ addDetector(detector: IProtectionDetector): void; /** * Remove a detector from the collection */ removeDetector(detector: IProtectionDetector): boolean; /** * Get information about configured detectors */ getDetectorInfo(): Array<{ name: string; configured: boolean; }>; /** * Get the current aggregation strategy */ getStrategy(): AggregationStrategy; /** * Get the number of configured detectors */ getDetectorCount(): number; /** * Get configuration summary */ getConfig(): { strategy: AggregationStrategy; timeout: number; maxConcurrency: number; detectorCount: number; enableLogging: boolean; }; } /** * Ordinals Detection Interface * * Specific interface for detecting Bitcoin ordinals and inscriptions. * This is a specialized subset of the general IProtectionDetector interface. */ /** * Inscription data structure for ordinals detection */ interface InscriptionData { /** Unique inscription identifier */ id: string; /** Inscription number */ number: number; /** Content type (mime type) */ contentType?: string; /** Content size in bytes */ contentLength?: number; /** Genesis block height */ genesisHeight?: number; /** Genesis transaction fee */ genesisFee?: number; /** Genesis timestamp */ genesisTimestamp?: number; /** Ordinal satoshi number */ satOrdinal?: string; /** Satoshi rarity */ satRarity?: string; /** Coinbase height for the satoshi */ satCoinbaseHeight?: number; /** Current owner address */ owner?: string; /** Output value */ outputValue?: string; /** Additional metadata */ metadata?: Record<string, any>; } /** * Ordinals-specific detector interface * * This interface is specifically for detecting Bitcoin ordinals and inscriptions. * It provides methods optimized for ordinals detection workflows. */ interface OrdinalsDetector { /** * Check if a UTXO contains protected ordinals/inscriptions * @param utxo The UTXO to check * @returns Promise<boolean> True if the UTXO contains ordinals/inscriptions */ isProtectedUtxo(utxo: UTXO$1): Promise<boolean>; /** * Get inscription data for a UTXO if it contains an inscription * @param utxo The UTXO to analyze * @returns Promise<InscriptionData | null> Inscription data if found, null otherwise */ getInscriptionData(utxo: UTXO$1): Promise<InscriptionData | null>; /** * Get asset data for a UTXO - only returns ordinal/inscription types * @param utxo The UTXO to analyze * @returns Promise<ProtectedAssetData | null> Asset data if found, null otherwise */ getAssetData(utxo: UTXO$1): Promise<ProtectedAssetData | null>; } /** * Hiro Ordinals API Detector * * Detects ordinals/inscriptions and runes using the Hiro Ordinals API. * Provides fail-safe detection that returns false on any error. */ /** * Configuration options for HiroOrdinalsDetector */ interface HiroOrdinalsDetectorOptions { /** Base URL for Hiro API (default: https://api.hiro.so) */ baseUrl?: string; /** Request timeout in milliseconds (default: 5000) */ timeout?: number; /** Maximum number of retries (default: 3) */ maxRetries?: number; } /** * Hiro Ordinals API detector implementation * * Integrates with the Hiro Ordinals API to detect: * - Bitcoin inscriptions (ordinals) * - Runes tokens * * Features: * - Fail-safe operation (never throws, returns false on errors) * - Configurable timeout and retry logic * - Exponential backoff for rate limiting */ declare class HiroOrdinalsDetector implements IProtectionDetector, OrdinalsDetector { private readonly baseUrl; private readonly timeout; private readonly maxRetries; constructor(options?: HiroOrdinalsDetectorOptions); /** * Check if a UTXO contains protected inscriptions/ordinals */ 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 - only returns ordinal/inscription types */ getAssetData(utxo: UTXO): Promise<ProtectedAssetData | null>; /** * Fetch with retry logic and exponential backoff */ private fetchWithRetry; } /** * Ord Server Detector * * Detects ordinals/inscriptions using the Ord Server API (ordinals.com). * Provides fail-safe detection that returns false on any error. */ /** * Configuration options for OrdServerDetector */ interface OrdServerDetectorOptions { /** Base URL for Ord Server API (default: https://ordinals.com) */ baseUrl?: string; /** Request timeout in milliseconds (default: 5000) */ timeout?: number; /** Maximum number of retries (default: 3) */ maxRetries?: number; } /** * Ord Server API detector implementation * * Integrates with the Ord Server API (ordinals.com) to detect: * - Bitcoin inscriptions (ordinals) * * Features: * - Fail-safe operation (never throws, returns false on errors) * - Configurable timeout and retry logic * - Exponential backoff for rate limiting */ declare class OrdServerDetector implements IProtectionDetector, OrdinalsDetector { private readonly baseUrl; private readonly timeout; private readonly maxRetries; constructor(options?: OrdServerDetectorOptions); /** * Check if a UTXO contains protected inscriptions/ordinals */ 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 - only returns ordinal/inscription types */ getAssetData(utxo: UTXO): Promise<ProtectedAssetData | null>; /** * Fetch with retry logic and exponential backoff */ private fetchWithRetry; } /** * Ordinals Multi-Provider Detector * * Orchestrates multiple ordinals detector providers with intelligent fallback strategies. * This detector ONLY handles ordinals and inscriptions via multiple APIs (Hiro, Ord, etc.) * and has nothing to do with Counterparty assets. */ /** * Detection strategies for multi-provider operation */ type DetectionStrategy = 'first-success' | 'any-positive' | 'consensus'; /** * Configuration options for OrdinalsMultiProviderDetector */ interface OrdinalsMultiProviderDetectorOptions { /** Detection strategy to use (default: 'first-success') */ strategy?: DetectionStrategy; /** Global timeout for all operations in milliseconds (default: 10000) */ timeout?: number; /** Maximum number of providers to query concurrently (default: 2) */ maxConcurrency?: number; /** Provider-specific options */ providerOptions?: { hiro?: HiroOrdinalsDetectorOptions; ordServer?: OrdServerDetectorOptions; }; } /** * Ordinals Multi-Provider Detector implementation * * Orchestrates multiple detector providers with intelligent fallback strategies: * - 'first-success': Query providers in order until one returns true * - 'any-positive': Query all providers in parallel, return true if ANY returns true * - 'consensus': Query multiple providers, return true only if majority returns true * * Features: * - Fail-safe operation (never throws, returns false on errors) * - Configurable detection strategies * - Provider-specific timeout and retry logic * - Graceful degradation when providers fail * - Comprehensive error logging */ declare class OrdinalsMultiProviderDetector implements IProtectionDetector, OrdinalsDetector { private readonly providers; private readonly strategy; private readonly timeout; private readonly maxConcurrency; constructor(providers?: OrdinalsDetector[], options?: OrdinalsMultiProviderDetectorOptions); /** * Check if a UTXO contains protected inscriptions/ordinals using multiple providers */ isProtectedUtxo(utxo: UTXO): Promise<boolean>; /** * Get inscription data from the first provider that has data for this UTXO */ getInscriptionData(utxo: UTXO): Promise<InscriptionData | null>; /** * Get asset data from the first provider that has data for this UTXO * Only returns 'ordinal' or 'inscription' types - never 'stamp' or 'src20' */ getAssetData(utxo: UTXO): Promise<ProtectedAssetData | null>; /** * First-success strategy: Query providers in order until one returns true */ private firstSuccessStrategy; /** * Any-positive strategy: Query all providers in parallel, return true if ANY returns true */ private anyPositiveStrategy; /** * Consensus strategy: Query multiple providers, return true only if majority returns true */ private consensusStrategy; /** * Create a timeout promise that resolves with the given value after the global timeout */ private createTimeoutPromise; /** * Get information about the configured providers */ getProviderInfo(): Array<{ name: string; configured: boolean; }>; /** * Get the current detection strategy */ getStrategy(): DetectionStrategy; /** * Get the number of configured providers */ getProviderCount(): number; } /** * SRC-20 Token Interface Definitions * * Defines types and interfaces for SRC-20 token transactions and configuration. * The actual Bitcoin protocol only requires the dust minimum (546 sats for P2PKH). */ /** * SRC-20 configuration options */ interface SRC20Options { /** * Custom dust threshold for outputs * * @default 546 * @description Bitcoin protocol dust threshold for outputs. * This is a protocol requirement. */ dustThreshold?: number; /** * Fee calculation mode * * @default 'market-aware' * @description How to calculate fees for stamp transactions * - 'market-aware': Use higher fees for stamp-related transactions * - 'standard': Use standard Bitcoin fee rates */ feeMode?: 'market-aware' | 'standard'; } /** * SRC-20 transaction operation types */ type SRC20OperationType = 'DEPLOY' | 'MINT' | 'TRANSFER'; /** * SRC-20 operation structure (generic interface for testing) */ interface SRC20Operation { p: 'SRC-20'; op: SRC20OperationType; tick: string; max?: string; lim?: string; amt?: string | string[]; dec?: string | number; description?: string; x?: string; web?: string; email?: string; tg?: string; img?: string; icon?: string; } /** * Base SRC-20 data structure for protocol JSON */ interface BaseSRC20Data { /** Protocol identifier - REQUIRED, always 'SRC-20' */ p: 'SRC-20'; op: SRC20OperationType; tick: string; } /** * SRC-20 Deploy operation data - protocol-specific interface using 'dec' field */ interface SRC20DeployData extends BaseSRC20Data { op: 'DEPLOY'; max: string; lim: string; dec?: number; x?: string; web?: string; email?: string; tg?: string; description?: string; img?: string; icon?: string; } interface SRC20EncodingOptions extends EncodingOptions { dustValue?: number; network?: Network; /** * Maximum number of outputs to create for encoding SRC-20 data * * @default 2940 (based on Bitcoin's 100KB standard transaction size limit) * @description This is a sanity check based on Bitcoin's relay policy, not a consensus rule. * Bitcoin Core nodes by default will not relay transactions larger than 100KB. * With ~34 bytes per P2WSH output, this allows approximately 2940 outputs. * The actual limit depends on the full transaction size including inputs. * You can set this higher if needed, but be aware of relay policy limits. */ maxOutputs?: number; useCompression?: boolean; fromAddress?: string; toAddress?: string; } interface SRC20EncodingResult extends EncodingResult { /** P2WSH outputs containing the SRC-20 data */ p2wshOutputs: TransactionOutput[]; /** The OP_RETURN output for Counterparty protocol */ opReturnOutput: TransactionOutput; /** The JSON data that was encoded */ jsonData: string; /** Number of chunks created */ chunkCount: number; /** Whether compression was used */ compressionUsed: boolean; /** Total dust value required */ totalDustValue: number; /** Total size of the encoded data (same as dataSize, for backward compatibility) */ totalSize: number; } /** * SRC-20 Mint operation data - protocol-specific interface */ interface SRC20MintData extends BaseSRC20Data { op: 'MINT'; amt: string; } /** * SRC-20 Transfer operation data - protocol-specific interface */ interface SRC20TransferData extends BaseSRC20Data { op: 'TRANSFER'; amt: string; } /** * Union type for all SRC-20 operation data */ type SRC20Data = SRC20DeployData | SRC20MintData | SRC20TransferData; /** * SRC-20 transaction builder options */ interface SRC20BuilderOptions extends SRC20Options { /** * Network to use for transactions */ network?: any; /** * Default fee rate in satoshis per virtual byte * * @default 15 */ defaultFeeRate?: number; /** * Enable Replace-by-Fee (RBF) by default * * @default true */ enableRbf?: boolean; /** * Enable Child-Pays-For-Parent (CPFP) support * * @default false */ enableCPFP?: boolean; /** * Maximum number of inputs to use in a transaction * * @default 50 */ maxInputs?: number; /** * Maximum number of data outputs to create * * @default 10 */ maxDataOutputs?: number; /** * Optional multi-asset protection detector for comprehensive UTXO protection (ordinals, inscriptions, Counterparty assets) * By default, uses MultiAssetProtectionDetector with both ordinals and Counterparty protection */ protectionDetector?: IProtectionDetector; /** * Configuration for the built-in detectors (alternative to providing custom detector). Set to false to disable protection entirely. */ detectorOptions?: OrdinalsMultiProviderDetectorOptions | false; /** * Configuration for MultiAssetProtectionDetector aggregation behavior */ multiAssetOptions?: MultiAssetProtectionDetectorOptions; /** * UTXO provider for fetching unspent outputs */ utxoProvider: any; /** * Selector factory for UTXO selection algorithms */ selectorFactory: any; /** * Optional logger for debugging */ logger?: any; } export { type AggregationStrategy as A, type DetectionStrategy as D, type EncodingResult as E, HiroOrdinalsDetector as H, type InscriptionData as I, MultiAssetProtectionDetector as M, type OrdinalsDetector as O, type SRC20Options as S, type UTXO as U, type SRC20BuilderOptions as a, type SRC20DeployData as b, type SRC20MintData as c, type SRC20TransferData as d, OrdinalsMultiProviderDetector as e, OrdServerDetector as f, type HiroOrdinalsDetectorOptions as g, type MultiAssetProtectionDetectorOptions as h, type OrdinalsMultiProviderDetectorOptions as i, type OrdServerDetectorOptions as j, type IDataEncoder as k, type SRC20Data as l, type SRC20Operation as m, type SRC20EncodingOptions as n, type SRC20EncodingResult as o };