import pino from 'pino'; import { EventEmitter } from 'eventemitter3'; import { Transform, TransformCallback } from 'stream'; import crypto, { webcrypto } from 'crypto'; export { randomBytes } from '@noble/post-quantum/utils'; declare class Cache { private value?; private valueTimestamp?; private readonly valueFactory; private readonly maxAgeInMilliseconds; constructor(valueFactory: () => Promise, maxAgeInMilliseconds: number); get(): Promise; invalidate(): void; } /** * Given an iterable of promises, settles them one at a time. * If all of them resolve, returns the list of values. * If one of them rejects, provides a callback for reverting the * preceding (already resolved) values. */ declare function pTransaction(promises: Iterable>, rollback: (target: T) => Promise | void): Promise; declare class AbortError extends Error { readonly code = "AbortError"; constructor(customErrorContext?: string); } /** * Wraps a Promise into one that can be aborted with `AbortSignal`. * Aborting causes the returned Promise to reject with `AbortError` unless * the underlying promise itself has already resolved or rejected. * * Notice that it is the user's responsibility to implement any custom cleanup * logic in a `finally` or `catch` block in case of resources that need to be * freed up. */ declare function asAbortable(promise: Promise, abortSignal?: AbortSignal, customErrorContext?: string): Promise; /** * setTimeout with AbortSignal support. Aborting will simply clear * the timeout silently. */ declare const setAbortableTimeout: (cb: () => void, ms: number, abortSignal: AbortSignal) => void; /** * setInterval with AbortSignal support. Aborting will simply clear * the interval silently. */ declare const setAbortableInterval: (cb: () => void, ms: number, abortSignal: AbortSignal) => void; type ResolveFn = (value: T | PromiseLike) => void; type RejectFn = (reason?: unknown) => void; /** * Deferred promise allowing external control of resolve / reject. */ declare class Defer extends Promise { private readonly resolveFn; private readonly rejectFn; private readonly ensureNoopCatchAttached; private settled; constructor(executor?: (resolve: ResolveFn, reject: RejectFn) => void); resolve(value: T): void; reject(error: unknown): void; wrap(fn: (...args: ArgsType) => T | PromiseLike): (...args: ArgsType) => Promise; } type BrandedString = string & { __brand: T; }; type Events = { [K in keyof T]: (payload: any) => void; }; type ChangeFieldType = Omit & Record; type MapKey = string | number | boolean | symbol | bigint | object; type ENSName = BrandedString<'ENSName'>; declare function toENSName(str: string): ENSName | never; type EthereumAddress = BrandedString<'EthereumAddress'>; declare function toEthereumAddress(str: string): EthereumAddress | never; declare function isENSName(domain: EthereumAddress | ENSName): domain is ENSName; /** * Computes a deterministic index for a given string or number key. * Used for deterministically selecting an entry from an ordered list * for various load balancing and partitioning purposes. * * @param lengthOfArray Number of items to select from * @param key Input string or number * @returns Array index between [0..lengthOfArray-1] */ declare function keyToArrayIndex(lengthOfArray: number, key: string | number): number; type LogLevel = 'silent' | 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; type LoggerModule = string | { id: string; }; declare class Logger { static NAME_LENGTH: number; private static rootLogger; private static getRootLogger; private readonly logger; fatal: (msg: string, metadata?: Record) => void; error: (msg: string, metadata?: Record) => void; warn: (msg: string, metadata?: Record) => void; info: (msg: string, metadata?: Record) => void; debug: (msg: string, metadata?: Record) => void; trace: (msg: string, metadata?: Record) => void; constructor(loggerModule: LoggerModule, contextBindings?: Record, defaultLogLevel?: LogLevel, parentLogger?: pino.Logger); static createName(loggerModule: LoggerModule): string; } type MetricsDefinition = Record; declare class Metric { private latestValue; private readonly eventEmitter; private readonly samplerFactory; record(value: number): void; getLatestValue(): number | undefined; } declare class CountMetric extends Metric { constructor(); } declare class LevelMetric extends Metric { constructor(initialValue?: number); } declare class RateMetric extends Metric { constructor(); } type MetricsReport = { period: { start: number; end: number; }; } & Record; declare class MetricsContext { private readonly metrics; addMetrics(namespace: string, definitions: MetricsDefinition): void; createReportProducer(onReport: (report: MetricsReport) => void, interval: number, abortSignal: AbortSignal, formatNumber?: (value: number) => string): void; getMetric(id: string): Metric | undefined; } /** * Generic multimap: a key which maps to multiple valuess. * The values is an array * -> when we query the data, we get it back in the same order * -> an array may contain duplicates, if same value is added multiple times * (we could implement a Multiset class if we need a different kind of duplication handling) **/ declare class Multimap { private readonly delegatee; get(key: K): V[]; has(key: K, value: V): boolean; add(key: K, value: V): void; addAll(key: K, values: V[]): void; remove(key: K, value: V): void; removeAll(key: K, values: V[]): void; keys(): Generator; values(): Generator; getKeyCount(): number; isEmpty(): boolean; } declare function randomString(length: number, charset?: string): string; declare const scheduleAtFixedRate: (task: (now: number) => Promise, interval: number, abortSignal: AbortSignal) => void; declare const scheduleAtInterval: (task: () => Promise, interval: number, executeAtStart: boolean, abortSignal: AbortSignal) => Promise; /** * @param {number} approximateIntervalInMs - approximate time (in milliseconds) to wait after a task is completed * @param {number} driftMultiplier how much the wait time can vary: e.g. if the interval is 60 minutes and the drift is 0.1, * the delay between invocations will range from 54 to 66 minutes */ declare const scheduleAtApproximateInterval: (task: () => Promise, approximateIntervalInMs: number, driftMultiplier: number, executeAtStart: boolean, abortSignal: AbortSignal) => Promise; declare function toEthereumAddressOrENSName(str: string): EthereumAddress | ENSName | never; /** * Wait for a specific time * @param ms time to wait for in milliseconds * @param abortSignal to control abortion of any wait * @returns {Promise} resolves when time has passed */ declare function wait(ms: number, abortSignal?: AbortSignal): Promise; /** * Wait for an event to be emitted on emitter within timeout. * * @param emitter emitter of event * @param eventName event to wait for * @param timeout amount of time in milliseconds to wait for * @param predicate function that gets passed the event arguments, should return true if event accepted * @param abortSignal * @returns {Promise>} resolves with event arguments if event occurred within timeout else rejects */ declare function waitForEvent void>, TEventName extends keyof TEvents>(emitter: { on: (eventName: TEventName, listener: TEvents[TEventName]) => unknown; off: (eventName: TEventName, listener: TEvents[TEventName]) => unknown; }, eventName: TEventName, timeout?: number, predicate?: (...eventArgs: Parameters) => boolean, abortSignal?: AbortSignal): Promise>; declare function raceForEvent void>, TEventName extends keyof TEvents>(emitter: { on: (eventName: TEventName, listener: TEvents[TEventName]) => unknown; off: (eventName: TEventName, listener: TEvents[TEventName]) => unknown; }, eventNames: TEventName[], timeout?: number): Promise<{ winnerName: TEventName; winnerArgs: Parameters; }>; declare class TimeoutError extends Error { readonly code = "TimeoutError"; constructor(timeoutInMs: number, customErrorContext?: string); } declare const withTimeout: (task: Promise, timeoutInMs: number, customErrorContext?: string, abortSignal?: AbortSignal) => Promise; type ComposedAbortSignal = AbortSignal & { destroy: () => void; }; /** * Compose a single AbortSignal from multiple AbortSignals with "OR" logic. * * WARNING: be aware of a potential memory leak that can occur if the composed * AbortSignal is never destroyed. This can happen if an instance of AbortSignal * is composed over and over with this utility but the composed AbortSignal (or * the other passed AbortSignal(s)) never abort. In this situation the * aforementioned instance of AbortSignal will have more and more listeners added * but never cleaned. */ declare function composeAbortSignals(...signals: (AbortSignal | undefined)[]): ComposedAbortSignal; /** * Wait for a condition to become true by re-evaluating `conditionFn` every `retryInterval` milliseconds. * * @param conditionFn condition to be evaluated; should return boolean or Promise and have * no side effects. * @param timeout amount of time in milliseconds to wait for * @param retryInterval how often, in milliseconds, to re-evaluate condition * @param abortSignal pass an abort signal to cancel prematurely * @param onTimeoutContext evaluated only on timeout. Used to associate human-friendly textual context to error. * @returns {Promise} resolves immediately if * conditionFn evaluates to true on a retry attempt within timeout. If timeout * is reached with conditionFn never evaluating to true, rejects. */ declare const until: (conditionFn: () => (boolean | Promise), timeout?: number, retryInterval?: number, abortSignal?: AbortSignal, onTimeoutContext?: () => string) => Promise; /** * Wraps a rate limiter around a function that ensures the function is invoked max once per `intervalInMs`. */ declare function withRateLimit(fn: () => Promise, intervalInMs: number): () => Promise; interface ObserverEvents> { addEventListener: (eventName: keyof E) => void; removeEventListener: (eventName: keyof E) => void; } declare class ObservableEventEmitter> { private delegate; private observer; on(eventName: T, listener: E[T]): void; once(eventName: T, listener: E[T]): void; off(eventName: T, listener: E[T]): void; removeAllListeners(): void; emit(eventName: T, payload: Parameters[0]): void; getListenerCount(eventName: T): number; getObserver(): EventEmitter>; } declare const initEventGateway: , T extends keyof E, P>(eventName: T, start: (emit: (payload: Parameters[0]) => void) => P, stop: (listener: P) => void, emitter: ObservableEventEmitter) => void; declare const addManagedEventListener: void>(emitter: { on: (eventName: TEventName, listener: TListener) => unknown; off: (eventName: TEventName, listener: TListener) => unknown; }, eventName: TEventName, listener: TListener, abortSignal: AbortSignal) => void; declare const merge: (...sources: (Partial | undefined)[]) => TTarget; declare const collect: (source: AsyncIterable, maxCount?: number) => Promise; declare class Gate { private pending?; constructor(isOpen: boolean); open(): void; close(): void; isOpen(): boolean; private clearPending; waitUntilOpen(): Promise; } interface GraphQLQuery { query: string; variables?: Record; } /** * Query one entity with queryEntity method, and a list of entitities with queryEntities method. * The queryEntities method does pagination automatically. * * If we want to ensure that The Graph index is up-to-date, we can call the updateRequiredBlockNumber() * method. In that case a queryEntity()/queryEntities() waits until The Graph has been indexed at least * to that block number. If the indexing takes longer than opts.indexTimeout, the query call rejects * with a TimeoutError. */ declare class TheGraphClient { private requiredBlockNumber; private readonly indexingState; private readonly serverUrl; private readonly fetch; private readonly logger; constructor(opts: { serverUrl: string; fetch: (url: string, init?: Record) => Promise; logger?: Logger; indexTimeout?: number; indexPollInterval?: number; }); queryEntity(query: GraphQLQuery): Promise; queryEntities(createQuery: (lastId: string, pageSize: number, requiredBlockNumber: number) => GraphQLQuery, parseItems?: ((response: any) => T[]), pageSize?: number): AsyncGenerator; updateRequiredBlockNumber(blockNumber: number): void; private sendQuery; private getIndexBlockNumber; } declare class Heap { private readonly items; private readonly compare; constructor(compare: (item1: T, item2: T) => number); push(item: T): void; pop(): T | undefined; peek(): T | undefined; contains(item: T): boolean; isEmpty(): boolean; values(): T[]; private getItemIndex; } /** * Execute a promise that should never reject. If it does, log the error and exit the process * (in Node/Electron) or throw an unhandled error (in browsers). * To be used in places where we want to "annotate" that the intention of a promise is never * to reject (unless something is really wrong). */ declare const executeSafePromise: (createPromise: () => Promise) => Promise; declare const binaryToUtf8: (bytes: Uint8Array) => string; declare const utf8ToBinary: (utf8: string) => Uint8Array; declare const binaryToHex: (bytes: Uint8Array, addPrefix?: boolean) => string; declare const hexToBinary: (hex: string) => Uint8Array; declare const areEqualBinaries: (arr1: Uint8Array, arr2: Uint8Array) => boolean; declare function filePathToNodeFormat(filePath: string): string; declare const retry: (task: () => Promise, onRetryableFailure: (message: string, error: any) => void, description: string, maxCount: number, delay: number) => Promise; /** * Utilities to deal with length-prefixed frames, i.e. | length [4 bytes] | payload [variable bytes] | */ declare const toLengthPrefixedFrame: (payload: Uint8Array) => Buffer; declare class LengthPrefixedFrameDecoder extends Transform { private buffer; constructor(); _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void; _flush(callback: TransformCallback): void; private processStreamData; } declare const ipv4ToNumber: (ip: string) => number; declare const numberToIpv4: (value: number) => string; declare class MapWithTtl { private readonly delegate; private readonly getTtl; constructor(getTtl: (value: V) => number); set(key: K, value: V): void; get(key: K): V | undefined; has(key: K): boolean; delete(key: K): void; clear(): void; size(): number; values(): IterableIterator; forEach(cb: (value: V, key: K) => void): void; private createTimeout; } type StreamID = BrandedString<'StreamID'>; /** * Create an instance of `StreamID` from a given string stream id or path. * * Supported formats: * - full stream id format, e.g., '0x0000000000000000000000000000000000000000/foo/bar' or 'name.eth/foo/bar' * - path-only format, e.g. , '/foo/bar' * - legacy format, e.g., '7wa7APtlTq6EC5iTCBy6dw' * * If `streamIdOrPath` is not in path-only format, `domain` can be left undefined. */ declare function toStreamID(streamIdOrPath: string, domain?: EthereumAddress | ENSName): StreamID | never; declare class StreamIDUtils { static isPathOnlyFormat(streamIdOrPath: string): boolean; static getDomain(streamId: StreamID): EthereumAddress | ENSName | undefined; static getPath(streamId: StreamID): string | undefined; static getDomainAndPath(streamId: StreamID): [EthereumAddress | ENSName, string] | undefined; } declare const DEFAULT_PARTITION_COUNT = 1; declare const MAX_PARTITION_COUNT = 100; declare function ensureValidStreamPartitionIndex(streamPartition: number | undefined): void | never; declare function ensureValidStreamPartitionCount(streamPartition: number | undefined): void | never; type StreamPartID = BrandedString<'StreamPartID'>; declare function toStreamPartID(streamId: StreamID, streamPartition: number): StreamPartID | never; declare class StreamPartIDUtils { static parse(streamPartIdAsStr: string): StreamPartID | never; static getStreamID(streamPartId: StreamPartID): StreamID; static getStreamPartition(streamPartId: StreamPartID): number; static getStreamIDAndPartition(streamPartId: StreamPartID): [StreamID, number]; static parseRawElements(str: string): [string, number | undefined]; } type UserID = BrandedString<'UserID'>; type UserIDRaw = Uint8Array; declare const toUserId: (input: string | UserIDRaw) => UserID | never; declare const toUserIdRaw: (userId: UserID) => UserIDRaw; declare const isValidUserId: (input: string) => boolean; declare const isEthereumAddressUserId: (userId: UserID) => boolean; type HexString = string; type WeiAmount = bigint; declare const multiplyWeiAmount: (val1: WeiAmount, val2: number) => WeiAmount; declare function getSubtle(): crypto.webcrypto.SubtleCrypto; type Jwk = webcrypto.JsonWebKey; type CryptoKey = webcrypto.CryptoKey; declare function computeMd5(input: string): Buffer; declare function computeSha1(input: string): Buffer; declare function createCipheriv(algorithm: string, key: Buffer | Uint8Array, iv: Buffer | Uint8Array | null): crypto.Cipheriv; declare function createDecipheriv(algorithm: string, key: Buffer | Uint8Array, iv: Buffer | Uint8Array | null): crypto.Decipheriv; declare function publicEncrypt(publicKey: string, buffer: Buffer | Uint8Array): Buffer; declare function privateDecrypt(privateKey: string, buffer: Buffer | Uint8Array): Buffer; declare const KEY_TYPES: readonly ["ECDSA_SECP256K1_EVM", "ECDSA_SECP256R1", "ML_DSA_87"]; type KeyType = typeof KEY_TYPES[number]; interface KeyPair { publicKey: Uint8Array; privateKey: Uint8Array; } declare abstract class SigningUtil { abstract generateKeyPair(): KeyPair; abstract createSignature(payload: Uint8Array, privateKey: Uint8Array): Promise; abstract verifySignature(publicKey: UserIDRaw, payload: Uint8Array, signature: Uint8Array): Promise; abstract assertValidKeyPair(publicKey: UserIDRaw, privateKey: Uint8Array): void; static getInstance(type: KeyType): SigningUtil; } /** * EVM compatible ECDSA signing scheme using keccak hash, magic bytes, and secp256k1 curve. */ declare class EcdsaSecp256k1Evm extends SigningUtil { generateKeyPair(): KeyPair; keccakHash(message: Uint8Array, useEthereumMagic?: boolean): Buffer; private recoverPublicKey; createSignature(payload: Uint8Array, privateKey: Uint8Array): Promise; publicKeyToAddress(publicKey: Uint8Array): Uint8Array; recoverSignerUserId(signature: Uint8Array, payload: Uint8Array): UserIDRaw; verifySignature(expectedUserId: UserIDRaw, payload: Uint8Array, signature: Uint8Array): Promise; assertValidKeyPair(address: UserIDRaw, privateKey: Uint8Array): void; } /** * Signing scheme using ECDSA with secp256r1 curve and SHA-256, natively supported by browsers */ declare class EcdsaSecp256r1 extends SigningUtil { generateKeyPair(compressPublicKey?: boolean): KeyPair; private isCompressedPublicKey; private isUncompressedPublicKey; private toBase64Url; getPublicKeyFromPrivateKey(privateKey: Uint8Array, compressed?: boolean): Uint8Array; getUncompressedPublicKey(publicKey: Uint8Array): Uint8Array; privateKeyToJWK(privateKey: Uint8Array): Jwk; /** * Pass the privateKey in JsonWebKey format for a slight performance gain. * You can convert raw keys to JWK using the privateKeyToJWK function. */ createSignature(payload: Uint8Array, privateKey: Uint8Array | Jwk): Promise; private publicKeyToCryptoKey; verifySignature(publicKey: UserIDRaw, payload: Uint8Array, signature: Uint8Array): Promise; assertValidKeyPair(publicKey: UserIDRaw, privateKey: Uint8Array): void; } /** * Signing scheme using ML-DSA-87 */ declare class MlDsa87 extends SigningUtil { generateKeyPair(): KeyPair; createSignature(payload: Uint8Array, privateKey: Uint8Array, seed?: Uint8Array): Promise; verifySignature(publicKey: UserIDRaw, payload: Uint8Array, signature: Uint8Array): Promise; assertValidKeyPair(publicKey: UserIDRaw, privateKey: Uint8Array): void; } export { AbortError, Cache, CountMetric, DEFAULT_PARTITION_COUNT, Defer, EcdsaSecp256k1Evm, EcdsaSecp256r1, Gate, Heap, KEY_TYPES, LengthPrefixedFrameDecoder, LevelMetric, Logger, MAX_PARTITION_COUNT, MapWithTtl, Metric, MetricsContext, MlDsa87, Multimap, ObservableEventEmitter, RateMetric, SigningUtil, StreamIDUtils, StreamPartIDUtils, TheGraphClient, TimeoutError, addManagedEventListener, areEqualBinaries, asAbortable, binaryToHex, binaryToUtf8, collect, composeAbortSignals, computeMd5, computeSha1, createCipheriv, createDecipheriv, ensureValidStreamPartitionCount, ensureValidStreamPartitionIndex, executeSafePromise, filePathToNodeFormat, getSubtle, hexToBinary, initEventGateway, ipv4ToNumber, isENSName, isEthereumAddressUserId, isValidUserId, keyToArrayIndex, merge, multiplyWeiAmount, numberToIpv4, pTransaction, privateDecrypt, publicEncrypt, raceForEvent, randomString, retry, scheduleAtApproximateInterval, scheduleAtFixedRate, scheduleAtInterval, setAbortableInterval, setAbortableTimeout, toENSName, toEthereumAddress, toEthereumAddressOrENSName, toLengthPrefixedFrame, toStreamID, toStreamPartID, toUserId, toUserIdRaw, until, utf8ToBinary, wait, waitForEvent, withRateLimit, withTimeout }; export type { BrandedString, ChangeFieldType, ComposedAbortSignal, CryptoKey, ENSName, EthereumAddress, Events, GraphQLQuery, HexString, Jwk, KeyType, LogLevel, LoggerModule, MapKey, MetricsDefinition, MetricsReport, StreamID, StreamPartID, UserID, UserIDRaw, WeiAmount };