"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RariFuseBorrowContractPositionFetcher = void 0;
const lodash_1 = require("lodash");
const blocks_1 = require("../../../app-toolkit/constants/blocks");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const multicall_ethers_1 = require("../../../multicall/multicall.ethers");
const position_interface_1 = require("../../../position/position.interface");
const custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
class RariFuseBorrowContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    getContract(address) {
        return this.getTokenContract(address);
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const poolDirectory = this.getPoolDirectoryContract(this.poolDirectoryAddress);
            const pools = yield this.getPools(poolDirectory);
            const definitions = yield Promise.all(pools.map((pool) => __awaiter(this, void 0, void 0, function* () {
                const comptroller = multicall.wrap(this.getComptrollerContract(pool.comptroller));
                const marketAddresses = yield this.getMarketTokenAddresses(comptroller);
                return marketAddresses.map(marketAddress => ({
                    address: marketAddress.toLowerCase(),
                    comptroller: pool.comptroller.toLowerCase(),
                    marketName: pool.name,
                }));
            })));
            return definitions.flat();
        });
    }
    getTokenDefinitions({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.BORROWED,
                    address: yield this.getUnderlyingTokenAddress(contract),
                    network: this.network,
                },
            ];
        });
    }
    getDataProps({ contract, contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [totalBorrowsRaw, borrowRateRaw] = yield Promise.all([
                this.getTotalBorrows(contract),
                this.getBorrowRateRaw(contract),
            ]);
            const blocksPerDay = blocks_1.BLOCKS_PER_DAY[this.network];
            const { marketName, comptroller } = definition;
            const borrowRate = Number(borrowRateRaw) / Math.pow(10, 18);
            const apy = (Math.pow(1 + blocksPerDay * borrowRate, 365) - 1) * 100;
            const liquidity = (-1 * Number(totalBorrowsRaw)) / Math.pow(10, contractPosition.tokens[0].decimals);
            return { apy, liquidity, marketName, comptroller };
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, image_present_1.getLabelFromToken)(contractPosition.tokens[0]);
        });
    }
    getTokenBalancesPerPosition({ address, contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                yield this.getBorrowBalance(address, contract).catch(err => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                        return 0;
                    throw err;
                }),
            ];
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const lens = this.getLensContract(this.lensAddress);
            const poolsBySupplier = yield this.getPoolsBySupplier(address, lens);
            const participatedComptrollers = poolsBySupplier[1].map(p => p.comptroller.toLowerCase());
            const multicall = this.appToolkit.getMulticall(this.network);
            const contractPositions = yield this.appToolkit.getAppContractPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
            const balances = yield Promise.all(contractPositions
                .filter(v => participatedComptrollers.includes(v.dataProps.comptroller))
                .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;
        });
    }
}
exports.RariFuseBorrowContractPositionFetcher = RariFuseBorrowContractPositionFetcher;
//# sourceMappingURL=rari-fuse.borrow.contract-position-fetcher.js.map