@ensnode/ensnode-sdk
Version:
A utility library for interacting with ENSNode and ENS data
1,309 lines (1,257 loc) • 160 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
ADDR_REVERSE_NODE: () => ADDR_REVERSE_NODE,
ATTR_PROTOCOL_NAME: () => ATTR_PROTOCOL_NAME,
ATTR_PROTOCOL_STEP: () => ATTR_PROTOCOL_STEP,
ATTR_PROTOCOL_STEP_RESULT: () => ATTR_PROTOCOL_STEP_RESULT,
AssetNamespaces: () => AssetNamespaces,
BASENAMES_NODE: () => BASENAMES_NODE,
ChainIndexingConfigTypeIds: () => ChainIndexingConfigTypeIds,
ChainIndexingStatusIds: () => ChainIndexingStatusIds,
ClientError: () => ClientError,
CrossChainIndexingStrategyIds: () => CrossChainIndexingStrategyIds,
CurrencyIds: () => CurrencyIds,
DEFAULT_EVM_CHAIN_ID: () => DEFAULT_EVM_CHAIN_ID,
DEFAULT_EVM_COIN_TYPE: () => DEFAULT_EVM_COIN_TYPE,
ENSNamespaceIds: () => import_datasources.ENSNamespaceIds,
ENSNodeClient: () => ENSNodeClient,
ENS_ROOT: () => ENS_ROOT,
ETH_COIN_TYPE: () => ETH_COIN_TYPE,
ETH_NODE: () => ETH_NODE,
ForwardResolutionProtocolStep: () => ForwardResolutionProtocolStep,
IndexingStatusResponseCodes: () => IndexingStatusResponseCodes,
LINEANAMES_NODE: () => LINEANAMES_NODE,
LruCache: () => LruCache,
NFTMintStatuses: () => NFTMintStatuses,
NFTTransferTypes: () => NFTTransferTypes,
NameTokenOwnershipTypes: () => NameTokenOwnershipTypes,
NameTokensResponseCodes: () => NameTokensResponseCodes,
NameTokensResponseErrorCodes: () => NameTokensResponseErrorCodes,
OmnichainIndexingStatusIds: () => OmnichainIndexingStatusIds,
PROTOCOL_ATTRIBUTE_PREFIX: () => PROTOCOL_ATTRIBUTE_PREFIX,
PluginName: () => PluginName,
RECORDS_PER_PAGE_DEFAULT: () => RECORDS_PER_PAGE_DEFAULT,
RECORDS_PER_PAGE_MAX: () => RECORDS_PER_PAGE_MAX,
ROOT_NODE: () => ROOT_NODE,
ReferrerDetailResponseCodes: () => ReferrerDetailResponseCodes,
ReferrerLeaderboardPageResponseCodes: () => ReferrerLeaderboardPageResponseCodes,
RegistrarActionTypes: () => RegistrarActionTypes,
RegistrarActionsFilterTypes: () => RegistrarActionsFilterTypes,
RegistrarActionsOrders: () => RegistrarActionsOrders,
RegistrarActionsResponseCodes: () => RegistrarActionsResponseCodes,
ResolutionStatusIds: () => ResolutionStatusIds,
ReverseResolutionProtocolStep: () => ReverseResolutionProtocolStep,
SWRCache: () => SWRCache,
TheGraphCannotFallbackReasonSchema: () => TheGraphCannotFallbackReasonSchema,
TheGraphFallbackSchema: () => TheGraphFallbackSchema,
TraceableENSProtocol: () => TraceableENSProtocol,
TtlCache: () => TtlCache,
ZERO_ENCODED_REFERRER: () => ZERO_ENCODED_REFERRER,
accountIdEqual: () => accountIdEqual,
addDuration: () => addDuration,
addPrices: () => addPrices,
addrReverseLabel: () => addrReverseLabel,
asLowerCaseAddress: () => asLowerCaseAddress,
beautifyName: () => beautifyName,
bigIntToNumber: () => bigIntToNumber,
bigintToCoinType: () => bigintToCoinType,
buildAssetId: () => buildAssetId,
buildEnsRainbowClientLabelSet: () => buildEnsRainbowClientLabelSet,
buildLabelSetId: () => buildLabelSetId,
buildLabelSetVersion: () => buildLabelSetVersion,
buildPageContext: () => buildPageContext,
buildUnresolvedIdentity: () => buildUnresolvedIdentity,
checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotBackfill: () => checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotBackfill,
checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotCompleted: () => checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotCompleted,
checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotFollowing: () => checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotFollowing,
checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotUnstarted: () => checkChainIndexingStatusSnapshotsForOmnichainStatusSnapshotUnstarted,
coinTypeReverseLabel: () => coinTypeReverseLabel,
coinTypeToEvmChainId: () => coinTypeToEvmChainId,
createIndexingConfig: () => createIndexingConfig,
createRealtimeIndexingStatusProjection: () => createRealtimeIndexingStatusProjection,
decodeDNSEncodedLiteralName: () => decodeDNSEncodedLiteralName,
decodeDNSEncodedName: () => decodeDNSEncodedName,
decodeEncodedReferrer: () => decodeEncodedReferrer,
deserializeAssetId: () => deserializeAssetId,
deserializeBlockNumber: () => deserializeBlockNumber,
deserializeBlockRef: () => deserializeBlockRef,
deserializeBlockrange: () => deserializeBlockrange,
deserializeChainId: () => deserializeChainId,
deserializeChainIndexingStatusSnapshot: () => deserializeChainIndexingStatusSnapshot,
deserializeConfigResponse: () => deserializeConfigResponse,
deserializeCrossChainIndexingStatusSnapshot: () => deserializeCrossChainIndexingStatusSnapshot,
deserializeDatetime: () => deserializeDatetime,
deserializeDuration: () => deserializeDuration,
deserializeENSApiPublicConfig: () => deserializeENSApiPublicConfig,
deserializeENSIndexerPublicConfig: () => deserializeENSIndexerPublicConfig,
deserializeErrorResponse: () => deserializeErrorResponse,
deserializeIndexingStatusResponse: () => deserializeIndexingStatusResponse,
deserializeOmnichainIndexingStatusSnapshot: () => deserializeOmnichainIndexingStatusSnapshot,
deserializeRealtimeIndexingStatusProjection: () => deserializeRealtimeIndexingStatusProjection,
deserializeReferrerDetailResponse: () => deserializeReferrerDetailResponse,
deserializeReferrerLeaderboardPageResponse: () => deserializeReferrerLeaderboardPageResponse,
deserializeRegistrarActionsResponse: () => deserializeRegistrarActionsResponse,
deserializeUnixTimestamp: () => deserializeUnixTimestamp,
deserializeUrl: () => deserializeUrl,
deserializedNameTokensResponse: () => deserializedNameTokensResponse,
durationBetween: () => durationBetween,
encodeLabelHash: () => encodeLabelHash,
evmChainIdToCoinType: () => evmChainIdToCoinType,
formatAccountId: () => formatAccountId,
formatAssetId: () => formatAssetId,
formatNFTTransferEventMetadata: () => formatNFTTransferEventMetadata,
getBasenamesSubregistryId: () => getBasenamesSubregistryId,
getBasenamesSubregistryManagedName: () => getBasenamesSubregistryManagedName,
getCurrencyInfo: () => getCurrencyInfo,
getDatasourceContract: () => getDatasourceContract,
getENSRootChainId: () => import_datasources2.getENSRootChainId,
getEthnamesSubregistryId: () => getEthnamesSubregistryId,
getEthnamesSubregistryManagedName: () => getEthnamesSubregistryManagedName,
getLatestIndexedBlockRef: () => getLatestIndexedBlockRef,
getLineanamesSubregistryId: () => getLineanamesSubregistryId,
getLineanamesSubregistryManagedName: () => getLineanamesSubregistryManagedName,
getNFTTransferType: () => getNFTTransferType,
getNameHierarchy: () => getNameHierarchy,
getNameTokenOwnership: () => getNameTokenOwnership,
getNameWrapperAccounts: () => getNameWrapperAccounts,
getOmnichainIndexingCursor: () => getOmnichainIndexingCursor,
getOmnichainIndexingStatus: () => getOmnichainIndexingStatus,
getParentNameFQDN: () => getParentNameFQDN,
getResolvePrimaryNameChainIdParam: () => getResolvePrimaryNameChainIdParam,
getTimestampForHighestOmnichainKnownBlock: () => getTimestampForHighestOmnichainKnownBlock,
getTimestampForLowestOmnichainStartBlock: () => getTimestampForLowestOmnichainStartBlock,
hasNullByte: () => hasNullByte,
interpretedLabelsToInterpretedName: () => interpretedLabelsToInterpretedName,
isEncodedLabelHash: () => isEncodedLabelHash,
isHttpProtocol: () => isHttpProtocol,
isLabelHash: () => isLabelHash,
isNormalizedLabel: () => isNormalizedLabel,
isNormalizedName: () => isNormalizedName,
isPriceCurrencyEqual: () => isPriceCurrencyEqual,
isPriceEqual: () => isPriceEqual,
isRegistrarActionPricingAvailable: () => isRegistrarActionPricingAvailable,
isRegistrarActionReferralAvailable: () => isRegistrarActionReferralAvailable,
isResolvedIdentity: () => isResolvedIdentity,
isSelectionEmpty: () => isSelectionEmpty,
isSubgraphCompatible: () => isSubgraphCompatible,
isWebSocketProtocol: () => isWebSocketProtocol,
labelHashToBytes: () => labelHashToBytes,
labelhashLiteralLabel: () => labelhashLiteralLabel,
literalLabelToInterpretedLabel: () => literalLabelToInterpretedLabel,
literalLabelsToInterpretedName: () => literalLabelsToInterpretedName,
literalLabelsToLiteralName: () => literalLabelsToLiteralName,
makeENSApiPublicConfigSchema: () => makeENSApiPublicConfigSchema,
makeSubdomainNode: () => makeSubdomainNode,
maybeGetDatasourceContract: () => maybeGetDatasourceContract,
nameTokensPrerequisites: () => nameTokensPrerequisites,
parseAccountId: () => parseAccountId,
parseAssetId: () => parseAssetId,
parseNonNegativeInteger: () => parseNonNegativeInteger,
parseReverseName: () => parseReverseName,
priceDai: () => priceDai,
priceEth: () => priceEth,
priceUsdc: () => priceUsdc,
registrarActionsFilter: () => registrarActionsFilter,
registrarActionsPrerequisites: () => registrarActionsPrerequisites,
reverseName: () => reverseName,
serializeAssetId: () => serializeAssetId,
serializeChainId: () => serializeChainId,
serializeChainIndexingSnapshots: () => serializeChainIndexingSnapshots,
serializeConfigResponse: () => serializeConfigResponse,
serializeCrossChainIndexingStatusSnapshotOmnichain: () => serializeCrossChainIndexingStatusSnapshotOmnichain,
serializeDatetime: () => serializeDatetime,
serializeDomainAssetId: () => serializeDomainAssetId,
serializeENSApiPublicConfig: () => serializeENSApiPublicConfig,
serializeENSIndexerPublicConfig: () => serializeENSIndexerPublicConfig,
serializeIndexedChainIds: () => serializeIndexedChainIds,
serializeIndexingStatusResponse: () => serializeIndexingStatusResponse,
serializeNameToken: () => serializeNameToken,
serializeNameTokensResponse: () => serializeNameTokensResponse,
serializeNamedRegistrarAction: () => serializeNamedRegistrarAction,
serializeOmnichainIndexingStatusSnapshot: () => serializeOmnichainIndexingStatusSnapshot,
serializePrice: () => serializePrice,
serializePriceEth: () => serializePriceEth,
serializeRealtimeIndexingStatusProjection: () => serializeRealtimeIndexingStatusProjection,
serializeReferrerDetailResponse: () => serializeReferrerDetailResponse,
serializeReferrerLeaderboardPageResponse: () => serializeReferrerLeaderboardPageResponse,
serializeRegisteredNameTokens: () => serializeRegisteredNameTokens,
serializeRegistrarAction: () => serializeRegistrarAction,
serializeRegistrarActionPricing: () => serializeRegistrarActionPricing,
serializeRegistrarActionsResponse: () => serializeRegistrarActionsResponse,
serializeUrl: () => serializeUrl,
sortChainStatusesByStartBlockAsc: () => sortChainStatusesByStartBlockAsc,
stripNullBytes: () => stripNullBytes,
translateDefaultableChainIdToChainId: () => translateDefaultableChainIdToChainId,
uint256ToHex32: () => uint256ToHex32,
uniq: () => uniq,
validateSupportedLabelSetAndVersion: () => validateSupportedLabelSetAndVersion
});
module.exports = __toCommonJS(index_exports);
// src/ensapi/config/deserialize.ts
var import_v45 = require("zod/v4");
// src/ensapi/config/zod-schemas.ts
var import_v44 = require("zod/v4");
// src/ensindexer/config/zod-schemas.ts
var import_v43 = __toESM(require("zod/v4"), 1);
// src/shared/account-id.ts
var import_viem = require("viem");
var accountIdEqual = (a, b) => {
return a.chainId === b.chainId && (0, import_viem.isAddressEqual)(a.address, b.address);
};
// src/shared/address.ts
function asLowerCaseAddress(address) {
return address.toLowerCase();
}
// src/shared/cache/lru-cache.ts
var LruCache = class {
_cache = /* @__PURE__ */ new Map();
_capacity;
/**
* Create a new LRU cache with the given capacity.
*
* @param capacity The maximum number of items in the cache. If set to 0, the cache is effectively disabled.
* @throws Error if capacity is not a non-negative integer.
*/
constructor(capacity) {
if (!Number.isInteger(capacity)) {
throw new Error(
`LruCache requires capacity to be an integer but a capacity of ${capacity} was requested.`
);
}
if (capacity < 0) {
throw new Error(
`LruCache requires a non-negative capacity but a capacity of ${capacity} was requested.`
);
}
this._capacity = capacity;
}
set(key, value) {
this._cache.set(key, value);
if (this._cache.size > this._capacity) {
const oldestKey = this._cache.keys().next().value;
this._cache.delete(oldestKey);
}
}
get(key) {
const value = this._cache.get(key);
if (value) {
this._cache.delete(key);
this._cache.set(key, value);
}
return value;
}
clear() {
this._cache.clear();
}
get size() {
return this._cache.size;
}
get capacity() {
return this._capacity;
}
};
// src/shared/cache/swr-cache.ts
var import_date_fns = require("date-fns");
var import_getUnixTime = require("date-fns/getUnixTime");
// src/shared/deserialize.ts
var import_v42 = require("zod/v4");
// src/shared/zod-schemas.ts
var import_caip = require("caip");
var import_viem8 = require("viem");
var import_v4 = __toESM(require("zod/v4"), 1);
// src/ens/index.ts
var import_datasources2 = require("@ensnode/datasources");
// src/ens/coin-type.ts
var import_utils = require("@ensdomains/address-encoder/utils");
var ETH_COIN_TYPE = 60;
var DEFAULT_EVM_CHAIN_ID = 0;
var DEFAULT_EVM_COIN_TYPE = 2147483648;
var coinTypeToEvmChainId = (coinType) => {
if (coinType === ETH_COIN_TYPE) return 1;
return (0, import_utils.coinTypeToEvmChainId)(coinType);
};
var evmChainIdToCoinType = (chainId) => {
if (chainId === 1) return ETH_COIN_TYPE;
return (0, import_utils.evmChainIdToCoinType)(chainId);
};
var bigintToCoinType = (value) => {
if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`'${value}' cannot represent as CoinType, it is too large.`);
}
return Number(value);
};
// src/ens/constants.ts
var import_viem2 = require("viem");
var ROOT_NODE = (0, import_viem2.namehash)("");
var ETH_NODE = (0, import_viem2.namehash)("eth");
var BASENAMES_NODE = (0, import_viem2.namehash)("base.eth");
var LINEANAMES_NODE = (0, import_viem2.namehash)("linea.eth");
var ADDR_REVERSE_NODE = (0, import_viem2.namehash)("addr.reverse");
// src/ens/dns-encoded-name.ts
var import_viem3 = require("viem");
function decodeDNSEncodedLiteralName(packet) {
return decodeDNSEncodedName(packet);
}
function decodeDNSEncodedName(packet) {
const segments = [];
const bytes = (0, import_viem3.hexToBytes)(packet);
if (bytes.length === 0) throw new Error(`Packet is empty.`);
let offset = 0;
while (offset < bytes.length) {
const len = bytes[offset];
if (len === void 0) {
throw new Error(`Invariant: bytes[offset] is undefined after offset < bytes.length check.`);
}
if (len < 0 || len > 255) {
throw new Error(
`Invariant: this should be literally impossible, but an unsigned byte was less than zero or greater than 255. The value in question is ${len}`
);
}
if (len === 0) break;
const segment = (0, import_viem3.bytesToString)(bytes.subarray(offset + 1, offset + len + 1));
segments.push(segment);
offset += len + 1;
}
if (offset >= bytes.length) throw new Error(`Overflow, offset >= bytes.length`);
if (offset !== bytes.length - 1) throw new Error(`Junk at end of name`);
return segments;
}
// src/ens/labelhash.ts
var import_viem4 = require("viem");
function isLabelHash(maybeLabelHash) {
const expectedLength = maybeLabelHash.length === 66;
const expectedEncoding = (0, import_viem4.isHex)(maybeLabelHash);
const expectedCasing = maybeLabelHash === maybeLabelHash.toLowerCase();
return expectedLength && expectedEncoding && expectedCasing;
}
// src/ens/encode-labelhash.ts
var encodeLabelHash = (labelHash) => `[${labelHash.slice(2)}]`;
function isEncodedLabelHash(maybeEncodedLabelHash) {
const expectedFormatting = maybeEncodedLabelHash.startsWith("[") && maybeEncodedLabelHash.endsWith("]");
const includesLabelHash = isLabelHash(`0x${maybeEncodedLabelHash.slice(1, -1)}`);
return expectedFormatting && includesLabelHash;
}
// src/ens/is-normalized.ts
var import_ens = require("viem/ens");
function isNormalizedName(name) {
try {
return name === (0, import_ens.normalize)(name);
} catch {
return false;
}
}
function isNormalizedLabel(label) {
if (label === "") return false;
if (label.includes(".")) return false;
try {
return label === (0, import_ens.normalize)(label);
} catch {
return false;
}
}
// src/ens/names.ts
var import_ens_normalize = require("@adraffy/ens-normalize");
var ENS_ROOT = "";
var getNameHierarchy = (name) => name.split(".").map((_, i, labels) => labels.slice(i).join("."));
var getParentNameFQDN = (name) => {
if (name === ENS_ROOT) {
throw new Error("There is no parent name for ENS Root.");
}
const labels = name.split(".");
if (labels.length === 1) {
return ENS_ROOT;
}
return labels.slice(1).join(".");
};
var beautifyName = (name) => {
const beautifiedLabels = name.split(".").map((label) => {
if (isNormalizedLabel(label)) {
return (0, import_ens_normalize.ens_beautify)(label);
} else {
return label;
}
});
return beautifiedLabels.join(".");
};
// src/ens/parse-reverse-name.ts
var import_viem5 = require("viem");
var REVERSE_NAME_REGEX = /^([0-9a-fA-F]+)\.([0-9a-f]{1,64}|addr|default)\.reverse$/;
var parseAddressLabel = (addressLabel) => {
const maybeAddress = `0x${addressLabel}`;
if (!(0, import_viem5.isAddress)(maybeAddress)) {
throw new Error(`Invalid EVM address "${maybeAddress}"`);
}
return asLowerCaseAddress(maybeAddress);
};
var parseCoinTypeLabel = (coinTypeLabel) => {
if (coinTypeLabel === "default") return DEFAULT_EVM_COIN_TYPE;
if (coinTypeLabel === "addr") return ETH_COIN_TYPE;
return bigintToCoinType((0, import_viem5.hexToBigInt)(`0x${coinTypeLabel}`));
};
function parseReverseName(name) {
const match = name.match(REVERSE_NAME_REGEX);
if (!match) return null;
try {
const [, addressLabel, coinTypeLabel] = match;
if (!addressLabel) return null;
if (!coinTypeLabel) return null;
return {
address: parseAddressLabel(addressLabel),
coinType: parseCoinTypeLabel(coinTypeLabel)
};
} catch {
return null;
}
}
// src/ens/reverse-name.ts
var addrReverseLabel = (address) => address.slice(2);
var coinTypeReverseLabel = (coinType) => coinType.toString(16);
function reverseName(address, coinType) {
const label = addrReverseLabel(address);
const middle = (() => {
switch (coinType) {
case ETH_COIN_TYPE:
return "addr";
case DEFAULT_EVM_COIN_TYPE:
return "default";
default:
return coinTypeReverseLabel(coinType);
}
})();
return `${label}.${middle}.reverse`;
}
// src/ens/subname-helpers.ts
var import_viem6 = require("viem");
var makeSubdomainNode = (labelHash, node) => (0, import_viem6.keccak256)((0, import_viem6.concat)([node, labelHash]));
var uint256ToHex32 = (num) => (0, import_viem6.toHex)(num, { size: 32 });
// src/ens/types.ts
var import_datasources = require("@ensnode/datasources");
// src/shared/currencies.ts
var CurrencyIds = {
ETH: "ETH",
USDC: "USDC",
DAI: "DAI"
};
var currencyInfo = {
[CurrencyIds.ETH]: {
id: CurrencyIds.ETH,
name: "ETH",
decimals: 18
},
[CurrencyIds.USDC]: {
id: CurrencyIds.USDC,
name: "USDC",
decimals: 6
},
[CurrencyIds.DAI]: {
id: CurrencyIds.DAI,
name: "Dai Stablecoin",
decimals: 18
}
};
function getCurrencyInfo(currencyId) {
return currencyInfo[currencyId];
}
function priceEth(amount) {
return {
amount,
currency: CurrencyIds.ETH
};
}
function priceUsdc(amount) {
return {
amount,
currency: CurrencyIds.USDC
};
}
function priceDai(amount) {
return {
amount,
currency: CurrencyIds.DAI
};
}
function isPriceCurrencyEqual(priceA, priceB) {
return priceA.currency === priceB.currency;
}
function isPriceEqual(priceA, priceB) {
return isPriceCurrencyEqual(priceA, priceB) && priceA.amount === priceB.amount;
}
function addPrices(...prices) {
const firstPrice = prices[0];
const allPricesInSameCurrency = prices.every((price) => isPriceCurrencyEqual(firstPrice, price));
if (allPricesInSameCurrency === false) {
throw new Error("All prices must have the same currency to be added together.");
}
const { currency } = firstPrice;
return prices.reduce(
(acc, price) => ({
amount: acc.amount + price.amount,
currency
}),
{
amount: 0n,
currency: firstPrice.currency
}
);
}
// src/shared/reinterpretation.ts
var import_viem7 = require("viem");
function reinterpretLabel(label) {
if (label === "") {
throw new Error(
`Cannot reinterpret an empty label that violates the invariants of an InterpretedLabel.`
);
}
if (isEncodedLabelHash(label)) return label;
if (isNormalizedLabel(label)) return label;
return encodeLabelHash((0, import_viem7.labelhash)(label));
}
function reinterpretName(name) {
if (name === "") return name;
const interpretedLabels = name.split(".");
const reinterpretedLabels = interpretedLabels.map(reinterpretLabel);
const reinterpretedName = reinterpretedLabels.join(".");
return reinterpretedName;
}
// src/shared/zod-schemas.ts
var makeFiniteNonNegativeNumberSchema = (valueLabel = "Value") => import_v4.default.number({
// NOTE: Zod's implementation of `number` automatically rejects NaN and Infinity values.
// and therefore the finite check is implicit.
error: `${valueLabel} must be a finite number.`
}).nonnegative({
error: `${valueLabel} must be a non-negative number (>=0).`
});
var makeIntegerSchema = (valueLabel = "Value") => import_v4.default.int({
error: `${valueLabel} must be an integer.`
});
var makePositiveIntegerSchema = (valueLabel = "Value") => makeIntegerSchema(valueLabel).positive({
error: `${valueLabel} must be a positive integer (>0).`
});
var makeNonNegativeIntegerSchema = (valueLabel = "Value") => makeIntegerSchema(valueLabel).nonnegative({
error: `${valueLabel} must be a non-negative integer (>=0).`
});
var makeDurationSchema = (valueLabel = "Value") => import_v4.default.coerce.number({
error: `${valueLabel} must be a number.`
}).pipe(makeNonNegativeIntegerSchema(valueLabel));
var makeChainIdSchema = (valueLabel = "Chain ID") => makePositiveIntegerSchema(valueLabel).transform((val) => val);
var makeChainIdStringSchema = (valueLabel = "Chain ID String") => import_v4.default.string({ error: `${valueLabel} must be a string representing a chain ID.` }).pipe(import_v4.default.coerce.number({ error: `${valueLabel} must represent a positive integer (>0).` })).pipe(makeChainIdSchema(`The numeric value represented by ${valueLabel}`));
var makeLowercaseAddressSchema = (valueLabel = "EVM address") => import_v4.default.string().check((ctx) => {
if (!(0, import_viem8.isAddress)(ctx.value)) {
ctx.issues.push({
code: "custom",
message: `${valueLabel} must be a valid EVM address`,
input: ctx.value
});
}
}).transform((val) => asLowerCaseAddress(val));
var makeDatetimeSchema = (valueLabel = "Datetime string") => import_v4.default.iso.datetime({ error: `${valueLabel} must be a string in ISO 8601 format.` }).transform((v) => new Date(v));
var makeUnixTimestampSchema = (valueLabel = "Timestamp") => makeIntegerSchema(valueLabel);
var makeUrlSchema = (valueLabel = "Value") => import_v4.default.url({
error: `${valueLabel} must be a valid URL string (e.g., http://localhost:8080 or https://example.com).`,
abort: true
}).transform((v) => new URL(v));
var makeBlockNumberSchema = (valueLabel = "Block number") => makeNonNegativeIntegerSchema(valueLabel);
var makeBlockrangeSchema = (valueLabel = "Value") => import_v4.default.strictObject(
{
startBlock: makeBlockNumberSchema(`${valueLabel}.startBlock`).optional(),
endBlock: makeBlockNumberSchema(`${valueLabel}.endBlock`).optional()
},
{
error: `${valueLabel} must be a valid Blockrange object.`
}
).refine(
(v) => {
if (v.startBlock && v.endBlock) {
return v.startBlock <= v.endBlock;
}
return true;
},
{ error: `${valueLabel}: startBlock must be before or equal to endBlock` }
);
var makeBlockRefSchema = (valueLabel = "Value") => import_v4.default.strictObject(
{
timestamp: makeUnixTimestampSchema(`${valueLabel}.timestamp`),
number: makeBlockNumberSchema(`${valueLabel}.number`)
},
{
error: `${valueLabel} must be a valid BlockRef object.`
}
);
var makeENSNamespaceIdSchema = (valueLabel = "ENSNamespaceId") => import_v4.default.enum(import_datasources.ENSNamespaceIds, {
error() {
return `Invalid ${valueLabel}. Supported ENS namespace IDs are: ${Object.keys(import_datasources.ENSNamespaceIds).join(", ")}`;
}
});
var makePriceAmountSchema = (valueLabel = "Amount") => import_v4.default.coerce.bigint({
error: `${valueLabel} must represent a bigint.`
}).nonnegative({
error: `${valueLabel} must not be negative.`
});
var makePriceCurrencySchema = (currency, valueLabel = "Price Currency") => import_v4.default.strictObject({
amount: makePriceAmountSchema(`${valueLabel} amount`),
currency: import_v4.default.literal(currency, {
error: `${valueLabel} currency must be set to '${currency}'.`
})
});
var makePriceEthSchema = (valueLabel = "Price ETH") => makePriceCurrencySchema(CurrencyIds.ETH, valueLabel).transform((v) => v);
var makeAccountIdSchema = (valueLabel = "AccountId") => import_v4.default.strictObject({
chainId: makeChainIdSchema(`${valueLabel} chain ID`),
address: makeLowercaseAddressSchema(`${valueLabel} address`)
});
var makeAccountIdStringSchema = (valueLabel = "Account ID String") => import_v4.default.coerce.string().transform((v) => {
const result = new import_caip.AccountId(v);
return {
chainId: Number(result.chainId.reference),
address: result.address
};
}).pipe(makeAccountIdSchema(valueLabel));
var makeHexStringSchema = (options, valueLabel = "String representation of bytes array") => import_v4.default.string().check(function invariant_isHexEncoded(ctx) {
if (!(0, import_viem8.isHex)(ctx.value)) {
ctx.issues.push({
code: "custom",
input: ctx.value,
message: `${valueLabel} must be a hexadecimal value which starts with '0x'.`
});
}
}).transform((v) => v).check(function invariant_encodesRequiredBytesCount(ctx) {
const expectedBytesCount = options.bytesCount;
const actualBytesCount = (0, import_viem8.size)(ctx.value);
if (actualBytesCount !== expectedBytesCount) {
ctx.issues.push({
code: "custom",
input: ctx.value,
message: `${valueLabel} must represent exactly ${expectedBytesCount} bytes. Currently represented bytes count: ${actualBytesCount}.`
});
}
});
var makeNodeSchema = (valueLabel = "Node") => makeHexStringSchema({ bytesCount: 32 }, valueLabel);
var makeTransactionHashSchema = (valueLabel = "Transaction hash") => makeHexStringSchema({ bytesCount: 32 }, valueLabel);
var makeReinterpretedNameSchema = (valueLabel = "Reinterpreted Name") => import_v4.default.string().transform((v) => v).check((ctx) => {
try {
reinterpretName(ctx.value);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
ctx.issues.push({
code: "custom",
input: ctx.value,
message: `${valueLabel} cannot be reinterpreted: ${errorMessage}`
});
}
}).transform(reinterpretName);
// src/shared/deserialize.ts
function deserializeChainId(maybeChainId, valueLabel) {
const schema = makeChainIdStringSchema(valueLabel);
const parsed = schema.safeParse(maybeChainId);
if (parsed.error) {
throw new Error(`Cannot deserialize ChainId:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeDatetime(maybeDatetime, valueLabel) {
const schema = makeDatetimeSchema(valueLabel);
const parsed = schema.safeParse(maybeDatetime);
if (parsed.error) {
throw new Error(`Cannot deserialize Datetime:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeUnixTimestamp(maybeTimestamp, valueLabel) {
const schema = makeUnixTimestampSchema(valueLabel);
const parsed = schema.safeParse(maybeTimestamp);
if (parsed.error) {
throw new Error(`Cannot deserialize Unix Timestamp:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeUrl(maybeUrl, valueLabel) {
const schema = makeUrlSchema(valueLabel);
const parsed = schema.safeParse(maybeUrl);
if (parsed.error) {
throw new Error(`Cannot deserialize URL:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeBlockNumber(maybeBlockNumber, valueLabel) {
const schema = makeBlockNumberSchema(valueLabel);
const parsed = schema.safeParse(maybeBlockNumber);
if (parsed.error) {
throw new Error(`Cannot deserialize BlockNumber:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeBlockrange(maybeBlockrange, valueLabel) {
const schema = makeBlockrangeSchema(valueLabel);
const parsed = schema.safeParse(maybeBlockrange);
if (parsed.error) {
throw new Error(`Cannot deserialize Blockrange:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeBlockRef(maybeBlockRef, valueLabel) {
const schema = makeBlockRefSchema(valueLabel);
const parsed = schema.safeParse(maybeBlockRef);
if (parsed.error) {
throw new Error(`Cannot deserialize BlockRef:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function deserializeDuration(maybeDuration, valueLabel) {
const schema = makeDurationSchema(valueLabel);
const parsed = schema.safeParse(maybeDuration);
if (parsed.error) {
throw new RangeError(`Cannot deserialize Duration:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
function parseAccountId(maybeAccountId, valueLabel) {
const schema = makeAccountIdStringSchema(valueLabel);
const parsed = schema.safeParse(maybeAccountId);
if (parsed.error) {
throw new RangeError(`Cannot deserialize AccountId:
${(0, import_v42.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
// src/shared/datetime.ts
function durationBetween(start, end) {
return deserializeDuration(end - start, "Duration");
}
function addDuration(timestamp, duration) {
return deserializeUnixTimestamp(timestamp + duration, "UnixTimestamp");
}
// src/shared/cache/swr-cache.ts
var SWRCache = class {
constructor(options) {
this.options = options;
if (options.proactiveRevalidationInterval) {
this.backgroundInterval = setInterval(
() => this.revalidate(),
(0, import_date_fns.secondsToMilliseconds)(options.proactiveRevalidationInterval)
);
}
if (options.proactivelyInitialize) this.revalidate();
}
cache = null;
inProgressRevalidate = null;
backgroundInterval = null;
async revalidate() {
if (!this.inProgressRevalidate) {
this.inProgressRevalidate = this.options.fn().then((result) => {
this.cache = {
result,
updatedAt: (0, import_getUnixTime.getUnixTime)(/* @__PURE__ */ new Date())
};
}).catch((error) => {
if (!this.cache) {
this.cache = {
// ensure thrown value is always an Error instance
result: error instanceof Error ? error : new Error(String(error)),
updatedAt: (0, import_getUnixTime.getUnixTime)(/* @__PURE__ */ new Date())
};
}
}).finally(() => {
this.inProgressRevalidate = null;
});
}
return this.inProgressRevalidate;
}
/**
* Read the most recently cached result from the `SWRCache`.
*
* @returns a `ValueType` that was most recently successfully returned by `fn` or `Error` if `fn`
* has never successfully returned.
*/
async read() {
if (!this.cache) await this.revalidate();
if (!this.cache) throw new Error("never");
if (durationBetween(this.cache.updatedAt, (0, import_getUnixTime.getUnixTime)(/* @__PURE__ */ new Date())) > this.options.ttl) {
this.revalidate();
}
return this.cache.result;
}
/**
* Destroys the background revalidation interval, if exists.
*/
destroy() {
if (this.backgroundInterval) {
clearInterval(this.backgroundInterval);
this.backgroundInterval = null;
}
}
};
// src/shared/cache/ttl-cache.ts
var import_getUnixTime2 = require("date-fns/getUnixTime");
var TtlCache = class {
_cache = /* @__PURE__ */ new Map();
_ttl;
/**
* Create a new TTL cache with the given TTL.
*
* @param ttl Time-to-live duration in seconds. Items expire after this duration.
*/
constructor(ttl) {
this._ttl = ttl;
}
_cleanup() {
const now = (0, import_getUnixTime2.getUnixTime)(/* @__PURE__ */ new Date());
for (const [key, entry] of this._cache.entries()) {
if (entry.expiresAt <= now) {
this._cache.delete(key);
}
}
}
set(key, value) {
this._cleanup();
const expiresAt = addDuration((0, import_getUnixTime2.getUnixTime)(/* @__PURE__ */ new Date()), this._ttl);
this._cache.set(key, { value, expiresAt });
}
get(key) {
this._cleanup();
const entry = this._cache.get(key);
if (!entry) {
return void 0;
}
if (entry.expiresAt <= (0, import_getUnixTime2.getUnixTime)(/* @__PURE__ */ new Date())) {
this._cache.delete(key);
return void 0;
}
return entry.value;
}
clear() {
this._cache.clear();
}
get size() {
this._cleanup();
return this._cache.size;
}
get capacity() {
return Number.MAX_SAFE_INTEGER;
}
has(key) {
this._cleanup();
const entry = this._cache.get(key);
if (!entry) {
return false;
}
if (entry.expiresAt <= (0, import_getUnixTime2.getUnixTime)(/* @__PURE__ */ new Date())) {
this._cache.delete(key);
return false;
}
return true;
}
delete(key) {
return this._cache.delete(key);
}
};
// src/shared/collections.ts
var uniq = (arr) => [...new Set(arr)];
// src/shared/datasource-contract.ts
var import_datasources3 = require("@ensnode/datasources");
var maybeGetDatasourceContract = (namespaceId, datasourceName, contractName) => {
const datasource = (0, import_datasources3.maybeGetDatasource)(namespaceId, datasourceName);
if (!datasource) return void 0;
const address = datasource.contracts[contractName]?.address;
if (address === void 0 || Array.isArray(address)) return void 0;
return {
chainId: datasource.chain.id,
address
};
};
var getDatasourceContract = (namespaceId, datasourceName, contractName) => {
const contract = maybeGetDatasourceContract(namespaceId, datasourceName, contractName);
if (!contract) {
throw new Error(
`Expected contract not found for ${namespaceId} ${datasourceName} ${contractName}`
);
}
return contract;
};
// src/shared/labelhash.ts
var import_viem9 = require("viem");
var labelhashLiteralLabel = (label) => (0, import_viem9.keccak256)((0, import_viem9.stringToBytes)(label));
// src/shared/interpretation.ts
function literalLabelToInterpretedLabel(label) {
if (isNormalizedLabel(label)) return label;
return encodeLabelHash(labelhashLiteralLabel(label));
}
function literalLabelsToInterpretedName(labels) {
return labels.map(literalLabelToInterpretedLabel).join(".");
}
function interpretedLabelsToInterpretedName(labels) {
return labels.join(".");
}
function literalLabelsToLiteralName(labels) {
return labels.join(".");
}
// src/shared/null-bytes.ts
var hasNullByte = (value) => value.indexOf("\0") !== -1;
var stripNullBytes = (value) => value.replaceAll("\0", "");
// src/shared/numbers.ts
function bigIntToNumber(n) {
if (n < Number.MIN_SAFE_INTEGER) {
throw new Error(
`The bigint '${n.toString()}' value is too low to be to converted into a number.'`
);
}
if (n > Number.MAX_SAFE_INTEGER) {
throw new Error(
`The bigint '${n.toString()}' value is too high to be to converted into a number.'`
);
}
return Number(n);
}
// src/shared/serialize.ts
var import_caip2 = require("caip");
function serializeChainId(chainId) {
return chainId.toString();
}
function serializeDatetime(datetime) {
return datetime.toISOString();
}
function serializeUrl(url) {
return url.toString();
}
function serializePrice(price) {
return {
currency: price.currency,
amount: price.amount.toString()
};
}
function serializePriceEth(price) {
return serializePrice(price);
}
function formatAccountId(accountId) {
return import_caip2.AccountId.format({
chainId: { namespace: "eip155", reference: accountId.chainId.toString() },
address: accountId.address
}).toLowerCase();
}
// src/shared/url.ts
function isHttpProtocol(url) {
return ["http:", "https:"].includes(url.protocol);
}
function isWebSocketProtocol(url) {
return ["ws:", "wss:"].includes(url.protocol);
}
// src/ensindexer/config/is-subgraph-compatible.ts
var import_datasources4 = require("@ensnode/datasources");
// src/ensindexer/config/types.ts
var PluginName = /* @__PURE__ */ ((PluginName2) => {
PluginName2["Subgraph"] = "subgraph";
PluginName2["Basenames"] = "basenames";
PluginName2["Lineanames"] = "lineanames";
PluginName2["ThreeDNS"] = "threedns";
PluginName2["ProtocolAcceleration"] = "protocol-acceleration";
PluginName2["Registrars"] = "registrars";
PluginName2["TokenScope"] = "tokenscope";
return PluginName2;
})(PluginName || {});
// src/ensindexer/config/is-subgraph-compatible.ts
function isSubgraphCompatible(config) {
const onlySubgraphPluginActivated = config.plugins.length === 1 && config.plugins[0] === "subgraph" /* Subgraph */;
const isSubgraphLabelSet = config.labelSet.labelSetId === "subgraph" && config.labelSet.labelSetVersion === 0;
const isEnsTestEnvLabelSet = config.labelSet.labelSetId === "ens-test-env" && config.labelSet.labelSetVersion === 0;
const labelSetIsSubgraphCompatible = isSubgraphLabelSet || config.namespace === import_datasources4.ENSNamespaceIds.EnsTestEnv && isEnsTestEnvLabelSet;
return onlySubgraphPluginActivated && labelSetIsSubgraphCompatible;
}
// src/ensindexer/config/validations.ts
function invariant_ensDbVersionIsSameAsEnsIndexerVersion(ctx) {
const versionInfo = ctx.value;
if (versionInfo.ensDb !== versionInfo.ensIndexer) {
ctx.issues.push({
code: "custom",
input: versionInfo,
message: "`ensDb` version must be same as `ensIndexer` version"
});
}
}
// src/ensindexer/config/zod-schemas.ts
var makeIndexedChainIdsSchema = (valueLabel = "Indexed Chain IDs") => import_v43.default.array(makeChainIdSchema(valueLabel), {
error: `${valueLabel} must be an array.`
}).min(1, { error: `${valueLabel} list must include at least one element.` }).transform((v) => new Set(v));
var makePluginsListSchema = (valueLabel = "Plugins") => import_v43.default.array(import_v43.default.string(), {
error: `${valueLabel} must be a list of strings.`
}).min(1, {
error: `${valueLabel} must be a list of strings with at least one string value`
}).refine((arr) => arr.length === uniq(arr).length, {
error: `${valueLabel} cannot contain duplicate values.`
});
var makeDatabaseSchemaNameSchema = (valueLabel = "Database schema name") => import_v43.default.string({ error: `${valueLabel} must be a string` }).trim().nonempty({
error: `${valueLabel} is required and must be a non-empty string.`
});
var makeLabelSetIdSchema = (valueLabel) => {
return import_v43.default.string({ error: `${valueLabel} must be a string` }).min(1, { error: `${valueLabel} must be 1-50 characters long` }).max(50, { error: `${valueLabel} must be 1-50 characters long` }).regex(/^[a-z-]+$/, {
error: `${valueLabel} can only contain lowercase letters (a-z) and hyphens (-)`
});
};
var makeLabelSetVersionSchema = (valueLabel) => {
return import_v43.default.coerce.number({ error: `${valueLabel} must be an integer.` }).pipe(makeNonNegativeIntegerSchema(valueLabel));
};
var makeFullyPinnedLabelSetSchema = (valueLabel = "Label set") => {
let valueLabelLabelSetId = valueLabel;
let valueLabelLabelSetVersion = valueLabel;
if (valueLabel === "LABEL_SET") {
valueLabelLabelSetId = "LABEL_SET_ID";
valueLabelLabelSetVersion = "LABEL_SET_VERSION";
} else {
valueLabelLabelSetId = `${valueLabel}.labelSetId`;
valueLabelLabelSetVersion = `${valueLabel}.labelSetVersion`;
}
return import_v43.default.object({
labelSetId: makeLabelSetIdSchema(valueLabelLabelSetId),
labelSetVersion: makeLabelSetVersionSchema(valueLabelLabelSetVersion)
});
};
var makeNonEmptyStringSchema = (valueLabel = "Value") => import_v43.default.string().nonempty({ error: `${valueLabel} must be a non-empty string.` });
var makeENSIndexerVersionInfoSchema = (valueLabel = "Value") => import_v43.default.strictObject(
{
nodejs: makeNonEmptyStringSchema(),
ponder: makeNonEmptyStringSchema(),
ensDb: makeNonEmptyStringSchema(),
ensIndexer: makeNonEmptyStringSchema(),
ensNormalize: makeNonEmptyStringSchema(),
ensRainbow: makeNonEmptyStringSchema(),
ensRainbowSchema: makePositiveIntegerSchema()
},
{
error: `${valueLabel} must be a valid ENSIndexerVersionInfo object.`
}
).check(invariant_ensDbVersionIsSameAsEnsIndexerVersion);
function invariant_isSubgraphCompatibleRequirements(ctx) {
const { value: config } = ctx;
if (config.isSubgraphCompatible && !isSubgraphCompatible(config)) {
ctx.issues.push({
code: "custom",
input: config,
message: `'isSubgraphCompatible' requires only the '${"subgraph" /* Subgraph */}' plugin to be active and labelSet must be {labelSetId: "subgraph", labelSetVersion: 0}`
});
}
}
var makeENSIndexerPublicConfigSchema = (valueLabel = "ENSIndexerPublicConfig") => import_v43.default.object({
labelSet: makeFullyPinnedLabelSetSchema(`${valueLabel}.labelSet`),
indexedChainIds: makeIndexedChainIdsSchema(`${valueLabel}.indexedChainIds`),
isSubgraphCompatible: import_v43.default.boolean({ error: `${valueLabel}.isSubgraphCompatible` }),
namespace: makeENSNamespaceIdSchema(`${valueLabel}.namespace`),
plugins: makePluginsListSchema(`${valueLabel}.plugins`),
databaseSchemaName: makeDatabaseSchemaNameSchema(`${valueLabel}.databaseSchemaName`),
versionInfo: makeENSIndexerVersionInfoSchema(`${valueLabel}.versionInfo`)
}).check(invariant_isSubgraphCompatibleRequirements);
// src/ensapi/config/zod-schemas.ts
var TheGraphCannotFallbackReasonSchema = import_v44.z.enum({
NotSubgraphCompatible: "not-subgraph-compatible",
NoApiKey: "no-api-key",
NoSubgraphUrl: "no-subgraph-url"
});
var TheGraphFallbackSchema = import_v44.z.strictObject({
canFallback: import_v44.z.boolean(),
reason: TheGraphCannotFallbackReasonSchema.nullable()
});
function makeENSApiPublicConfigSchema(valueLabel) {
const label = valueLabel ?? "ENSApiPublicConfig";
return import_v44.z.strictObject({
version: import_v44.z.string().min(1, `${label}.version must be a non-empty string`),
theGraphFallback: TheGraphFallbackSchema,
ensIndexerPublicConfig: makeENSIndexerPublicConfigSchema(`${label}.ensIndexerPublicConfig`)
});
}
// src/ensapi/config/deserialize.ts
function deserializeENSApiPublicConfig(maybeConfig, valueLabel) {
const schema = makeENSApiPublicConfigSchema(valueLabel);
try {
return schema.parse(maybeConfig);
} catch (error) {
if (error instanceof import_v45.ZodError) {
throw new Error(`Cannot deserialize ENSApiPublicConfig:
${(0, import_v45.prettifyError)(error)}
`);
}
throw error;
}
}
// src/ensindexer/config/deserialize.ts
var import_v46 = require("zod/v4");
function deserializeENSIndexerPublicConfig(maybeConfig, valueLabel) {
const schema = makeENSIndexerPublicConfigSchema(valueLabel);
const parsed = schema.safeParse(maybeConfig);
if (parsed.error) {
throw new Error(`Cannot deserialize ENSIndexerPublicConfig:
${(0, import_v46.prettifyError)(parsed.error)}
`);
}
return parsed.data;
}
// src/ensindexer/config/label-utils.ts
var import_viem10 = require("viem");
function labelHashToBytes(labelHash) {
try {
if (labelHash.length !== 66) {
throw new Error(`Invalid labelHash length ${labelHash.length} characters (expected 66)`);
}
if (labelHash !== labelHash.toLowerCase()) {
throw new Error("Labelhash must be in lowercase");
}
if (!labelHash.startsWith("0x")) {
throw new Error("Labelhash must be 0x-prefixed");
}
const bytes = (0, import_viem10.hexToBytes)(labelHash);
if (bytes.length !== 32) {
throw new Error(`Invalid labelHash length ${bytes.length} bytes (expected 32)`);
}
return bytes;
} catch (e) {
if (e instanceof Error) {
throw e;
}
throw new Error("Invalid hex format");
}
}
// src/ensindexer/config/labelset-utils.ts
function buildLabelSetId(maybeLabelSetId) {
return makeLabelSetIdSchema("LabelSetId").parse(maybeLabelSetId);
}
function buildLabelSetVersion(maybeLabelSetVersion) {
return makeLabelSetVersionSchema("LabelSetVersion").parse(maybeLabelSetVersion);
}
function buildEnsRainbowClientLabelSet(labelSetId, labelSetVersion) {
if (labelSetVersion !== void 0 && labelSetId === void 0) {
throw new Error("When a labelSetVersion is defined, labelSetId must also be defined.");
}
return { labelSetId, labelSetVersion };
}
function validateSupportedLabelSetAndVersion(serverSet, clientSet) {
if (clientSet.labelSetId === void 0) {
return;
}
if (serverSet.labelSetId !== clientSet.labelSetId) {
throw new Error(
`Server label set ID "${serverSet.labelSetId}" does not match client's requested label set ID "${clientSet.labelSetId}".`
);
}
if (clientSet.labelSetVersion !== void 0 && serverSet.highestLabelSetVersion < clientSet.labelSetVersion) {
throw new Error(
`Server highest label set version ${serverSet.highestLabelSetVersion} is less than client's requested version ${clientSet.labelSetVersion} for label set ID "${clientSet.labelSetId}".`
);
}
}
// src/ensindexer/config/parsing.ts
function parseNonNegativeInteger(maybeNumber) {
const trimmed = maybeNumber.trim();
if (!trimmed) {
throw new Error("Input cannot be empty");
}
if (trimmed === "-0") {
throw new Error("Negative zero is not a valid non-negative integer");
}
const num = Number(maybeNumber);
if (Number.isNaN(num)) {
throw new Error(`"${maybeNumber}" is not a valid number`);
}
if (!Number.isFinite(num)) {
throw new Error(`"${maybeNumber}" is not a finite number`);
}
if (!Number.isInteger(num)) {
throw new Error(`"${maybeNumber}" is not an integer`);
}
if (num < 0) {
throw new Error(`"${maybeNumber}" is not a non-negative integer`);
}
return num;
}
// src/ensindexer/config/serialize.ts
function serializeIndexedChainIds(indexedChainIds) {
return Array.from(indexedChainIds);
}
function serializeENSIndexerPublicConfig(config) {
const {
labelSet,
indexedChainIds,
databaseSchemaName,
isSubgraphCompatible: isSubgraphCompatible2,
namespace,
plugins,
versionInfo
} = config;
return {
labelSet,
indexedChainIds: serializeIndexedChainIds(indexedChainIds),
databaseSchemaName,
isSubgraphCompatible: isSubgraphCompatible2,
namespace,
plugins,
versionInfo
};
}
// src/ensindexer/indexing-status/deserialize.ts
var import_v48 = require("zod/v4");
// src/ensindexer/indexing-status/zod-schemas.ts
var import_v47 = __toESM(require("zod/v4"), 1);
// src/ensindexer/indexing-status/types.ts
var ChainIndexingConfigTypeIds = {
/**
* Represents that indexing of the chain should be performed for an indefinite range.
*/
Indefinite: "indefinite",
/**
* Represents that indexing of the chain should be performed for a definite range.
*/
Definite: "definite"
};
var ChainIndexingStatusIds = {
/**
* Represents that indexing of the chain is not ready to begin yet because:
* - ENSIndexer is in its initialization phase and the data to build a
* "true" {@link ChainIndexingSnapshot} for the chain is still being loaded; or
* - ENSIndexer is using an omnichain indexing strategy and the
* `omnichainIndexingCursor` is <= `config.startBlock.timestamp` for the chain's
* {@link ChainIndexingSnapshot}.
*/
Queued: "chain-queued",
/**
* Represents that indexing of the chain is in progress and under a special
* "backfill" phase that optimizes for accelerate