"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 __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.EthereumUniswapV2PoolTokenFetcher = void 0;
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const address_1 = require("../../../app-toolkit/constants/address");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const position_interface_1 = require("../../../position/position.interface");
const uniswap_v2_default_subgraph_template_token_fetcher_1 = require("../common/uniswap-v2.default.subgraph.template.token-fetcher");
const UNISWAP_V2_BALANCES_QUERY = (0, graphql_request_1.gql) `
  query getBalances($address: String!) {
    user(id: $address) {
      liquidityPositions {
        pair {
          id
        }
      }
    }
  }
`;
let EthereumUniswapV2PoolTokenFetcher = class EthereumUniswapV2PoolTokenFetcher extends uniswap_v2_default_subgraph_template_token_fetcher_1.UniswapV2DefaultPoolSubgraphTemplateTokenFetcher {
    constructor() {
        super(...arguments);
        this.groupLabel = 'Pools';
        this.factoryAddress = '0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f';
        this.subgraphUrl = 'https://api.thegraph.com/subgraphs/name/ianlapham/uniswapv2';
        this.ignoredPools = ['0x3016a43b482d0480460f6625115bd372fe90c6bf'];
        this.first = 5000;
    }
    getPositionsForBalances() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.appToolkit.getAppTokenPositionsFromDatabase({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
        });
    }
    getBalances(_address) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector();
            const address = yield this.getAccountAddress(_address);
            if (address === address_1.ZERO_ADDRESS)
                return [];
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: UNISWAP_V2_BALANCES_QUERY,
                variables: { address: address.toLowerCase() },
            });
            const heldTokenAddresses = (_b = (_a = data.user) === null || _a === void 0 ? void 0 : _a.liquidityPositions.map(v => v.pair.id.toLowerCase())) !== null && _b !== void 0 ? _b : [];
            const heldTokens = yield tokenLoader.getMany(heldTokenAddresses.map(t => ({ address: t, network: this.network })));
            const sanitized = (0, lodash_1.compact)(heldTokens).filter(position_interface_1.isAppToken);
            const balances = yield Promise.all(sanitized.map((appToken) => __awaiter(this, void 0, void 0, function* () {
                const balanceRaw = yield this.getBalancePerToken({ multicall, address, appToken });
                const tokenBalance = (0, drill_balance_helper_1.drillBalance)(appToken, balanceRaw.toString(), { isDebt: this.isDebt });
                return tokenBalance;
            })));
            return balances;
        });
    }
    getRawBalances(_address) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector();
            const address = yield this.getAccountAddress(_address);
            if (address === address_1.ZERO_ADDRESS)
                return [];
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: UNISWAP_V2_BALANCES_QUERY,
                variables: { address: address.toLowerCase() },
            });
            const heldTokenAddresses = (_b = (_a = data.user) === null || _a === void 0 ? void 0 : _a.liquidityPositions.map(v => v.pair.id.toLowerCase())) !== null && _b !== void 0 ? _b : [];
            const heldTokens = yield tokenLoader.getMany(heldTokenAddresses.map(t => ({ address: t, network: this.network })));
            const sanitized = (0, lodash_1.compact)(heldTokens).filter(position_interface_1.isAppToken);
            let results = [];
            for (const batch of (0, lodash_1.chunk)(sanitized, 100).values()) {
                results = results.concat(yield Promise.all(batch.map((appToken) => __awaiter(this, void 0, void 0, function* () {
                    return ({
                        key: this.appToolkit.getPositionKey(appToken),
                        balance: (yield this.getBalancePerToken({ multicall, address, appToken })).toString(),
                    });
                }))));
            }
            return results;
        });
    }
};
EthereumUniswapV2PoolTokenFetcher = __decorate([
    (0, position_template_decorator_1.PositionTemplate)()
], EthereumUniswapV2PoolTokenFetcher);
exports.EthereumUniswapV2PoolTokenFetcher = EthereumUniswapV2PoolTokenFetcher;
//# sourceMappingURL=uniswap-v2.pool.token-fetcher.js.map