import time
from datetime import datetime, timedelta
from web3 import Web3

API_KEY = "6db42aeb3b1e4572bb72d1ae305e2e0b"
INFURA_URL = f"https://mainnet.infura.io/v3/{API_KEY}"
web3 = Web3(Web3.HTTPProvider(INFURA_URL))

# Uniswap V2 & V3 Router Addresses
UNISWAP_V2_ROUTER = Web3.to_checksum_address("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
UNISWAP_V3_ROUTER = Web3.to_checksum_address("0xE592427A0AEce92De3Edee1F18E0157C05861564")

# Number of blocks in ~7 days (Ethereum block ~12 sec)
BLOCKS_7_DAYS = int((7 * 24 * 60 * 60) / 12)
BLOCKS_7_DAYS = int((1 * 60 * 60) / 12)

def get_current_block():
    return web3.eth.block_number

def fetch_router_txs(contract_address, from_block, to_block):
    txs = []
    CHUNK_SIZE = 3000
    current = from_block
    while current <= to_block:
        end = min(current + CHUNK_SIZE - 1, to_block)
        print(f"Consultando bloques {current}-{end}...")
        try:
            for i, block_num in enumerate(range(current, end + 1)):
                block = web3.eth.get_block(block_num, full_transactions=True)
                for tx in block["transactions"]:
                    if tx["to"] and tx["to"].lower() == contract_address.lower():
                        txs.append(tx)
                if i % 100 == 0:
                    time.sleep(1)
        except Exception as e:
            print(f"Error al procesar bloques {current}-{end}: {e}. Reintentando en 5s...")
            time.sleep(5)
            continue
        current = end + 1
    return txs

def main():
    current_block = get_current_block()
    from_block = current_block - BLOCKS_7_DAYS

    print("Buscando transacciones en Uniswap V2 Router...")
    v2_txs = fetch_router_txs(UNISWAP_V2_ROUTER, from_block, current_block)

    print("Buscando transacciones en Uniswap V3 Router...")
    v3_txs = fetch_router_txs(UNISWAP_V3_ROUTER, from_block, current_block)

    all_txs = v2_txs + v3_txs

    print(f"Total de transacciones encontradas: {len(all_txs)}")

    wallet_activity = {}

    for tx in all_txs:
        sender = tx["from"]
        wallet_activity[sender] = wallet_activity.get(sender, 0) + 1

    # Ordenar por número de transacciones
    sorted_wallets = sorted(wallet_activity.items(), key=lambda x: x[1], reverse=True)

    print("\nWallets con más transacciones en Uniswap Routers los últimos 7 días:")
    for wallet, count in sorted_wallets[:20]:
        print(f"- {wallet} -> {count} transacciones")

if __name__ == "__main__":
    main()