@xmtp/node-sdk
Version:
XMTP Node client SDK for interacting with XMTP networks
1,221 lines (1,201 loc) • 73.8 kB
TypeScript
import { ContentCodec, ContentTypeId } from '@xmtp/content-type-primitives';
import * as _xmtp_node_bindings from '@xmtp/node-bindings';
import { ContentTypeId as ContentTypeId$1, DeliveryStatus, GroupMessageKind, Reaction, DecodedMessage as DecodedMessage$1, LeaveRequest, ReadReceipt, Attachment, RemoteAttachment, TransactionReference, WalletSendCalls, Actions, Intent, MultiRemoteAttachment, GroupUpdated, DeletedMessage, Backend, LogLevel, WorkerConfigOptions, VisibilityConfirmationOptions, XmtpEnv as XmtpEnv$1, Identifier, StreamCloser, Conversation as Conversation$1, Message, EncodedContent, SendMessageOpts, SendOpts, Reply, ListMessagesOptions, ConsentState, PermissionUpdateType, PermissionPolicy, MetadataField, Conversations as Conversations$1, CreateGroupOptions, CreateDmOptions, ListConversationsOptions, ConversationType, Client as Client$1, Consent, ConsentEntityType, UserPreferenceUpdate, SignatureRequestHandle, InboxState, ArchiveOptions, AvailableArchiveInfo, ArchiveMetadata, GroupSyncSummary } from '@xmtp/node-bindings';
export { Action, ActionStyle, Actions, ApiStats, ArchiveMetadata, ArchiveOptions, Attachment, AvailableArchiveInfo, Backend, BackendBuilder, BackupElementSelectionOption, Consent, ConsentEntityType, ConsentState, ContentType, ConversationDebugInfo, ConversationListItem, ConversationType, CreateDmOptions, CreateGroupOptions, Cursor, DeliveryStatus, EncryptedAttachment, GroupMember, GroupMembershipState, GroupMessageKind, GroupMetadata, GroupPermissions, GroupPermissionsOptions, GroupSyncSummary, GroupUpdated, HmacKey, Identifier, IdentifierKind, IdentityStats, Inbox, InboxState, Installation, Intent, KeyPackageStatus, LeaveRequest, Lifetime, ListConversationsOptions, ListConversationsOrderBy, ListMessagesOptions, LogLevel, LogOptions, Message, MessageDisappearingSettings, MessageSortBy, MetadataField, MetadataFieldChange, MultiRemoteAttachment, PermissionLevel, PermissionPolicy, PermissionPolicySet, PermissionUpdateType, Reaction, ReactionAction, ReactionSchema, ReadReceipt, RemoteAttachment, Reply, SendMessageOpts, SendOpts, SignatureRequestHandle, SortDirection, TransactionMetadata, TransactionReference, UserPreferenceUpdate, VisibilityConfirmationOptions, WalletCall, WalletSendCalls, WorkerConfigOptions, WorkerIntervalOverride, WorkerJitterOverride, WorkerKind, contentTypeActions, contentTypeAttachment, contentTypeGroupUpdated, contentTypeIntent, contentTypeLeaveRequest, contentTypeMarkdown, contentTypeMultiRemoteAttachment, contentTypeReaction, contentTypeReadReceipt, contentTypeRemoteAttachment, contentTypeReply, contentTypeText, contentTypeTransactionReference, contentTypeWalletSendCalls, decryptAttachment, encodeActions, encodeAttachment, encodeIntent, encodeMarkdown, encodeMultiRemoteAttachment, encodeReaction, encodeReadReceipt, encodeRemoteAttachment, encodeText, encodeTransactionReference, encodeWalletSendCalls, encryptAttachment, flushTelemetry, initLogging } from '@xmtp/node-bindings';
/**
* Pre-configured URLs for the XMTP network based on the environment
*
* @deprecated Use `createBackend()` instead.
* @constant
* @property {string} local - The local URL for the XMTP network
* @property {string} dev - The development URL for the XMTP network
* @property {string} production - The production URL for the XMTP network
*/
declare const ApiUrls: {
readonly local: "http://localhost:5556";
readonly dev: "https://grpc.dev.xmtp.network:443";
readonly production: "https://grpc.production.xmtp.network:443";
};
/**
* Pre-configured URLs for the XMTP history sync service based on the environment
*
* @constant
* @property {string} local - The local URL for the XMTP history sync service
* @property {string} dev - The development URL for the XMTP history sync service
* @property {string} production - The production URL for the XMTP history sync service
*/
declare const HistorySyncUrls: {
readonly local: "http://localhost:5558";
readonly dev: "https://message-history.dev.ephemera.network";
readonly production: "https://message-history.production.ephemera.network";
readonly "testnet-staging": "https://message-history.dev.ephemera.network";
readonly "testnet-dev": "https://message-history.dev.ephemera.network";
readonly testnet: "https://message-history.dev.ephemera.network";
readonly mainnet: "https://message-history.production.ephemera.network";
};
declare class CodecRegistry {
#private;
constructor(codecs: ContentCodec[]);
/**
* Gets the codec for a given content type
*
* @param contentType - The content type to get the codec for
* @returns The codec, if found
*/
getCodec<ContentType = unknown>(contentType: ContentTypeId): ContentCodec<ContentType> | undefined;
}
/**
* Represents a decoded XMTP message
*
* @class
* @property {unknown} content - The decoded content of the message
* @property {ContentTypeId} contentType - The content type of the message content
* @property {string} conversationId - Unique identifier for the conversation
* @property {MessageDeliveryStatus} deliveryStatus - Current delivery status of the message ("unpublished" | "published" | "failed")
* @property {bigint} expiresAtNs - Timestamp when the message will expire (in nanoseconds)
* @property {Date} expiresAt - Timestamp when the message will expire
* @property {string} [fallback] - Optional fallback text for the message
* @property {string} id - Unique identifier for the message
* @property {MessageKind} kind - Type of message ("application" | "membership_change")
* @property {number} numReplies - Number of replies to the message
* @property {DecodedMessage<Reaction>[]} reactions - Reactions to the message
* @property {string} senderInboxId - Identifier for the sender's inbox
* @property {Date} sentAt - Timestamp when the message was sent
* @property {bigint} sentAtNs - Timestamp when the message was sent (in nanoseconds)
*/
declare class DecodedMessage<ContentTypes = unknown> {
content: ContentTypes | undefined;
contentType: ContentTypeId$1;
conversationId: string;
deliveryStatus: DeliveryStatus;
expiresAtNs?: bigint;
expiresAt?: Date;
fallback?: string;
id: string;
kind: GroupMessageKind;
numReplies: number;
reactions: DecodedMessage<Reaction>[];
senderInboxId: string;
sentAt: Date;
sentAtNs: bigint;
constructor(codecRegistry: CodecRegistry, message: DecodedMessage$1);
}
type HexString = `0x${string}`;
declare function isHexString(value: unknown): value is HexString;
declare function validHex(value: unknown): HexString;
/**
* XMTP environment
*/
type XmtpEnv = "local" | "dev" | "production" | "testnet-staging" | "testnet-dev" | "testnet" | "mainnet";
/**
* Network options
*/
type NetworkOptions = {
/**
* Specify which XMTP environment to connect to. (default: `dev`)
*
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-a-client#xmtp-network-environments
*/
env?: XmtpEnv;
/**
* apiUrl can be used to override the `env` flag and connect to a
* specific endpoint
*/
apiUrl?: string;
/**
* The host of the XMTP Gateway for your application
*
* Only valid for `dev` and `production` environments
*
* @see https://docs.xmtp.org/fund-agents-apps/run-gateway
*/
gatewayHost?: string;
/**
* Custom app version
*/
appVersion?: string;
};
/**
* Device sync options
*/
type DeviceSyncOptions = {
/**
* historySyncUrl can be used to override the `env` flag and connect to a
* specific endpoint for syncing history
*
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/history-sync
*/
historySyncUrl?: string | null;
/**
* Disable device sync
*/
disableDeviceSync?: boolean;
};
/**
* Storage options
*/
type StorageOptions = {
/**
* Path to the local DB
*
* There are 4 value types that can be used to specify the database path:
*
* - `undefined` (or excluded from the client options)
* The database will be created in the current working directory and is based on
* the XMTP environment and client inbox ID.
* Example: `xmtp-dev-<inbox-id>.db3`
*
* - `null`
* No database will be created and all data will be lost once the client disconnects.
*
* - `string`
* The given path will be used to create the database.
* Example: `./my-db.db3`
*
* - `function`
* A callback function that receives the inbox ID and returns a string path.
* Example: `(inboxId) => string`
*/
dbPath?: string | null | ((inboxId: string) => string);
/**
* Encryption key for the local DB (32 bytes, hex)
*
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-a-client#view-an-encrypted-database
*/
dbEncryptionKey?: Uint8Array | HexString;
/**
* Maximum number of connections in the local DB connection pool.
*
* Defaults to 25 when unset. Ignored when `useSingleConnection` is `true`.
*/
maxDbPoolSize?: number;
/**
* Minimum number of connections kept warm in the local DB connection pool.
*
* Defaults to 5 when unset. Ignored when `useSingleConnection` is `true`.
*/
minDbPoolSize?: number;
/**
* When `true`, the native DB uses a single connection (one file descriptor)
* instead of a pool. The pool-size options above are ignored. Intended for
* services running many clients in one process.
*
* Defaults to `false` (pooled).
*/
useSingleConnection?: boolean;
};
type ContentOptions = {
/**
* Allow configuring codecs for additional content types
*/
codecs?: ContentCodec[];
};
type OtherOptions = {
/**
* Enable structured JSON logging
*/
structuredLogging?: boolean;
/**
* Logging level. Also the level exported to OTLP when `otelEndpoint` is set.
*/
loggingLevel?: LogLevel;
/**
* Level for the stdout console layer only. Defaults to `loggingLevel`. Set to
* `LogLevel.Warn` to quiet stdout below the OTLP export level — e.g. so a log
* shipper does not duplicate logs already exported via OTLP, while OTLP still
* receives `loggingLevel`.
*/
stdoutLoggingLevel?: LogLevel;
/**
* OTLP endpoint (e.g. `"http://collector:4317"`) for exporting telemetry
* spans and logs. When set, spans (and `tracing` events as correlated logs)
* are exported via OTLP to this endpoint, where a downstream OpenTelemetry
* Collector can derive metrics from the spans and forward the logs.
*
* Call {@link flushTelemetry} on graceful shutdown to flush buffered spans.
*/
otelEndpoint?: string;
/**
* Resource attributes attached to all exported telemetry spans
* (e.g. `{ "service.instance.id": "herald-7", "deployment.environment": "prod" }`).
* Use these to attribute telemetry to its source.
*/
resourceAttributes?: Record<string, string>;
/**
* Tuning for the background worker scheduler (intervals, jitter, per-worker
* overrides, and disabled workers). All fields are optional; omitting this
* object preserves the default worker behavior.
*
* Intervals are specified in nanoseconds.
*/
workerConfig?: WorkerConfigOptions;
/**
* Disable automatic registration when creating a client
*/
disableAutoRegister?: boolean;
/**
* The nonce to use when generating an inbox ID
* (default: undefined = 1)
*/
nonce?: bigint;
/**
* Options for waiting until client registration is visible on the network.
*
* When set, `registerIdentity` will wait for the specified quorum of nodes
* to confirm the registration before resolving.
*/
waitForRegistrationVisible?: VisibilityConfirmationOptions;
};
type ClientOptions = (NetworkOptions | {
backend: Backend;
}) & DeviceSyncOptions & StorageOptions & ContentOptions & OtherOptions;
/**
* `Omit` that distributes over unions. The built-in `Omit` collapses a union
* (e.g. `ClientOptions`' `NetworkOptions | { backend }` arm) because
* `keyof (A | B)` only yields shared keys. This preserves each arm, so options
* like `{ backend }` survive `Omit<ClientOptions, "codecs">`.
*/
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type EnrichedReply<T = unknown, U = unknown> = {
referenceId: string;
content: T;
contentType: ContentTypeId$1 | undefined;
inReplyTo: DecodedMessage<U> | null;
};
type BuiltInContentTypes = string | LeaveRequest | Reaction | ReadReceipt | Attachment | RemoteAttachment | TransactionReference | WalletSendCalls | Actions | Intent | MultiRemoteAttachment | GroupUpdated | DeletedMessage;
type ExtractCodecContentTypes<C extends ContentCodec[] = []> = C extends readonly [] ? BuiltInContentTypes : [...C][number] extends ContentCodec<infer T> ? T | BuiltInContentTypes | EnrichedReply<T | BuiltInContentTypes, T | BuiltInContentTypes> : BuiltInContentTypes;
declare const envToString: (env: XmtpEnv$1) => XmtpEnv;
declare const createBackend: (options?: NetworkOptions) => Promise<Backend>;
declare class InboxReassignError extends Error {
constructor();
}
declare class AccountAlreadyAssociatedError extends Error {
constructor(inboxId: string);
}
declare class MissingContentTypeError extends Error {
constructor();
}
declare class SignerUnavailableError extends Error {
constructor();
}
declare class ClientNotInitializedError extends Error {
constructor();
}
declare class StreamFailedError extends Error {
constructor(retryAttempts: number);
}
declare class StreamInvalidRetryAttemptsError extends Error {
constructor();
}
declare const generateInboxId: (identifier: Identifier, nonce?: bigint) => string;
declare const getInboxIdForIdentifier: (backend: Backend, identifier: Identifier) => Promise<string | null>;
type SignMessage = (message: string) => Promise<Uint8Array> | Uint8Array;
type GetIdentifier = () => Promise<Identifier> | Identifier;
type GetChainId = () => bigint;
type GetBlockNumber = () => bigint;
type Signer = {
type: "EOA";
signMessage: SignMessage;
getIdentifier: GetIdentifier;
} | {
type: "SCW";
signMessage: SignMessage;
getIdentifier: GetIdentifier;
getBlockNumber?: GetBlockNumber;
getChainId: GetChainId;
};
type EOASigner = Extract<Signer, {
type: "EOA";
}>;
type SCWSigner = Extract<Signer, {
type: "SCW";
}>;
type ResolveValue<T> = {
value: T;
done: boolean;
};
interface AsyncStreamProxy<T> extends AsyncIterable<T> {
next(): Promise<ResolveValue<T>>;
return(): Promise<ResolveValue<undefined>>;
end(): Promise<ResolveValue<undefined>>;
isDone: boolean;
}
declare const DEFAULT_RETRY_DELAY = 60000;
declare const DEFAULT_RETRY_ATTEMPTS = 10;
type StreamOptions<T = unknown, V = T> = {
/**
* Called when the stream ends
*/
onEnd?: () => void;
/**
* Called when a stream error occurs
*/
onError?: (error: Error) => void;
/**
* Called when the stream fails
*/
onFail?: () => void;
/**
* Called when the stream is restarted
*/
onRestart?: () => void;
/**
* Called when the stream is retried
*/
onRetry?: (attempts: number, maxAttempts: number) => void;
/**
* Called when a value is emitted from the stream
*/
onValue?: (value: V) => void;
/**
* The number of times to retry the stream
* (default: 10)
*/
retryAttempts?: number;
/**
* The delay between retries (in milliseconds)
* (default: 60000)
*/
retryDelay?: number;
/**
* Whether to retry the stream if it fails
* (default: true)
*/
retryOnFail?: boolean;
/**
* Whether to disable network sync before starting the stream
* (default: false)
*/
disableSync?: boolean;
};
type StreamCallback<T = unknown> = (error: Error | null, value: T | undefined) => void;
type StreamFunction<T = unknown> = (callback: StreamCallback<T>, onFail: () => void) => Promise<StreamCloser>;
type StreamValueMutator<T = unknown, V = T> = (value: T) => V | Promise<V>;
/**
* Creates a stream from a stream function
*
* If the stream fails, an attempt will be made to restart it.
*
* This function is not intended to be used directly.
*
* @param streamFunction - The stream function to create a stream from
* @param streamValueMutator - An optional function to mutate the value emitted from the stream
* @param options - The options for the stream
* @param args - Additional arguments to pass to the stream function
* @returns An async iterable stream proxy
* @throws {StreamInvalidRetryAttemptsError} if the retryAttempts option is less than 0 and retryOnFail is true
* @throws {StreamFailedError} if the stream fails and can't be restarted
*/
declare const createStream: <T = unknown, V = T>(streamFunction: StreamFunction<T>, streamValueMutator?: StreamValueMutator<T, V | undefined>, options?: StreamOptions<T, V>) => Promise<AsyncStreamProxy<V>>;
declare const isReaction: (m: DecodedMessage) => m is DecodedMessage<Reaction>;
declare const isReply: (m: DecodedMessage) => m is DecodedMessage<EnrichedReply>;
declare const isTextReply: (m: DecodedMessage) => m is DecodedMessage<EnrichedReply<string>>;
declare const isText: (m: DecodedMessage) => m is DecodedMessage<string>;
declare const isRemoteAttachment: (m: DecodedMessage) => m is DecodedMessage<RemoteAttachment>;
declare const isAttachment: (m: DecodedMessage) => m is DecodedMessage<Attachment>;
declare const isMultiRemoteAttachment: (m: DecodedMessage) => m is DecodedMessage<MultiRemoteAttachment>;
declare const isTransactionReference: (m: DecodedMessage) => m is DecodedMessage<TransactionReference>;
declare const isGroupUpdated: (m: DecodedMessage) => m is DecodedMessage<GroupUpdated>;
declare const isReadReceipt: (m: DecodedMessage) => m is DecodedMessage<ReadReceipt>;
declare const isLeaveRequest: (m: DecodedMessage) => m is DecodedMessage<LeaveRequest>;
declare const isWalletSendCalls: (m: DecodedMessage) => m is DecodedMessage<WalletSendCalls>;
declare const isIntent: (m: DecodedMessage) => m is DecodedMessage<Intent>;
declare const isActions: (m: DecodedMessage) => m is DecodedMessage<Actions>;
declare const isMarkdown: (m: DecodedMessage) => m is DecodedMessage<string>;
/**
* Represents a conversation
*
* This class is not intended to be initialized directly.
*/
declare class Conversation<ContentTypes = unknown> {
#private;
/**
* Creates a new conversation instance
*
* @param client - The client instance managing the conversation
* @param codecRegistry - The codec registry instance
* @param conversation - The underlying conversation instance
*/
constructor(client: Client<ContentTypes>, codecRegistry: CodecRegistry, conversation: Conversation$1);
/**
* Gets the unique identifier for this conversation
*/
get id(): string;
/**
* Gets whether this conversation is currently active
*/
get isActive(): boolean;
/**
* Gets the inbox ID that added this client's inbox to the conversation
*/
get addedByInboxId(): string;
/**
* Gets the timestamp when the conversation was created in nanoseconds
*/
get createdAtNs(): bigint;
/**
* Gets the date when the conversation was created
*/
get createdAt(): Date;
get topic(): string;
pausedForVersion(): string | undefined;
/**
* Gets HMAC keys for this conversation
*
* @returns The HMAC keys for this conversation
*/
hmacKeys(): Record<string, _xmtp_node_bindings.HmacKey[]>;
/**
* Gets the metadata for this conversation
*
* @returns Promise that resolves with the conversation metadata
*/
metadata(): Promise<{
creatorInboxId: string;
conversationType: _xmtp_node_bindings.ConversationType;
}>;
/**
* Gets the members of this conversation
*
* @returns Promise that resolves with the conversation members
*/
members(): Promise<_xmtp_node_bindings.GroupMember[]>;
/**
* Synchronizes conversation data from the network
*
* @returns Promise that resolves when synchronization is complete
*/
sync(): Promise<void>;
/**
* Creates a stream for new messages in this conversation
*
* @param options - Optional stream options
* @returns Stream instance for new messages
*/
stream(options?: StreamOptions<Message, DecodedMessage<ContentTypes>>): Promise<AsyncStreamProxy<DecodedMessage<ContentTypes>>>;
/**
* Decodes, decrypts, and persists a raw envelope from a group message stream.
*
* @param envelopeBytes - Raw protobuf-encoded envelope bytes from the stream
* @returns The processed and stored messages
*/
processStreamedMessage(envelopeBytes: Uint8Array): Promise<Message[]>;
/**
* Publishes pending messages that were sent optimistically
*
* @returns Promise that resolves when publishing is complete
*/
publishMessages(): Promise<void>;
/**
* Sends a message with configurable delivery behavior
*
* @param encodedContent - The encoded content to send
* @param sendOptions - Options for sending the message
* @param sendOptions.shouldPush - Indicates whether this message should be
* included in push notifications
* @param sendOptions.optimistic - Indicates whether this message should be
* sent optimistically and published later via `publishMessages`
* @param sendOptions.idempotencyKey - Optional idempotency key; re-sending
* identical content with the same key produces the same deduplicated message id
* @returns Promise that resolves with the message ID after it has been sent
*/
send(encodedContent: EncodedContent, sendOptions?: SendMessageOpts): Promise<string>;
/**
* Sends a text message
*
* @param text - The text to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendText(text: string, opts?: SendOpts): Promise<string>;
/**
* Sends a markdown message
*
* @param markdown - The markdown to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendMarkdown(markdown: string, opts?: SendOpts): Promise<string>;
/**
* Sends a reaction message
*
* @param reaction - The reaction to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendReaction(reaction: Reaction, opts?: SendOpts): Promise<string>;
/**
* Sends a read receipt message
*
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendReadReceipt(opts?: SendOpts): Promise<string>;
/**
* Sends a reply message
*
* @param reply - The reply to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendReply(reply: Reply, opts?: SendOpts): Promise<string>;
/**
* Sends a transaction reference message
*
* @param transactionReference - The transaction reference to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendTransactionReference(transactionReference: TransactionReference, opts?: SendOpts): Promise<string>;
/**
* Sends a wallet send calls message
*
* @param walletSendCalls - The wallet send calls to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendWalletSendCalls(walletSendCalls: WalletSendCalls, opts?: SendOpts): Promise<string>;
/**
* Sends a actions message
*
* @param actions - The actions to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendActions(actions: Actions, opts?: SendOpts): Promise<string>;
/**
* Sends a intent message
*
* @param intent - The intent to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendIntent(intent: Intent, opts?: SendOpts): Promise<string>;
/**
* Sends an attachment message
*
* @param attachment - The attachment to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendAttachment(attachment: Attachment, opts?: SendOpts): Promise<string>;
/**
* Sends a multi remote attachment message
*
* @param multiRemoteAttachment - The multi remote attachment to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendMultiRemoteAttachment(multiRemoteAttachment: MultiRemoteAttachment, opts?: SendOpts): Promise<string>;
/**
* Sends a remote attachment message
*
* @param remoteAttachment - The remote attachment to send
* @param opts - Send options (optimistic delivery, idempotency key)
* @returns Promise that resolves with the message ID after it has been sent
*/
sendRemoteAttachment(remoteAttachment: RemoteAttachment, opts?: SendOpts): Promise<string>;
/**
* Lists messages in this conversation
*
* @param options - Optional filtering and pagination options
* @returns Promise that resolves with an array of decoded messages
*/
messages(options?: ListMessagesOptions): Promise<DecodedMessage<ContentTypes>[]>;
/**
* Counts messages in this conversation
*
* @param options - Optional filtering options
* @returns Promise that resolves with the count of messages
*/
countMessages(options?: Omit<ListMessagesOptions, "limit" | "direction">): Promise<number>;
/**
* Gets the last message in this conversation
*
* @returns Promise that resolves with the last message or undefined if none exists
*/
lastMessage(): Promise<DecodedMessage<ContentTypes> | undefined>;
/**
* Gets the consent state for this conversation
*/
consentState(): ConsentState;
/**
* Updates the consent state for this conversation
*
* @param consentState - The new consent state to set
*/
updateConsentState(consentState: ConsentState): void;
/**
* Gets the message disappearing settings for this conversation
*
* @returns The current message disappearing settings or undefined if not set
*/
messageDisappearingSettings(): _xmtp_node_bindings.MessageDisappearingSettings | undefined;
/**
* Updates message disappearing settings for this conversation
*
* @param fromNs - The timestamp from which messages should start disappearing
* @param inNs - The duration after which messages should disappear
* @returns Promise that resolves when the update is complete
*/
updateMessageDisappearingSettings(fromNs: bigint, inNs: bigint): Promise<void>;
/**
* Removes message disappearing settings from this conversation
*
* @returns Promise that resolves when the settings are removed
*/
removeMessageDisappearingSettings(): Promise<void>;
/**
* Checks if message disappearing is enabled for this conversation
*
* @returns Whether message disappearing is enabled
*/
isMessageDisappearingEnabled(): boolean;
/**
* Retrieves information for this conversation to help with debugging
*
* @returns The debug information for this conversation
*/
debugInfo(): Promise<_xmtp_node_bindings.ConversationDebugInfo>;
/**
* Retrieves the last read times for this conversation
*
* @returns A map keyed by inbox ID with the last read timestamp
* (nanoseconds since epoch)
*/
lastReadTimes(): Promise<Record<string, number>>;
}
/**
* Represents a direct message conversation between two inboxes
*
* This class is not intended to be initialized directly.
*/
declare class Dm<ContentTypes = unknown> extends Conversation<ContentTypes> {
#private;
/**
* Creates a new direct message conversation instance
*
* @param client - The client instance managing this direct message conversation
* @param codecRegistry - The codec registry instance
* @param conversation - The underlying conversation instance
*/
constructor(client: Client<ContentTypes>, codecRegistry: CodecRegistry, conversation: Conversation$1);
/**
* Retrieves the inbox ID of the other participant in the DM
*
* @returns Promise that resolves with the peer's inbox ID
*/
get peerInboxId(): string;
duplicateDms(): Promise<Dm<ContentTypes>[]>;
}
/**
* Represents a group conversation between multiple inboxes
*
* This class is not intended to be initialized directly.
*/
declare class Group<ContentTypes = unknown> extends Conversation<ContentTypes> {
#private;
/**
* Creates a new group conversation instance
*
* @param client - The client instance managing this group conversation
* @param codecRegistry - The codec registry instance
* @param conversation - The underlying conversation object
*/
constructor(client: Client<ContentTypes>, codecRegistry: CodecRegistry, conversation: Conversation$1);
/**
* The name of the group
*/
get name(): string;
/**
* Updates the group's name
*
* @param name The new name for the group
*/
updateName(name: string): Promise<void>;
/**
* The image URL of the group
*/
get imageUrl(): string;
/**
* Updates the group's image URL
*
* @param imageUrl The new image URL for the group
*/
updateImageUrl(imageUrl: string): Promise<void>;
/**
* The description of the group
*/
get description(): string;
/**
* Updates the group's description
*
* @param description The new description for the group
*/
updateDescription(description: string): Promise<void>;
/**
* The app data of the group
*/
get appData(): string;
/**
* Updates the group's app data (max 8192 bytes)
*
* @param appData The new app data for the group
*/
updateAppData(appData: string): Promise<void>;
/**
* The permissions of the group
*/
permissions(): {
policyType: _xmtp_node_bindings.GroupPermissionsOptions;
policySet: _xmtp_node_bindings.PermissionPolicySet;
};
/**
* Updates a specific permission policy for the group
*
* @param permissionType The type of permission to update
* @param policy The new permission policy
* @param metadataField Optional metadata field for the permission
*/
updatePermission(permissionType: PermissionUpdateType, policy: PermissionPolicy, metadataField?: MetadataField): Promise<void>;
/**
* The list of admins of the group
*/
listAdmins(): string[];
/**
* The list of super admins of the group
*/
listSuperAdmins(): string[];
/**
* Checks if an inbox is an admin of the group
*
* @param inboxId The inbox ID to check
* @returns Boolean indicating if the inbox is an admin
*/
isAdmin(inboxId: string): boolean;
/**
* Checks if an inbox is a super admin of the group
*
* @param inboxId The inbox ID to check
* @returns Boolean indicating if the inbox is a super admin
*/
isSuperAdmin(inboxId: string): boolean;
/**
* Adds members to the group using identifiers
*
* @param identifiers Array of member identifiers to add
*/
addMembersByIdentifiers(identifiers: Identifier[]): Promise<void>;
/**
* Adds members to the group using inbox IDs
*
* @param inboxIds Array of inbox IDs to add
*/
addMembers(inboxIds: string[]): Promise<void>;
/**
* Removes members from the group using identifiers
*
* @param identifiers Array of member identifiers to remove
*/
removeMembersByIdentifiers(identifiers: Identifier[]): Promise<void>;
/**
* Removes members from the group using inbox IDs
*
* @param inboxIds Array of inbox IDs to remove
*/
removeMembers(inboxIds: string[]): Promise<void>;
/**
* Promotes a group member to admin status
*
* @param inboxId The inbox ID of the member to promote
*/
addAdmin(inboxId: string): Promise<void>;
/**
* Removes admin status from a group member
*
* @param inboxId The inbox ID of the admin to demote
*/
removeAdmin(inboxId: string): Promise<void>;
/**
* Promotes a group member to super admin status
*
* @param inboxId The inbox ID of the member to promote
*/
addSuperAdmin(inboxId: string): Promise<void>;
/**
* Removes super admin status from a group member
*
* @param inboxId The inbox ID of the super admin to demote
*/
removeSuperAdmin(inboxId: string): Promise<void>;
/**
* Request to leave the group
*/
requestRemoval(): Promise<void>;
/**
* Checks if the current user has requested to leave the group
*
* @returns Boolean
*/
isPendingRemoval(): boolean;
}
/**
* Manages conversations
*
* This class is not intended to be initialized directly.
*/
declare class Conversations<ContentTypes = unknown> {
#private;
/**
* Creates a new conversations instance
*
* @param client - The client instance managing the conversations
* @param codecRegistry - The codec registry instance
* @param conversations - The underlying conversations instance
*/
constructor(client: Client<ContentTypes>, codecRegistry: CodecRegistry, conversations: Conversations$1);
get topic(): string;
/**
* Retrieves a conversation by its ID
*
* @param id - The conversation ID to look up
* @returns The conversation if found, undefined otherwise
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#conversation-helper-methods
*/
getConversationById(id: string): Promise<Group<ContentTypes> | Dm<ContentTypes> | undefined>;
/**
* Retrieves a DM by inbox ID
*
* @param inboxId - The inbox ID to look up
* @returns The DM if found, undefined otherwise
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#conversation-helper-methods
*/
getDmByInboxId(inboxId: string): Dm<ContentTypes> | undefined;
/**
* Retrieves a DM by identifier
*
* @param identifier - The identifier to look up
* @returns Promise that resolves with the DM, if found
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#conversation-helper-methods
*/
fetchDmByIdentifier(identifier: Identifier): Promise<Dm<ContentTypes> | undefined>;
/**
* Retrieves a message by its ID
*
* @param id - The message ID to look up
* @returns The decoded message if found, undefined otherwise
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#conversation-helper-methods
*/
getMessageById(id: string): DecodedMessage<ContentTypes> | undefined;
/**
* Creates a new group conversation without publishing to the network
*
* @param options - Optional group creation options
* @returns The new group
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#optimistically-create-a-new-group-chat
*/
createGroupOptimistic(options?: CreateGroupOptions): Group<ContentTypes>;
/**
* Creates a new group conversation with the specified identifiers
*
* @param identifiers - Array of identifiers for group members
* @param options - Optional group creation options
* @returns The new group
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#create-a-new-group-chat
*/
createGroupWithIdentifiers(identifiers: Identifier[], options?: CreateGroupOptions): Promise<Group<ContentTypes>>;
/**
* Creates a new group conversation with the specified inbox IDs
*
* @param inboxIds - Array of inbox IDs for group members
* @param options - Optional group creation options
* @returns The new group
* @see https://docs.xmtp.org/chat-apps/core-messaging/create-conversations#create-a-new-group-chat
*/
createGroup(inboxIds: string[], options?: CreateGroupOptions): Promise<Group<ContentTypes>>;
/**
* Creates a new DM conversation with the specified identifier
*
* @param identifier - Identifier for the DM recipient
* @param options - Optional DM creation options
* @returns The new DM
* @see https://docs.xmtp.org/agents/build-agents/create-conversations#by-ethereum-address-1
*/
createDmWithIdentifier(identifier: Identifier, options?: CreateDmOptions): Promise<Dm<ContentTypes>>;
/**
* Creates a new DM conversation with the specified inbox ID
*
* @param inboxId - Inbox ID for the DM recipient
* @param options - Optional DM creation options
* @returns The new DM
* @see https://docs.xmtp.org/agents/build-agents/create-conversations#by-inbox-id-1
*/
createDm(inboxId: string, options?: CreateDmOptions): Promise<Dm<ContentTypes>>;
/**
* Lists all conversations with optional filtering
*
* @param options - Optional filtering and pagination options
* @returns Array of conversations
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/list
*/
list(options?: ListConversationsOptions): Promise<(Group<ContentTypes> | Dm<ContentTypes>)[]>;
/**
* Lists all groups with optional filtering
*
* @param options - Optional filtering and pagination options
* @returns Array of groups
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/list#list-existing-conversations
*/
listGroups(options?: Omit<ListConversationsOptions, "conversationType">): Group<ContentTypes>[];
/**
* Lists all DMs with optional filtering
*
* @param options - Optional filtering and pagination options
* @returns Array of DMs
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/list#list-existing-conversations
*/
listDms(options?: Omit<ListConversationsOptions, "conversationType">): Dm<ContentTypes>[];
/**
* Synchronizes conversations for the current client from the network
*
* @returns Promise that resolves when sync is complete
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/sync-and-syncall
*/
sync(): Promise<void>;
/**
* Synchronizes all conversations and messages from the network with optional
* consent state filtering
*
* @param consentStates - Optional array of consent states to filter by
* @returns Promise that resolves when sync is complete
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/sync-and-syncall#sync-all-new-welcomes-conversations-messages-and-preferences
*/
syncAll(consentStates?: ConsentState[]): Promise<_xmtp_node_bindings.GroupSyncSummary>;
/**
* Creates a stream for new conversations
*
* @param options - Optional stream options
* @param options.conversationType - Optional conversation type to filter by
* @returns Stream instance for new conversations
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-conversations
*/
stream(options?: StreamOptions<Conversation$1, Group<ContentTypes> | Dm<ContentTypes> | undefined> & {
conversationType?: ConversationType;
}): Promise<AsyncStreamProxy<Group<ContentTypes> | Dm<ContentTypes>>>;
/**
* Creates a stream for new group conversations
*
* @param options - Optional stream options
* @returns Stream instance for new group conversations
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-conversations
*/
streamGroups(options?: StreamOptions<Conversation$1, Group<ContentTypes>>): Promise<AsyncStreamProxy<Group<ContentTypes>>>;
/**
* Creates a stream for new DM conversations
*
* @param options - Optional stream options
* @returns Stream instance for new DM conversations
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-conversations
*/
streamDms(options?: StreamOptions<Conversation$1, Dm<ContentTypes>>): Promise<AsyncStreamProxy<Dm<ContentTypes>>>;
/**
* Creates a stream for all new messages
*
* @param options - Optional stream options
* @param options.conversationType - Optional conversation type to filter by
* @param options.consentStates - Optional array of consent states to filter by
* @returns Stream instance for new messages
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-messages
*/
streamAllMessages(options?: StreamOptions<Message, DecodedMessage<ContentTypes>> & {
conversationType?: ConversationType;
consentStates?: ConsentState[];
}): Promise<AsyncStreamProxy<DecodedMessage<ContentTypes>>>;
/**
* Creates a stream for all new group messages
*
* @param options - Optional stream options
* @param options.consentStates - Optional array of consent states to filter by
* @returns Stream instance for new group messages
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-messages
*/
streamAllGroupMessages(options?: StreamOptions<Message, DecodedMessage<ContentTypes>> & {
consentStates?: ConsentState[];
}): Promise<AsyncStreamProxy<DecodedMessage<ContentTypes>>>;
/**
* Creates a stream for all new DM messages
*
* @param options - Optional stream options
* @param options.consentStates - Optional array of consent states to filter by
* @returns Stream instance for new DM messages
* @see https://docs.xmtp.org/chat-apps/list-stream-sync/stream#stream-new-group-chat-and-dm-messages
*/
streamAllDmMessages(options?: StreamOptions<Message, DecodedMessage<ContentTypes>> & {
consentStates?: ConsentState[];
}): Promise<AsyncStreamProxy<DecodedMessage<ContentTypes>>>;
/**
* Creates a stream for message deletions that streams the message IDs of
* deleted messages
*
* This is a local stream, does not require network sync, and will not fail
* like other streams.
*
* @param options - Optional stream options
* @returns Stream instance for message deletions
* @deprecated Use streamDeletedMessages instead
*/
streamMessageDeletions(options?: Omit<StreamOptions<DecodedMessage$1, string>, "disableSync" | "onFail" | "onRetry" | "onRestart" | "retryAttempts" | "retryDelay" | "retryOnFail">): Promise<AsyncStreamProxy<string>>;
/**
* Creates a stream for message deletions that streams the deleted messages
*
* This is a local stream, does not require network sync, and will not fail
* like other streams.
*
* @param options - Optional stream options
* @returns Stream instance for message deletions
*/
streamDeletedMessages(options?: Omit<StreamOptions<DecodedMessage$1, DecodedMessage<ContentTypes>>, "disableSync" | "onFail" | "onRetry" | "onRestart" | "retryAttempts" | "retryDelay" | "retryOnFail">): Promise<AsyncStreamProxy<DecodedMessage<ContentTypes>>>;
/**
* Gets the HMAC keys for all conversations
*
* @returns The HMAC keys for all conversations
* @see https://docs.xmtp.org/chat-apps/push-notifs/push-notifs#get-hmac-keys-for-a-conversation
*/
hmacKeys(): Record<string, _xmtp_node_bindings.HmacKey[]>;
}
/**
* Debug information helpers for the client
*
* This class is not intended to be initialized directly.
*/
declare class DebugInformation {
#private;
constructor(client: Client$1);
apiStatistics(): _xmtp_node_bindings.ApiStats;
apiIdentityStatistics(): _xmtp_node_bindings.IdentityStats;
apiAggregateStatistics(): string;
clearAllStatistics(): void;
}
/**
* Manages user preferences and consent states
*
* This class is not intended to be initialized directly.
*/
declare class Preferences {
#private;
/**
* Creates a new preferences instance
*
* @param client - The client instance managing preferences
* @param conversations - The underlying conversations instance
*/
constructor(client: Client$1, conversations: Conversations$1);
sync(): Promise<_xmtp_node_bindings.GroupSyncSummary>;
/**
* Retrieves the current inbox state of this client from the local database
*
* @returns Promise that resolves with the inbox state
*/
inboxState(): Promise<_xmtp_node_bindings.InboxState>;
/**
* Retrieves the latest inbox state of this clientfrom the network
*
* @returns Promise that resolves with the inbox state
*/
fetchInboxState(): Promise<_xmtp_node_bindings.InboxState>;
/**
* Retrieves the current inbox states for specified inbox IDs from the local
* database
*
* @param inboxIds - Array of inbox IDs to get state for
* @returns Promise that resolves with the inbox states for the inbox IDs
*/
getInboxStates(inboxIds: string[]): Promise<_xmtp_node_bindings.InboxState[]>;
/**
* Retrieves the latest inbox states for specified inbox IDs from the network
*
* @param inboxIds - Array of inbox IDs to get state for
* @returns Promise that resolves with the inbox states for the inbox IDs
*/
fetchInboxStates(inboxIds: string[]): Promise<_xmtp_node_bindings.InboxState[]>;
/**
* Updates consent states for multiple records
*
* @param consentStates - Array of consent records to update
* @returns Promise that resolves when consent states are updated
*/
setConsentStates(consentStates: Consent[]): Promise<void>;
/**
* Retrieves consent state for a specific entity
*
* @param entityType - Type of entity to get consent for
* @param entity - Entity identifier
* @returns Promise that resolves with the consent state
*/
getConsentState(entityType: ConsentEntityType, entity: string): Promise<_xmtp_node_bindings.ConsentState>;
/**
* Creates a stream of consent state updates
*
* @param options - Optional stream options
* @returns Stream instance for consent updates
*/
streamConsent(options?: StreamOptions<Consent[]>): Promise<AsyncStreamProxy<Consent[]>>;
/**
* Creates a stream of user preference updates
*
* @param options - Optional stream options
* @returns Stream instance for preference updates
*/
streamPreferences(options?: StreamOptions<UserPreferenceUpdate[]>): Promise<AsyncStreamProxy<UserPreferenceUpdate[]>>;
}
/**
* Client for interacting with the XMTP network
*/
declare class Client<ContentTypes = ExtractCodecContentTypes> {
#private;
/**
* Creates a new XMTP client instance
*
* This class is not intended to be initialized directly.
* Use `Client.create` or `Client.build` instead.
*
* @param options - Optional configuration for the client
*/
constructor(options?: ClientOptions);
/**
* Initializes the client with the provided identifier
*
* This is not meant to be called directly.
* Use `Client.create` or `Client.build` instead.
*
* @param identifier - The identifier to initialize the client with
*/
init(identifier: Identifier): Promise<void>;
/**
* Creates a new client instance with a signer
*
* @param signer - The signer to use for authentication
* @param options - Optional configuration for the client
* @returns A new client instance
*/
static create<ContentCodecs extends ContentCodec[] = []>(signer: Signer, options?: DistributiveOmit<ClientOptions, "codecs"> & {
codecs?: ContentCodecs;
}): Promise<Client<ExtractCodecContentTypes<ContentCodecs>>>;
/**
* Creates a new client instance with an identifier
*
* Clients created with this method must already be registered.
* Any methods called that require a signer will throw an error.
*
* @param identifier - The identifier to use
* @param options - Optional configuration for the client
* @returns A new client instance
*/
static build<ContentCodecs extends ContentCodec[] = []>(identifier: Identifier, options?: DistributiveOmit<ClientOptions, "codecs"> & {
codecs?: ContentCodecs;
}): Promise<Client<ExtractCodecContentTypes<ContentCodecs>>>;
/**
* Gets the version of libxmtp used in the bindings
*/
get libxmtpVersion(): string | undefined;
/**