"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.EthereumStrikeBorrowContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
const display_item_present_1 = require("../../../app-toolkit/helpers/presentation/display-item.present");
const compound_borrow_contract_position_fetcher_1 = require("../../../apps/compound/common/compound.borrow.contract-position-fetcher");
const multicall_ethers_1 = require("../../../multicall/multicall.ethers");
const contracts_1 = require("../contracts");
let EthereumStrikeBorrowContractPositionFetcher = class EthereumStrikeBorrowContractPositionFetcher extends compound_borrow_contract_position_fetcher_1.CompoundBorrowContractPositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Lending';
        this.comptrollerAddress = '0xe2e17b2cbbf48211fa7eb8a875360e5e39ba2602';
    }
    getCompoundCTokenContract(address) {
        return this.contractFactory.strikeSToken({ address, network: this.network });
    }
    getCompoundComptrollerContract(address) {
        return this.contractFactory.strikeComptroller({ address, network: this.network });
    }
    getMarkets({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.getAllMarkets();
        });
    }
    getUnderlyingAddress({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.underlying();
        });
    }
    getExchangeRate({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.callStatic.exchangeRateCurrent();
        });
    }
    getBorrowRate({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.borrowRatePerBlock();
        });
    }
    getCash({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.getCash();
        });
    }
    getCTokenSupply({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.totalSupply();
        });
    }
    getCTokenDecimals({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.decimals();
        });
    }
    getBorrowBalance({ address, contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.callStatic.borrowBalanceCurrent(address);
        });
    }
    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 [underlyingToken] = params.contractPosition.tokens;
            const [decimals, supplyRaw, pricePerShare, cashRaw] = yield Promise.all([
                this.getCTokenDecimals(params),
                this.getCTokenSupply(params),
                this.getPricePerShare(params),
                this.getCash(params).catch(e => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(e))
                        return 0;
                    throw e;
                }),
            ]);
            const supply = Number(supplyRaw) / Math.pow(10, decimals);
            const price = pricePerShare * underlyingToken.price;
            const underlyingLiquidity = price * supply;
            const comptrollerContract = this.getCompoundComptrollerContract(this.comptrollerAddress);
            const collateralFactorRaw = yield params.multicall
                .wrap(comptrollerContract)
                .markets(params.contractPosition.address);
            const collateralFactor = Number(collateralFactorRaw.collateralFactorMantissa) / Math.pow(10, 18);
            const cashSupply = Number(cashRaw) / Math.pow(10, underlyingToken.decimals);
            const borrowedPositionliquidity = cashSupply * underlyingToken.price;
            const borrowLiquidity = borrowedPositionliquidity > underlyingLiquidity ? 0 : underlyingLiquidity - borrowedPositionliquidity;
            return Object.assign(Object.assign({}, defaultDataProps), { liquidity: -borrowLiquidity, isActive: Boolean(borrowLiquidity > 0), collateralFactor });
        });
    }
    getStatsItems({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { apy, liquidity, exchangeRate, symbol, collateralFactor } = 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) },
                { label: 'Collateral Factor', value: (0, display_item_present_1.buildPercentageDisplayItem)(collateralFactor) },
            ];
        });
    }
};
EthereumStrikeBorrowContractPositionFetcher = __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.StrikeContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.StrikeContractFactory])
], EthereumStrikeBorrowContractPositionFetcher);
exports.EthereumStrikeBorrowContractPositionFetcher = EthereumStrikeBorrowContractPositionFetcher;
//# sourceMappingURL=strike.borrow.contract-position-fetcher.js.map