"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.CompoundBorrowContractPositionFetcher = void 0;
const address_1 = require("../../../app-toolkit/constants/address");
const blocks_1 = require("../../../app-toolkit/constants/blocks");
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 position_interface_1 = require("../../../position/position.interface");
const contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
class CompoundBorrowContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    getContract(address) {
        return this.getCompoundCTokenContract(address);
    }
    getDefinitions(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const comptroller = this.getCompoundComptrollerContract(this.comptrollerAddress);
            const addresses = yield this.getMarkets(Object.assign(Object.assign({}, params), { contract: comptroller }));
            return addresses.map(addr => ({ address: addr.toLowerCase() }));
        });
    }
    getTokenDefinitions(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const underlyingAddressRaw = yield this.getUnderlyingAddress(params).catch(err => {
                if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                    return address_1.ZERO_ADDRESS;
                throw err;
            });
            const underlyingAddress = underlyingAddressRaw.toLowerCase().replace(address_1.ETH_ADDR_ALIAS, address_1.ZERO_ADDRESS);
            return [
                {
                    metaType: position_interface_1.MetaType.BORROWED,
                    address: underlyingAddress,
                    network: this.network,
                },
            ];
        });
    }
    getLabel({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [underlyingToken] = contractPosition.tokens;
            return (0, image_present_1.getLabelFromToken)(underlyingToken);
        });
    }
    getSecondaryLabel({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [underlyingToken] = contractPosition.tokens;
            return (0, display_item_present_1.buildDollarDisplayItem)(underlyingToken.price);
        });
    }
    getDenormalizedRate({ blocksPerDay, rate }) {
        return 100 * (Math.pow(1 + (blocksPerDay * Number(rate)) / Number(1e18), 365) - 1);
    }
    getApy(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const [underlyingToken] = params.contractPosition.tokens;
            const borrowRate = yield this.getBorrowRate(params);
            const blocksPerDay = blocks_1.BLOCKS_PER_DAY[this.network];
            return this.getDenormalizedRate({
                blocksPerDay,
                rate: borrowRate,
                decimals: underlyingToken.decimals,
            });
        });
    }
    getExchangeRateMantissa({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [underlyingToken] = contractPosition.tokens;
            return underlyingToken.decimals + 10;
        });
    }
    getPricePerShare(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const [rateRaw, mantissa] = yield Promise.all([this.getExchangeRate(params), this.getExchangeRateMantissa(params)]);
            return Number(rateRaw) / Math.pow(10, mantissa);
        });
    }
    getDataProps(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const [underlyingToken] = params.contractPosition.tokens;
            const multicall = params.multicall;
            const erc20 = this.appToolkit.globalContracts.erc20({
                address: params.contractPosition.address,
                network: this.network,
            });
            const symbol = yield multicall.wrap(erc20).symbol();
            const [decimals, supplyRaw, pricePerShare, apy, cashRaw, exchangeRate] = yield Promise.all([
                this.getCTokenDecimals(params),
                this.getCTokenSupply(params),
                this.getPricePerShare(params),
                this.getApy(params),
                this.getCash(params).catch(e => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(e))
                        return 0;
                    throw e;
                }),
                this.getPricePerShare(params),
            ]);
            const supply = Number(supplyRaw) / Math.pow(10, decimals);
            const price = pricePerShare * underlyingToken.price;
            const underlyingLiquidity = price * supply;
            const cashSupply = Number(cashRaw) / Math.pow(10, underlyingToken.decimals);
            const borrowedPositionliquidity = cashSupply * underlyingToken.price;
            const borrowLiquidity = borrowedPositionliquidity > underlyingLiquidity ? 0 : underlyingLiquidity - borrowedPositionliquidity;
            return {
                liquidity: -borrowLiquidity,
                isActive: Boolean(borrowLiquidity > 0),
                exchangeRate,
                symbol,
                apy,
            };
        });
    }
    getStatsItems({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { apy, liquidity, exchangeRate, symbol } = contractPosition.dataProps;
            const exchangeRateFormatted = `${(1 / exchangeRate).toFixed(3)} ${symbol} = 1 ${contractPosition.tokens[0].symbol}`;
            return [
                { label: 'APY', value: (0, display_item_present_1.buildPercentageDisplayItem)(apy) },
                { label: 'Liquidity', value: (0, display_item_present_1.buildDollarDisplayItem)(liquidity) },
                { label: 'Exchange Rate', value: (0, display_item_present_1.buildStringDisplayItem)(exchangeRateFormatted) },
            ];
        });
    }
    getTokenBalancesPerPosition(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const balanceRaw = yield this.getBorrowBalance(params);
            return [balanceRaw];
        });
    }
}
exports.CompoundBorrowContractPositionFetcher = CompoundBorrowContractPositionFetcher;
//# sourceMappingURL=compound.borrow.contract-position-fetcher.js.map