"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.KyberswapElasticLiquidityContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = 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 the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
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_apy_data_loader_1 = require("./kyberswap-elastic.apy.data-loader");
const kyberswap_elastic_liquidity_contract_position_builder_1 = require("./kyberswap-elastic.liquidity.contract-position-builder");
const kyberswap_elastic_pool_subgraph_types_1 = require("./kyberswap-elastic.pool.subgraph.types");
let KyberswapElasticLiquidityContractPositionFetcher = class KyberswapElasticLiquidityContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, kyberElasticLiquidityContractPositionBuilder, apyDataLoaderBuilder) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.kyberElasticLiquidityContractPositionBuilder = kyberElasticLiquidityContractPositionBuilder;
        this.apyDataLoaderBuilder = apyDataLoaderBuilder;
    }
    getContract(address) {
        return this.contractFactory.positionManager({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            this.apyDataLoader = this.apyDataLoaderBuilder.getLoader({
                subgraphUrl: this.subgraphUrl,
                blockSubgraphUrl: this.blockSubgraphUrl,
            });
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: kyberswap_elastic_pool_subgraph_types_1.GET_TOP_POOLS_QUERY,
            });
            return data.pools.map(v => ({
                address: this.positionManagerAddress,
                poolAddress: v.id.toLowerCase(),
                token0Address: v.token0.id.toLowerCase(),
                token1Address: v.token1.id.toLowerCase(),
                feeTier: Number(v.feeTier) / Math.pow(10, 4),
            }));
        });
    }
    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,
                },
            ];
        });
    }
    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;
            const apy = yield this.apyDataLoader.load(poolAddress);
            return { feeTier, reserves, liquidity, poolAddress, assetStandard, apy, 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 positionManager = this.contractFactory.positionManager({
                address: this.positionManagerAddress,
                network: this.network,
            });
            const numPositionsRaw = yield positionManager.balanceOf(address);
            const balances = yield Promise.all((0, lodash_1.range)(0, numPositionsRaw.toNumber()).map((index) => __awaiter(this, void 0, void 0, function* () {
                return this.kyberElasticLiquidityContractPositionBuilder.buildPosition({
                    positionId: yield multicall.wrap(positionManager).tokenOfOwnerByIndex(address, index),
                    network: this.network,
                    multicall,
                    tokenLoader,
                });
            })));
            return (0, lodash_1.compact)(balances);
        });
    }
};
KyberswapElasticLiquidityContractPositionFetcher = __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_liquidity_contract_position_builder_1.KyberswapElasticLiquidityContractPositionBuilder)),
    __param(3, (0, common_1.Inject)(kyberswap_elastic_apy_data_loader_1.KyberswapElasticApyDataLoader)),
    __metadata("design:paramtypes", [Object, contracts_1.KyberswapElasticContractFactory,
        kyberswap_elastic_liquidity_contract_position_builder_1.KyberswapElasticLiquidityContractPositionBuilder,
        kyberswap_elastic_apy_data_loader_1.KyberswapElasticApyDataLoader])
], KyberswapElasticLiquidityContractPositionFetcher);
exports.KyberswapElasticLiquidityContractPositionFetcher = KyberswapElasticLiquidityContractPositionFetcher;
//# sourceMappingURL=kyberswap-elastic.liquidity.contract-position-fetcher.js.map