"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.EthereumRenDarknodeContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
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 drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
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 ren_api_client_1 = require("../common/ren.api.client");
const contracts_1 = require("../contracts");
let EthereumRenDarknodeContractPositionFetcher = class EthereumRenDarknodeContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, apiClient) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.apiClient = apiClient;
        this.groupLabel = 'Darknodes';
    }
    getContract(address) {
        return this.contractFactory.renDarknodeRegistry({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: '0x2d7b6c95afeffa50c068d50f89c5c0014e054f0a' }];
        });
    }
    getTokenDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const { assets } = yield this.apiClient.getDarknodeAssets();
            const claimable = [address_1.ZERO_ADDRESS, ...assets.map(v => v.tokenAddress)];
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: '0x408e41876cccdc0f92210600ef50372656052a38',
                    network: this.network,
                },
                ...claimable.map(claimableTokenAddress => ({
                    metaType: position_interface_1.MetaType.CLAIMABLE,
                    address: claimableTokenAddress,
                    network: this.network,
                })),
            ];
        });
    }
    getLabel(params) {
        return __awaiter(this, void 0, void 0, function* () {
            const suppliedToken = params.contractPosition.tokens[0];
            return `${suppliedToken.symbol} in Darknodes`;
        });
    }
    getTokenBalancesPerPosition() {
        return __awaiter(this, void 0, void 0, function* () {
            return [];
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const { darknodes = [] } = yield this.apiClient.getDarknodeBalance(address);
            if (darknodes.length === 0)
                return [];
            const contractPositions = yield this.appToolkit.getAppContractPositions({
                appId: this.appId,
                network: this.network,
                groupIds: [this.groupId],
            });
            const darknodePosition = contractPositions[0];
            if (!darknodePosition)
                return [];
            const supplied = darknodePosition.tokens.find(position_utils_1.isSupplied);
            const claimable = darknodePosition.tokens.filter(position_utils_1.isClaimable);
            const balanceRaw = darknodes
                .filter(x => +x.registeredAt > 0)
                .reduce((sum, x) => new bignumber_js_1.default(x.bond).plus(sum), new bignumber_js_1.default(0));
            const ungroupedClaimable = (darknodes !== null && darknodes !== void 0 ? darknodes : [])
                .filter(x => +x.registeredAt > 0)
                .flatMap(v => v.balances)
                .map(balance => {
                const token = claimable.find(p => balance.symbol === p.symbol);
                return token ? (0, drill_balance_helper_1.drillBalance)(token, balance.amount) : null;
            });
            const groupedClaimable = (0, lodash_1.values)((0, lodash_1.groupBy)((0, lodash_1.compact)(ungroupedClaimable), v => v.address));
            const suppliedBalances = (0, drill_balance_helper_1.drillBalance)(supplied, balanceRaw.toFixed(0));
            const claimableBalances = groupedClaimable.map(v => {
                const totalBalanceRaw = v.reduce((acc, t) => acc.plus(t.balanceRaw), new bignumber_js_1.default(0)).toFixed(0);
                return (0, drill_balance_helper_1.drillBalance)(v[0], totalBalanceRaw);
            });
            const tokens = [suppliedBalances, ...claimableBalances];
            const balanceUSD = (0, lodash_1.sumBy)(tokens, t => t.balanceUSD);
            const balance = Object.assign(Object.assign({}, darknodePosition), { tokens, balanceUSD });
            return [balance];
        });
    }
};
EthereumRenDarknodeContractPositionFetcher = __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.RenContractFactory)),
    __param(2, (0, common_1.Inject)(ren_api_client_1.RenApiClient)),
    __metadata("design:paramtypes", [Object, contracts_1.RenContractFactory,
        ren_api_client_1.RenApiClient])
], EthereumRenDarknodeContractPositionFetcher);
exports.EthereumRenDarknodeContractPositionFetcher = EthereumRenDarknodeContractPositionFetcher;
//# sourceMappingURL=ren.darknode.contract-position-fetcher.js.map