"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPriceById = exports.storePriceStorage = exports.getPriceStorage = void 0;
var cross_fetch_1 = __importDefault(require("cross-fetch"));
var constants_1 = require("./constants");
var coingeckoIdMap = {
    // for networks
    localhost: 'ethereum',
    avalanche: 'avalanche-2',
    mainnet: 'ethereum',
    optimism: 'ethereum',
    arbitrum: 'ethereum',
    // for underlying symbols
    ETH: 'ethereum',
    WETH: 'ethereum',
    weth: 'ethereum',
    USDC: 'usd-coin',
    usdc: 'usd-coin',
    SECT: 'sector',
};
var _a = process.env.PUBLIC_COIN_MARKET_CAP_API, PUBLIC_COIN_MARKET_CAP_API = _a === void 0 ? '' : _a;
function getPriceStorage(currency) {
    if (!(0, constants_1.isBrowser)())
        return;
    var lsId = "price__".concat(currency);
    var obj = localStorage === null || localStorage === void 0 ? void 0 : localStorage.getItem(lsId);
    var _a = (obj && JSON.parse(obj)) || {}, price = _a.price, expires = _a.expires;
    var expired = Date.now() > expires;
    if (expired)
        return;
    return Number(price);
}
exports.getPriceStorage = getPriceStorage;
function storePriceStorage(currency, price) {
    if (!(0, constants_1.isBrowser)())
        return {};
    var lsId = "price__".concat(currency);
    var expires = Date.now() + 1000 * 60 * 30; // 30 min
    localStorage === null || localStorage === void 0 ? void 0 : localStorage.setItem(lsId, JSON.stringify({ price: price, expires: expires }));
    return;
}
exports.storePriceStorage = storePriceStorage;
var getPriceById = function (id) { return __awaiter(void 0, void 0, void 0, function () {
    var currency, price, url, res, json, e_1, url, res, json, key, price, e_2;
    var _a, _b, _c, _d, _e, _f, _g;
    return __generator(this, function (_h) {
        switch (_h.label) {
            case 0:
                currency = coingeckoIdMap[id] || id;
                _h.label = 1;
            case 1:
                _h.trys.push([1, 6, , 12]);
                price = getPriceStorage(currency);
                if (!price) return [3 /*break*/, 2];
                return [2 /*return*/, price];
            case 2:
                url = "https://api.coingecko.com/api/v3/simple/price?ids=".concat(currency, "&vs_currencies=usd");
                return [4 /*yield*/, (0, cross_fetch_1.default)(url, { method: 'Get' })];
            case 3:
                res = _h.sent();
                return [4 /*yield*/, res.json()];
            case 4:
                json = _h.sent();
                price = (_a = json === null || json === void 0 ? void 0 : json[currency]) === null || _a === void 0 ? void 0 : _a.usd;
                if (price != null) {
                    storePriceStorage(currency, price);
                }
                else {
                    throw new Error("Price for ".concat(currency, " from coingecko == null."));
                }
                return [2 /*return*/, price];
            case 5: return [3 /*break*/, 12];
            case 6:
                e_1 = _h.sent();
                console.error("Coingecko API Error: No price found for ".concat(currency), e_1);
                _h.label = 7;
            case 7:
                _h.trys.push([7, 10, , 11]);
                url = "https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=".concat(currency, "&convert=USD");
                return [4 /*yield*/, (0, cross_fetch_1.default)(url, {
                        headers: { 'X-CMC_PRO_API_KEY': PUBLIC_COIN_MARKET_CAP_API },
                    })];
            case 8:
                res = _h.sent();
                return [4 /*yield*/, (res === null || res === void 0 ? void 0 : res.json())];
            case 9:
                json = _h.sent();
                key = (_b = Object.keys(json.data)) === null || _b === void 0 ? void 0 : _b[0];
                price = (_g = (_f = (_e = (_d = (_c = json === null || json === void 0 ? void 0 : json.data) === null || _c === void 0 ? void 0 : _c[key]) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.quote) === null || _f === void 0 ? void 0 : _f.USD) === null || _g === void 0 ? void 0 : _g.price;
                if (price)
                    storePriceStorage(currency, price);
                return [2 /*return*/, price];
            case 10:
                e_2 = _h.sent();
                console.error("Coinmarketcap API Error: No price found for ".concat(currency), e_2);
                return [2 /*return*/];
            case 11: return [3 /*break*/, 12];
            case 12: return [2 /*return*/];
        }
    });
}); };
exports.getPriceById = getPriceById;
//# sourceMappingURL=price.js.map