@exromany/lido-csm-sdk
Version:
[](https://github.com/lidofinance/lido-csm-sdk/blob/main/LICENSE.txt) [](h
219 lines • 13.5 kB
JavaScript
;
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeysWithStatusSDK = void 0;
const viem_1 = require("viem");
const csm_sdk_module_js_1 = require("../common/class-primitives/csm-sdk-module.js");
const cache_js_1 = require("../common/decorators/cache.js");
const error_handler_js_1 = require("../common/decorators/error-handler.js");
const logger_js_1 = require("../common/decorators/logger.js");
const index_js_1 = require("../common/index.js");
const compare_lowercase_js_1 = require("../common/utils/compare-lowercase.js");
const fetch_json_js_1 = require("../common/utils/fetch-json.js");
const is_defined_js_1 = require("../common/utils/is-defined.js");
const cl_chunks_js_1 = require("./cl-chunks.js");
const utils_js_1 = require("./utils.js");
let KeysWithStatusSDK = (() => {
var _a;
let _classSuper = csm_sdk_module_js_1.CsmSDKModule;
let _instanceExtraInitializers = [];
let _getApiKeys_decorators;
let _getApiKeysDuplicates_decorators;
let _getClKeysStatus_decorators;
let _getCurrentEpoch_decorators;
let _getKeys_decorators;
return _a = class KeysWithStatusSDK extends _classSuper {
async getApiKeys(pubkeys) {
const keysApi = this.core.keysApiLink;
if (!keysApi) {
throw new Error('Keys API link is not configured');
}
if (pubkeys.length === 0)
return [];
const url = `${keysApi}/v1/keys/find`;
const response = await (0, fetch_json_js_1.fetchJson)(url, {
method: 'POST',
body: JSON.stringify({ pubkeys }),
headers: { 'Content-Type': 'application/json' },
}).catch(() => null);
if (!response)
return null;
return response.data;
}
async getApiKeysDuplicates(nodeOperatorId, pubkeys) {
const keys = await this.getApiKeys(pubkeys);
if (!keys)
return null;
const csmAddress = this.core.getContractAddress(index_js_1.CSM_CONTRACT_NAMES.csModule);
const duplicates = [
...keys.map(({ key }) => key).filter(is_defined_js_1.isNotUnique),
...keys
.filter((key) => key.operatorIndex !== Number(nodeOperatorId) ||
!(0, viem_1.isAddressEqual)(key.moduleAddress, csmAddress))
.map(({ key }) => key),
].filter(is_defined_js_1.isUnique);
return duplicates;
}
async getClKeysStatus(pubkeys) {
if (!this.core.clApiUrl) {
return null;
}
const urls = (0, cl_chunks_js_1.getClUrls)(pubkeys, this.core.clApiUrl);
const results = await Promise.all(urls.map((url) => (0, fetch_json_js_1.fetchJson)(url)));
return results.flatMap(({ data }) => data.map(cl_chunks_js_1.prepareKey));
}
async getCurrentEpoch() {
const [[slotsPerEpoch, secondsPerSlot, genesisTime], { timestamp: latestBlockTimestamp },] = await Promise.all([
this.core.contractHashConsensus.read.getChainConfig(),
this.core.client.getBlock({ blockTag: 'latest' }),
]);
const latestSlot = (latestBlockTimestamp - genesisTime) / secondsPerSlot;
const currentEpoch = latestSlot / slotsPerEpoch;
return currentEpoch;
}
async getKeys(id) {
const [info, unboundCount, keys, currentEpoch] = await Promise.all([
this.bus.getOrThrow('operator').getInfo(id),
this.bus.getOrThrow('operator').getUnboundKeysCount(id),
this.bus.getOrThrow('operator').getKeys(id),
this.getCurrentEpoch(),
]);
const [withdrawalSubmitted, requestedToExit, duplicates, clKeysStatus, keysWithStrikes,] = await Promise.all([
this.bus.getOrThrow('events').getWithdrawalSubmittedKeys(id),
this.bus.getOrThrow('events').getRequestedToExitKeys(id),
this.getApiKeysDuplicates(id, keys),
this.getClKeysStatus(keys),
this.bus.getOrThrow('strikes').getKeysWithStrikes(id),
]);
const ejectableEpoch = currentEpoch - index_js_1.EJECTABLE_EPOCH_COUNT;
const getStatuses = (pubkey, nodeOperatorKeyIndex) => {
const statuses = [];
const prefilled = clKeysStatus?.find((item) => item.pubkey === pubkey);
if (prefilled?.slashed) {
statuses.push(index_js_1.KEY_STATUS.SLASHED);
}
if (withdrawalSubmitted?.includes(pubkey)) {
return [...statuses, index_js_1.KEY_STATUS.WITHDRAWN];
}
if (keysWithStrikes
.find((item) => item.pubkey === pubkey)
?.strikes.reduce((a, b) => a + b, 0)) {
statuses.push(index_js_1.KEY_STATUS.WITH_STRIKES);
}
if (nodeOperatorKeyIndex >= info.totalVettedKeys) {
if (duplicates?.includes(pubkey)) {
return [...statuses, index_js_1.KEY_STATUS.DUPLICATED];
}
else if (nodeOperatorKeyIndex === info.totalVettedKeys) {
return [...statuses, index_js_1.KEY_STATUS.INVALID];
}
}
if (nodeOperatorKeyIndex >= info.totalDepositedKeys &&
info.enqueuedCount < info.depositableValidatorsCount) {
statuses.push(index_js_1.KEY_STATUS.NON_QUEUED);
}
else if (nodeOperatorKeyIndex >= info.totalVettedKeys) {
statuses.push(index_js_1.KEY_STATUS.UNCHECKED);
}
else if (prefilled?.status) {
if (prefilled.activationEpoch < ejectableEpoch) {
statuses.push(index_js_1.KEY_STATUS.EJECTABLE);
}
statuses.push(prefilled.status);
}
else if (nodeOperatorKeyIndex >= info.totalDepositedKeys) {
statuses.push(index_js_1.KEY_STATUS.DEPOSITABLE);
}
else {
if (!prefilled || prefilled.activationEpoch < ejectableEpoch) {
statuses.push(index_js_1.KEY_STATUS.EJECTABLE);
}
statuses.push(clKeysStatus ? index_js_1.KEY_STATUS.ACTIVATION_PENDING : index_js_1.KEY_STATUS.ACTIVE);
}
if ((0, utils_js_1.hasNoInterception)(statuses, [
index_js_1.KEY_STATUS.SLASHED,
index_js_1.KEY_STATUS.WITHDRAWN,
index_js_1.KEY_STATUS.WITHDRAWAL_PENDING,
index_js_1.KEY_STATUS.EXITING,
])) {
const exitRequestIndex = requestedToExit.findIndex((key) => (0, compare_lowercase_js_1.compareLowercase)(pubkey, key));
if (exitRequestIndex >= 0) {
statuses.push(index_js_1.KEY_STATUS.EXIT_REQUESTED);
}
}
if ((0, utils_js_1.hasNoInterception)(statuses, [
index_js_1.KEY_STATUS.SLASHED,
index_js_1.KEY_STATUS.WITHDRAWN,
index_js_1.KEY_STATUS.EXIT_REQUESTED,
]) &&
unboundCount &&
info.totalAddedKeys - nodeOperatorKeyIndex < unboundCount) {
statuses.push(index_js_1.KEY_STATUS.UNBONDED);
}
return statuses;
};
return keys.map((pubkey, index) => ({
pubkey,
index,
statuses: getStatuses(pubkey, index),
validatorIndex: clKeysStatus?.find((item) => item.pubkey === pubkey)
?.validatorIndex,
strikes: keysWithStrikes.find((item) => item.pubkey === pubkey)?.strikes,
}));
}
constructor() {
super(...arguments);
__runInitializers(this, _instanceExtraInitializers);
}
},
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
_getApiKeys_decorators = [(0, logger_js_1.Logger)('API:'), (0, error_handler_js_1.ErrorHandler)(), (0, cache_js_1.Cache)(60 * 1000)];
_getApiKeysDuplicates_decorators = [(0, logger_js_1.Logger)('API:'), (0, error_handler_js_1.ErrorHandler)(), (0, cache_js_1.Cache)(60 * 1000)];
_getClKeysStatus_decorators = [(0, logger_js_1.Logger)('API:'), (0, error_handler_js_1.ErrorHandler)(), (0, cache_js_1.Cache)(60 * 1000)];
_getCurrentEpoch_decorators = [(0, logger_js_1.Logger)('Views:'), (0, error_handler_js_1.ErrorHandler)()];
_getKeys_decorators = [(0, logger_js_1.Logger)('Utils:'), (0, error_handler_js_1.ErrorHandler)()];
__esDecorate(_a, null, _getApiKeys_decorators, { kind: "method", name: "getApiKeys", static: false, private: false, access: { has: obj => "getApiKeys" in obj, get: obj => obj.getApiKeys }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_a, null, _getApiKeysDuplicates_decorators, { kind: "method", name: "getApiKeysDuplicates", static: false, private: false, access: { has: obj => "getApiKeysDuplicates" in obj, get: obj => obj.getApiKeysDuplicates }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_a, null, _getClKeysStatus_decorators, { kind: "method", name: "getClKeysStatus", static: false, private: false, access: { has: obj => "getClKeysStatus" in obj, get: obj => obj.getClKeysStatus }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_a, null, _getCurrentEpoch_decorators, { kind: "method", name: "getCurrentEpoch", static: false, private: false, access: { has: obj => "getCurrentEpoch" in obj, get: obj => obj.getCurrentEpoch }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_a, null, _getKeys_decorators, { kind: "method", name: "getKeys", static: false, private: false, access: { has: obj => "getKeys" in obj, get: obj => obj.getKeys }, metadata: _metadata }, null, _instanceExtraInitializers);
if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
})(),
_a;
})();
exports.KeysWithStatusSDK = KeysWithStatusSDK;
//# sourceMappingURL=keys-with-status-sdk.js.map