"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.EthereumPolygonStakingContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const axios_1 = __importDefault(require("axios"));
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
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 image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const cache_on_interval_decorator_1 = require("../../../cache/cache-on-interval.decorator");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
const GQL_ENDPOINT = `https://api.thegraph.com/subgraphs/name/maticnetwork/mainnet-root-subgraphs`;
const DELEGATED_MATIC_QUERY = (0, graphql_request_1.gql) `
  query getDelegatedMatic($address: String!, $first: Int, $lastId: String) {
    delegators(where: { address: $address, id_gt: $lastId }, first: $first) {
      validatorId
      delegatedAmount
    }
  }
`;
let EthereumPolygonStakingContractPositionFetcher = class EthereumPolygonStakingContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Deposits';
    }
    getValidators() {
        return __awaiter(this, void 0, void 0, function* () {
            const url = `https://sentinel.matic.network/api/v2/validators?limit=1000`;
            const { data } = yield axios_1.default.get(url);
            return data;
        });
    }
    getContract(address) {
        return this.contractFactory.polygonStakeManager({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const validators = yield this.getValidators();
            return validators.result.map(validator => ({
                address: '0x5e3ef299fddf15eaa0432e6e66473ace8c13d908',
                validatorId: validator.id,
                validatorName: validator.name,
                validatorShareAddress: validator.contractAddress,
            }));
        });
    }
    getTokenDefinitions(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: '0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0',
                    network: this.network,
                },
                {
                    metaType: position_interface_1.MetaType.CLAIMABLE,
                    address: '0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0',
                    network: this.network,
                },
            ];
        });
    }
    getDataProps({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return {
                validatorId: definition.validatorId,
                validatorName: definition.validatorName,
                validatorShareAddress: definition.validatorShareAddress,
                positionKey: `${definition.validatorId}`,
            };
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            const validatorLabel = `${contractPosition.dataProps.validatorName} (ID: ${contractPosition.dataProps.validatorId})`;
            return `Delegated ${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])}: ${validatorLabel}`;
        });
    }
    getImages({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, image_present_1.getImagesFromToken)(contractPosition.tokens[0]);
        });
    }
    getTokenBalancesPerPosition(_params) {
        return __awaiter(this, void 0, void 0, function* () {
            throw new Error('Method not implemented.');
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const data = yield (0, the_graph_helper_1.gqlFetchAll)({
                endpoint: GQL_ENDPOINT,
                query: DELEGATED_MATIC_QUERY,
                dataToSearch: 'delegators',
                variables: {
                    address: address.toLowerCase(),
                },
            });
            const positions = yield this.appToolkit.getAppContractPositions({
                network: this.network,
                appId: this.appId,
                groupIds: [this.groupId],
            });
            const balances = yield Promise.all(data.delegators.map((delegator) => __awaiter(this, void 0, void 0, function* () {
                const position = positions.find(v => v.dataProps.validatorId === Number(delegator.validatorId));
                if (!position)
                    return null;
                const contract = this.contractFactory.polygonValidatorShare({
                    address: position.dataProps.validatorShareAddress,
                    network: this.network,
                });
                const [balanceRaw, claimableBalanceRaw] = yield Promise.all([
                    multicall.wrap(contract).balanceOf(address),
                    multicall.wrap(contract).getLiquidRewards(address),
                ]);
                const suppliedToken = position.tokens.find(position_utils_1.isSupplied);
                const claimableToken = position.tokens.find(position_utils_1.isClaimable);
                if (!suppliedToken || !claimableToken)
                    return null;
                const tokens = [
                    (0, drill_balance_helper_1.drillBalance)(suppliedToken, balanceRaw.toString()),
                    (0, drill_balance_helper_1.drillBalance)(claimableToken, claimableBalanceRaw.toString()),
                ];
                const balanceUSD = (0, lodash_1.sumBy)(tokens, v => v.balanceUSD);
                const balance = Object.assign(Object.assign({}, position), { tokens,
                    balanceUSD });
                return balance;
            })));
            return (0, lodash_1.compact)(balances);
        });
    }
};
__decorate([
    (0, cache_on_interval_decorator_1.CacheOnInterval)({
        key: `studio:polygon-staking:deposit:ethereum:validators`,
        timeout: 15 * 60 * 1000,
        failOnMissingData: false,
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], EthereumPolygonStakingContractPositionFetcher.prototype, "getValidators", null);
EthereumPolygonStakingContractPositionFetcher = __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.PolygonStakingContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.PolygonStakingContractFactory])
], EthereumPolygonStakingContractPositionFetcher);
exports.EthereumPolygonStakingContractPositionFetcher = EthereumPolygonStakingContractPositionFetcher;
//# sourceMappingURL=polygon-staking.deposit.contract-position-fetcher.js.map