"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.KyberswapElasticFarmContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = __importDefault(require("lodash"));
const lodash_2 = 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 position_interface_1 = require("../../../position/position.interface");
const custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
const kyberswap_elastic_farm_contract_position_builder_1 = require("./kyberswap-elastic.farm.contract-position-builder");
let KyberswapElasticFarmContractPositionFetcher = class KyberswapElasticFarmContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, kyberElasticFarmContractPositionBuilder) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.kyberElasticFarmContractPositionBuilder = kyberElasticFarmContractPositionBuilder;
    }
    getContract(address) {
        return this.contractFactory.kyberswapElasticLm({ address, network: this.network });
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const kyberswapElasticLmContract = this.contractFactory.kyberswapElasticLm({
                address: this.kyberswapElasticLmAddress,
                network: this.network,
            });
            const poolLengthRaw = yield multicall.wrap(kyberswapElasticLmContract).poolLength();
            const definitionsRaw = yield Promise.all((0, lodash_2.range)(0, poolLengthRaw.toNumber()).map((index) => __awaiter(this, void 0, void 0, function* () {
                const poolInfos = yield multicall.wrap(kyberswapElasticLmContract).getPoolInfo(index);
                const poolContract = this.contractFactory.pool({ address: poolInfos.poolAddress, network: this.network });
                const [token0Raw, token1Raw, feeTier] = yield Promise.all([
                    multicall.wrap(poolContract).token0(),
                    multicall.wrap(poolContract).token1(),
                    multicall.wrap(poolContract).swapFeeUnits(),
                ]);
                if (Number(poolInfos.numStakes) === 0)
                    return null;
                return {
                    address: this.kyberswapElasticLmAddress,
                    poolAddress: poolInfos.poolAddress,
                    token0Address: token0Raw.toLowerCase(),
                    token1Address: token1Raw.toLowerCase(),
                    rewardTokenAddresses: poolInfos.rewardTokens,
                    feeTier: feeTier,
                };
            })));
            const definitions = lodash_1.default.compact(definitionsRaw);
            return definitions;
        });
    }
    getTokenDefinitions({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.token0Address,
                    network: this.network,
                },
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.token1Address,
                    network: this.network,
                },
                ...definition.rewardTokenAddresses.map(v => ({
                    metaType: position_interface_1.MetaType.CLAIMABLE,
                    address: v,
                    network: this.network,
                })),
            ];
        });
    }
    getDataProps({ multicall, contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { poolAddress, feeTier } = definition;
            const { tokens } = contractPosition;
            const [reserveRaw0, reserveRaw1] = yield Promise.all([
                multicall.wrap(this.contractFactory.erc20(tokens[0])).balanceOf(poolAddress),
                multicall.wrap(this.contractFactory.erc20(tokens[1])).balanceOf(poolAddress),
            ]);
            const reservesRaw = [reserveRaw0, reserveRaw1];
            const reserves = reservesRaw.map((r, i) => Number(r) / Math.pow(10, tokens[i].decimals));
            const liquidity = reserves[0] * tokens[0].price + reserves[1] * tokens[1].price;
            const assetStandard = position_interface_1.Standard.ERC_721;
            return { feeTier, reserves, liquidity, poolAddress, assetStandard, positionKey: `${feeTier}` };
        });
    }
    getLabel({ contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const symbolLabel = contractPosition.tokens.map(t => (0, image_present_1.getLabelFromToken)(t)).join(' / ');
            const label = `${symbolLabel} (${definition.feeTier.toFixed(4)}%)`;
            return label;
        });
    }
    getTokenBalancesPerPosition() {
        return __awaiter(this, void 0, void 0, function* () {
            throw new common_1.NotImplementedException();
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector({
                tags: { network: this.network, context: `${this.appId}__template_balances` },
            });
            const kyberswapElasticLmContract = this.contractFactory.kyberswapElasticLm({
                address: this.kyberswapElasticLmAddress,
                network: this.network,
            });
            const nftIds = yield multicall.wrap(kyberswapElasticLmContract).getDepositedNFTs(address);
            const balances = yield Promise.all(nftIds.map((nftId) => __awaiter(this, void 0, void 0, function* () {
                const poolIds = yield multicall.wrap(kyberswapElasticLmContract).getJoinedPools(nftId);
                const position = yield Promise.all(poolIds.map(poolId => {
                    return this.kyberElasticFarmContractPositionBuilder.buildPosition({
                        positionId: nftId,
                        poolId,
                        network: this.network,
                        multicall,
                        tokenLoader,
                        kyberswapElasticLmAddress: this.kyberswapElasticLmAddress,
                    });
                }));
                return position;
            })));
            return (0, lodash_2.compact)(balances.flat());
        });
    }
};
KyberswapElasticFarmContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.KyberswapElasticContractFactory)),
    __param(2, (0, common_1.Inject)(kyberswap_elastic_farm_contract_position_builder_1.KyberswapElasticFarmContractPositionBuilder)),
    __metadata("design:paramtypes", [Object, contracts_1.KyberswapElasticContractFactory,
        kyberswap_elastic_farm_contract_position_builder_1.KyberswapElasticFarmContractPositionBuilder])
], KyberswapElasticFarmContractPositionFetcher);
exports.KyberswapElasticFarmContractPositionFetcher = KyberswapElasticFarmContractPositionFetcher;
//# sourceMappingURL=kyberswap-elastic.farm.contract-position-fetcher.js.map