import * as _streamr_network_contracts from '@streamr/network-contracts'; import { Sponsorship, Operator as Operator$1 } from '@streamr/network-contracts'; import * as ethers from 'ethers'; import { Eip1193Provider, Overrides, Provider, AbstractProvider, AbstractSigner, EventFragment, BaseContract, ContractTransactionResponse, ContractTransactionReceipt, InterfaceAbi, Signer, Contract, JsonRpcApiProvider, BigNumberish } from 'ethers'; export { AbstractSigner, Eip1193Provider, Overrides } from 'ethers'; import * as _streamr_utils from '@streamr/utils'; import { LogLevel, KeyType, HexString, UserID, UserIDRaw, LoggerModule, Logger, TheGraphClient, StreamID, EthereumAddress, StreamPartID, MetricsContext, ObservableEventEmitter, WeiAmount } from '@streamr/utils'; export { BrandedString, EthereumAddress, KeyType, LogLevel, Metric, MetricsContext, MetricsDefinition, MetricsReport, StreamID, StreamPartID, UserID } from '@streamr/utils'; import * as tsyringe from 'tsyringe'; import { IceServer, PortRange, TlsCertificate, DhtAddress, PeerDescriptor } from '@streamr/dht'; export { DhtAddress, IceServer, PeerDescriptor, PortRange } from '@streamr/dht'; import { SignatureType, ContentType, EncryptionType, EncryptedGroupKey, NetworkOptions, StreamMessage as StreamMessage$1, StreamPartDeliveryOptions, ProxyDirection, ExternalRpcClient, ExternalRpcClientClass } from '@streamr/trackerless-network'; export { ContentType, EncryptedGroupKey, EncryptionType, ProxyDirection, SignatureType, StreamPartDeliveryOptions } from '@streamr/trackerless-network'; import { MarkOptional, MarkRequired } from 'ts-essentials'; import { IMessageType } from '@protobuf-ts/runtime'; import { ServerCallContext } from '@protobuf-ts/runtime-rpc'; import { ProtoRpcClient } from '@streamr/proto-rpc'; import { EventEmitter } from 'eventemitter3'; /** * For passing in an Ethereum provider (= wallet) for signing. Any {@link https://eips.ethereum.org/EIPS/eip-1193 EIP-1193} * compatible provider will do. The {@link https://docs.ethers.org/v6/api/providers/#Eip1193Provider Eip1193Provider} type * definition used here is from the `ethers` library. */ interface EthereumProviderIdentityConfig { ethereum: Eip1193Provider; } /** * For configuring identities based on a cryptographic key / key pair */ interface KeyPairIdentityConfig { publicKey?: string; privateKey: string; keyType?: KeyType; } /** * For passing in an Identity implementation */ interface CustomIdentityConfig { identity: Identity; } type IdentityConfig = KeyPairIdentityConfig | EthereumProviderIdentityConfig | CustomIdentityConfig; interface ControlLayerConfig { /** * The list of entry point PeerDescriptors used to join the Streamr Network. */ entryPoints?: NetworkPeerDescriptor[]; /** * The maximum number of connections before unwanted connections are clean up. * This is a soft limit, meaning that the number of connections may exceed the count temporarily. * Locked connections such as the ones used for stream operations are not counted towards this limit. */ maxConnections?: number; /** * If true, an attempt is made to discover additional network entrypoint nodes * by querying them from The Graph. If false, only the nodes * listed in entryPoints are used. */ entryPointDiscovery?: EntryPointDiscovery; /** * The list of STUN and TURN servers to use in ICE protocol when * forming WebRTC connections. */ iceServers?: IceServer[]; /** * When set to true private addresses will not be probed when forming * WebRTC connections. * * Probing private addresses can trigger false-positive incidents in * some port scanning detection systems employed by web hosting * providers. Disallowing private addresses may prevent direct * connections from being formed between nodes using IPv4 addresses * on a local network. * * Details: https://github.com/streamr-dev/network/wiki/WebRTC-private-addresses */ webrtcAllowPrivateAddresses?: boolean; /** * Sets the low-water mark used by send buffers of WebRTC connections. */ webrtcDatachannelBufferThresholdLow?: number; /** * Sets the high-water mark used by send buffers of WebRTC connections. */ webrtcDatachannelBufferThresholdHigh?: number; /** * Defines a custom UDP port range to be used for WebRTC connections. * This port range should not be restricted by enclosing firewalls * or virtual private cloud configurations. NodeJS only. */ webrtcPortRange?: PortRange; /** * The maximum outgoing message size (in bytes) accepted by connections. * Messages exceeding the maximum size are simply discarded. */ maxMessageSize?: number; /** * Contains connectivity information to the client's Network Node, used in the network layer. * Can be used in cases where the client's public IP address is known before * starting the network node. If not specified, the PeerDescriptor will be auto-generated. */ peerDescriptor?: NetworkPeerDescriptor; /** * The port range used to find a free port for the client's network layer WebSocket server. * If set to `null`, a server will not be started. * The server is used by the network layer to accept incoming connections * over the public internet to improve the network node's connectivity. */ websocketPortRange?: PortRange | null; /** * The host name or IP address of the WebSocket server used to connect to it over the internet. * If not specified, the host name will be auto-detected. * Can be useful in situations where the host is running behind a reverse-proxy or load balancer. */ websocketHost?: string; /** * TLS configuration for the WebSocket server */ tlsCertificate?: TlsCertificate; externalIp?: string; /** * The maximum time to wait when establishing connectivity to the control layer. If the connection * is not formed within this time, the client's network node will throw an error. */ networkConnectivityTimeout?: number; /** * URL of the autocertifier service used to obtain TLS certificates and subdomain names for the WS server. */ autoCertifierUrl?: string; /** * File path to the autocertified subdomain file. The file contains the autocertified subdomain name * and it's TLS certificate. */ autoCertifierConfigFile?: string; /** * If the node is running a WS server, this option can be used to disable TLS autocertification to * run the server without TLS. This will speed up the starting time of the network node * (especially when starting the node for the first time on a new machine). */ websocketServerEnableTls?: boolean; /** * Define a geo ip database folder path to be used by the network node. When left undefined * geoip functionality is disabled. */ geoIpDatabaseFolder?: string; } interface NetworkNodeConfig { /** * The number of connections the client's network node should have * on each stream partition. */ streamPartitionNeighborTargetCount?: number; /** * The minimum number of peers in a stream partition that the client's network node * will attempt to propagate messages to */ streamPartitionMinPropagationTargets?: number; /** * The maximum number of messages that can be buffered in the propagation buffer. */ streamPartitionMaxPropagationBufferSize?: number; /** * Whether to buffer while connecting in the content delivery layer. */ contentDeliveryBufferWhileConnecting?: boolean; /** * Whether to accept proxy connections. Enabling this option allows * this network node to act as proxy on behalf of other nodes / clients. * When enabling this option, a WebSocket server should be configured for the client * and the node needs to be in the open internet. The server can be started by setting * the websocketPort configuration to a free port in the network control layer configuration. */ acceptProxyConnections?: boolean; } interface NetworkConfig { controlLayer?: ControlLayerConfig; node?: NetworkNodeConfig; } declare enum NetworkNodeType { NODEJS = "nodejs", BROWSER = "browser" } interface NetworkPeerDescriptor { nodeId: string; type?: NetworkNodeType; websocket?: ConnectivityMethod; region?: number; } interface EntryPointDiscovery { enabled?: boolean; maxEntryPoints?: number; maxQueryResults?: number; maxHeartbeatAgeHours?: number; } interface ConnectivityMethod { host: string; port: number; tls: boolean; } interface ConnectionInfo { url: string; } interface EthereumNetworkConfig { chainId: number; overrides?: Overrides; highGasPriceStrategy?: boolean; } declare const ENVIRONMENT_IDS: readonly ["polygon", "polygonAmoy", "peaq", "iotex", "dev2"]; type EnvironmentId = typeof ENVIRONMENT_IDS[number]; declare const DEFAULT_ENVIRONMENT_ID: EnvironmentId; type GapFillStrategy = 'light' | 'full'; /** * @category Important */ interface StreamrClientConfig { environment?: EnvironmentId; /** Custom human-readable debug id for client. Used in logging. */ id?: string; /** * Override the default logging level. */ logLevel?: LogLevel; /** * The cryptographic identity to be used by the client. The chosen identity * also determines the type of signatures on published messages. */ auth?: IdentityConfig; /** * Due to the distributed nature of the network, messages may occasionally * arrive to the client out-of-order. Set this option to `true` if you want * the client to reorder received messages to the intended order. * * */ orderMessages?: boolean; /** * Set to true to enable gap filling. * * Some messages may occasionally not reach the client due to networking * issues. Missing messages form gaps that are often detectable and * retrievable on demand. By enabling gap filling, the client will detect * and fix gaps automatically for you. */ gapFill?: boolean; /** * When gap filling is enabled, this option controls the maximum amount of * times a gap will try to be actively filled before giving up and * proceeding forwards. */ maxGapRequests?: number; /** * When gap filling is enabled and a gap is encountered, this option * defines the amount of time in milliseconds to wait before attempting to * _actively_ fill in the gap. * * Rationale: data may just be arriving out-of-order and the missing * message(s) may be on their way. For efficiency, it makes sense to wait a * little before actively attempting to fill in a gap, as this involves * a resend request / response interaction with a storage node. */ gapFillTimeout?: number; /** * Config for the decentralized network layer. */ network?: NetworkConfig; /** * When gap filling is enabled and a gap is encountered, a resend request * may eventually be sent to a storage node in an attempt to _actively_ * fill in the gap. This option controls how long to wait for, in * milliseconds, for a resend response from the storage node before * proceeding to the next attempt. */ retryResendAfter?: number; /** * When gap filling is enabled, this setting controls whether to enable a * lighter (default) or a full gap fill strategy. * * While filling a gap, new gaps may emerge further along the message * chain. After a gap has been filled, the gap filling mechanism will * attend to the next gap until that has been resolved and so forth. * * This is great in theory, but sometimes in practice, especially in * streams with heavy traffic, the gap filling mechanism may never catch * up leading to permanently increased latency, and even dropped messages * (due to buffer overflows) further exacerbating the presence of gaps. * * With `light` strategy, when a gap cannot be successfully filled and * must be dropped, all subsequent accumulated gaps will be dropped as * well. This improves the ability to stay up-to-date at the cost of * potentially missing messages. With `full` strategy the subsequent gaps * will not be dropped. */ gapFillStrategy?: GapFillStrategy; /** * Controls how messages encryption and decryption should be handled and * how encryption keys should be exchanged. */ encryption?: { /** * When requesting an encryption key using the standard Streamr * key-exchange system, defines how many milliseconds should a response * be awaited for. */ keyRequestTimeout?: number; /** * The maximum amount of encryption key requests that should be sent via * the standard Streamr key-exchange system per second. * * In streams with 1000+ publishers, it is important to limit the amount * of control message traffic that gets generated to avoid network buffers * from overflowing. */ maxKeyRequestsPerSecond?: number; /** * Defines how strong RSA key, in bits, is used when an encryption key is * requested via the standard Streamr key-exchange. */ rsaKeyLength?: number; /** * Default: false. * * The default behavior on subscribers is to request key exchange using ML-KEM if a quantum secure * identity key pair is configured, otherwise RSA. * * The default behavior on publishers is to do key exchange using whichever method requested by subscribers. * * If set to true, subscribers will always request using ML-KEM, and publishers will reject key requests that use RSA. */ requireQuantumResistantKeyExchange?: boolean; /** * Default: false. If true, configuring a non-quantum-resistant identity key pair will produce an error, * and subscribed messages will only be accepted if they are signed using a quantum resistant algorithm. */ requireQuantumResistantSignatures?: boolean; /** * Default: false. If true on subscribers, data encrypted with non-quantum-resistant methods will be rejected. * If true on publishers, only data encrypted with quantum resistant methods can be published. * Note that subscribers will still accept unencrypted (public) data despite this setting. */ requireQuantumResistantEncryption?: boolean; /** * If this is defined only these encryption keys will be used. This will disable the Streamr key-exchange. */ keys?: Record; }; contracts?: { streamRegistryChainAddress?: HexString; streamStorageRegistryChainAddress?: HexString; storageNodeRegistryChainAddress?: HexString; sponsorshipFactoryChainAddress?: HexString; ethereumNetwork?: EthereumNetworkConfig; rpcs?: ConnectionInfo[]; rpcQuorum?: number; /** Some TheGraph instance, that indexes the streamr registries */ theGraphUrl?: string; maxConcurrentCalls?: number; pollInterval?: number; }; validation?: { permissions?: boolean; partitions?: boolean; }; /** * Determines the telemetry metrics that are sent to the Streamr Network * at regular intervals. * * By setting this to false, you disable the feature. */ metrics?: { periods?: { streamId: string; duration: number; }[]; maxPublishDelay?: number; } | boolean; /** * Determines caching behaviour for certain repeated smart contract queries. */ cache?: { maxSize?: number; maxAge?: number; }; } type StrictStreamrClientConfig = MarkOptional, 'auth' | 'metrics'> & { network: Exclude, undefined>; contracts: Exclude, undefined>; encryption: Exclude, undefined>; validation: Exclude, undefined>; cache: Exclude, undefined>; }; /** * @deprecated use {@link STREAMR_STORAGE_NODE_ADDRESS} instead */ declare const STREAMR_STORAGE_NODE_GERMANY = "0x31546eEA76F2B2b3C5cC06B1c93601dc35c9D916"; declare const STREAMR_STORAGE_NODE_ADDRESS: HexString; declare const ConfigInjectionToken: unique symbol; declare class RpcProviderSource { private readonly config; private provider?; private subProviders?; constructor(config: Pick); getProvider(): Provider; /** * Use this method only if you need access each provider separately. In most cases it is better to use * the `getProvider` method as it provides better fail-safety. */ getSubProviders(): AbstractProvider[]; } /** * The {@link https://docs.ethers.org/v6/api/providers/abstract-signer/#AbstractSigner AbstractSigner} type is from the `ethers` library. */ type SignerWithProvider = AbstractSigner; /** * Identity represents a digital identity, specified by cryptographic keys, * and capable of signing. You can configure new Identities in IdentityMapping.ts. */ declare abstract class Identity { abstract getUserId(): Promise; abstract getUserIdRaw(): Promise; abstract getSignatureType(): SignatureType; abstract createMessageSignature(payload: Uint8Array): Promise; abstract getTransactionSigner(rpcProviderSource: RpcProviderSource): Promise; } type SignalListener = (...args: T) => (unknown | Promise); type SignalListenerWrap = SignalListener & { listener: SignalListener; }; declare enum TRIGGER_TYPE { ONCE = "ONCE", ONE = "ONE", QUEUE = "QUEUE", PARALLEL = "PARALLEL" } /** * Like an event emitter, but for a single event. Listeners are executed * in-order, in an async sequence. Any errors in listerns errors will be * thrown by trigger() as an AggregateError at end. * * Allows attaching onEvent properties to classes e.g. * ```ts * class Messages { * onMessage = Signal.create(this) * async push(msg: Message) { * await this.onMessage.trigger(msg) * } * } * * const msgs = new Messages() * msgs.onMessage((msg) => console.log(msg)) * await msgs.push(new Message()) * ``` */ declare class Signal { static TRIGGER_TYPE: typeof TRIGGER_TYPE; /** * Create a Signal's listen function with signal utility methods attached. * See example above. */ static create(triggerType?: TRIGGER_TYPE): Signal; /** * Will only trigger once. Adding listeners after already fired will fire * listener immediately. Calling trigger after already triggered is a * noop. */ static once(): Signal; /** * Only one pending trigger call at a time. Calling trigger again while * listeners are pending will not trigger listeners again, and will resolve * when listeners are resolved. */ static one(): Signal; /** * Only one pending trigger call at a time, but calling trigger again while * listeners are pending will enqueue the trigger until after listeners are * resolved. */ static queue(): Signal; /** * Trigger does not wait for pending trigger calls at all. * Listener functions are still executed in async series, * but multiple triggers can be active in parallel. */ static parallel(): Signal; protected listeners: (SignalListener | SignalListenerWrap)[]; protected isEnded: boolean; protected triggerCountValue: number; protected triggerType: TRIGGER_TYPE; constructor(triggerType?: TRIGGER_TYPE); triggerCount(): number; lastValue: ArgsType | undefined; /** * No more events. */ end: (...args: ArgsType) => void; /** * Promise that resolves on next trigger. */ wait(): Promise; getLastValue(): Promise; /** * Attach a callback listener to this Signal. */ listen(): Promise; listen(cb: SignalListener): this; once(): Promise; once(cb: SignalListener): this; countListeners(): number; /** * Remove a callback listener from this Signal. */ unlisten(cb: SignalListener): this; protected execTrigger(...args: ArgsType): Promise; currentTask: Promise | undefined; /** * Trigger the signal with optional value, like emitter.emit. */ trigger(...args: ArgsType): Promise; [Symbol.asyncIterator](): AsyncGenerator, void, unknown>; } /** * Listen to onDestroy to fire cleanup code on destroy. * Careful not to introduce memleaks. * Trigger this to destroy the client. */ declare class DestroySignal { readonly onDestroy: Signal<[]>; readonly trigger: () => Promise; readonly abortSignal: AbortSignal; constructor(); destroy(): Promise; assertNotDestroyed(): void; isDestroyed(): boolean; } declare class LoggerFactory { private readonly config; constructor(config: Pick); createLogger(loggerModule: LoggerModule): Logger; } interface FindOperatorsOnStreamResult { operatorId: EthereumAddress; peerDescriptor: NetworkPeerDescriptor; } declare class OperatorRegistry { private readonly theGraphClient; private readonly logger; constructor(theGraphClient: TheGraphClient, loggerFactory: LoggerFactory); findRandomNetworkEntrypoints(maxEntryPoints: number, maxQueryResults: number, maxHeartbeatAgeHours: number): Promise; findOperatorsOnStream(streamId: StreamID, maxQueryResults: number, maxHeartbeatAgeHours: number): Promise; } declare class MessageRef { readonly timestamp: number; readonly sequenceNumber: number; constructor(timestamp: number, sequenceNumber: number); compareTo(other: MessageRef): number; } declare class MessageID { readonly streamId: StreamID; readonly streamPartition: number; readonly timestamp: number; readonly sequenceNumber: number; readonly publisherId: UserID; readonly msgChainId: string; constructor(streamId: StreamID, streamPartition: number, timestamp: number, sequenceNumber: number, publisherId: UserID, msgChainId: string); getStreamPartID(): StreamPartID; toMessageRef(): MessageRef; } declare enum StreamMessageType { MESSAGE = 0, GROUP_KEY_REQUEST = 1, GROUP_KEY_RESPONSE = 2 } interface StreamMessageOptions { messageId: MessageID; prevMsgRef?: MessageRef; messageType?: StreamMessageType; content: Uint8Array; contentType: ContentType; signature: Uint8Array; signatureType: SignatureType; encryptionType: EncryptionType; groupKeyId?: string; newGroupKey?: EncryptedGroupKey; } /** * Encrypted StreamMessage. */ type StreamMessageAESEncrypted = StreamMessage & { encryptionType: EncryptionType.AES; groupKeyId: string; }; /** * An internal class representing a message in a stream. Applications see instances of the Message class. */ declare class StreamMessage implements StreamMessageOptions { readonly messageId: MessageID; readonly prevMsgRef?: MessageRef; readonly messageType: StreamMessageType; readonly content: Uint8Array; readonly contentType: ContentType; readonly signature: Uint8Array; readonly signatureType: SignatureType; readonly encryptionType: EncryptionType; readonly groupKeyId?: string; readonly newGroupKey?: EncryptedGroupKey; constructor({ messageId, prevMsgRef, messageType, content, contentType, signature, signatureType, encryptionType, groupKeyId, newGroupKey, }: StreamMessageOptions); getStreamId(): StreamID; getStreamPartition(): number; getStreamPartID(): StreamPartID; getTimestamp(): number; getSequenceNumber(): number; getPublisherId(): UserID; getMsgChainId(): string; getMessageRef(): MessageRef; getParsedContent(): Uint8Array | Record | unknown[]; static isAESEncrypted(msg: StreamMessage): msg is StreamMessageAESEncrypted; } /** * Wrap a network node. */ interface NetworkNodeStub { getNodeId: () => DhtAddress; addMessageListener: (listener: (msg: StreamMessage$1) => void) => void; removeMessageListener: (listener: (msg: StreamMessage$1) => void) => void; join: (streamPartId: StreamPartID, neighborRequirement?: { minCount: number; timeout: number; }, deliveryOptions?: StreamPartDeliveryOptions) => Promise; leave: (streamPartId: StreamPartID) => Promise; broadcast: (streamMessage: StreamMessage$1, deliveryOptions?: StreamPartDeliveryOptions) => Promise; getStreamParts: () => StreamPartID[]; getNeighbors: (streamPartId: StreamPartID) => readonly DhtAddress[]; getPeerDescriptor: () => PeerDescriptor; getOptions: () => NetworkOptions; getMetricsContext: () => MetricsContext; getDiagnosticInfo: () => Record; hasStreamPart: (streamPartId: StreamPartID) => boolean; inspect(node: PeerDescriptor, streamPartId: StreamPartID): Promise; start: (doJoin?: boolean) => Promise; stop: () => Promise; setProxies: (streamPartId: StreamPartID, nodes: PeerDescriptor[], userId: UserID, direction?: ProxyDirection, connectionCount?: number) => Promise; isProxiedStreamPart(streamPartId: StreamPartID): boolean; setStreamPartEntryPoints: (streamPartId: StreamPartID, peerDescriptors: PeerDescriptor[]) => void; createExternalRpcClient(clientClass: ExternalRpcClientClass): ProtoRpcClient; registerExternalNetworkRpcMethod, ResponseClass extends IMessageType, RequestType extends object, ResponseType extends object>(request: RequestClass, response: ResponseClass, name: string, fn: (req: RequestType, context: ServerCallContext) => Promise): void; } interface Events { start: () => void; } /** * The factory is used so that integration tests can replace the real network node with a fake instance */ declare class NetworkNodeFactory { createNetworkNode(opts: NetworkOptions): NetworkNodeStub; } /** * Wrap a network node. * Lazily creates & starts node on first call to getNode(). */ declare class NetworkNodeFacade { private cachedNode?; private startNodeCalled; private startNodeComplete; private readonly messageListeners; private readonly networkNodeFactory; private readonly operatorRegistry; private readonly config; private readonly identity; private readonly eventEmitter; private readonly destroySignal; constructor(networkNodeFactory: NetworkNodeFactory, operatorRegistry: OperatorRegistry, config: Pick, identity: Identity, destroySignal: DestroySignal); private getNetworkOptions; /** * Stop network node, or wait for it to stop if already stopping. * Subsequent calls to getNode/start will fail. */ private destroy; /** * Start network node, or wait for it to start if already started. */ private startNodeTask; private initNode; startNode: () => Promise; getNode(): Promise>; getNodeId(): Promise; join(streamPartId: StreamPartID, neighborRequirement?: { minCount: number; timeout: number; }, deliveryOptions?: StreamPartDeliveryOptions): Promise; leave(streamPartId: StreamPartID): Promise; broadcast(msg: StreamMessage, deliveryOptions?: StreamPartDeliveryOptions): Promise; addMessageListener(listener: (msg: StreamMessage) => void): void; removeMessageListener(listener: (msg: StreamMessage) => void): void; isProxiedStreamPart(streamPartId: StreamPartID): Promise; getMetricsContext(): Promise; getPeerDescriptor(): Promise; getDiagnosticInfo(): Promise>; getStreamParts(): Promise; getNeighbors(streamPartId: StreamPartID): Promise; getOptions(): Promise; inspect(node: NetworkPeerDescriptor, streamPartId: StreamPartID): Promise; setProxies(streamPartId: StreamPartID, nodes: NetworkPeerDescriptor[], direction?: ProxyDirection, connectionCount?: number): Promise; setStreamPartEntryPoints(streamPartId: StreamPartID, nodeDescriptors: NetworkPeerDescriptor[]): Promise; discoverOperators(leader: NetworkPeerDescriptor, streamPartId: StreamPartID): Promise; private createExternalRpcClient; registerOperator(opts: { getAssignedNodesForStreamPart: (streamPartId: StreamPartID) => NetworkPeerDescriptor[]; }): Promise; private isStarting; once(eventName: E, listener: Events[E]): void; private getEntryPoints; } /** * Utility Types */ type StreamDefinition = string | { id: string; partition?: number; } | { stream: string; partition?: number; } | { streamId: string; partition?: number; }; type StreamMetadata = Record; declare const parseMetadata: (metadata: string) => StreamMetadata; declare const getPartitionCount: (metadata: StreamMetadata) => number; declare enum StreamPermission { EDIT = "edit", DELETE = "delete", PUBLISH = "publish", SUBSCRIBE = "subscribe", GRANT = "grant" } interface UserPermissionQuery { streamId: string; permission: StreamPermission; userId: HexString; allowPublic: boolean; } interface PublicPermissionQuery { streamId: string; permission: StreamPermission; public: true; } type PermissionQuery = UserPermissionQuery | PublicPermissionQuery; interface UserPermissionAssignment { permissions: StreamPermission[]; userId: HexString; } interface PublicPermissionAssignment { permissions: StreamPermission[]; public: true; } type PermissionAssignment = UserPermissionAssignment | PublicPermissionAssignment; interface SearchStreamsPermissionFilter { userId: HexString; allOf?: StreamPermission[]; anyOf?: StreamPermission[]; allowPublic: boolean; } interface StreamCreationEvent { readonly streamId: StreamID; readonly metadata: StreamMetadata; readonly blockNumber: number; } interface EventListenerDefinition { onEvent: (eventArgs: TEventArgs, blockNumber: number) => void; contractInterfaceFragment: EventFragment; contractAddress: EthereumAddress; } declare class ChainEventPoller { private listeners; private providers; private pollInterval; private abortController?; constructor(rpcProviderSource: RpcProviderSource, config: Pick); on(definition: EventListenerDefinition): void; off(definition: EventListenerDefinition): void; private start; } interface ContractEvent { onMethodExecute: (methodName: string) => void; onTransactionSubmit: (methodName: string, tx: ContractTransactionResponse) => void; onTransactionConfirm: (methodName: string, receipt: ContractTransactionReceipt | null) => void; } type ObservableContract = T & { eventEmitter: EventEmitter; }; declare class ContractFactory { private readonly config; private readonly eventEmitter; private readonly loggerFactory; constructor(config: Pick, eventEmitter: StreamrClientEventEmitter, loggerFactory: LoggerFactory); createReadContract(address: EthereumAddress, contractInterface: InterfaceAbi, provider: Provider, name: string): ObservableContract; createWriteContract(address: EthereumAddress, contractInterface: InterfaceAbi, signer: Signer, name: string): ObservableContract; createEventContract(address: EthereumAddress, contractInterface: InterfaceAbi, provider: AbstractProvider): Contract; } interface StorageNodeAssignmentEvent { readonly streamId: StreamID; readonly nodeAddress: EthereumAddress; readonly blockNumber: number; } interface SponsorshipCreatedEvent { readonly sponsorshipContractAddress: EthereumAddress; readonly streamId: StreamID; readonly blockNumber: number; } interface StreamrClientEvents { streamCreated: (payload: StreamCreationEvent) => void; streamAddedToStorageNode: (payload: StorageNodeAssignmentEvent) => void; streamRemovedFromStorageNode: (payload: StorageNodeAssignmentEvent) => void; sponsorshipCreated: (payload: SponsorshipCreatedEvent) => void; } interface InternalEvents { messagePublished: (message: StreamMessage) => void; streamPartSubscribed: () => void; } declare class StreamrClientEventEmitter extends ObservableEventEmitter { } /** * GroupKeys are AES cipher keys, which are used to encrypt/decrypt StreamMessages (when encryptionType is AES). * Each group key contains 256 random bits of key data and an UUID. */ declare class GroupKey { constructor(id: string, data: Buffer); private static validate; static generate(id?: string): GroupKey; } /** * @privateRemarks * * In the client API we use the term EncryptionKey instead of GroupKey. * The GroupKey name comes from the protocol. TODO: we could rename all classes * and methods to use the term EncryptionKey (except protocol-classes, which * should use the protocol level term GroupKey) */ interface UpdateEncryptionKeyOptions { /** * The Stream ID for which this key update applies. */ streamId: string; /** * Determines how the new key will be distributed to subscribers. * * @remarks * With `rotate`, the new key will be sent to the stream alongside the next published message. The key will be * encrypted using the current key. Only after this will the new key be used for publishing. This * provides forward secrecy. * * With `rekey`, we for each subscriber to fetch the new key individually. This ensures each subscriber's * permissions are revalidated before they are given the new key. */ distributionMethod: 'rotate' | 'rekey'; /** * Provide a specific key to be used. If left undefined, a new key is generated automatically. */ key?: GroupKey; } declare class MessageSigner { private readonly identity; constructor(identity: Identity); createSignedMessage(opts: MarkRequired, 'messageType'>, signatureType: SignatureType): Promise; } interface StorageNodeMetadata { urls: string[]; } interface ResendRef { timestamp: number | Date | string; sequenceNumber?: number; } /** * Resend the latest "n" messages. */ interface ResendLastOptions { last: number; } /** * Resend messages starting from a given point in time. */ interface ResendFromOptions { from: ResendRef; publisherId?: HexString; } /** * Resend messages between two points in time. */ interface ResendRangeOptions { from: ResendRef; to: ResendRef; msgChainId?: string; publisherId?: HexString; } /** * The supported resend types. */ type ResendOptions = ResendLastOptions | ResendFromOptions | ResendRangeOptions; type MessageSignatureType = KeyType | 'ECDSA_SECP256K1_LEGACY' | 'ERC_1271'; /** * Represents a message in the Streamr Network. * * @category Important */ interface Message { /** * The message contents / payload. Given as JSON or Uint8Array */ content: unknown; /** * Identifies the stream the message was published to. */ streamId: StreamID; /** * The partition number the message was published to. */ streamPartition: number; /** * The timestamp of when the message was published. */ timestamp: number; /** * Tiebreaker used to determine order in the case of multiple messages within a message chain having the same exact timestamp. */ sequenceNumber: number; /** * Signature of message signed by publisher. */ signature: Uint8Array; /** * Signature method used to sign message. */ signatureType: MessageSignatureType; /** * Publisher of message. */ publisherId: HexString; /** * Identifies the message chain the message was published to. */ msgChainId: string; /** * Identifiers group key used to encrypt the message. */ encryptionKeyId: string | undefined; } type MessageMetadata = Omit; type MessageListener = (content: unknown, metadata: MessageMetadata) => unknown | Promise; /** * Provides asynchronous iteration with * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of | for await .. of}. */ declare class MessageStream implements AsyncIterable { private readonly pipeline; [Symbol.asyncIterator](): AsyncIterator; } /** * Events emitted by {@link Subscription}. */ interface SubscriptionEvents { /** * Emitted if an error occurred in the subscription. */ error: (err: Error) => void; /** * Emitted when a resend is complete. */ resendCompleted: () => void; } /** * A convenience API for managing an individual subscription. * * @category Important */ declare class Subscription extends MessageStream { readonly streamPartId: StreamPartID; readonly erc1271ContractAddress: EthereumAddress | undefined; readonly deliveryOptions: StreamPartDeliveryOptions | undefined; private readonly eventEmitter; private readonly logger; /** * Unsubscribes this subscription. * * @remarks The instance should not be used after calling this. */ unsubscribe(): Promise; /** * Adds an event listener to the subscription. * @param eventName - event name, see {@link SubscriptionEvents} for options * @param listener - the callback function */ on(eventName: E, listener: SubscriptionEvents[E]): void; /** * Adds an event listener to the subscription that is invoked only once. * @param eventName - event name, see {@link SubscriptionEvents} for options * @param listener - the callback function */ once(eventName: E, listener: SubscriptionEvents[E]): void; /** * Removes an event listener from the subscription. * @param eventName - event name, see {@link SubscriptionEvents} for options * @param listener - the callback function to remove */ off(eventName: E, listener: SubscriptionEvents[E]): void; } interface PublishMetadata { timestamp?: string | number | Date; partitionKey?: string | number; msgChainId?: string; /** * Publish a message on behalf of a contract implementing the [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) * standard. The streamr client wallet address must be an authorized signer for the contract. */ erc1271Contract?: string; } /** * A convenience API for managing and accessing an individual stream. * * @category Important */ declare class Stream { readonly id: StreamID; private readonly client; /** * See {@link StreamrClient.publish | StreamrClient.publish}. * * @category Important */ publish(content: unknown, metadata?: PublishMetadata): Promise; /** * See {@link StreamrClient.hasPermission | StreamrClient.hasPermission}. * * @category Important */ hasPermission(query: Omit | Omit): Promise; /** * See {@link StreamrClient.getPermissions | StreamrClient.getPermissions}. * * @category Important */ getPermissions(): Promise; /** * See {@link StreamrClient.grantPermissions | StreamrClient.grantPermissions}. * * @category Important */ grantPermissions(...assignments: PermissionAssignment[]): Promise; /** * See {@link StreamrClient.revokePermissions | StreamrClient.revokePermissions}. * * @category Important */ revokePermissions(...assignments: PermissionAssignment[]): Promise; /** * See {@link StreamrClient.addStreamToStorageNode | StreamrClient.addStreamToStorageNode}. * * @category Important */ addToStorageNode(storageNodeAddress: HexString, opts?: { wait: boolean; timeout?: number; }): Promise; /** * See {@link StreamrClient.removeStreamFromStorageNode | StreamrClient.removeStreamFromStorageNode}. */ removeFromStorageNode(nodeAddress: HexString): Promise; /** * See {@link StreamrClient.getStorageNodes | StreamrClient.getStorageNodes}. */ getStorageNodes(): Promise; /** * Returns the partitions of the stream. */ getStreamParts(): Promise; getPartitionCount(): Promise; getDescription(): Promise; setDescription(description: string): Promise; /** * Gets the value of `storageDays` field */ getStorageDayCount(): Promise; /** * Sets the value of `storageDays` field */ setStorageDayCount(count: number): Promise; /** * Returns the metadata of the stream. */ getMetadata(): Promise; /** * Updates the metadata of the stream. */ setMetadata(metadata: StreamMetadata): Promise; } interface EarningsData { sponsorshipAddresses: EthereumAddress[]; sum: WeiAmount; maxAllowedEarnings: WeiAmount; } /** * @deprecated * @hidden */ interface StakeEvent { sponsorship: EthereumAddress; } /** * @deprecated * @hidden */ interface ReviewRequestEvent { sponsorship: EthereumAddress; targetOperator: EthereumAddress; partition: number; votingPeriodStartTimestamp: number; votingPeriodEndTimestamp: number; } /** * @deprecated * @hidden */ interface OperatorEvents { staked: (payload: StakeEvent) => void; unstaked: (payload: StakeEvent) => void; reviewRequested: (payload: ReviewRequestEvent) => void; } /** * @deprecated * @hidden */ interface GetOperatorSponsorshipsResult { sponsorshipAddress: EthereumAddress; streamId: StreamID; operatorCount: number; } /** * @deprecated * @hidden */ interface Flag { id: string; flaggingTimestamp: number; targetOperator: EthereumAddress; sponsorship: EthereumAddress; } /** * @deprecated This in an internal class * @hidden */ declare class Operator { private readonly contractAddress; private contract?; private readonly contractReadonly; private readonly contractFactory; private readonly rpcProviderSource; private readonly theGraphClient; private readonly identity; private readonly getEthersOverrides; private readonly eventEmitter; constructor(contractAddress: EthereumAddress, contractFactory: ContractFactory, rpcProviderSource: RpcProviderSource, chainEventPoller: ChainEventPoller, theGraphClient: TheGraphClient, identity: Identity, destroySignal: DestroySignal, loggerFactory: LoggerFactory, getEthersOverrides: () => Promise); private initEventGateways; writeHeartbeat(nodeDescriptor: NetworkPeerDescriptor): Promise; getTimestampOfLastHeartbeat(): Promise; getContractAddress(): Promise; getSponsorships(): Promise; getExpiredFlags(sponsorshipAddresses: EthereumAddress[], maxAgeInMs: number): Promise; getOperatorsInSponsorship(sponsorshipAddress: EthereumAddress): Promise; flag(sponsorship: EthereumAddress, operator: EthereumAddress, partition: number): Promise; /** * Find the sum of earnings in Sponsorships (that the Operator must withdraw before the sum reaches a limit), * SUBJECT TO the constraints: * - only take at most maxSponsorshipsInWithdraw addresses (those with most earnings), or all if undefined * - only take sponsorships that have more than minSponsorshipEarningsInWithdraw, or all if undefined */ getEarnings(minSponsorshipEarningsInWithdraw: WeiAmount, maxSponsorshipsInWithdraw: number): Promise; withdrawEarningsFromSponsorships(sponsorshipAddresses: EthereumAddress[]): Promise; triggerAnotherOperatorWithdraw(targetOperatorAddress: EthereumAddress, sponsorshipAddresses: EthereumAddress[]): Promise; getStakedOperators(): Promise; pullStakedStreams(requiredBlockNumber: number): AsyncGenerator<{ sponsorship: EthereumAddress; streamId: StreamID; }, undefined, undefined>; hasOpenFlag(sponsorshipAddress: EthereumAddress): Promise; getStreamId(sponsorshipAddress: EthereumAddress): Promise; voteOnFlag(sponsorshipAddress: EthereumAddress, targetOperator: EthereumAddress, kick: boolean): Promise; closeFlag(sponsorshipAddress: EthereumAddress, targetOperatorAddress: EthereumAddress): Promise; fetchRedundancyFactor(): Promise; getCurrentBlockNumber(): Promise; on(eventName: E, listener: OperatorEvents[E]): void; off(eventName: E, listener: OperatorEvents[E]): void; private connectToContract; } type SubscribeOptions = StreamDefinition & ExtraSubscribeOptions; interface ExtraSubscribeOptions { resend?: ResendOptions; /** * Subscribe raw with validation, permission checking, ordering, gap filling, * and decryption _disabled_. */ raw?: boolean; /** * Subscribe on behalf of a contract implementing the [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) standard. * The streamr client wallet address must be an authorized signer for the contract. */ erc1271Contract?: HexString; delivery?: StreamPartDeliveryOptions; } /** * The main API used to interact with Streamr. * * @category Important */ declare class StreamrClient { readonly id: string; private readonly publisher; private readonly subscriber; private readonly resends; private readonly node; private readonly rpcProviderSource; private readonly streamRegistry; private readonly streamStorageRegistry; private readonly storageNodeRegistry; private readonly operatorRegistry; private readonly contractFactory; private readonly localGroupKeyStore; private readonly chainEventPoller; private readonly theGraphClient; private readonly streamIdBuilder; private readonly config; private readonly identity; private readonly eventEmitter; private readonly destroySignal; private readonly loggerFactory; private readonly proxyNodeFinder; constructor(config?: StreamrClientConfig, /** @internal */ parentContainer?: tsyringe.DependencyContainer); /** * Publishes a message to a stream partition in the network. * * @category Important * * @param streamDefinition - the stream or stream partition to publish the message to * @param content - the content (the payload) of the message (must be JSON serializable) * @param metadata - provide additional metadata to be included in the message or to control the publishing process * @returns the published message (note: the field {@link Message.content} is encrypted if the stream is private) */ publish(streamDefinition: StreamDefinition, content: unknown, metadata?: PublishMetadata, deliveryOptions?: StreamPartDeliveryOptions): Promise; publishRaw(message: StreamMessage, deliveryOptions?: StreamPartDeliveryOptions): Promise; /** * Manually updates the encryption key used when publishing messages to a given stream. */ updateEncryptionKey(opts: UpdateEncryptionKeyOptions): Promise; /** * Adds an encryption key for a given publisher to the key store. * * @remarks Keys will be added to the store automatically by the client as encountered. This method can be used to * manually add some known keys into the store. */ addEncryptionKey(key: GroupKey, publisherId: HexString): Promise; /** * Subscribes to a stream partition in the network. * * @category Important * * @param options - the stream or stream partition to subscribe to, * additionally a resend can be performed by providing resend options * @param onMessage - callback will be invoked for each message received in subscription * @returns a {@link Subscription} that can be used to manage the subscription etc. */ subscribe(options: SubscribeOptions, onMessage?: MessageListener): Promise; /** * Unsubscribes from streams or stream partitions in the network. * * @remarks no-op if subscription does not exist * * @category Important * * @param streamDefinitionOrSubscription - leave as `undefined` to unsubscribe from all existing subscriptions. */ unsubscribe(streamDefinitionOrSubscription?: StreamDefinition | Subscription): Promise; /** * Returns a list of subscriptions matching the given criteria. * * @category Important * * @param streamDefinition - leave as `undefined` to get all subscriptions */ getSubscriptions(streamDefinition?: StreamDefinition): Promise; /** * Performs a resend of stored historical data. * * @category Important * * @param streamDefinition - the stream partition for which data should be resent * @param options - defines the kind of resend that should be performed * @param onMessage - callback will be invoked for each message retrieved * @returns a {@link MessageStream} that provides an alternative way of iterating messages. Rejects if the stream is * not stored (i.e. is not assigned to a storage node). */ resend(streamDefinition: StreamDefinition, options: ResendOptions, onMessage?: MessageListener): Promise; /** * Waits for a message to be stored by a storage node. * * @param message - the message to be awaited for * @param options - additional options for controlling waiting and message matching * @returns rejects if message was found in storage before timeout */ waitForStorage(message: Message, options?: { /** * Determines how often should storage node be polled. */ interval?: number; /** * Timeout after which to give up if message was not seen. */ timeout?: number; /** * Controls size of internal resend used in polling. */ count?: number; }): Promise; /** * Gets a stream. * * @category Important * * @returns rejects if the stream is not found */ getStream(streamIdOrPath: string): Promise; /** * Creates a new stream. * * @category Important * * @param propsOrStreamIdOrPath - the stream id to be used for the new stream, and optionally, any * associated metadata * * @remarks when creating a stream with an ENS domain, the returned promise can take several minutes to settle */ createStream(propsOrStreamIdOrPath: StreamMetadata & { id: string; } | string): Promise; /** * Gets a stream, creating one if it does not exist. * * @category Important * * @param props - the stream id to get or create. Field `partitions` is only used if creating the stream. * * @remarks when creating a stream with an ENS domain, the returned promise can take several minutes to settle */ getOrCreateStream(props: { id: string; partitions?: number; }): Promise; /** * Returns the metadata of a stream. */ getStreamMetadata(streamIdOrPath: string): Promise; /** * Updates the metadata of a stream. */ setStreamMetadata(streamIdOrPath: string, metadata: StreamMetadata): Promise; /** * Deletes a stream. */ deleteStream(streamIdOrPath: string): Promise; /** * Searches for streams based on given criteria. * * @param term - a search term that should be part of the stream id of a result * @param permissionFilter - permissions that should be in effect for a result */ searchStreams(term: string | undefined, permissionFilter: SearchStreamsPermissionFilter | undefined): AsyncIterable; /** * Gets all user ids that have {@link StreamPermission.PUBLISH} permission to the stream. */ getStreamPublishers(streamIdOrPath: string): AsyncIterable; /** * Gets all user ids that have {@link StreamPermission.SUBSCRIBE} permission to the stream. */ getStreamSubscribers(streamIdOrPath: string): AsyncIterable; /** * Checks whether the given permission is in effect. */ hasPermission(query: PermissionQuery): Promise; /** * Returns the list of all permissions in effect for a given stream. */ getPermissions(streamIdOrPath: string): Promise; /** * Grants permissions on a given stream. */ grantPermissions(streamIdOrPath: string, ...assignments: PermissionAssignment[]): Promise; /** * Revokes permissions on a given stream. */ revokePermissions(streamIdOrPath: string, ...assignments: PermissionAssignment[]): Promise; /** * Sets a list of permissions to be in effect. * * @remarks Can be used to set the permissions of multiple streams in one transaction. Great for doing bulk * operations and saving gas costs. Notice that the behaviour is overwriting, therefore any existing permissions not * defined will be removed (per stream). */ setPermissions(...items: { streamId: string; assignments: PermissionAssignment[]; }[]): Promise; /** * Checks whether a given userId has {@link StreamPermission.PUBLISH} permission to a stream. */ isStreamPublisher(streamIdOrPath: string, userId: HexString): Promise; /** * Checks whether a given userId has {@link StreamPermission.SUBSCRIBE} permission to a stream. */ isStreamSubscriber(streamIdOrPath: string, userId: HexString): Promise; /** * Assigns a stream to a storage node. * * @param opts - control how long to wait for storage node to pick up on assignment * @returns If opts.wait=true, the promise resolves when the storage node acknowledges the assignment and * is therefore ready to store published messages. If we don't receive the acknowledgment within the `timeout`, * the promise rejects, but the assignment may still succeed later. */ addStreamToStorageNode(streamIdOrPath: string, storageNodeAddress: HexString, opts?: { wait: boolean; timeout?: number; }): Promise; /** * Unassigns a stream from a storage node. */ removeStreamFromStorageNode(streamIdOrPath: string, storageNodeAddress: HexString): Promise; /** * Checks whether a stream is assigned to a storage node. */ isStoredStream(streamIdOrPath: string, storageNodeAddress: HexString): Promise; /** * Gets all streams assigned to a storage node. * * @returns a list of {@link Stream} as well as `blockNumber` of result (i.e. blockchain state) */ getStoredStreams(storageNodeAddress: HexString): Promise<{ streams: Stream[]; blockNumber: number; }>; /** * Gets a list of storage nodes. * * @param streamIdOrPath - if a stream is given, returns the list of storage nodes the stream has been assigned to; * leave as `undefined` to return all storage nodes */ getStorageNodes(streamIdOrPath?: string): Promise; /** * Sets the metadata of a storage node in the storage node registry. * * @remarks Acts on behalf of the wallet associated with the current {@link StreamrClient} instance. * * @param metadata - if `undefined`, removes the storage node from the registry */ setStorageNodeMetadata(metadata: StorageNodeMetadata | undefined): Promise; /** * Gets the metadata of a storage node from the storage node registry. * * @returns rejects if the storage node is not found */ getStorageNodeMetadata(storageNodeAddress: HexString): Promise; /** * Gets the Signer associated with the current {@link StreamrClient} instance. */ getSigner(): Promise; /** * Gets the user id (i.e. Ethereum address or public key) of the wallet associated with the current {@link StreamrClient} instance. */ getUserId(): Promise; /** * Alias to {@link getUserId|getUserId()} */ getAddress(): Promise; /** * @deprecated This in an internal method * @hidden */ getNode(): NetworkNodeFacade; inspect(node: NetworkPeerDescriptor, streamDefinition: StreamDefinition): Promise; setProxies(streamDefinition: StreamDefinition, nodes: NetworkPeerDescriptor[], direction?: ProxyDirection, connectionCount?: number): Promise; /** * Used to set known entry points for a stream partition. If entry points are not set they * will be automatically discovered from the Streamr Network. */ setStreamPartitionEntryPoints(streamDefinition: StreamDefinition, entryPoints: NetworkPeerDescriptor[]): Promise; /** * Used to manually initialize the network stack and connect to the network. * * @remarks Connecting is handled automatically by the client. Generally this method need not be called by the user. */ connect(): Promise; private _connect; /** * Destroys an instance of a {@link StreamrClient} by disconnecting from peers, clearing any pending tasks, and * freeing up resources. This should be called once a user is done with the instance. * * @remarks As the name implies, the client instance (or any streams or subscriptions returned by it) should _not_ * be used after calling this method. */ destroy(): Promise; private _destroy; getPeerDescriptor(): Promise; /** * Get the network-level node id of the client. */ getNodeId(): Promise; /** * Get diagnostic info about the underlying network. Useful for debugging issues. * * @remarks returned object's structure can change without semver considerations */ getDiagnosticInfo(): Promise>; /** * @deprecated This in an internal method * @hidden */ getConfig(): StrictStreamrClientConfig; /** * @deprecated This in an internal method * @hidden */ getTheGraphClient(): TheGraphClient; /** * Get overrides for transaction options. Use as a parameter when submitting * transactions via ethers library. * * The {@link https://docs.ethers.org/v6/api/contract/#Overrides Overrides} type is from the `ethers` library. */ getEthersOverrides(): Promise; /** * @deprecated This in an internal method * @hidden */ getOperator(operatorContractAddress: EthereumAddress): Operator; findProxyNodes(streamDefinition: StreamDefinition, numberOfProxies?: number, maxQueryResults?: number, maxHeartbeatAgeHours?: number): Promise; /** * Adds an event listener to the client. * @param eventName - event name, see {@link StreamrClientEvents} for options * @param listener - the callback function */ on(eventName: T, listener: StreamrClientEvents[T]): void; /** * Adds an event listener to the client that is invoked only once. * @param eventName - event name, see {@link StreamrClientEvents} for options * @param listener - the callback function */ once(eventName: T, listener: StreamrClientEvents[T]): void; /** * Removes an event listener from the client. * @param eventName - event name, see {@link StreamrClientEvents} for options * @param listener - the callback function to remove */ off(eventName: T, listener: StreamrClientEvents[T]): void; } declare const DEFAULT_KEY_TYPE: KeyType; declare function formStorageNodeAssignmentStreamId(clusterAddress: string): StreamID; declare function peerDescriptorTranslator(json: NetworkPeerDescriptor): PeerDescriptor; /** * KeyPairIdentity is an Identity that is defined by a public key and a private key. * It uses the public key as the UserID. */ declare abstract class KeyPairIdentity extends Identity { protected readonly publicKeyString: UserID; protected readonly publicKey: UserIDRaw; protected readonly privateKey: Uint8Array; constructor(publicKey: Uint8Array, privateKey: Uint8Array); abstract assertValidKeyPair(): void; getUserIdRaw(): Promise; getUserId(): Promise; getPrivateKey(): Promise; getTransactionSigner(_rpcProviderSource: RpcProviderSource): Promise; } /** * An Identity that derives an Ethereum address from a secp256k1 private key * and uses that as the UserID instead of the actual public key. */ declare class EthereumKeyPairIdentity extends KeyPairIdentity { assertValidKeyPair(): void; getSignatureType(): SignatureType; createMessageSignature(payload: Uint8Array): Promise; getTransactionSigner(rpcProviderSource: RpcProviderSource): Promise; static fromPrivateKey(privateKey: HexString, address?: HexString): EthereumKeyPairIdentity; static generate(): EthereumKeyPairIdentity; } /** * An identity that uses an Ethereum provider (= external wallet) to sign messages */ declare class EthereumProviderIdentity extends Identity { private provider; private expectedChainId; private signer; private cachedUserIdString; private cachedUserIdBytes; private rateLimitedSigner; constructor(provider: JsonRpcApiProvider, expectedChainId: number | undefined); getUserIdRaw(): Promise; getUserId(): Promise; getSignatureType(): SignatureType; createMessageSignature(payload: Uint8Array): Promise; getTransactionSigner(): Promise; } /** * An identity that uses a quantum-resistant ML-DSA-87 key pair to sign messages. */ declare class MLDSAKeyPairIdentity extends KeyPairIdentity { assertValidKeyPair(): void; getSignatureType(): SignatureType; createMessageSignature(payload: Uint8Array): Promise; static generate(): MLDSAKeyPairIdentity; } /** * An identity that uses ECDSA on the SECP256R1 curve */ declare class ECDSAKeyPairIdentity extends KeyPairIdentity { private cachedJWK; assertValidKeyPair(): void; getSignatureType(): SignatureType; createMessageSignature(payload: Uint8Array): Promise; static generate(): ECDSAKeyPairIdentity; } declare function convertStreamMessageToBytes(oldStreamMessage: StreamMessage): Uint8Array; declare function convertBytesToStreamMessage(bytes: Uint8Array): StreamMessage; /** * @deprecated * @hidden */ interface DeployOperatorContractOpts { deployer: SignerWithProvider; operatorsCutPercentage?: number; metadata?: string; operatorTokenName?: string; environmentId: EnvironmentId; transactionTimeout?: number; } /** * @deprecated * @hidden */ interface TransactionOpts { gasLimit?: BigNumberish; gasPrice?: BigNumberish; nonce?: number; } /** * @param opts.deployer should be the operator's Wallet * @returns Operator */ declare function deployOperatorContract(opts: DeployOperatorContractOpts): Promise; /** * @deprecated * @hidden */ interface DeploySponsorshipContractOpts { streamId: string; deployer: SignerWithProvider; metadata?: string; earningsPerSecond: WeiAmount; minOperatorCount?: number; maxOperatorCount?: number; minStakeDuration?: number; environmentId: EnvironmentId; sponsorAmount?: WeiAmount; transactionTimeout?: number; } declare function deploySponsorshipContract(opts: DeploySponsorshipContractOpts): Promise; /** * @deprecated * @hidden */ declare const _operatorContractUtils: { delegate: (delegator: SignerWithProvider, operatorContractAddress: string, amount: _streamr_utils.WeiAmount, transactionTimeout?: number) => Promise; undelegate: (delegator: SignerWithProvider, operatorContractAddress: string, amount: _streamr_utils.WeiAmount, transactionTimeout?: number) => Promise; deploySponsorshipContract: typeof deploySponsorshipContract; sponsor: (sponsorer: SignerWithProvider, sponsorshipContractAddress: string, amount: _streamr_utils.WeiAmount, transactionTimeout?: number) => Promise; stake: (staker: SignerWithProvider, operatorContractAddress: string, sponsorshipContractAddress: string, amount: _streamr_utils.WeiAmount, txOpts?: TransactionOpts, onSubmit?: (tx: ethers.ContractTransactionResponse) => void, transactionTimeout?: number) => Promise; unstake: (staker: SignerWithProvider, operatorContractAddress: string, sponsorshipContractAddress: string, amount: _streamr_utils.WeiAmount, txOpts?: TransactionOpts, onSubmit?: (tx: ethers.ContractTransactionResponse) => void, transactionTimeout?: number) => Promise; deployOperatorContract: typeof deployOperatorContract; getOperatorContract: (operatorAddress: string) => _streamr_network_contracts.Operator; }; export { ConfigInjectionToken, DEFAULT_ENVIRONMENT_ID, DEFAULT_KEY_TYPE, ECDSAKeyPairIdentity, ENVIRONMENT_IDS, GroupKey as EncryptionKey, EthereumKeyPairIdentity, EthereumProviderIdentity, Identity, KeyPairIdentity, MLDSAKeyPairIdentity, MessageID, MessageRef, MessageSigner, MessageStream, NetworkNodeType, Operator, RpcProviderSource, STREAMR_STORAGE_NODE_ADDRESS, STREAMR_STORAGE_NODE_GERMANY, Stream, StreamMessage, StreamMessageType, StreamPermission, StreamrClient, Subscription, _operatorContractUtils, convertBytesToStreamMessage, convertStreamMessageToBytes, formStorageNodeAssignmentStreamId, getPartitionCount as getStreamPartitionCount, parseMetadata as parseStreamMetadata, peerDescriptorTranslator }; export type { ConnectionInfo, ConnectivityMethod, ControlLayerConfig, CustomIdentityConfig, DeployOperatorContractOpts, DeploySponsorshipContractOpts, EntryPointDiscovery, EnvironmentId, EthereumNetworkConfig, EthereumProviderIdentityConfig, ExtraSubscribeOptions, Flag, GapFillStrategy, GetOperatorSponsorshipsResult, IdentityConfig, KeyPairIdentityConfig, Message, MessageListener, MessageMetadata, MessageSignatureType, NetworkConfig, NetworkNodeConfig, NetworkPeerDescriptor, OperatorEvents, PermissionAssignment, PermissionQuery, PublicPermissionAssignment, PublicPermissionQuery, PublishMetadata, ResendFromOptions, ResendLastOptions, ResendOptions, ResendRangeOptions, ResendRef, ReviewRequestEvent, SearchStreamsPermissionFilter, SignerWithProvider, SponsorshipCreatedEvent, StakeEvent, StorageNodeAssignmentEvent, StorageNodeMetadata, StreamCreationEvent, StreamDefinition, StreamMessageAESEncrypted, StreamMessageOptions, StreamMetadata, StreamrClientConfig, StreamrClientEvents, StrictStreamrClientConfig, SubscribeOptions, SubscriptionEvents, TransactionOpts, UpdateEncryptionKeyOptions, UserPermissionAssignment, UserPermissionQuery };