|
| 1 | +import time |
| 2 | +import random |
| 3 | +import os |
| 4 | +from database import init_db, insert_analysis |
| 5 | +from json_rpc_request import ( |
| 6 | + get_block_count, |
| 7 | + get_block_tx_details, |
| 8 | + get_raw_mempool, |
| 9 | + get_block_template, |
| 10 | + get_estimated_fee_rate_satvb |
| 11 | +) |
| 12 | + |
| 13 | +# Configuration for the collector loop |
| 14 | +COLLECTOR_SLEEP_TIME = 30 # for a new block every 30 seconds |
| 15 | +LAST_PROCESSED_HEIGHT = 0 |
| 16 | +INITIAL_HISTORY_DEPTH = 1000 # The number of blocks to fetch initially |
| 17 | + |
| 18 | +# custom fee logic |
| 19 | + |
| 20 | +def get_custom_fee_prediction_asap() -> float: |
| 21 | + """ |
| 22 | + CRITICAL: This is the placeholder where your custom, robust fee estimation |
| 23 | + logic must be implemented. It should use the latest RPC data to make a prediction. |
| 24 | + |
| 25 | + Returns: A single ASAP feerate prediction in sat/vB. |
| 26 | + """ |
| 27 | + try: |
| 28 | + # 1. Fetch real-time data from the node |
| 29 | + # These are available for your custom logic: |
| 30 | + # mempool_data = get_raw_mempool(verbose=False) |
| 31 | + # block_template = get_block_template() |
| 32 | + |
| 33 | + # A SIMPLE, TEMPORARY MODEL BASED ON Core's 1-Block Estimate |
| 34 | + # REPLACE THIS WITH YOUR CUSTOM LOGIC (Feerate Bucketing, Resting Time Analysis, etc.) |
| 35 | + |
| 36 | + # We use Core's estimate as a reliable temporary proxy for demonstration |
| 37 | + core_estimate = get_estimated_fee_rate_satvb(conf_target=1, mode='conservative') |
| 38 | + predicted_fee = core_estimate.get('feerate_sat_per_vb') |
| 39 | + |
| 40 | + if predicted_fee is None or predicted_fee < 1.0: |
| 41 | + # Fallback for when estimatesmartfee fails |
| 42 | + print("Warning: estimatesmartfee failed. Using a random prediction.") |
| 43 | + return round(random.uniform(5.0, 15.0), 2) |
| 44 | + |
| 45 | + # Add a small random jitter to simulate a model slightly different from Core |
| 46 | + jitter = random.uniform(-0.5, 1.5) |
| 47 | + return max(1.0, predicted_fee + jitter) |
| 48 | + |
| 49 | + except Exception as e: |
| 50 | + print(f"Prediction Error: {e}. Returning fallback fee.") |
| 51 | + return 10.0 # Safe fallback fee |
| 52 | + |
| 53 | +# block processing |
| 54 | + |
| 55 | +def process_block(height: int): |
| 56 | + """ |
| 57 | + Fetches actual block data, runs prediction, and stores the result. |
| 58 | + """ |
| 59 | + try: |
| 60 | + # 1. Run the Prediction Logic (What would we have predicted for this block?) |
| 61 | + # Since we are processing blocks sequentially, we use the current prediction |
| 62 | + # as a proxy for the prediction we would have made just before the block was found. |
| 63 | + predicted_fee = get_custom_fee_prediction_asap() |
| 64 | + |
| 65 | + # 2. Get Actuals (Ground Truth) for the MINED block |
| 66 | + block_details = get_block_tx_details(height) |
| 67 | + |
| 68 | + if block_details and block_details.get('min_fee') is not None: |
| 69 | + min_fee = block_details['min_fee'] |
| 70 | + max_fee = block_details['max_fee'] |
| 71 | + |
| 72 | + # 3. Store the result |
| 73 | + insert_analysis(height, min_fee, max_fee, predicted_fee) |
| 74 | + print(f"[COLLECTOR] Processed Block {height}: Actual Min={min_fee}, Predicted={predicted_fee}") |
| 75 | + return True |
| 76 | + else: |
| 77 | + # This happens if the block is still being processed or is empty/invalid |
| 78 | + print(f"[COLLECTOR] Skipped Block {height}: No valid fee details found.") |
| 79 | + return False |
| 80 | + |
| 81 | + except Exception as e: |
| 82 | + print(f"[COLLECTOR] Error processing block {height}: {e}") |
| 83 | + return False |
| 84 | + |
| 85 | +def run_collector_cycle(initial_population: bool = False): |
| 86 | + """ |
| 87 | + Executes one cycle: detects and processes new blocks since the last check. |
| 88 | + """ |
| 89 | + global LAST_PROCESSED_HEIGHT |
| 90 | + |
| 91 | + current_height = get_block_count() |
| 92 | + if current_height is None: |
| 93 | + return |
| 94 | + |
| 95 | + if LAST_PROCESSED_HEIGHT == 0: |
| 96 | + # On first run, set the last processed height to the current height minus one |
| 97 | + LAST_PROCESSED_HEIGHT = current_height - 1 |
| 98 | + |
| 99 | + |
| 100 | + if initial_population: |
| 101 | + # For initial run, process a large range of historical blocks |
| 102 | + start_height = max(1, current_height - INITIAL_HISTORY_DEPTH) |
| 103 | + print(f"\n[COLLECTOR] Starting initial population from Block {start_height} to {current_height}...") |
| 104 | + else: |
| 105 | + # For continuous run, process only new blocks |
| 106 | + start_height = LAST_PROCESSED_HEIGHT + 1 |
| 107 | + |
| 108 | + |
| 109 | + blocks_to_process = range(start_height, current_height + 1) |
| 110 | + |
| 111 | + for height in blocks_to_process: |
| 112 | + if height > LAST_PROCESSED_HEIGHT: |
| 113 | + if process_block(height): |
| 114 | + LAST_PROCESSED_HEIGHT = height |
| 115 | + else: |
| 116 | + # Skip blocks already processed during initial population |
| 117 | + continue |
| 118 | + |
| 119 | + |
| 120 | +def start_collector(): |
| 121 | + """Main function to run the collector indefinitely.""" |
| 122 | + print("--- Starting Fee Estimation Collector ---") |
| 123 | + |
| 124 | + # 1. Initial Historical Population (fills the database) |
| 125 | + run_collector_cycle(initial_population=True) |
| 126 | + |
| 127 | + print("\nInitial historical population complete. Monitoring for new blocks...") |
| 128 | + |
| 129 | + # 2. Continuous Monitoring Loop |
| 130 | + while True: |
| 131 | + try: |
| 132 | + run_collector_cycle(initial_population=False) |
| 133 | + except Exception as e: |
| 134 | + print(f"[COLLECTOR] Critical main loop error: {e}. Retrying in {COLLECTOR_SLEEP_TIME}s.") |
| 135 | + |
| 136 | + time.sleep(COLLECTOR_SLEEP_TIME) |
| 137 | + |
| 138 | +if __name__ == '__main__': |
| 139 | + init_db() |
| 140 | + start_collector() |
0 commit comments