"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MuxPerpContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = __importDefault(require("lodash"));
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const utils_1 = require("../../../apps/mux/common/utils");
const position_interface_1 = require("../../../position/position.interface");
const contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
let MuxPerpContractPositionFetcher = class MuxPerpContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.muxVault({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const indexTokenList = yield (0, utils_1.getMarketTokensByNetwork)(this.network, this.appToolkit);
            const collateralTokensList = yield (0, utils_1.getCollateralTokensByNetwork)(this.network, this.appToolkit);
            const definitions = collateralTokensList.flatMap(collateralToken => {
                return indexTokenList.flatMap(indexToken => {
                    const collateralTokenAddress = collateralToken.address;
                    const collateralTokenId = collateralToken.muxTokenId;
                    const indexTokenAddress = indexToken.address;
                    const indexTokenId = indexToken.muxTokenId;
                    const indexTokenMinProfitRate = indexToken.minProfitRate.toFixed(0);
                    const indexTokenMinProfitTime = indexToken.minProfitTime;
                    const long = {
                        address: this.vaultAddress,
                        collateralTokenAddress,
                        collateralTokenId,
                        indexTokenAddress,
                        indexTokenId,
                        indexTokenMinProfitRate,
                        indexTokenMinProfitTime,
                        isLong: true,
                    };
                    const short = {
                        address: this.vaultAddress,
                        collateralTokenAddress,
                        collateralTokenId,
                        indexTokenAddress,
                        indexTokenId,
                        indexTokenMinProfitRate,
                        indexTokenMinProfitTime,
                        isLong: false,
                    };
                    return [long, short];
                });
            });
            return lodash_1.default.compact(definitions);
        });
    }
    getTokenDefinitions({ definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.collateralTokenAddress,
                    network: this.network,
                },
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.indexTokenAddress,
                    network: this.network,
                },
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: this.usdcAddress,
                    network: this.network,
                },
            ];
        });
    }
    getDataProps({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return {
                isLong: definition.isLong,
                indexTokenId: definition.indexTokenId,
                collateralTokenId: definition.collateralTokenId,
                indexTokenMinProfitRate: definition.indexTokenMinProfitRate,
                indexTokenMinProfitTime: definition.indexTokenMinProfitTime,
                positionKey: `${definition.isLong}`,
            };
        });
    }
    getLabel({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [collateralToken, indexToken] = contractPosition.tokens;
            const marketLabel = [indexToken, collateralToken].map(v => (0, image_present_1.getLabelFromToken)(v)).join(' / ');
            return `${contractPosition.dataProps.isLong ? 'Long' : 'Short'} ${marketLabel}`;
        });
    }
    getTokenBalancesPerPosition({ address, contractPosition, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { collateralTokenId, indexTokenId, isLong } = contractPosition.dataProps;
            const [collateralToken, indexToken, usdcToken] = contractPosition.tokens;
            const subAccountId = (0, utils_1.encodeSubAccountId)(address, collateralTokenId, indexTokenId, isLong);
            if (!subAccountId)
                return [0, 0, 0];
            const reader = this.contractFactory.muxReader({ address: this.readerAddress, network: this.network });
            const subAccounts = yield multicall.wrap(reader).getSubAccounts([subAccountId]);
            const [{ collateral, size, entryPrice, lastIncreasedTime }] = subAccounts;
            const { pnlUsd } = (0, utils_1.computePositionPnlUsd)(indexToken.price, contractPosition.dataProps.indexTokenMinProfitTime, contractPosition.dataProps.indexTokenMinProfitRate, (0, utils_1.fromWei)(size).toFixed(0), (0, utils_1.fromWei)(entryPrice).toFixed(0), lastIncreasedTime, isLong);
            const collateralAmount = (0, utils_1.fromWei)(collateral);
            const collateralAmountUsd = collateralAmount.times(collateralToken.price);
            const hasProfit = pnlUsd.gt(0);
            const profitToken = isLong ? indexToken : usdcToken;
            const collateralBalanceRaw = hasProfit
                ? collateralAmount
                : collateralAmountUsd.plus(pnlUsd).div(collateralToken.price);
            const collateralBalance = collateralBalanceRaw.shiftedBy(collateralToken.decimals).toFixed(0);
            const profitTokenBalanceRaw = pnlUsd.div(profitToken.price);
            const profitTokenBalance = profitTokenBalanceRaw.shiftedBy(profitToken.decimals).toFixed(0);
            return [collateralBalance, 0, profitTokenBalance];
        });
    }
};
MuxPerpContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.MuxContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.MuxContractFactory])
], MuxPerpContractPositionFetcher);
exports.MuxPerpContractPositionFetcher = MuxPerpContractPositionFetcher;
//# sourceMappingURL=mux.perp.contract-position-fetcher.js.map