import { defineChain } from 'viem';
import { mainnet, sepolia } from 'viem/chains';
import { chainConfig } from 'viem/op-stack';
let chainByID = {};
let chainByName = {};
const chainListURL = 'https://raw.githubusercontent.com/ethereum-optimism/superchain-registry/refs/heads/main/chainList.json';
export async function initChainConfig() {
    const response = await fetch(chainListURL);
    const chainList = (await response.json());
    chainByID = chainList.reduce((acc, config) => {
        const stringId = config.identifier.split('/')[1];
        const rpcURL = process.env[`${stringId.toUpperCase()}_RPC_URL`] ??
            config.rpc[0];
        const isMainnet = config.parent.chain === 'mainnet';
        // TODO: Does not support custom gas tokens
        acc[config.chainId] = defineChain({
            ...chainConfig,
            id: config.chainId,
            name: stringId,
            sourceId: isMainnet ? mainnet.id : sepolia.id,
            nativeCurrency: {
                name: 'Ether',
                symbol: 'ETH',
                decimals: 18,
            },
            blockExplorers: {
                default: {
                    name: 'Blockscout',
                    url: config.explorers[0],
                },
            },
            rpcUrls: {
                default: {
                    http: [rpcURL],
                },
            },
            multicall: {
                address: '0xcA11bde05977b3631167028862bE2a173976CA11',
            },
        });
        return acc;
    }, {});
    chainByName = chainList.reduce((acc, config) => {
        if (chainByID[config.chainId]) {
            acc[config.identifier] = chainByID[config.chainId];
        }
        return acc;
    }, {});
    return chainList;
}
export function getChainByNetworkIdentifier(l1ID, l2ID) {
    return chainByName[`${l1ID}/${l2ID}`];
}
export function getChainByID(id) {
    return chainByID[id];
}
