"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.EthereumSpoolStakingContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const ethers_1 = require("ethers");
const utils_1 = require("ethers/lib/utils");
const lodash_1 = __importDefault(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 display_item_present_1 = require("../../../app-toolkit/helpers/presentation/display-item.present");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const contracts_1 = require("../../../apps/spool/contracts");
const spool_constants_1 = require("../../../apps/spool/ethereum/spool.constants");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
let EthereumSpoolStakingContractPositionFetcher = class EthereumSpoolStakingContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Staking';
    }
    getContract(address) {
        return this.contractFactory.spoolStaking({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: spool_constants_1.STAKING_ADDRESS }];
        });
    }
    getTokenDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const now = parseInt(String(new Date().getTime() / 1000));
            const stakingRewards = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: spool_constants_1.SUBGRAPH_API_BASE_URL,
                query: spool_constants_1.REWARDS_QUERY,
            });
            const rewardAddresses = lodash_1.default.uniq(stakingRewards.stakingRewardTokens
                .filter(reward => !reward.isRemoved && parseInt(reward.startTime) >= now && parseInt(reward.endTime) <= now)
                .map(reward => reward.token.id)
                .concat([spool_constants_1.SPOOL_ADDRESS]));
            return [
                { metaType: position_interface_1.MetaType.SUPPLIED, address: spool_constants_1.SPOOL_ADDRESS, network: this.network },
                { metaType: position_interface_1.MetaType.VESTING, address: spool_constants_1.VOSPOOL_ADDRESS, network: this.network },
                ...rewardAddresses.map(address => ({ metaType: position_interface_1.MetaType.CLAIMABLE, address, network: this.network })),
            ];
        });
    }
    getDataProps({ multicall, contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            const [spoolToken, voSpoolToken] = contractPosition.tokens;
            const spoolContract = this.contractFactory.erc20(spoolToken);
            const voSpoolContract = this.contractFactory.spoolVospool(voSpoolToken);
            const totalStaked = yield multicall.wrap(spoolContract).balanceOf(spool_constants_1.STAKING_ADDRESS);
            const votingPowerRaw = yield multicall.wrap(voSpoolContract).getTotalGradualVotingPower();
            const spoolStaked = totalStaked.div(ethers_1.BigNumber.from(10).pow(spoolToken.decimals)).toNumber();
            const totalAccVoSpool = votingPowerRaw.div(ethers_1.BigNumber.from(10).pow(voSpoolToken.decimals)).toNumber();
            const pricePrecision = Math.pow(10, 10);
            const tvl = ethers_1.BigNumber.from(pricePrecision * spoolToken.price)
                .mul(totalStaked)
                .div(pricePrecision)
                .div(ethers_1.BigNumber.from(10).pow(spoolToken.decimals))
                .toNumber();
            return { tvl, spoolStaked, totalAccVoSpool };
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])} Staking`;
        });
    }
    getStatsItems({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                { label: 'TVL', value: (0, display_item_present_1.buildDollarDisplayItem)(contractPosition.dataProps.tvl) },
                { label: 'SPOOL Staked', value: (0, display_item_present_1.buildNumberDisplayItem)(contractPosition.dataProps.spoolStaked) },
                { label: 'voSPOOL Accumulated', value: (0, display_item_present_1.buildNumberDisplayItem)(contractPosition.dataProps.totalAccVoSpool) },
            ];
        });
    }
    getTokenBalancesPerPosition({ address, contractPosition, multicall, }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const suppliedToken = contractPosition.tokens.find(position_utils_1.isSupplied);
            const rewardTokens = contractPosition.tokens.filter(position_utils_1.isClaimable);
            const staking = this.contractFactory.spoolStaking({ address: spool_constants_1.STAKING_ADDRESS, network: this.network });
            const voSpool = this.contractFactory.spoolVospool({ address: spool_constants_1.VOSPOOL_ADDRESS, network: this.network });
            const [votingPowerRaw, voSpoolRewards, ...tokenRewards] = yield Promise.all([
                multicall.wrap(voSpool).getUserGradualVotingPower(address),
                multicall.wrap(staking).callStatic.getUpdatedVoSpoolRewardAmount({ from: address }),
                ...rewardTokens.map(reward => multicall.wrap(staking).earned(reward.address, address)),
            ]);
            const stakedSpool = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: spool_constants_1.SUBGRAPH_API_BASE_URL,
                query: spool_constants_1.SPOOL_STAKED_QUERY,
                variables: { address },
            });
            const stakedAmount = (0, utils_1.parseEther)(((_a = stakedSpool === null || stakedSpool === void 0 ? void 0 : stakedSpool.userSpoolStaking) === null || _a === void 0 ? void 0 : _a.spoolStaked) || '0').toString();
            const rewardBalances = rewardTokens.map((token, idx) => {
                const rewards = token.address.toLowerCase() == suppliedToken.address.toLowerCase()
                    ? tokenRewards[idx].add(voSpoolRewards)
                    : tokenRewards[idx];
                return rewards.toString();
            });
            return [stakedAmount, votingPowerRaw.toString(), ...rewardBalances];
        });
    }
};
EthereumSpoolStakingContractPositionFetcher = __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.SpoolContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.SpoolContractFactory])
], EthereumSpoolStakingContractPositionFetcher);
exports.EthereumSpoolStakingContractPositionFetcher = EthereumSpoolStakingContractPositionFetcher;
//# sourceMappingURL=spool.staking.contract-position-fetcher.js.map