"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppTokenTemplatePositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = __importStar(require("lodash"));
const app_toolkit_interface_1 = require("../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../app-toolkit/constants/address");
const drill_balance_helper_1 = require("../../app-toolkit/helpers/drill-balance.helper");
const display_item_present_1 = require("../../app-toolkit/helpers/presentation/display-item.present");
const image_present_1 = require("../../app-toolkit/helpers/presentation/image.present");
const multicall_ethers_1 = require("../../multicall/multicall.ethers");
const contract_interface_1 = require("../../position/contract.interface");
const position_interface_1 = require("../../position/position.interface");
let AppTokenTemplatePositionFetcher = class AppTokenTemplatePositionFetcher {
    constructor(appToolkit) {
        this.appToolkit = appToolkit;
        this.isDebt = false;
        this.isExcludedFromBalances = false;
        this.isExcludedFromExplore = false;
        this.isExcludedFromTvl = false;
        this.minLiquidity = 1000;
    }
    getDefinitions(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const addresses = yield this.getAddresses(Object.assign(Object.assign({}, params), { definitions: [] }));
            return addresses.map(address => ({ address: address.toLowerCase() }));
        });
    }
    getSymbol({ address, multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
            return multicall.wrap(erc20).symbol();
        });
    }
    getDecimals({ address, multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
            return multicall.wrap(erc20).decimals();
        });
    }
    getSupply({ address, multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const erc20 = this.appToolkit.globalContracts.erc20({ address, network: this.network });
            return multicall.wrap(erc20).totalSupply();
        });
    }
    getPrice({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, lodash_1.sum)(appToken.tokens.map((v, i) => v.price * appToken.pricePerShare[i]));
        });
    }
    getLiquidity({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (this.isDebt ? -1 : 1) * appToken.price * appToken.supply;
        });
    }
    getReserves({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.pricePerShare.map(v => v * appToken.supply);
        });
    }
    getApy(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return 0;
        });
    }
    getDataProps(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const [liquidity, reserves, apy] = yield Promise.all([
                this.getLiquidity(params),
                this.getReserves(params),
                this.getApy(params),
            ]);
            return { liquidity, reserves, apy };
        });
    }
    getLabel({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.symbol;
        });
    }
    getLabelDetailed(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return undefined;
        });
    }
    getSecondaryLabel({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, display_item_present_1.buildDollarDisplayItem)(appToken.price);
        });
    }
    getTertiaryLabel({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof appToken.dataProps.apy === 'number' && appToken.dataProps.apy > 0)
                return `${appToken.dataProps.apy.toFixed(3)}% APY`;
            return undefined;
        });
    }
    getImages({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.tokens.flatMap(v => (0, image_present_1.getImagesFromToken)(v));
        });
    }
    getBalanceDisplayMode(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return undefined;
        });
    }
    getStatsItems({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            const statsItems = [];
            if (typeof appToken.dataProps.liquidity === 'number')
                statsItems.push({ label: 'Liquidity', value: (0, display_item_present_1.buildDollarDisplayItem)(appToken.dataProps.liquidity) });
            if (typeof appToken.dataProps.apy === 'number' && appToken.dataProps.apy > 0)
                statsItems.push({ label: 'APY', value: (0, display_item_present_1.buildPercentageDisplayItem)(appToken.dataProps.apy) });
            return statsItems;
        });
    }
    getPositionsForBatch(definitions) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector({
                tags: { network: this.network, context: `${this.appId}__template` },
            });
            const maybeSkeletons = yield Promise.all(definitions.map((definition) => __awaiter(this, void 0, void 0, function* () {
                const address = definition.address.toLowerCase();
                const contract = multicall.wrap(this.getContract(address));
                const context = { address, definition, contract, multicall, tokenLoader };
                const underlyingTokenDefinitions = yield this.getUnderlyingTokenDefinitions(context)
                    .then(v => v.map(t => ({ address: t.address.toLowerCase(), network: t.network, tokenId: t.tokenId })))
                    .catch(err => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                        return null;
                    throw err;
                });
                if (!underlyingTokenDefinitions)
                    return null;
                return { address, definition, underlyingTokenDefinitions };
            })));
            const skeletons = (0, lodash_1.compact)(maybeSkeletons);
            const [base, meta] = (0, lodash_1.partition)(skeletons, t => {
                const tokenAddresses = skeletons.map(v => v.address);
                const underlyingTokenAddresses = t.underlyingTokenDefinitions.map(v => v.address);
                return (0, lodash_1.intersection)(underlyingTokenAddresses, tokenAddresses).length === 0;
            });
            const currentTokens = [];
            for (const skeletonsSubset of [base, meta]) {
                const underlyingTokenQueries = skeletons.flatMap(v => v.underlyingTokenDefinitions);
                const underlyingTokenRequestsUnique = (0, lodash_1.uniqWith)(underlyingTokenQueries, lodash_1.isEqual);
                const tokenDependencies = yield tokenLoader
                    .getMany(underlyingTokenRequestsUnique)
                    .then(tokenDeps => (0, lodash_1.compact)(tokenDeps));
                const allTokens = [...currentTokens, ...tokenDependencies];
                const skeletonsWithResolvedTokens = yield Promise.all(skeletonsSubset.map(({ address, definition, underlyingTokenDefinitions }) => __awaiter(this, void 0, void 0, function* () {
                    const maybeTokens = underlyingTokenDefinitions.map(definition => {
                        const match = allTokens.find(token => {
                            var _a;
                            const isAddressMatch = token.address === definition.address;
                            const isNetworkMatch = token.network === definition.network;
                            const isMaybeTokenIdMatch = (0, lodash_1.isUndefined)(definition.tokenId) ||
                                (token.type === contract_interface_1.ContractType.APP_TOKEN && token.dataProps.tokenId === definition.tokenId) ||
                                (token.type === contract_interface_1.ContractType.NON_FUNGIBLE_TOKEN &&
                                    Number((_a = token.assets) === null || _a === void 0 ? void 0 : _a[0].tokenId) === definition.tokenId);
                            return isAddressMatch && isNetworkMatch && isMaybeTokenIdMatch;
                        });
                        return match;
                    });
                    const tokens = (0, lodash_1.compact)(maybeTokens);
                    if (maybeTokens.length !== tokens.length)
                        return null;
                    const collapsedTokens = tokens.reduce((acc, token) => {
                        var _a, _b;
                        if (token.type !== contract_interface_1.ContractType.NON_FUNGIBLE_TOKEN)
                            return [...acc, token];
                        const existingNftCollection = acc
                            .filter(position_interface_1.isNonFungibleToken)
                            .find(v => v.address === token.address && v.network === token.network);
                        if (existingNftCollection) {
                            (_a = existingNftCollection.assets) !== null && _a !== void 0 ? _a : (existingNftCollection.assets = []);
                            existingNftCollection.assets.push(...((_b = token.assets) !== null && _b !== void 0 ? _b : []));
                            existingNftCollection.assets = existingNftCollection.assets.slice(0, 5);
                            return acc;
                        }
                        return [...acc, token];
                    }, []);
                    return { address, definition, tokens: collapsedTokens };
                })));
                const tokens = yield Promise.all((0, lodash_1.compact)(skeletonsWithResolvedTokens).map(({ address, definition, tokens }) => __awaiter(this, void 0, void 0, function* () {
                    const contract = multicall.wrap(this.getContract(address));
                    const baseContext = { address, contract, multicall, tokenLoader, definition };
                    const baseFragment = {
                        type: contract_interface_1.ContractType.APP_TOKEN,
                        appId: this.appId,
                        groupId: this.groupId,
                        network: this.network,
                        address,
                        tokens,
                    };
                    const tokenPropsContext = Object.assign(Object.assign({}, baseContext), { appToken: baseFragment });
                    const [symbol, decimals, totalSupplyRaw] = yield Promise.all([
                        this.getSymbol(tokenPropsContext),
                        this.getDecimals(tokenPropsContext),
                        this.getSupply(tokenPropsContext),
                    ]);
                    const supply = Number(totalSupplyRaw) / Math.pow(10, decimals);
                    const pricePerShareStageFragment = Object.assign(Object.assign({}, baseFragment), { symbol, decimals, supply });
                    const pricePerShareContext = Object.assign(Object.assign({}, baseContext), { appToken: pricePerShareStageFragment });
                    const pricePerShare = yield this.getPricePerShare(pricePerShareContext).then(v => ((0, lodash_1.isArray)(v) ? v : [v]));
                    const priceStageFragment = Object.assign(Object.assign({}, pricePerShareStageFragment), { pricePerShare });
                    const priceContext = Object.assign(Object.assign({}, baseContext), { appToken: priceStageFragment });
                    const price = yield this.getPrice(priceContext);
                    const dataPropsStageFragment = Object.assign(Object.assign({}, priceStageFragment), { price });
                    const dataPropsStageParams = Object.assign(Object.assign({}, baseContext), { appToken: dataPropsStageFragment });
                    const dataProps = yield this.getDataProps(dataPropsStageParams);
                    const displayPropsStageFragment = Object.assign(Object.assign({}, dataPropsStageFragment), { dataProps });
                    const displayPropsStageParams = Object.assign(Object.assign({}, baseContext), { appToken: displayPropsStageFragment });
                    const displayProps = {
                        label: yield this.getLabel(displayPropsStageParams),
                        labelDetailed: yield this.getLabelDetailed(displayPropsStageParams),
                        secondaryLabel: yield this.getSecondaryLabel(displayPropsStageParams),
                        tertiaryLabel: yield this.getTertiaryLabel(displayPropsStageParams),
                        images: yield this.getImages(displayPropsStageParams),
                        statsItems: yield this.getStatsItems(displayPropsStageParams),
                        balanceDisplayMode: yield this.getBalanceDisplayMode(displayPropsStageParams),
                    };
                    const appToken = Object.assign(Object.assign({}, displayPropsStageFragment), { displayProps });
                    const key = this.appToolkit.getPositionKey(appToken);
                    return Object.assign({ key }, appToken);
                })));
                const positionsSubset = (0, lodash_1.compact)(tokens);
                currentTokens.push(...positionsSubset);
            }
            return (0, lodash_1.sortBy)(currentTokens, t => {
                if (typeof t.dataProps.liquidity === 'number')
                    return -t.dataProps.liquidity;
                return 1;
            });
        });
    }
    getPositions() {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector({
                tags: { network: this.network, context: `${this.appId}__template` },
            });
            const definitions = yield this.getDefinitions({ multicall, tokenLoader });
            return this.getPositionsForBatch(definitions);
        });
    }
    getAccountAddress(address) {
        return __awaiter(this, void 0, void 0, function* () {
            return address;
        });
    }
    getPositionsForBalances() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.appToolkit.getAppTokenPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
        });
    }
    getBalancePerToken({ address, appToken, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return multicall.wrap(this.getContract(appToken.address)).balanceOf(address);
        });
    }
    getBalances(_address) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const address = yield this.getAccountAddress(_address);
            const appTokens = yield this.getPositionsForBalances();
            if (address === address_1.ZERO_ADDRESS)
                return [];
            const balances = yield Promise.all(appTokens.map((appToken) => __awaiter(this, void 0, void 0, function* () {
                const balanceRaw = yield this.getBalancePerToken({ multicall, address, appToken });
                const tokenBalance = (0, drill_balance_helper_1.drillBalance)(appToken, balanceRaw.toString(), { isDebt: this.isDebt });
                return tokenBalance;
            })));
            return balances;
        });
    }
    getRawBalances(_address) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const address = yield this.getAccountAddress(_address);
            if (address === address_1.ZERO_ADDRESS)
                return [];
            const appTokens = yield this.getPositionsForBalances();
            let results = [];
            for (const batch of lodash_1.default.chunk(appTokens, 100).values()) {
                results = results.concat(yield Promise.all(batch.map((appToken) => __awaiter(this, void 0, void 0, function* () {
                    return ({
                        key: this.appToolkit.getPositionKey(appToken),
                        balance: (yield this.getBalancePerToken({ multicall, address, appToken })).toString(),
                    });
                }))));
            }
            return results;
        });
    }
    drillRawBalances(balances) {
        return __awaiter(this, void 0, void 0, function* () {
            const appTokens = yield this.getPositionsForBalances();
            const balancesByKey = (0, lodash_1.default)(balances)
                .groupBy(b => b.key)
                .mapValues(v => v[0])
                .value();
            const appTokenBalances = appTokens.map(token => {
                const key = this.appToolkit.getPositionKey(token);
                const tokenBalance = balancesByKey[key];
                if (!tokenBalance)
                    return null;
                const result = (0, drill_balance_helper_1.drillBalance)(token, tokenBalance.balance, { isDebt: this.isDebt });
                return result;
            });
            return (0, lodash_1.compact)(appTokenBalances);
        });
    }
};
AppTokenTemplatePositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __metadata("design:paramtypes", [Object])
], AppTokenTemplatePositionFetcher);
exports.AppTokenTemplatePositionFetcher = AppTokenTemplatePositionFetcher;
//# sourceMappingURL=app-token.template.position-fetcher.js.map