#!/usr/bin/env python3 """ Interactive Bitcoin Fee Rate Calculator Real-time dust threshold calculations across fee environments """ import json import math from typing import Dict, List, Optional, Any from dataclasses import dataclass from datetime import datetime @dataclass class FeeScenario: """Fee rate scenario for analysis""" sat_per_vbyte: float name: str description: str class InteractiveFeeCalculator: """Interactive fee rate and dust calculator""" def __init__(self): self.scenarios = [ FeeScenario(1.0, "Minimum", "Network minimum fee"), FeeScenario(2.5, "Low", "Low priority"), FeeScenario(5.0, "Standard", "Standard priority"), FeeScenario(10.0, "High", "High priority"), FeeScenario(25.0, "Very High", "Urgent transactions"), FeeScenario(50.0, "Extreme", "Emergency transactions"), FeeScenario(100.0, "Crisis", "Network congestion crisis"), ] # Dust thresholds by script type self.dust_thresholds = { 'p2pkh': 546, 'p2wpkh': 294, 'p2sh': 294, 'p2tr': 330 } # Transaction size estimates (vbytes) self.tx_sizes = { 'p2pkh': {'input': 148, 'output': 34}, 'p2wpkh': {'input': 68, 'output': 31}, 'p2sh': {'input': 91, 'output': 32}, 'p2tr': {'input': 64, 'output': 43} } def calculate_dust_threshold(self, script_type: str, fee_rate: float) -> Dict[str, Any]: """Calculate dynamic dust threshold based on fee rate""" base_dust = self.dust_thresholds[script_type] # Calculate cost to spend dust at current fee rate spend_cost = self.tx_sizes[script_type]['input'] * fee_rate + \ self.tx_sizes[script_type]['output'] * fee_rate # Economic dust threshold (where spending costs > 50% of value) economic_dust = spend_cost * 2 return { 'script_type': script_type, 'fee_rate': fee_rate, 'protocol_dust': base_dust, 'spend_cost': spend_cost, 'economic_dust': economic_dust, 'is_economical': base_dust > spend_cost, 'waste_percentage': (spend_cost / base_dust * 100) if base_dust > 0 else 100 } def calculate_utxo_economics(self, utxo_value: int, script_type: str, fee_rate: float, target_outputs: int = 1) -> Dict[str, Any]: """Calculate complete UTXO economics""" # Transaction costs input_size = self.tx_sizes[script_type]['input'] output_size = self.tx_sizes[script_type]['output'] * target_outputs total_size = input_size + output_size + 10 # +10 for tx overhead fee = math.ceil(total_size * fee_rate) # Minimum output values min_output_value = self.dust_thresholds[script_type] * target_outputs # Analysis is_spendable = utxo_value > (fee + min_output_value) is_protocol_dust = utxo_value <= self.dust_thresholds[script_type] is_economic_dust = utxo_value <= (fee * 2) # Efficiency metrics fee_percentage = (fee / utxo_value * 100) if utxo_value > 0 else 100 net_value = utxo_value - fee return { 'utxo_value': utxo_value, 'script_type': script_type, 'fee_rate': fee_rate, 'target_outputs': target_outputs, 'transaction_size': total_size, 'fee': fee, 'min_output_value': min_output_value, 'is_spendable': is_spendable, 'is_protocol_dust': is_protocol_dust, 'is_economic_dust': is_economic_dust, 'fee_percentage': fee_percentage, 'net_value': net_value, 'efficiency': 'high' if fee_percentage < 5 else 'medium' if fee_percentage < 15 else 'low' } def generate_fee_matrix(self) -> Dict[str, Any]: """Generate comprehensive fee analysis matrix""" matrix = { 'timestamp': datetime.now().isoformat(), 'scenarios': {}, 'dust_analysis': {}, 'economic_thresholds': {} } # Analyze each scenario for scenario in self.scenarios: scenario_data = { 'fee_rate': scenario.sat_per_vbyte, 'name': scenario.name, 'description': scenario.description, 'script_types': {} } for script_type in self.dust_thresholds.keys(): # Dust analysis dust_info = self.calculate_dust_threshold(script_type, scenario.sat_per_vbyte) # Test different UTXO values test_values = [100, 500, 1000, 2500, 5000, 10000, 25000, 50000] utxo_tests = [] for value in test_values: utxo_info = self.calculate_utxo_economics(value, script_type, scenario.sat_per_vbyte) utxo_tests.append(utxo_info) scenario_data['script_types'][script_type] = { 'dust_analysis': dust_info, 'utxo_tests': utxo_tests, 'min_economic_value': dust_info['economic_dust'] } matrix['scenarios'][scenario.name] = scenario_data # Calculate economic thresholds across all scenarios for script_type in self.dust_thresholds.keys(): threshold_data = { 'script_type': script_type, 'protocol_dust': self.dust_thresholds[script_type], 'fee_scenarios': [] } for scenario in self.scenarios: dust_info = self.calculate_dust_threshold(script_type, scenario.sat_per_vbyte) threshold_data['fee_scenarios'].append({ 'fee_rate': scenario.sat_per_vbyte, 'scenario_name': scenario.name, 'economic_dust': dust_info['economic_dust'], 'spend_cost': dust_info['spend_cost'], 'waste_percentage': dust_info['waste_percentage'] }) matrix['economic_thresholds'][script_type] = threshold_data return matrix def find_break_even_points(self) -> Dict[str, Any]: """Calculate break-even points where dust becomes spendable""" break_even = { 'timestamp': datetime.now().isoformat(), 'script_types': {} } for script_type in self.dust_thresholds.keys(): script_data = { 'script_type': script_type, 'break_even_points': [] } # Find fee rate where protocol dust becomes economically spendable protocol_dust = self.dust_thresholds[script_type] for fee_rate in [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0]: spend_cost = self.tx_sizes[script_type]['input'] * fee_rate + \ self.tx_sizes[script_type]['output'] * fee_rate # Break-even when spend cost <= 50% of dust value is_break_even = spend_cost <= (protocol_dust * 0.5) script_data['break_even_points'].append({ 'fee_rate': fee_rate, 'spend_cost': spend_cost, 'protocol_dust': protocol_dust, 'is_break_even': is_break_even, 'efficiency_ratio': (protocol_dust / spend_cost) if spend_cost > 0 else 0 }) break_even['script_types'][script_type] = script_data return break_even def create_interactive_calculator_data(self) -> Dict[str, Any]: """Create data structure for interactive calculator""" calculator_data = { 'timestamp': datetime.now().isoformat(), 'fee_scenarios': [ { 'rate': scenario.sat_per_vbyte, 'name': scenario.name, 'description': scenario.description } for scenario in self.scenarios ], 'script_types': [ { 'type': script_type, 'dust_threshold': self.dust_thresholds[script_type], 'tx_sizes': self.tx_sizes[script_type] } for script_type in self.dust_thresholds.keys() ], 'precomputed_matrix': self.generate_fee_matrix(), 'break_even_analysis': self.find_break_even_points() } return calculator_data def main(): """Run interactive fee calculator analysis""" calculator = InteractiveFeeCalculator() # Generate comprehensive analysis fee_matrix = calculator.generate_fee_matrix() break_even = calculator.find_break_even_points() interactive_data = calculator.create_interactive_calculator_data() # Example calculations example_utxo = calculator.calculate_utxo_economics(1000, 'p2wpkh', 5.0) example_dust = calculator.calculate_dust_threshold('p2tr', 10.0) results = { 'fee_matrix': fee_matrix, 'break_even_analysis': break_even, 'interactive_calculator_data': interactive_data, 'examples': { 'utxo_economics': example_utxo, 'dust_threshold': example_dust } } # Save results with open('interactive_fee_calculator.json', 'w') as f: json.dump(results, f, indent=2) print("✅ Interactive fee calculator analysis complete") print(f"📊 Analyzed {len(calculator.scenarios)} fee scenarios") print(f"💰 Example UTXO efficiency: {example_utxo['efficiency']}") print(f"🎯 Break-even points calculated for {len(break_even['script_types'])} script types") return results if __name__ == "__main__": main()