"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriceFeed = void 0;
const baseAdapter_1 = require("./baseAdapter");
class PriceFeed extends baseAdapter_1.BaseHTTPAdapter {
    apiKey = undefined;
    constructor({ name, apiKey, timeout = 5000, retries = 3 } = {}) {
        super(name ?? apiKey ? "CoinGecko Pro" : "CoinGecko Free", apiKey ? "pro-api.coingecko.com" : "api.coingecko.com", {
            timeout,
            retries,
        });
        this.apiKey = apiKey;
    }
    async getPriceByAddress(address, currency = "usd") {
        const price = await this.getPricesByAddress([address], currency);
        return price[0];
    }
    async getPricesByAddress(addresses, currency = "usd") {
        const queryArgs = {
            contract_addresses: addresses.map((address) => address.toLowerCase()).join(","),
            vs_currencies: currency,
            include_last_updated_at: true,
        };
        if (this.apiKey)
            queryArgs["x_cg_pro_api_key"] = this.apiKey;
        const prices = await this.query("api/v3/simple/token_price/ethereum", queryArgs);
        if (!this.validateResponse(prices, currency))
            throw new Error(`Unexpected ${this.name} response: ${JSON.stringify(prices)}`);
        return addresses
            .filter((address) => prices[address.toLowerCase()] !== undefined)
            .map((address) => {
            const price = prices[address.toLowerCase()];
            return { address, price: price[currency], timestamp: price.last_updated_at };
        });
    }
    validateResponse(response, currency) {
        if (typeof response !== "object")
            return false;
        return Object.entries(response).every(([address, tokenPrice]) => {
            return (/0x[0-9a-fA-F]{40}/.exec(address) !== undefined
                && typeof tokenPrice === "object"
                && !isNaN(tokenPrice[currency])
                && !isNaN(tokenPrice.last_updated_at));
        });
    }
}
exports.PriceFeed = PriceFeed;
//# sourceMappingURL=coingecko.js.map