UNPKG

@exromany/lido-csm-sdk

Version:

[![GitHub license](https://img.shields.io/github/license/lidofinance/lido-csm-sdk?color=limegreen)](https://github.com/lidofinance/lido-csm-sdk/blob/main/LICENSE.txt) [![Version npm](https://img.shields.io/npm/v/@lidofinance/lido-csm-sdk?label=version)](h

235 lines 15.6 kB
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; import { convertSharesToEth, } from '../accounting-sdk/index.js'; import { CsmSDKModule } from '../common/class-primitives/csm-sdk-module.js'; import { Cache, ErrorHandler, Logger } from '../common/decorators/index.js'; import { CACHE_LONG, CACHE_MID, PERCENT_BASIS, } from '../common/index.js'; import { bigIntRange, fetchOneOf, fetchTree, isDefined, isUnique, sortRewardsByRefSlot, } from '../common/utils/index.js'; import { epochToTimestamp, ESTIMATED_BLOCK_GAP, slotToApproximateBlockNumber, } from '../frame-sdk/utils.js'; import { REPORT_V1_LOG_CIDS } from './consts.js'; import { findOperatorRewards } from './find-operator-rewards.js'; import { findProofAndAmount } from './find-proof.js'; import { getValidatorsRewards } from './get-validators-rewards.js'; import { parseReport } from './parse-report.js'; import { parseRewardsTree } from './parse-rewards-tree.js'; let RewardsSDK = (() => { var _a; let _classSuper = CsmSDKModule; let _instanceExtraInitializers = []; let _getProofTreeUrls_decorators; let _getReportUrls_decorators; let _getHistoryCount_decorators; let _getReportConfig_decorators; let _getLastReportConfig_decorators; let _getProofTree_decorators; let _getProof_decorators; let _getAvailable_decorators; let _getRewards_decorators; let _getReportByCid_decorators; let _getLastReport_decorators; let _getOperatorRewardsInLastReport_decorators; let _getLastReportTransactionHash_decorators; let _getOperatorRewardsHistory_decorators; return _a = class RewardsSDK extends _classSuper { get distributorContract() { return this.core.contractFeeDistributor; } getProofTreeUrls(cid) { return [...this.core.getIpfsUrls(cid), this.core.rewardsTreeLink].filter(isDefined); } getReportUrls(cid) { return this.core.getIpfsUrls(cid).filter(isDefined); } async getHistoryCount() { return this.distributorContract.read.distributionDataHistoryCount(); } async getReportConfig(number) { return this.distributorContract.read.getHistoricalDistributionData([ number, ]); } async getLastReportConfig() { const historyCount = await this.getHistoryCount(); if (!historyCount) return null; return this.getReportConfig(historyCount - 1n); } async getProofTree() { const config = await this.getLastReportConfig(); if (!config) return null; const urls = this.getProofTreeUrls(config.treeCid); return fetchTree({ urls, root: config.treeRoot, parse: parseRewardsTree }); } async getProof(nodeOperatorId) { const proofTree = await this.getProofTree(); return findProofAndAmount(proofTree, nodeOperatorId); } async getAvailable(nodeOperatorId, { proof, shares }) { if (proof.length === 0) return 0n; const available = await this.distributorContract.read.getFeesToDistribute([ nodeOperatorId, shares, proof, ]); return await this.bus.accounting.sharesToEth(available); } async getRewards(nodeOperatorId) { const proof = await this.getProof(nodeOperatorId); const available = await this.getAvailable(nodeOperatorId, proof); return { ...proof, available, }; } async getReportByCid(cid) { const urls = this.getReportUrls(cid); return fetchOneOf({ urls, parse: parseReport, }); } async getLastReport() { const config = await this.getLastReportConfig(); if (!config) return; const report = await this.getReportByCid(config?.logCid); return Array.isArray(report) ? report.at(-1) : report; } async getOperatorRewardsInLastReport(nodeOperatorId) { const report = await this.getLastReport(); if (!report) return undefined; const { shares, ...rest } = findOperatorRewards(nodeOperatorId, report); const distributed = await this.bus.accounting.sharesToEth(shares, report.blockstamp.block_number); return { ...rest, shares, distributed }; } async getLastReportTransactionHash() { const [config, lastRefSlot, currentBlock] = await Promise.all([ this.bus.frame.getConfig(), this.bus.frame.getLastProcessedRefSlot(), this.bus.frame.getLatestBlock(), ]); const estimatedBlock = slotToApproximateBlockNumber(lastRefSlot, config, currentBlock); const fromBlock = estimatedBlock - ESTIMATED_BLOCK_GAP; const logs = await this.bus.events.getRewardsReports({ fromBlock }); const lastLog = logs.at(-1); return lastLog?.transactionHash; } async getAllReports() { const reportsCount = await this.getHistoryCount(); const oldReportLogCids = REPORT_V1_LOG_CIDS[this.core.chainId]; const reports = await Promise.all([ ...oldReportLogCids.map((cid) => this.getReportByCid(cid)), ...[...bigIntRange(reportsCount)].map(async (index) => { const { logCid } = await this.getReportConfig(index); return this.getReportByCid(logCid); }), ]); return reports.flat().filter(isDefined); } async getOperatorRewardsHistory(nodeOperatorId) { const [reports, keys, frameConfig, digest] = await Promise.all([ this.getAllReports(), this.bus.keysWithStatus.getClKeysStatus(nodeOperatorId), this.bus.frame.getConfig(), this.bus.module.getDigest(), ]); if (reports.length === 0) return []; const validatorsRewards = reports.flatMap((report) => getValidatorsRewards(nodeOperatorId, report)); const blockNumbers = validatorsRewards .map((r) => r.blockNumber) .filter(isUnique); const poolDataByBlock = await this.bus.accounting.getStethPoolDataByBlockNumbers(blockNumbers); const enhancedRewards = validatorsRewards.map((vr) => { const fee = (BigInt(Number(PERCENT_BASIS) * vr.rewardShare) * digest.state.stakingModuleFee) / PERCENT_BASIS; const pubkey = keys?.find((k) => k.validatorIndex === vr.validatorIndex)?.pubkey; const poolData = poolDataByBlock.get(vr.blockNumber); return { ...vr, fee, pubkey, startTimestamp: epochToTimestamp(vr.frame[0], frameConfig), endTimestamp: epochToTimestamp(vr.frame[1], frameConfig), receivedRewards: convertSharesToEth(vr.receivedShares, poolData), }; }); return enhancedRewards.sort(sortRewardsByRefSlot); } constructor() { super(...arguments); __runInitializers(this, _instanceExtraInitializers); } }, (() => { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; _getProofTreeUrls_decorators = [Logger('Utils:')]; _getReportUrls_decorators = [Logger('Utils:')]; _getHistoryCount_decorators = [Logger('Views:'), ErrorHandler(), Cache(CACHE_MID)]; _getReportConfig_decorators = [Logger('Views:'), ErrorHandler(), Cache(CACHE_LONG)]; _getLastReportConfig_decorators = [Logger('Views:'), ErrorHandler(), Cache(CACHE_MID)]; _getProofTree_decorators = [Logger('API:'), Cache(CACHE_LONG)]; _getProof_decorators = [Logger('Utils:')]; _getAvailable_decorators = [Logger('Views:'), ErrorHandler()]; _getRewards_decorators = [Logger('Utils:')]; _getReportByCid_decorators = [Logger('Views:'), ErrorHandler()]; _getLastReport_decorators = [Logger('Views:'), ErrorHandler()]; _getOperatorRewardsInLastReport_decorators = [Logger('Utils:')]; _getLastReportTransactionHash_decorators = [Logger('Utils:')]; _getOperatorRewardsHistory_decorators = [Logger('Views:'), ErrorHandler()]; __esDecorate(_a, null, _getProofTreeUrls_decorators, { kind: "method", name: "getProofTreeUrls", static: false, private: false, access: { has: obj => "getProofTreeUrls" in obj, get: obj => obj.getProofTreeUrls }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getReportUrls_decorators, { kind: "method", name: "getReportUrls", static: false, private: false, access: { has: obj => "getReportUrls" in obj, get: obj => obj.getReportUrls }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getHistoryCount_decorators, { kind: "method", name: "getHistoryCount", static: false, private: false, access: { has: obj => "getHistoryCount" in obj, get: obj => obj.getHistoryCount }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getReportConfig_decorators, { kind: "method", name: "getReportConfig", static: false, private: false, access: { has: obj => "getReportConfig" in obj, get: obj => obj.getReportConfig }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getLastReportConfig_decorators, { kind: "method", name: "getLastReportConfig", static: false, private: false, access: { has: obj => "getLastReportConfig" in obj, get: obj => obj.getLastReportConfig }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getProofTree_decorators, { kind: "method", name: "getProofTree", static: false, private: false, access: { has: obj => "getProofTree" in obj, get: obj => obj.getProofTree }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getProof_decorators, { kind: "method", name: "getProof", static: false, private: false, access: { has: obj => "getProof" in obj, get: obj => obj.getProof }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getAvailable_decorators, { kind: "method", name: "getAvailable", static: false, private: false, access: { has: obj => "getAvailable" in obj, get: obj => obj.getAvailable }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getRewards_decorators, { kind: "method", name: "getRewards", static: false, private: false, access: { has: obj => "getRewards" in obj, get: obj => obj.getRewards }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getReportByCid_decorators, { kind: "method", name: "getReportByCid", static: false, private: false, access: { has: obj => "getReportByCid" in obj, get: obj => obj.getReportByCid }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getLastReport_decorators, { kind: "method", name: "getLastReport", static: false, private: false, access: { has: obj => "getLastReport" in obj, get: obj => obj.getLastReport }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getOperatorRewardsInLastReport_decorators, { kind: "method", name: "getOperatorRewardsInLastReport", static: false, private: false, access: { has: obj => "getOperatorRewardsInLastReport" in obj, get: obj => obj.getOperatorRewardsInLastReport }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getLastReportTransactionHash_decorators, { kind: "method", name: "getLastReportTransactionHash", static: false, private: false, access: { has: obj => "getLastReportTransactionHash" in obj, get: obj => obj.getLastReportTransactionHash }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getOperatorRewardsHistory_decorators, { kind: "method", name: "getOperatorRewardsHistory", static: false, private: false, access: { has: obj => "getOperatorRewardsHistory" in obj, get: obj => obj.getOperatorRewardsHistory }, metadata: _metadata }, null, _instanceExtraInitializers); if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); })(), _a; })(); export { RewardsSDK }; //# sourceMappingURL=rewards-sdk.js.map