"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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.usePoolTokens = void 0;
var react_1 = require("react");
var utils_1 = require("../../utils");
var useQueries_1 = require("../useQueries");
var common_1 = require("../common");
var emptyToken = {
    base: undefined,
    quote: undefined,
    symbol: undefined,
    decimals: undefined,
};
function usePoolTokens(chain, vaultAddress, contract, // either pool, or arrakis vault
forceUseContract) {
    // Returns info about token0 and token1, and which is base / quote.
    // To force use of the contract instead of subgraph (such as for important transactions)
    // ...use the forceUseContract flag.
    if (forceUseContract === void 0) { forceUseContract = false; }
    var provider = (0, common_1.useSignerOrProvider)(chain);
    var _a = __read((0, react_1.useState)({
        base: emptyToken,
        quote: emptyToken,
        token0: emptyToken,
        token1: emptyToken,
        t0IsBase: undefined,
    }), 2), state = _a[0], setState = _a[1];
    var _b = (0, useQueries_1.useArrakisVaultArkiver)(vaultAddress, chain), data = _b.data, error = _b.error, arkiverFailed = _b.failed;
    var getT0IsBase = (0, react_1.useCallback)(function (token0Addr, vaultAddr) {
        var _a, _b;
        if (!vaultAddr || !token0Addr)
            return;
        var id = (_a = (0, utils_1.getDeploymentByAddr)(chain, vaultAddr)) === null || _a === void 0 ? void 0 : _a.id;
        if (!id)
            return;
        var config = utils_1.mmConfig[id];
        if (!config)
            return;
        var t0IsBase = ((_b = config.baseToken) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === (token0Addr === null || token0Addr === void 0 ? void 0 : token0Addr.toLowerCase());
        return t0IsBase;
    }, [chain]);
    (0, react_1.useEffect)(function () {
        var _a, _b, _c, _d, _e, _f;
        function fallback() {
            return __awaiter(this, void 0, void 0, function () {
                var _a, token0_1, token1_1, _b, t0, t1, _c, t0Symbol, t1Symbol, t0Decimals, t1Decimals, t0IsBase_1, t0Obj_1, t1Obj_1, e_1;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0:
                            if (!provider || !contract)
                                return [2 /*return*/];
                            _d.label = 1;
                        case 1:
                            _d.trys.push([1, 4, , 5]);
                            return [4 /*yield*/, Promise.all([
                                    contract === null || contract === void 0 ? void 0 : contract.token0(),
                                    contract === null || contract === void 0 ? void 0 : contract.token1(),
                                ])];
                        case 2:
                            _a = __read.apply(void 0, [_d.sent(), 2]), token0_1 = _a[0], token1_1 = _a[1];
                            if (!token0_1 || !token1_1)
                                return [2 /*return*/];
                            _b = __read([
                                (0, utils_1.getErc20)(token0_1, provider),
                                (0, utils_1.getErc20)(token1_1, provider),
                            ], 2), t0 = _b[0], t1 = _b[1];
                            return [4 /*yield*/, Promise.all([
                                    t0 === null || t0 === void 0 ? void 0 : t0.symbol(),
                                    t1 === null || t1 === void 0 ? void 0 : t1.symbol(),
                                    t0 === null || t0 === void 0 ? void 0 : t0.decimals(),
                                    t1 === null || t1 === void 0 ? void 0 : t1.decimals(),
                                ])];
                        case 3:
                            _c = __read.apply(void 0, [_d.sent(), 4]), t0Symbol = _c[0], t1Symbol = _c[1], t0Decimals = _c[2], t1Decimals = _c[3];
                            t0IsBase_1 = getT0IsBase(token0_1, vaultAddress);
                            t0Obj_1 = {
                                contract: t0,
                                address: token0_1,
                                symbol: t0Symbol,
                                decimals: t0Decimals,
                                isBase: t0IsBase_1,
                            };
                            t1Obj_1 = {
                                contract: t1,
                                address: token1_1,
                                symbol: t1Symbol,
                                decimals: t1Decimals,
                                isBase: !t0IsBase_1,
                            };
                            setState({
                                base: t0IsBase_1 ? t0Obj_1 : t1Obj_1,
                                quote: t0IsBase_1 ? t1Obj_1 : t0Obj_1,
                                token0: t0Obj_1,
                                token1: t1Obj_1,
                                t0IsBase: t0IsBase_1,
                            });
                            return [3 /*break*/, 5];
                        case 4:
                            e_1 = _d.sent();
                            console.error(e_1);
                            return [3 /*break*/, 5];
                        case 5: return [2 /*return*/];
                    }
                });
            });
        }
        // if error, fallback to contract calls
        var vaultAddr = vaultAddress || ((_b = (_a = data === null || data === void 0 ? void 0 : data.Vaults) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.address);
        if (!vaultAddr)
            return;
        if (forceUseContract) {
            console.log('forced to use fallback() in usePoolTokens()');
            fallback();
            return;
        }
        if (arkiverFailed) {
            // Data was queried but no vault was found.
            // Or, error was thrown, and either query failed or no vault was found.
            console.log('falling back in usePoolTokens()');
            fallback();
            return;
        }
        if (!vaultAddr)
            return;
        if (!data)
            return;
        // get tokens from subgraph
        var _g = ((_c = data === null || data === void 0 ? void 0 : data.Vaults) === null || _c === void 0 ? void 0 : _c[0]) || {}, token0 = _g.token0, token1 = _g.token1;
        var t0IsBase = getT0IsBase((_f = (_e = (_d = data === null || data === void 0 ? void 0 : data.Vaults) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.token0) === null || _f === void 0 ? void 0 : _f.address, vaultAddr);
        if (t0IsBase == null)
            return;
        var sOrP = (contract === null || contract === void 0 ? void 0 : contract.signer) || provider;
        if (!sOrP)
            return;
        var t0Obj = __assign({ contract: (token0 === null || token0 === void 0 ? void 0 : token0.address) && sOrP ? (0, utils_1.getErc20)(token0 === null || token0 === void 0 ? void 0 : token0.address, sOrP) : undefined, isBase: t0IsBase }, token0);
        var t1Obj = __assign({ contract: (token1 === null || token1 === void 0 ? void 0 : token1.address) && sOrP ? (0, utils_1.getErc20)(token1 === null || token1 === void 0 ? void 0 : token1.address, sOrP) : undefined, isBase: !t0IsBase }, token1);
        setState({
            base: t0IsBase ? t0Obj : t1Obj,
            quote: t0IsBase ? t1Obj : t0Obj,
            token0: t0Obj,
            token1: t1Obj,
            t0IsBase: t0IsBase,
        });
    }, [
        data,
        error,
        contract,
        getT0IsBase,
        provider,
        forceUseContract,
        vaultAddress,
    ]);
    return state;
}
exports.usePoolTokens = usePoolTokens;
//# sourceMappingURL=usePoolTokens.js.map