"use strict";
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 __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.EthereumMorphoAaveV2SupplyContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const utils_1 = require("ethers/lib/utils");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../../app-toolkit/constants/address");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
const morpho_supply_contract_position_fetcher_1 = require("../../../apps/morpho/common/morpho.supply.contract-position-fetcher");
const contracts_1 = require("../../../apps/morpho/contracts");
const multicall_ethers_1 = require("../../../multicall/multicall.ethers");
let EthereumMorphoAaveV2SupplyContractPositionFetcher = class EthereumMorphoAaveV2SupplyContractPositionFetcher extends morpho_supply_contract_position_fetcher_1.MorphoSupplyContractPositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Morpho Aave';
        this.morphoAddress = '0x777777c9898d384f785ee44acfe945efdff5f3e0';
        this.lensAddress = '0x507fa343d0a90786d86c7cd885f5c49263a91ff4';
    }
    getContract(address) {
        return this.contractFactory.morphoAaveV2({ address, network: this.network });
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const morphoAaveV2 = this.contractFactory.morphoAaveV2({ address: this.morphoAddress, network: this.network });
            const morpho = multicall.wrap(morphoAaveV2);
            const markets = yield morpho.getMarketsCreated();
            return Promise.all(markets.map((marketAddress) => __awaiter(this, void 0, void 0, function* () {
                const market = this.contractFactory.morphoAToken({ address: marketAddress, network: this.network });
                const marketContract = multicall.wrap(market);
                const supplyTokenAddress = yield marketContract.UNDERLYING_ASSET_ADDRESS().catch(err => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                        return address_1.ZERO_ADDRESS;
                    throw err;
                });
                return {
                    address: this.morphoAddress,
                    marketAddress: marketAddress.toLowerCase(),
                    supplyTokenAddress: supplyTokenAddress.toLowerCase(),
                };
            })));
        });
    }
    getDataProps({ contractPosition, multicall, definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            const lens = this.contractFactory.morphoAaveV2Lens({ address: this.lensAddress, network: this.network });
            const lensContract = multicall.wrap(lens);
            const marketAddress = definition.marketAddress;
            const [supplyRateRaw, borrowRateRaw, totalMarketSupplyRaw, totalMarketBorrowRaw, marketConfiguration] = yield Promise.all([
                lensContract.getAverageSupplyRatePerYear(marketAddress),
                lensContract.getAverageBorrowRatePerYear(marketAddress),
                lensContract.getTotalMarketSupply(marketAddress),
                lensContract.getTotalMarketBorrow(marketAddress),
                lensContract.getMarketConfiguration(marketAddress),
            ]);
            const secondsPerYear = 3600 * 24 * 365;
            const supplyRate = supplyRateRaw.avgSupplyRatePerYear;
            const borrowRate = borrowRateRaw.avgBorrowRatePerYear;
            const supplyApy = Math.pow(1 + +(0, utils_1.formatUnits)(supplyRate.div(secondsPerYear), 27), secondsPerYear) - 1;
            const borrowApy = Math.pow(1 + +(0, utils_1.formatUnits)(borrowRate.div(secondsPerYear), 27), secondsPerYear) - 1;
            const p2pDisabled = marketConfiguration.isP2PDisabled;
            const underlyingToken = contractPosition.tokens[0];
            const supplyRaw = totalMarketSupplyRaw.p2pSupplyAmount.add(totalMarketSupplyRaw.poolSupplyAmount);
            const supply = +(0, utils_1.formatUnits)(supplyRaw, underlyingToken.decimals);
            const supplyUSD = supply * underlyingToken.price;
            const borrowRaw = totalMarketBorrowRaw.p2pBorrowAmount.add(totalMarketBorrowRaw.poolBorrowAmount);
            const matchedUSD = +(0, utils_1.formatUnits)(borrowRaw, underlyingToken.decimals) * underlyingToken.price;
            const borrow = +(0, utils_1.formatUnits)(borrowRaw, underlyingToken.decimals);
            const borrowUSD = borrow * underlyingToken.price;
            const liquidity = supply * underlyingToken.price;
            return {
                marketAddress,
                supplyApy,
                borrowApy,
                liquidity,
                p2pDisabled,
                supply,
                supplyUSD,
                borrow,
                borrowUSD,
                matchedUSD,
            };
        });
    }
    getTokenBalancesPerPosition({ address, contractPosition, multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const _lens = this.contractFactory.morphoAaveV2Lens({ address: this.lensAddress, network: this.network });
            const lens = multicall.wrap(_lens);
            const [{ totalBalance: supplyRaw }, { totalBalance: borrowRaw }] = yield Promise.all([
                lens.getCurrentSupplyBalanceInOf(contractPosition.dataProps.marketAddress, address),
                lens.getCurrentBorrowBalanceInOf(contractPosition.dataProps.marketAddress, address),
            ]);
            return [supplyRaw, borrowRaw];
        });
    }
};
EthereumMorphoAaveV2SupplyContractPositionFetcher = __decorate([
    (0, position_template_decorator_1.PositionTemplate)(),
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.MorphoContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.MorphoContractFactory])
], EthereumMorphoAaveV2SupplyContractPositionFetcher);
exports.EthereumMorphoAaveV2SupplyContractPositionFetcher = EthereumMorphoAaveV2SupplyContractPositionFetcher;
//# sourceMappingURL=morpho.morpho-aave-v2.contract-position-fetcher.js.map