"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.RariFuseSupplyTokenFetcher = void 0;
const common_1 = require("@nestjs/common");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
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 display_interface_1 = require("../../../position/display.interface");
const app_token_template_position_fetcher_1 = require("../../../position/template/app-token.template.position-fetcher");
let RariFuseSupplyTokenFetcher = class RariFuseSupplyTokenFetcher extends app_token_template_position_fetcher_1.AppTokenTemplatePositionFetcher {
    constructor(appToolkit) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.minLiquidity = 0;
    }
    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();
        });
    }
    getAddresses({ definitions }) {
        return __awaiter(this, void 0, void 0, function* () {
            return definitions.map(v => v.address);
        });
    }
    getUnderlyingTokenDefinitions({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: yield this.getUnderlyingTokenAddress(contract), network: this.network }];
        });
    }
    getPricePerShare({ contract, appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const supplyRateRaw = yield this.getExchangeRateCurrent(contract).catch(err => {
                if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                    return 0;
                throw err;
            });
            const mantissa = 18 + appToken.tokens[0].decimals - appToken.decimals;
            const supplyRate = Number(supplyRateRaw) / Math.pow(10, mantissa);
            return [supplyRate];
        });
    }
    getLiquidity({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.supply * appToken.price;
        });
    }
    getReserves({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [appToken.pricePerShare[0] * appToken.supply];
        });
    }
    getApy({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            const supplyRateRaw = yield this.getSupplyRateRaw(contract);
            const blocksPerDay = blocks_1.BLOCKS_PER_DAY[this.network];
            const supplyRate = Number(supplyRateRaw) / Math.pow(10, 18);
            const apy = (Math.pow(1 + blocksPerDay * supplyRate, 365) - 1) * 100;
            return apy;
        });
    }
    getDataProps(params) {
        const _super = Object.create(null, {
            getDataProps: { get: () => super.getDataProps }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const defaultDataProps = yield _super.getDataProps.call(this, params);
            const { marketName, comptroller } = params.definition;
            return Object.assign(Object.assign({}, defaultDataProps), { marketName, comptroller });
        });
    }
    getLabel({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, image_present_1.getLabelFromToken)(appToken.tokens[0]);
        });
    }
    getLabelDetailed({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.symbol;
        });
    }
    getSecondaryLabel({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, display_item_present_1.buildDollarDisplayItem)(appToken.tokens[0].price);
        });
    }
    getBalanceDisplayMode() {
        return __awaiter(this, void 0, void 0, function* () {
            return display_interface_1.BalanceDisplayMode.UNDERLYING;
        });
    }
    getRawBalances(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(t => t.comptroller.toLowerCase());
            const multicall = this.appToolkit.getMulticall(this.network);
            const appTokens = yield this.appToolkit.getAppTokenPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
            return Promise.all(appTokens
                .filter(v => participatedComptrollers.includes(v.dataProps.comptroller))
                .map((appToken) => __awaiter(this, void 0, void 0, function* () {
                const balanceRaw = yield this.getBalancePerToken({ multicall, address, appToken });
                return {
                    key: this.appToolkit.getPositionKey(appToken),
                    balance: balanceRaw.toString(),
                };
            })));
        });
    }
};
RariFuseSupplyTokenFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __metadata("design:paramtypes", [Object])
], RariFuseSupplyTokenFetcher);
exports.RariFuseSupplyTokenFetcher = RariFuseSupplyTokenFetcher;
//# sourceMappingURL=rari-fuse.supply.token-fetcher.js.map