"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());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractPositionTemplatePositionFetcher = 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 contract_interface_1 = require("../../position/contract.interface");
const position_interface_1 = require("../../position/position.interface");
const position_utils_1 = require("../../position/position.utils");
let ContractPositionTemplatePositionFetcher = class ContractPositionTemplatePositionFetcher {
    constructor(appToolkit) {
        this.appToolkit = appToolkit;
        this.isExcludedFromBalances = false;
        this.isExcludedFromExplore = false;
        this.isExcludedFromTvl = false;
    }
    getDataProps(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return {};
        });
    }
    getLabelDetailed(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return undefined;
        });
    }
    getSecondaryLabel(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return undefined;
        });
    }
    getTertiaryLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof contractPosition.dataProps.apy === 'number')
                return `${contractPosition.dataProps.apy.toFixed(3)}% APY`;
            return undefined;
        });
    }
    getImages({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contractPosition.tokens.flatMap(v => (0, image_present_1.getImagesFromToken)(v));
        });
    }
    getStatsItems({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            const statsItems = [];
            if (typeof contractPosition.dataProps.liquidity === 'number' && Math.abs(contractPosition.dataProps.liquidity) > 0)
                statsItems.push({ label: 'Liquidity', value: (0, display_item_present_1.buildDollarDisplayItem)(contractPosition.dataProps.liquidity) });
            if (typeof contractPosition.dataProps.apy === 'number' && contractPosition.dataProps.apy > 0)
                statsItems.push({ label: 'APY', value: (0, display_item_present_1.buildPercentageDisplayItem)(contractPosition.dataProps.apy) });
            return statsItems;
        });
    }
    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 });
            const skeletons = yield Promise.all(definitions.map((definition) => __awaiter(this, void 0, void 0, function* () {
                const address = definition.address.toLowerCase();
                const contract = multicall.wrap(this.getContract(definition.address));
                const context = { address, contract, definition, multicall, tokenLoader };
                const maybeTokenDefinitions = yield this.getTokenDefinitions(context);
                if (!maybeTokenDefinitions)
                    return null;
                const tokenDefinitionsArr = Array.isArray(maybeTokenDefinitions)
                    ? maybeTokenDefinitions
                    : [maybeTokenDefinitions];
                const tokenDefinitions = tokenDefinitionsArr.map(t => (Object.assign(Object.assign({}, t), { address: t.address.toLowerCase() })));
                return { address, definition, tokenDefinitions };
            })));
            const underlyingTokenRequests = (0, lodash_1.compact)(skeletons)
                .flatMap(v => v.tokenDefinitions)
                .map(v => ({ address: v.address, network: v.network, tokenId: v.tokenId }));
            const tokenDependencies = yield tokenLoader.getMany(underlyingTokenRequests).then(tokenDeps => (0, lodash_1.compact)(tokenDeps));
            const skeletonsWithResolvedTokens = yield Promise.all((0, lodash_1.compact)(skeletons).map(({ address, tokenDefinitions, definition }) => {
                const maybeTokens = tokenDefinitions.map(definition => {
                    const match = tokenDependencies.find(token => {
                        const isAddressMatch = token.address === definition.address;
                        const isNetworkMatch = token.network == definition.network;
                        const isMaybeErc1155TokenIdMatch = !definition.tokenId ||
                            (token.type === contract_interface_1.ContractType.APP_TOKEN && token.dataProps.tokenId === definition.tokenId);
                        return isAddressMatch && isNetworkMatch && isMaybeErc1155TokenIdMatch;
                    });
                    if (match) {
                        const tokenWithMetaType = (0, position_utils_1.metatyped)(match, definition.metaType);
                        if (tokenWithMetaType.type === contract_interface_1.ContractType.APP_TOKEN) {
                            const { key } = tokenWithMetaType, token = __rest(tokenWithMetaType, ["key"]);
                            return Object.assign(Object.assign({}, token), { key: this.appToolkit.getPositionKey(token) });
                        }
                        return tokenWithMetaType;
                    }
                    return null;
                });
                const tokens = (0, lodash_1.compact)(maybeTokens);
                if (maybeTokens.length !== tokens.length)
                    return null;
                return { address, tokens, definition };
            }));
            const tokens = yield Promise.all((0, lodash_1.compact)(skeletonsWithResolvedTokens).map(({ address, tokens, definition }) => __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.POSITION,
                    appId: this.appId,
                    groupId: this.groupId,
                    network: this.network,
                    address,
                    tokens,
                };
                const dataPropsStageParams = Object.assign(Object.assign({}, baseContext), { contractPosition: baseFragment });
                const dataProps = yield this.getDataProps(dataPropsStageParams);
                const displayPropsStageFragment = Object.assign(Object.assign({}, baseFragment), { dataProps });
                const displayPropsStageParams = Object.assign(Object.assign({}, dataPropsStageParams), { contractPosition: 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),
                };
                const contractPosition = Object.assign(Object.assign({}, baseFragment), { dataProps, displayProps });
                const key = this.appToolkit.getPositionKey(contractPosition);
                return Object.assign({ key }, contractPosition);
            })));
            return tokens;
        });
    }
    getAccountAddress(address) {
        return __awaiter(this, void 0, void 0, function* () {
            return address;
        });
    }
    getPositionsForBalances() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.appToolkit.getAppContractPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
        });
    }
    filterPositionsForAddress(address, positions) {
        return __awaiter(this, void 0, void 0, function* () {
            return positions;
        });
    }
    getBalances(_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 contractPositions = yield this.getPositionsForBalances();
            const filteredPositions = yield this.filterPositionsForAddress(address, contractPositions);
            const balances = yield Promise.all(filteredPositions.map((contractPosition) => __awaiter(this, void 0, void 0, function* () {
                const contract = multicall.wrap(this.getContract(contractPosition.address));
                const balancesRaw = yield this.getTokenBalancesPerPosition({ address, contract, contractPosition, multicall });
                const allTokens = contractPosition.tokens.map((cp, idx) => { var _a, _b; return (0, drill_balance_helper_1.drillBalance)(cp, (_b = (_a = balancesRaw[idx]) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '0', { isDebt: cp.metaType === position_interface_1.MetaType.BORROWED }); });
                const tokens = allTokens.filter(v => Math.abs(v.balanceUSD) > 0.01);
                const balanceUSD = (0, lodash_1.sumBy)(tokens, t => t.balanceUSD);
                const balance = Object.assign(Object.assign({}, contractPosition), { tokens, balanceUSD });
                return balance;
            })));
            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 contractPositions = yield this.getPositionsForBalances();
            const filteredPositions = yield this.filterPositionsForAddress(address, contractPositions);
            let results = [];
            for (const batch of lodash_1.default.chunk(filteredPositions, 100).values()) {
                results = results.concat(yield Promise.all(batch.map((contractPosition) => __awaiter(this, void 0, void 0, function* () {
                    const contract = multicall.wrap(this.getContract(contractPosition.address));
                    const balancesRaw = yield this.getTokenBalancesPerPosition({
                        address,
                        contract,
                        contractPosition,
                        multicall,
                    });
                    return {
                        key: this.appToolkit.getPositionKey(contractPosition),
                        tokens: contractPosition.tokens.map((token, i) => {
                            var _a, _b;
                            return ({
                                key: this.appToolkit.getPositionKey(token),
                                balance: (_b = (_a = balancesRaw[i]) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '0',
                            });
                        }),
                    };
                }))));
            }
            return results;
        });
    }
    drillRawBalances(balances) {
        return __awaiter(this, void 0, void 0, function* () {
            const contractPositions = yield this.getPositionsForBalances();
            const balancesByKey = (0, lodash_1.default)(balances)
                .groupBy(b => b.key)
                .mapValues(v => v[0])
                .value();
            return (0, lodash_1.compact)(contractPositions.map(contractPosition => {
                const key = this.appToolkit.getPositionKey(contractPosition);
                const positionBalances = balancesByKey[key];
                if (!positionBalances)
                    return null;
                const positionTokensByKey = (0, lodash_1.default)(positionBalances.tokens)
                    .groupBy(t => t.key)
                    .mapValues(v => v[0])
                    .value();
                const allTokens = contractPosition.tokens.map(token => {
                    const key = this.appToolkit.getPositionKey(token);
                    const tokenBalance = positionTokensByKey[key];
                    if (!tokenBalance)
                        return null;
                    return (0, drill_balance_helper_1.drillBalance)(token, tokenBalance.balance, {
                        isDebt: token.metaType === position_interface_1.MetaType.BORROWED,
                    });
                });
                const tokens = (0, lodash_1.compact)(allTokens).filter(t => Math.abs(t.balanceUSD) > 0.01);
                const balanceUSD = (0, lodash_1.sumBy)(tokens, t => t.balanceUSD);
                return Object.assign(Object.assign({}, contractPosition), { tokens, balanceUSD });
            }));
        });
    }
};
ContractPositionTemplatePositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __metadata("design:paramtypes", [Object])
], ContractPositionTemplatePositionFetcher);
exports.ContractPositionTemplatePositionFetcher = ContractPositionTemplatePositionFetcher;
//# sourceMappingURL=contract-position.template.position-fetcher.js.map