"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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTotalTvl = void 0;
var client_1 = require("@apollo/client");
var react_1 = require("react");
var getTotalTvlQuery_1 = require("../gql/subgraphQueries/getTotalTvlQuery");
var utils_1 = require("../utils");
function useTotalTvl() {
    var _a = __read((0, react_1.useState)(), 2), totalTvl = _a[0], setTotalTvl = _a[1];
    var _b = __read((0, react_1.useState)(true), 2), loading = _b[0], setLoading = _b[1];
    var client = (0, client_1.useApolloClient)();
    (0, react_1.useEffect)(function () {
        if (client)
            updateTotalTvl();
    }, [!!client]);
    function updateTotalTvl() {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var chains, subgraphData, allVaultData, tvlBySymbol, usdTvls, newTotalTvl;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        setLoading(true);
                        if (!client)
                            return [2 /*return*/];
                        chains = (0, utils_1.getRelevantChains)();
                        return [4 /*yield*/, Promise.all(chains === null || chains === void 0 ? void 0 : chains.map(function (chainProp) { return __awaiter(_this, void 0, void 0, function () {
                                var chain, data, e_1;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            if (chainProp === 'localhost')
                                                return [2 /*return*/];
                                            if (chainProp === 'ALL')
                                                return [2 /*return*/];
                                            chain = chainProp;
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 3, , 4]);
                                            return [4 /*yield*/, client.query({
                                                    query: getTotalTvlQuery_1.GET_TOTAL_TVL_QUERY,
                                                    context: { chain: chain },
                                                    variables: {
                                                        network: (0, utils_1.fixChainId)(chain),
                                                    },
                                                })];
                                        case 2:
                                            data = (_a.sent()).data;
                                            return [2 /*return*/, data];
                                        case 3:
                                            e_1 = _a.sent();
                                            console.error(e_1);
                                            return [3 /*break*/, 4];
                                        case 4: return [2 /*return*/];
                                    }
                                });
                            }); }))];
                    case 1:
                        subgraphData = _b.sent();
                        allVaultData = subgraphData.flatMap(function (x) { return x; });
                        tvlBySymbol = allVaultData === null || allVaultData === void 0 ? void 0 : allVaultData.reduce(function (acc, data) {
                            var _a, _b, _c, _d, _e, _f;
                            for (var key in data === null || data === void 0 ? void 0 : data.scyVaults) {
                                // add all scy tvls
                                var scyVault = data === null || data === void 0 ? void 0 : data.scyVaults[key];
                                var symbol = (scyVault === null || scyVault === void 0 ? void 0 : scyVault.underlyingSymbol) || 'Unknown';
                                var uDec = (_a = scyVault === null || scyVault === void 0 ? void 0 : scyVault.underlyingDecimals) !== null && _a !== void 0 ? _a : 0;
                                var tvlBN = (_b = scyVault === null || scyVault === void 0 ? void 0 : scyVault.tvl) !== null && _b !== void 0 ? _b : (0, utils_1.toBN)(0);
                                var thisTvl = (0, utils_1.bnToNumber)(tvlBN, uDec);
                                var prevTvl = (_c = acc[symbol]) !== null && _c !== void 0 ? _c : 0;
                                acc[symbol] = prevTvl + thisTvl;
                            }
                            for (var key in data === null || data === void 0 ? void 0 : data.aggregatorVaults) {
                                // add all agg floats
                                var aggVault = data === null || data === void 0 ? void 0 : data.aggregatorVaults[key];
                                var symbol = (aggVault === null || aggVault === void 0 ? void 0 : aggVault.underlyingSymbol) || 'Unknown';
                                var uDec = (_d = aggVault === null || aggVault === void 0 ? void 0 : aggVault.underlyingDecimals) !== null && _d !== void 0 ? _d : 0;
                                var floatBN = (_e = aggVault === null || aggVault === void 0 ? void 0 : aggVault.float) !== null && _e !== void 0 ? _e : (0, utils_1.toBN)(0);
                                var thisTvl = (0, utils_1.bnToNumber)(floatBN, uDec);
                                var prevTvl = (_f = acc[symbol]) !== null && _f !== void 0 ? _f : 0;
                                acc[symbol] = prevTvl + thisTvl;
                            }
                            return acc;
                        }, {});
                        return [4 /*yield*/, Promise.all((_a = Object.keys(tvlBySymbol)) === null || _a === void 0 ? void 0 : _a.map(function (symbol) {
                                return __awaiter(this, void 0, void 0, function () {
                                    var nativeTvl, price, e_2;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                nativeTvl = tvlBySymbol[symbol];
                                                if ((symbol === null || symbol === void 0 ? void 0 : symbol.toLowerCase()) === 'usdc')
                                                    return [2 /*return*/, nativeTvl];
                                                _a.label = 1;
                                            case 1:
                                                _a.trys.push([1, 3, , 4]);
                                                return [4 /*yield*/, (0, utils_1.getPriceById)(symbol)];
                                            case 2:
                                                price = _a.sent();
                                                if (price == null || price === 0)
                                                    throw new Error('No price from coingecko');
                                                else {
                                                    return [2 /*return*/, nativeTvl / price];
                                                }
                                                return [3 /*break*/, 4];
                                            case 3:
                                                e_2 = _a.sent();
                                                setLoading(false);
                                                throw new Error(e_2);
                                            case 4: return [2 /*return*/];
                                        }
                                    });
                                });
                            }))];
                    case 2:
                        usdTvls = _b.sent();
                        newTotalTvl = usdTvls === null || usdTvls === void 0 ? void 0 : usdTvls.reduce(function (acc, x) { return (acc = (acc || 0) + (x || 0)); }, 0);
                        if (usdTvls === null || usdTvls === void 0 ? void 0 : usdTvls.length)
                            setTotalTvl(newTotalTvl);
                        setLoading(false);
                        return [2 /*return*/];
                }
            });
        });
    }
    return { totalTvl: totalTvl, loading: loading };
}
exports.useTotalTvl = useTotalTvl;
//# sourceMappingURL=useTotalTvl.js.map