#!/usr/bin/env node
/**
 * Find tokens via Transfer events
 * ERC-20 tokens emit Transfer events, we can find token addresses this way
 */

import { ethers } from 'ethers';

const RPC_URL = 'https://mainnet-rpc.alltra.global';
const CHAIN_ID = 651940;

// Transfer event signature
const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';

async function findTokensViaEvents() {
  const provider = new ethers.JsonRpcProvider(RPC_URL);
  
  console.log(`🔍 Finding tokens via Transfer events on ALL Mainnet (ChainID ${CHAIN_ID})\n`);
  
  const currentBlock = await provider.getBlockNumber();
  const fromBlock = Math.max(0, currentBlock - 10000); // Last 10k blocks
  
  console.log(`Scanning blocks ${fromBlock} to ${currentBlock} for Transfer events...\n`);
  
  try {
    // Get Transfer events
    const filter = {
      topics: [TRANSFER_TOPIC],
      fromBlock: fromBlock,
      toBlock: currentBlock
    };
    
    const logs = await provider.getLogs(filter);
    console.log(`Found ${logs.length} Transfer events\n`);
    
    // Extract unique contract addresses (token addresses)
    const tokenAddresses = new Set();
    logs.forEach(log => {
      tokenAddresses.add(log.address);
    });
    
    console.log(`Found ${tokenAddresses.size} unique token addresses\n`);
    console.log('Token addresses found:\n');
    
    const addresses = Array.from(tokenAddresses).slice(0, 20); // Limit to first 20
    addresses.forEach((addr, i) => {
      console.log(`${i + 1}. ${addr}`);
    });
    
    if (addresses.length > 0) {
      console.log('\n💡 Use extract-tokens-from-explorer.js to get metadata:');
      console.log(`node token-lists/scripts/extract-tokens-from-explorer.js ${addresses.join(' ')}`);
    }
    
  } catch (error) {
    console.error('Error:', error.message);
    console.log('\n💡 Alternative: Visit https://alltra.global/tokens to get token addresses');
  }
}

findTokensViaEvents().catch(console.error);
