"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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.HomoraV2FarmContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = __importStar(require("lodash"));
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../../app-toolkit/constants/address");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
const cache_decorator_1 = require("../../../cache/cache.decorator");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
const _types_1 = require("../../../types");
const contracts_1 = require("../contracts");
const httpClient_1 = __importDefault(require("../helpers/httpClient"));
const enums_1 = require("../interfaces/enums");
let HomoraV2FarmContractPositionFetcher = class HomoraV2FarmContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.homoraBank({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const pools = yield this.getPools();
            const tradingVolumes = yield this.getTradingVolumes();
            return pools
                .filter(pool => ![enums_1.Poolstatus.delisting, enums_1.Poolstatus.delisted, enums_1.Poolstatus.emergency_delisted].includes(pool.status) &&
                !pool.migrateTo)
                .map(pool => {
                var _a;
                return ({
                    key: pool.key,
                    address: this.homoraBankAddress,
                    exchange: pool.exchange.name,
                    poolAddress: pool.lpTokenAddress.toLowerCase(),
                    poolName: pool.name,
                    tokenAddresses: pool.tokens.map((token) => token.toLowerCase()),
                    feeTier: pool.exchange.name === enums_1.Exchange.UniswapV3 ? Number((_a = pool.uniswapV3Info) === null || _a === void 0 ? void 0 : _a.poolFeeBps) / Math.pow(10, 4) : undefined,
                    rewardAddress: pool.rewardAddress,
                    tradingVolume: Number(tradingVolumes[pool.key]),
                });
            });
        });
    }
    getTokenDefinitions({ definition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.poolAddress,
                    network: this.network,
                },
                ...definition.tokenAddresses.map(token => ({
                    metaType: position_interface_1.MetaType.BORROWED,
                    address: token,
                    network: this.network,
                })),
            ];
        });
    }
    getDataProps({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { poolAddress, feeTier, key } = definition;
            return {
                key,
                poolAddress,
                tradingVolume: definition.tradingVolume,
                feeTier,
                positionKey: key,
            };
        });
    }
    getLabel({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (definition.feeTier) {
                const label = `[${definition.exchange}] ${definition.poolName} (${definition.feeTier.toFixed(2)}%)`;
                return label;
            }
            return `[${definition.exchange}] ${definition.poolName}`;
        });
    }
    getNativeToken() {
        return __awaiter(this, void 0, void 0, function* () {
            const baseTokens = yield this.appToolkit.getBaseTokenPrices(this.network);
            const nativeToken = baseTokens.find(t => t.address === address_1.ZERO_ADDRESS);
            return nativeToken;
        });
    }
    getPools() {
        return __awaiter(this, void 0, void 0, function* () {
            const chainId = _types_1.NETWORK_IDS[this.network];
            const { data } = yield httpClient_1.default.get(`${chainId}/pools`);
            return data;
        });
    }
    getTradingVolumes() {
        return __awaiter(this, void 0, void 0, function* () {
            const chainId = _types_1.NETWORK_IDS[this.network];
            const { data } = yield httpClient_1.default.get(`${chainId}/trading-volumes`);
            return data;
        });
    }
    getTokenBalancesPerPosition() {
        return __awaiter(this, void 0, void 0, function* () {
            throw new common_1.NotImplementedException();
        });
    }
    getPositionsData(network) {
        return __awaiter(this, void 0, void 0, function* () {
            const chainId = _types_1.NETWORK_IDS[network];
            const { data } = yield httpClient_1.default.get(`${chainId}/positions`);
            return data;
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const data = yield this.getPositionsData(this.network);
            if (lodash_1.default.isEmpty(data))
                return [];
            const userPositions = data.filter(v => v.owner === address);
            if (!userPositions.length)
                return [];
            const bankContract = this.contractFactory.homoraBank({ address: this.homoraBankAddress, network: this.network });
            const multicall = this.appToolkit.getMulticall(this.network);
            const contractPositions = yield this.appToolkit.getAppContractPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
            const balances = yield Promise.all(userPositions.map((position) => __awaiter(this, void 0, void 0, function* () {
                const contractPosition = contractPositions.find(v => v.dataProps.key === position.pool.key);
                if (!contractPosition)
                    return null;
                const [positionInfo, positionDebt] = yield Promise.all([
                    multicall.wrap(bankContract).getPositionInfo(position.id),
                    multicall.wrap(bankContract).getPositionDebts(position.id),
                ]);
                const collateralAmount = positionInfo.collateralSize;
                const debtAmounts = contractPosition.tokens.filter(position_utils_1.isBorrowed).map(t => {
                    const debtArrayIndex = positionDebt.tokens.findIndex(dt => dt.toLowerCase() === t.address);
                    return debtArrayIndex >= 0 ? positionDebt.debts[debtArrayIndex].toString() : '0';
                });
                const amounts = [collateralAmount, ...debtAmounts];
                const allTokens = contractPosition.tokens.map((t, i) => { var _a, _b; return (0, drill_balance_helper_1.drillBalance)(t, (_b = (_a = amounts[i]) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '0', { isDebt: t.metaType === position_interface_1.MetaType.BORROWED }); });
                const tokens = allTokens.filter(v => Math.abs(v.balanceUSD) > 0.01);
                const balanceUSD = (0, lodash_1.sumBy)(tokens, t => t.balanceUSD);
                const balance = Object.assign(Object.assign({}, contractPosition), { tokens,
                    balanceUSD });
                return balance;
            })));
            return (0, lodash_1.compact)(balances);
        });
    }
};
__decorate([
    (0, cache_decorator_1.Cache)({
        instance: 'business',
        key: (network) => `studio:homora-v2:${network}:positions-data`,
        ttl: 3 * 60,
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], HomoraV2FarmContractPositionFetcher.prototype, "getPositionsData", null);
HomoraV2FarmContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.HomoraV2ContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.HomoraV2ContractFactory])
], HomoraV2FarmContractPositionFetcher);
exports.HomoraV2FarmContractPositionFetcher = HomoraV2FarmContractPositionFetcher;
//# sourceMappingURL=homora-v2.farm.contract-position-fetcher.js.map