import { ethers } from 'ethers';

const ABI = [
  'function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)',
  'function decimals() view returns (uint8)',
];

const feeds = [
  ['base',      'ETH/USD',   'https://base-rpc.publicnode.com',                  '0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70'],
  ['base',      'BTC/USD',   'https://base-rpc.publicnode.com',                  '0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F'],
  ['base',      'USDC/USD',  'https://base-rpc.publicnode.com',                  '0x7e860098F58bBFC8648a4311b374B1D669a2bc6B'],
  ['base',      'LINK/USD',  'https://base-rpc.publicnode.com',                  '0x17CAb8FE31E32f08326e5E27412894e49B0f9D65'],
  ['avalanche', 'AVAX/USD',  'https://api.avax.network/ext/bc/C/rpc',            '0x0A77230d17318075983913bC2145DB16C7366156'],
  ['avalanche', 'ETH/USD',   'https://api.avax.network/ext/bc/C/rpc',            '0x976B3D034E162d8bD72D6b9C989d545b839003b0'],
  ['avalanche', 'BTC/USD',   'https://api.avax.network/ext/bc/C/rpc',            '0x2779D32d5166BAaa2B2b658333bA7e6Ec0C65743'],
  ['avalanche', 'LINK/USD',  'https://api.avax.network/ext/bc/C/rpc',            '0x49ccd9ca821EfEab2b98c60dC60F518E765EDe9a'],
  ['arbitrum',  'ETH/USD',   'https://arb1.arbitrum.io/rpc',                     '0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612'],
  ['arbitrum',  'BTC/USD',   'https://arb1.arbitrum.io/rpc',                     '0x6ce185860a4963106506C203335A2910413708e9'],
  ['arbitrum',  'LINK/USD',  'https://arb1.arbitrum.io/rpc',                     '0x86E53CF1B870786351Da77A57575e79CB55812CB'],
  ['polygon',   'MATIC/USD', 'https://polygon-bor-rpc.publicnode.com',           '0xAB594600376Ec9fD91F8e885dADF0CE036862dE0'],
  ['polygon',   'ETH/USD',   'https://polygon-bor-rpc.publicnode.com',           '0xF9680D99D6C9589e2a93a78A04A279e509205945'],
  ['polygon',   'BTC/USD',   'https://polygon-bor-rpc.publicnode.com',           '0xc907E116054Ad103354f2D350FD2514433D57F6f'],
  ['polygon',   'LINK/USD',  'https://polygon-bor-rpc.publicnode.com',           '0xd9FFdb71EbE7496cC440152d43986Aae0AB76665'],
];

const now = Math.floor(Date.now()/1000);
for (const [chain, pair, rpc, addr] of feeds) {
  try {
    const provider = new ethers.JsonRpcProvider(rpc);
    const c = new ethers.Contract(addr, ABI, provider);
    const [r, dec] = await Promise.all([c.latestRoundData(), c.decimals()]);
    const updatedAt = Number(r[3]);
    const age = now - updatedAt;
    const answer = Number(r[1]) / 10 ** Number(dec);
    console.log(`${chain.padEnd(10)} ${pair.padEnd(10)} $${answer.toFixed(4).padStart(14)} dec=${dec} age=${age}s ${age < 86400 ? 'FRESH' : 'STALE'}`);
  } catch (e) {
    console.log(`${chain.padEnd(10)} ${pair.padEnd(10)} FAILED: ${e.shortMessage || e.message}`);
  }
}
