"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.DefiedgeStrategyTokenFetcher = void 0;
const common_1 = require("@nestjs/common");
const ethers_1 = require("ethers");
const utils_1 = require("ethers/lib/utils");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const display_item_present_1 = require("../../../app-toolkit/helpers/presentation/display-item.present");
const app_token_template_position_fetcher_1 = require("../../../position/template/app-token.template.position-fetcher");
const contracts_1 = require("../contracts");
const utils_2 = require("../utils");
const defiedge_strategy_definitions_resolver_1 = require("./defiedge.strategy.definitions-resolver");
let DefiedgeStrategyTokenFetcher = class DefiedgeStrategyTokenFetcher extends app_token_template_position_fetcher_1.AppTokenTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, definitionResolver) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.definitionResolver = definitionResolver;
        this.groupLabel = 'Strategies';
    }
    getContract(address) {
        return this.contractFactory.strategy({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const apiDefinitions = yield this.definitionResolver.getStrategies(this.network);
            const definitions = apiDefinitions.map(v => ({
                address: v.id.toLowerCase(),
                title: v.title,
                subTitle: v.subTitle,
                token0Address: v.token0.id.toLowerCase(),
                token1Address: v.token1.id.toLowerCase(),
            }));
            return definitions;
        });
    }
    getAddresses({ definitions }) {
        return __awaiter(this, void 0, void 0, function* () {
            return definitions.map(v => v.address);
        });
    }
    getSymbol({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return ethers_1.ethers.utils.parseBytes32String(yield contract.symbol());
        });
    }
    getUnderlyingTokenDefinitions({ definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                { address: definition.token0Address, network: this.network },
                { address: definition.token1Address, network: this.network },
            ];
        });
    }
    getPrice({ contract, appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [aumWithFee, totalSupplyBN] = yield Promise.all([
                contract.callStatic.getAUMWithFees(false),
                contract.totalSupply(),
            ]);
            const { amount0, amount1 } = aumWithFee;
            const [token0, token1] = appToken.tokens;
            const t0Price = (0, utils_1.parseEther)(token0.price.toString());
            const t1Price = (0, utils_1.parseEther)(token1.price.toString());
            const aumBN = (0, utils_2.expandTo18Decimals)(amount0, token0.decimals)
                .mul(t0Price)
                .add((0, utils_2.expandTo18Decimals)(amount1, token1.decimals).mul(t1Price));
            const sharePrice = totalSupplyBN.eq(0) ? 0 : +Number(+(0, utils_1.formatEther)(aumBN.div(totalSupplyBN))).toFixed(8) || 100;
            return sharePrice;
        });
    }
    getPricePerShare({ contract, appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [aumWithFee, totalSupplyBN] = yield Promise.all([
                contract.callStatic.getAUMWithFees(false),
                contract.totalSupply(),
            ]);
            if (totalSupplyBN.eq(0))
                return [0, 0];
            const { amount0, amount1 } = aumWithFee;
            const [token0, token1] = appToken.tokens;
            const totalSupply = +(0, utils_1.formatEther)(totalSupplyBN);
            const pricePerShare = [
                +(0, utils_1.formatEther)((0, utils_2.expandTo18Decimals)(amount0, token0.decimals)) / totalSupply,
                +(0, utils_1.formatEther)((0, utils_2.expandTo18Decimals)(amount1, token1.decimals)) / totalSupply,
            ];
            return pricePerShare;
        });
    }
    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 { contract, appToken } = params;
            const [aumWithFee, totalSupplyBN] = yield Promise.all([
                contract.callStatic.getAUMWithFees(true),
                contract.totalSupply(),
            ]);
            const [token0, token1] = appToken.tokens;
            const sharePrice = appToken.price;
            const liquidity = +(0, utils_1.formatEther)(totalSupplyBN) * appToken.price;
            const unclaimedFees = +(0, utils_1.formatEther)(aumWithFee.totalFee0) * token0.price + +(0, utils_1.formatEther)(aumWithFee.totalFee1) * token1.price;
            return Object.assign(Object.assign({}, defaultDataProps), { unclaimedFees,
                liquidity,
                sharePrice, sinceInception: sharePrice - 100 });
        });
    }
    getLabel({ definition, }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            return (_a = definition.subTitle) !== null && _a !== void 0 ? _a : definition.title;
        });
    }
    getSecondaryLabel({ definition, }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            return (_a = definition.subTitle) !== null && _a !== void 0 ? _a : '';
        });
    }
    getStatsItems({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { liquidity, apy, reserves, sinceInception, unclaimedFees } = appToken.dataProps;
            const reservesDisplay = reserves.map(v => (v < 0.01 ? '<0.01' : v.toFixed(2))).join(' / ');
            return [
                { label: 'Liquidity', value: (0, display_item_present_1.buildDollarDisplayItem)(liquidity) },
                { label: 'Reserves', value: reservesDisplay },
                { label: 'APY', value: (0, display_item_present_1.buildPercentageDisplayItem)(apy) },
                { label: 'Since inception', value: (0, display_item_present_1.buildPercentageDisplayItem)(sinceInception) },
                { label: 'Unclaimed Fees', value: (0, display_item_present_1.buildDollarDisplayItem)(unclaimedFees) },
            ];
        });
    }
};
DefiedgeStrategyTokenFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.DefiedgeContractFactory)),
    __param(2, (0, common_1.Inject)(defiedge_strategy_definitions_resolver_1.DefiedgeStrategyDefinitionsResolver)),
    __metadata("design:paramtypes", [Object, contracts_1.DefiedgeContractFactory,
        defiedge_strategy_definitions_resolver_1.DefiedgeStrategyDefinitionsResolver])
], DefiedgeStrategyTokenFetcher);
exports.DefiedgeStrategyTokenFetcher = DefiedgeStrategyTokenFetcher;
//# sourceMappingURL=defiedge.strategy.token-fetcher.js.map