#!/usr/bin/env node
/**
 * Token Extraction Helper for ALL Mainnet
 * 
 * This script helps extract token information from ALL Mainnet explorer
 * or queries RPC for token metadata.
 * 
 * Usage:
 *   node extract-tokens-from-explorer.js <token-address> [token-address2 ...]
 */

import { ethers } from 'ethers';

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

// ERC-20 ABI (minimal)
const ERC20_ABI = [
  'function symbol() view returns (string)',
  'function name() view returns (string)',
  'function decimals() view returns (uint8)',
  'function totalSupply() view returns (uint256)'
];

async function getTokenInfo(address) {
  try {
    const provider = new ethers.JsonRpcProvider(RPC_URL);
    
    // Verify chain ID
    const network = await provider.getNetwork();
    if (Number(network.chainId) !== CHAIN_ID) {
      console.error(`⚠️  Chain ID mismatch: expected ${CHAIN_ID}, got ${Number(network.chainId)}`);
    }
    
    // Check if contract exists
    const code = await provider.getCode(address);
    if (code === '0x') {
      console.error(`❌ No contract code at address ${address}`);
      return null;
    }
    
    const contract = new ethers.Contract(address, ERC20_ABI, provider);
    
    const [symbol, name, decimals] = await Promise.all([
      contract.symbol().catch(() => 'UNKNOWN'),
      contract.name().catch(() => 'UNKNOWN'),
      contract.decimals().catch(() => 18)
    ]);
    
    // Checksum address
    const checksummedAddress = ethers.getAddress(address);
    
    return {
      chainId: CHAIN_ID,
      address: checksummedAddress,
      name: name,
      symbol: symbol,
      decimals: Number(decimals),
      verified: code !== '0x'
    };
  } catch (error) {
    console.error(`❌ Error querying ${address}:`, error.message);
    return null;
  }
}

async function main() {
  const addresses = process.argv.slice(2);
  
  if (addresses.length === 0) {
    console.log('Usage: node extract-tokens-from-explorer.js <token-address> [token-address2 ...]');
    console.log('');
    console.log('Example:');
    console.log('  node extract-tokens-from-explorer.js 0x... 0x...');
    console.log('');
    console.log('To find token addresses:');
    console.log('  1. Visit https://alltra.global/tokens');
    console.log('  2. Copy token contract addresses');
    console.log('  3. Run this script with the addresses');
    process.exit(1);
  }
  
  console.log(`🔍 Querying ${addresses.length} token(s) on ALL Mainnet (ChainID ${CHAIN_ID})...\n`);
  
  const results = [];
  
  for (const address of addresses) {
    console.log(`Querying ${address}...`);
    const info = await getTokenInfo(address);
    if (info) {
      results.push(info);
      console.log(`  ✅ ${info.symbol} (${info.name}) - ${info.decimals} decimals\n`);
    }
  }
  
  if (results.length > 0) {
    console.log('\n📋 Token List JSON:\n');
    console.log(JSON.stringify({
      tokens: results.map(t => ({
        chainId: t.chainId,
        address: t.address,
        name: t.name,
        symbol: t.symbol,
        decimals: t.decimals
      }))
    }, null, 2));
  }
}

main().catch(console.error);
