const { ElectrumClient, ElectrumTransport } = require('electrum-cash');
const axios = require('axios');

async function fetchAndExtractAddresses(url) {
    try {
        const response = await axios.get(url);
        const htmlContent = response.data;

        // Regular expression to extract the addresses
        const regex = /">nexa:(.*?)<\/a>/g;

        const addresses = [];
        let match;
        while ((match = regex.exec(htmlContent)) !== null) {
            if (match[1].includes(" ")) {
                continue;
            }
            addresses.push(match[1]);
        }

        return addresses;

    } catch (error) {
        console.error(`Failed to fetch the website or extract addresses. Error: ${error}`);
        return [];
    }
}

async function getBalance(electrum, address) {
    return electrum.request('blockchain.address.get_balance', address);
}

const bch_port = ElectrumTransport.WS.Port;
const nexa_port = 20003;

(async () => {
    const electrum = new ElectrumClient('Test client',
        '1.4.1', '127.0.0.1', nexa_port, ElectrumTransport.WS.Scheme);

    await electrum.connect();

    const addresses = await fetchAndExtractAddresses("https://explorer.nexa.org/rich-list");
    const balances = await Promise.all(addresses.map(addr => getBalance(electrum, addr)));

    console.log(balances);

    electrum.disconnect();

})().catch((e) => { console.error(e) });
