"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.EthereumEthereumStakingDepositContractPositionFetcher = void 0;
const querystring_1 = require("querystring");
const common_1 = require("@nestjs/common");
const axios_1 = __importDefault(require("axios"));
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../../app-toolkit/constants/address");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
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 contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
const SUBGRAPH_DEPOSITS_ENDPOINT = `https://api.thegraph.com/subgraphs/name/terryyyyyy/eth2staking`;
const BEACON_CHAIN_API_ENDPOINT = `https://beaconcha.in/api/v1`;
const ETH2_DEPOSITS_QUERY = (0, graphql_request_1.gql) `
  query getEth2Deposits($address: String!, $first: Int, $lastId: String) {
    deposits(where: { from: $address, isDepositor: true, id_gt: $lastId }, first: $first) {
      id
      amount
      index
    }
  }
`;
let EthereumEthereumStakingDepositContractPositionFetcher = class EthereumEthereumStakingDepositContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Deposits';
    }
    getContract(address) {
        return this.contractFactory.ethereumStakingDeposit({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: '0x00000000219ab540356cbb839cbe05303d7705fa' }];
        });
    }
    getTokenDefinitions(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: address_1.ZERO_ADDRESS,
                    network: this.network,
                },
            ];
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])} in Eth2 Deposit`;
        });
    }
    getTokenBalancesPerPosition({ address }) {
        return __awaiter(this, void 0, void 0, function* () {
            const depositsCount = yield this.getDepositsCountFromSubgraph(address);
            if (depositsCount === 0) {
                return [0];
            }
            if (depositsCount > 500) {
                const balanceRaw = new bignumber_js_1.default(depositsCount).times(32).times(1e18).toFixed(0);
                return [balanceRaw];
            }
            const indices = yield this.getAllIndices(address);
            const totalBalanceRaw = yield this.getTotalBalanceForIndices(indices);
            return [totalBalanceRaw];
        });
    }
    getDepositsCountFromSubgraph(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const data = yield (0, the_graph_helper_1.gqlFetchAll)({
                endpoint: SUBGRAPH_DEPOSITS_ENDPOINT,
                query: ETH2_DEPOSITS_QUERY,
                dataToSearch: 'deposits',
                variables: {
                    address: address.toLowerCase(),
                },
            });
            return data.deposits.length;
        });
    }
    getAllIndices(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const axiosInstance = yield this.getAxiosInstance();
            const { data: indicesData } = yield axiosInstance.get(`/validator/eth1/${address.toLowerCase()}`, { params: { limit: 2000 } });
            let currentIndices = indicesData.data.map(({ validatorindex }) => validatorindex);
            let indices = indicesData.data.map(({ validatorindex }) => validatorindex);
            while (currentIndices.length === 2000) {
                const { data: indicesData } = yield axiosInstance.get(`/validator/eth1/${address.toLowerCase()}`, { params: { limit: 2000, offset: indices.length } });
                currentIndices = indicesData.data.map(({ validatorindex }) => validatorindex);
                indices = [...indices, ...currentIndices];
            }
            return indices;
        });
    }
    getTotalBalanceForIndices(indices) {
        return __awaiter(this, void 0, void 0, function* () {
            const axiosInstance = yield this.getAxiosInstance();
            const chunks = (0, lodash_1.chunk)(indices, 100);
            const allBalances = yield Promise.all(chunks.map(chunk => axiosInstance.get(`/validator/${(0, querystring_1.escape)(chunk.join(','))}/balancehistory`, {
                params: {
                    limit: 1,
                },
            })));
            if (!allBalances.every(({ data }) => data.status === 'OK')) {
                throw new Error('Failed to fetch balance history');
            }
            const totalBalanceRawNormalized = allBalances.reduce((acc, { data }) => acc.plus(data.data.reduce((acc, { balance }) => acc.plus(balance), new bignumber_js_1.default(0))), new bignumber_js_1.default(0));
            const totalBalanceRaw = totalBalanceRawNormalized.div(1e9).times(1e18).toFixed(0);
            return totalBalanceRaw;
        });
    }
    getAxiosInstance() {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            return axios_1.default.create({
                baseURL: BEACON_CHAIN_API_ENDPOINT,
                params: { apikey: (_a = process.env.BEACONCHAIN_API_KEY) !== null && _a !== void 0 ? _a : '' },
            });
        });
    }
};
EthereumEthereumStakingDepositContractPositionFetcher = __decorate([
    (0, position_template_decorator_1.PositionTemplate)(),
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.EthereumStakingContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.EthereumStakingContractFactory])
], EthereumEthereumStakingDepositContractPositionFetcher);
exports.EthereumEthereumStakingDepositContractPositionFetcher = EthereumEthereumStakingDepositContractPositionFetcher;
//# sourceMappingURL=ethereum-staking.deposit.contract-position-fetcher.js.map