"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.UniswapV3LiquidityContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const graphql_request_1 = require("graphql-request");
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 uniswap_v3_liquidity_contract_position_builder_1 = require("./uniswap-v3.liquidity.contract-position-builder");
const GET_TOP_POOLS_QUERY = (0, graphql_request_1.gql) `
  query topPools {
    pools(first: 50, orderBy: totalValueLockedUSD, orderDirection: desc, subgraphError: allow) {
      id
      feeTier
      token0 {
        id
      }
      token1 {
        id
      }
    }
  }
`;
let UniswapV3LiquidityContractPositionFetcher = class UniswapV3LiquidityContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, uniswapV3LiquidityContractPositionBuilder) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.uniswapV3LiquidityContractPositionBuilder = uniswapV3LiquidityContractPositionBuilder;
    }
    getContract(address) {
        return this.contractFactory.uniswapV3PositionManager({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: 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;
            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(2)}%)`;
            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.uniswapV3PositionManager({
                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.uniswapV3LiquidityContractPositionBuilder.buildPosition({
                    positionId: yield multicall.wrap(positionManager).tokenOfOwnerByIndex(address, index),
                    network: this.network,
                    multicall,
                    tokenLoader,
                });
            })));
            return (0, lodash_1.compact)(balances);
        });
    }
};
UniswapV3LiquidityContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.UniswapV3ContractFactory)),
    __param(2, (0, common_1.Inject)(uniswap_v3_liquidity_contract_position_builder_1.UniswapV3LiquidityContractPositionBuilder)),
    __metadata("design:paramtypes", [Object, contracts_1.UniswapV3ContractFactory,
        uniswap_v3_liquidity_contract_position_builder_1.UniswapV3LiquidityContractPositionBuilder])
], UniswapV3LiquidityContractPositionFetcher);
exports.UniswapV3LiquidityContractPositionFetcher = UniswapV3LiquidityContractPositionFetcher;
//# sourceMappingURL=uniswap-v3.liquidity.contract-position-fetcher.js.map