UNPKG

@rust-nostr/nostr-sdk

Version:

Nostr protocol implementation, Relay, RelayPool, high-level client library, NWC client and more.

1,910 lines (1,904 loc) 96.9 kB
/* tslint:disable */ /* eslint-disable */ export function initLogger(level: LogLevel): void; /** * Encrypt (NIP04) */ export function nip04Encrypt(secret_key: SecretKey, public_key: PublicKey, text: string): string; /** * Decrypt (NIP04) */ export function nip04Decrypt(secret_key: SecretKey, public_key: PublicKey, encrypted_content: string): string; /** * Encrypt (NIP44) */ export function nip44Encrypt(secret_key: SecretKey, public_key: PublicKey, content: string, version: NIP44Version): string; /** * Decrypt (NIP44) */ export function nip44Decrypt(secret_key: SecretKey, public_key: PublicKey, payload: string): string; export function nip57AnonymousZapRequest(data: ZapRequestData): Event; export function nip57PrivateZapRequest(data: ZapRequestData, keys: Keys): Event; export function nip57DecryptSentPrivateZapMessage(secret_key: SecretKey, public_key: PublicKey, private_zap: Event): Event; export function nip57DecryptReceivedPrivateZapMessage(secret_key: SecretKey, private_zap: Event): Event; export function extractRelayList(event: Event): RelayListItem[]; /** * Generate shared key * * **Important: use of a strong cryptographic hash function may be critical to security! Do NOT use * unless you understand cryptographical implications.** */ export function generateSharedKey(secret_key: SecretKey, public_key: PublicKey): Uint8Array; /** * Run some stuff when the Wasm module is instantiated. * * Right now, it does the following: * * * Redirect Rust panics to JavaScript console. */ export function start(): void; export function gitHashVersion(): string | undefined; export enum AdmitStatus { Success = 0, Rejected = 1, } export enum Alphabet { A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22, X = 23, Y = 24, Z = 25, } export enum DataVendingMachineStatus { PaymentRequired = 0, Processing = 1, Error = 2, Success = 3, Partial = 4, } /** * Encrypted Secret Key version (NIP49) */ export enum EncryptedSecretKeyVersion { V2 = 0, } /** * Flag checks */ export enum FlagCheck { /** * Use `OR` logic operator */ Any = 0, /** * Use `AND` logic operator */ All = 1, } export enum HttpMethod { GET = 0, POST = 1, PUT = 2, PATCH = 3, } /** * Key security */ export enum KeySecurity { /** * The key has been known to have been handled insecurely (stored unencrypted, cut and paste unencrypted, etc) */ Weak = 0, /** * The key has NOT been known to have been handled insecurely (stored encrypted, cut and paste encrypted, etc) */ Medium = 1, /** * The client does not track this data */ Unknown = 2, } /** * Standardized kind */ export enum KindStandard { /** * Metadata (NIP01 and NIP05) */ Metadata = 0, /** * Short Text Note (NIP01) */ TextNote = 1, /** * Contacts (NIP02) */ ContactList = 2, /** * OpenTimestamps Attestations (NIP03) */ OpenTimestamps = 3, /** * Event Deletion (NIP09) */ EventDeletion = 4, /** * Repost (NIP18) */ Repost = 5, /** * Generic Repost (NIP18) */ GenericRepost = 6, /** * Comment (NIP22) */ Comment = 7, /** * Reaction (NIP25) */ Reaction = 8, /** * Badge Award (NIP58) */ BadgeAward = 9, /** * Blossom Authorization */ BlossomAuth = 10, /** * Channel Creation (NIP28) */ ChannelCreation = 11, /** * Channel Metadata (NIP28) */ ChannelMetadata = 12, /** * Channel Message (NIP28) */ ChannelMessage = 13, /** * Channel Hide Message (NIP28) */ ChannelHideMessage = 14, /** * Channel Mute User (NIP28) */ ChannelMuteUser = 15, /** * Git Patch * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitPatch = 16, /** * Git Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitIssue = 17, /** * Git Reply * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitReply = 18, /** * Open Status of Git Patch or Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitStatusOpen = 19, /** * Applied / Merged Status of Git Patch or Resolved Status of Git Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitStatusApplied = 20, /** * Closed Status of Git Patch or Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitStatusClosed = 21, /** * Draft Status of Git Patch or Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitStatusDraft = 22, /** * Torrent * * <https://github.com/nostr-protocol/nips/blob/master/35.md> */ Torrent = 23, /** * Torrent comment * * <https://github.com/nostr-protocol/nips/blob/master/35.md> */ TorrentComment = 24, /** * Label * * <https://github.com/nostr-protocol/nips/blob/master/32.md> */ Label = 25, /** * Wallet Service Info (NIP47) */ WalletConnectInfo = 26, /** * Reporting (NIP56) */ Reporting = 27, /** * Zap Private Message (NIP57) */ ZapPrivateMessage = 28, /** * Zap Request (NIP57) */ ZapRequest = 29, /** * Zap Receipt (NIP57) */ ZapReceipt = 30, /** * Mute List * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ MuteList = 31, /** * Pin List * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ PinList = 32, /** * Bookmarks * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ Bookmarks = 33, /** * Communities * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ Communities = 34, /** * Public Chats * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ PublicChats = 35, /** * Blocked Relays * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ BlockedRelays = 36, /** * Search Relays * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ SearchRelays = 37, /** * Simple Groups * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ SimpleGroups = 38, /** * Interests * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ Interests = 39, /** * Emojis * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ Emojis = 40, /** * Follow Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ FollowSet = 41, /** * Relay Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ RelaySet = 42, /** * Bookmark Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ BookmarkSet = 43, /** * Articles Curation Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ ArticlesCurationSet = 44, /** * Videos Curation Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ VideosCurationSet = 45, /** * Interest Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ InterestSet = 46, /** * Emoji Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ EmojiSet = 47, /** * Release Artifact Set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ ReleaseArtifactSet = 48, /** * Relay List Metadata (NIP65) */ RelayList = 49, /** * Peer-to-peer Order events * * <https://github.com/nostr-protocol/nips/blob/master/69.md> */ PeerToPeerOrder = 50, /** * Request to Vanish (NIP62) * * <https://github.com/nostr-protocol/nips/blob/master/62.md> */ RequestToVanish = 51, /** * Client Authentication (NIP42) */ Authentication = 52, /** * Wallet Connect Request (NIP47) */ WalletConnectRequest = 53, /** * Wallet Connect Response (NIP47) */ WalletConnectResponse = 54, WalletConnectNotification = 55, /** * Nostr Connect (NIP46) */ NostrConnect = 56, /** * Live Event (NIP53) */ LiveEvent = 57, /** * Live Event Message (NIP53) */ LiveEventMessage = 58, /** * Profile Badges (NIP58) */ ProfileBadges = 59, /** * Badge Definition (NIP58) */ BadgeDefinition = 60, /** * Seal (NIP59) */ Seal = 61, /** * Gift Wrap (NIP59) */ GiftWrap = 62, /** * Private Direct message * * <https://github.com/nostr-protocol/nips/blob/master/17.md> */ PrivateDirectMessage = 63, /** * Inbox Relays (NIP17) */ InboxRelays = 64, /** * MLS Key Package Relays (NIP104) */ MlsKeyPackageRelays = 65, /** * MLS Key Package (NIP104) */ MlsKeyPackage = 66, /** * MLS Welcome (NIP104) */ MlsWelcome = 67, /** * MLS Group Message (NIP104) */ MlsGroupMessage = 68, /** * Long-form Text Note (NIP23) */ LongFormTextNote = 69, /** * Git Repository Announcement * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ GitRepoAnnouncement = 70, /** * Application-specific Data (NIP78) */ ApplicationSpecificData = 71, /** * File Metadata (NIP94) */ FileMetadata = 72, /** * HTTP Auth (NIP98) */ HttpAuth = 73, /** * Set stall (NIP15) */ SetStall = 74, /** * Set product (NIP15) */ SetProduct = 75, /** * Job Feedback (NIP90) */ JobFeedback = 76, /** * User Status * * <https://github.com/nostr-protocol/nips/blob/master/38.md> */ UserStatus = 77, /** * Cashu Wallet * * <https://github.com/nostr-protocol/nips/blob/master/60.md> */ CashuWallet = 78, /** * Cashu Wallet Unspent Proof * * <https://github.com/nostr-protocol/nips/blob/master/60.md> */ CashuWalletUnspentProof = 79, /** * Cashu Wallet Spending History * * <https://github.com/nostr-protocol/nips/blob/master/60.md> */ CashuWalletSpendingHistory = 80, /** * Code Snippet * * <https://github.com/nostr-protocol/nips/blob/master/C0.md> */ CodeSnippet = 81, Poll = 82, PollResponse = 83, } export enum NIP44Version { V2 = 2, } /** * NIP47 Response Error codes */ export enum Nip47ErrorCode { /** * The client is sending commands too fast. */ RateLimited = 0, /** * The command is not known of is intentionally not implemented */ NotImplemented = 1, /** * The wallet does not have enough funds to cover a fee reserve or the payment amount */ InsufficientBalance = 2, /** * The payment failed. This may be due to a timeout, exhausting all routes, insufficient capacity or similar. */ PaymentFailed = 3, /** * The invoice could not be found by the given parameters. */ NotFound = 4, /** * The wallet has exceeded its spending quota */ QuotaExceeded = 5, /** * This public key is not allowed to do this operation */ Restricted = 6, /** * This public key has no wallet connected */ Unauthorized = 7, /** * An internal error */ Internal = 8, /** * Other error */ Other = 9, } export enum RelayMetadata { Read = 0, Write = 1, } export enum RelayStatus { /** * Initialized */ Initialized = 0, /** * Pending */ Pending = 1, /** * Connecting */ Connecting = 2, /** * Connected */ Connected = 3, /** * Disconnected, will retry to connect again */ Disconnected = 4, /** * Completely disconnected */ Terminated = 5, /** * The relay has been banned. */ Banned = 6, /** * Relay is sleeping */ Sleeping = 7, } /** * Report * * <https://github.com/nostr-protocol/nips/blob/master/56.md> */ export enum Report { /** * Depictions of nudity, porn, etc */ Nudity = 0, /** * Virus, trojan horse, worm, robot, spyware, adware, back door, ransomware, rootkit, kidnapper, etc. */ Malware = 1, /** * Profanity, hateful speech, etc. */ Profanity = 2, /** * Something which may be illegal in some jurisdiction */ Illegal = 3, /** * Spam */ Spam = 4, /** * Someone pretending to be someone else */ Impersonation = 5, /** * Reports that don't fit in the above categories */ Other = 6, } export enum SaveEventStatus { /** * The event has been successfully saved into the database */ Success = 0, /** * Ephemeral events aren't expected to be stored */ Ephemeral = 1, /** * The event already exists */ Duplicate = 2, /** * The event was deleted */ Deleted = 3, /** * The event is expired */ Expired = 4, /** * The event was replaced */ Replaced = 5, /** * Attempt to delete a non-owned event */ InvalidDelete = 6, /** * Other reason */ Other = 7, } export enum SyncDirection { Up = 0, Down = 1, Both = 2, } /** * Transaction Type */ export enum TransactionType { /** * Incoming payments */ Incoming = 0, /** * Outgoing payments */ Outgoing = 1, } export enum ZapType { /** * Public */ Public = 0, /** * Private */ Private = 1, /** * Anonymous */ Anonymous = 2, } interface HandleNotification { handleEvent: (relayUrl: string, subscriptionId: string, event: Event) => Promise<boolean>; handleMsg: (relayUrl: string, message: RelayMessage) => Promise<boolean>; } interface AdmitPolicy { admitEvent: (event: Event) => Promise<AdmitStatus>; } export class AbortHandle { private constructor(); free(): void; /** * Abort thread */ abort(): void; /** * Check if thread is aborted */ is_aborted(): boolean; } export class Aes256Gcm { free(): void; constructor(key: string, iv: string); key: string; iv: string; } /** * Groups of articles picked by users as interesting and/or belonging to the same category * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ export class ArticlesCuration { free(): void; constructor(); coordinate: Coordinate[]; event_ids: EventId[]; } export class AtomicRelayServiceFlags { private constructor(); free(): void; static new(flags: RelayServiceFlags): AtomicRelayServiceFlags; add(flags: RelayServiceFlags): void; remove(flags: RelayServiceFlags): void; /** * Check whether `RelayServiceFlags` are included in this one. */ has(flags: RelayServiceFlags, check: FlagCheck): boolean; /** * Check if `READ` service is enabled */ has_read(): boolean; /** * Check if `WRITE` service is enabled */ has_write(): boolean; /** * Check if `PING` service is enabled */ has_ping(): boolean; } /** * Uncategorized, "global" list of things a user wants to save * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ export class Bookmarks { free(): void; constructor(); event_ids: EventId[]; coordinate: Coordinate[]; hashtags: string[]; urls: string[]; } /** * Signer for interaction with browser extensions (ex. Alby) * * <https://github.com/aljazceru/awesome-nostr#nip-07-browser-extensions> * * <https://github.com/nostr-protocol/nips/blob/master/07.md> */ export class BrowserSigner { free(): void; constructor(); getPublicKey(): Promise<PublicKey>; signEvent(unsigned: UnsignedEvent): Promise<Event>; nip04Encrypt(public_key: PublicKey, plaintext: string): Promise<string>; nip04Decrypt(public_key: PublicKey, ciphertext: string): Promise<string>; nip44Encrypt(public_key: PublicKey, plaintext: string): Promise<string>; nip44Decrypt(public_key: PublicKey, ciphertext: string): Promise<string>; } export class Client { free(): void; constructor(signer?: NostrSigner | null); /** * Construct `ClientBuilder` */ static builder(): ClientBuilder; /** * Auto authenticate to relays (default: true) * * <https://github.com/nostr-protocol/nips/blob/master/42.md> */ automaticAuthentication(enable: boolean): void; /** * Get current nostr signer * * Rise error if it not set. */ signer(): Promise<NostrSigner>; /** * Completely shutdown `Client` */ shutdown(): Promise<void>; /** * Get relays with `READ` or `WRITE` flags */ relays(): Promise<Relay[]>; /** * Get a previously added `Relay` */ relay(url: string): Promise<Relay>; /** * Add new relay * * Relays added with this method will have both `READ` and `WRITE` flags enabled * * If the relay already exists, the flags will be updated and `false` returned. * * If are set pool subscriptions, the new added relay will inherit them. Use `subscribeTo` method instead of `subscribe`, * to avoid to set pool subscriptions. * * This method use previously set or default `Options` to configure the `Relay` (ex. set proxy, set min POW, set relay limits, ...). * * Connection is **NOT** automatically started with relay, remember to call `connect` method! */ addRelay(url: string): Promise<boolean>; addRelayWithOpts(url: string, opts: RelayOptions): Promise<boolean>; /** * Add discovery relay * * If relay already exists, this method automatically add the `DISCOVERY` flag to it and return `false`. * * <https://github.com/nostr-protocol/nips/blob/master/65.md> */ addDiscoveryRelay(url: string): Promise<boolean>; /** * Add read relay * * If relay already exists, this method add the `READ` flag to it and return `false`. * * If are set pool subscriptions, the new added relay will inherit them. Use `subscribe_to` method instead of `subscribe`, * to avoid to set pool subscriptions. */ addReadRelay(url: string): Promise<boolean>; /** * Add write relay * * If relay already exists, this method add the `WRITE` flag to it and return `false`. */ addWriteRelay(url: string): Promise<boolean>; /** * Remove and disconnect relay * * If the relay has `GOSSIP` flag, it will not be removed from the pool and its * flags will be updated (remove `READ`, `WRITE` and `DISCOVERY` flags). */ removeRelay(url: string): Promise<void>; /** * Force remove and disconnect relay * * Note: this method will remove the relay, also if it's in use for the gossip model or other service! */ forceRemoveRelay(url: string): Promise<void>; /** * Disconnect and remove all relays * * Some relays used by some services could not be disconnected with this method * (like the ones used for gossip). * Use [`Client::force_remove_all_relays`] to remove every relay. */ removeAllRelays(): Promise<void>; /** * Disconnect and force remove all relays */ forceRemoveAllRelays(): Promise<void>; /** * Connect to a previously added relay */ connectRelay(url: string): Promise<void>; /** * Disconnect relay */ disconnectRelay(url: string): Promise<void>; /** * Connect to all added relays * * Attempts to initiate a connection for every relay currently in * [`RelayStatus::Initialized`] or [`RelayStatus::Terminated`]. * A background connection task is spawned for each such relay, which then tries * to establish the connection. * Any relay not in one of these two statuses is skipped. * * For further details, see the documentation of [`Relay::connect`]. */ connect(): Promise<void>; /** * Waits for relays connections * * Wait for relays connections at most for the specified `timeout`. * The code continues when the relays are connected or the `timeout` is reached. */ waitForConnection(timeout: Duration): Promise<void>; /** * Try to establish a connection with the relays. * * Attempts to establish a connection for every relay currently in * [`RelayStatus::Initialized`] or [`RelayStatus::Terminated`] * without spawning the connection task if it fails. * This means that if the connection fails, no automatic retries are scheduled. * Use [`Client::connect`] if you want to immediately spawn a connection task, * regardless of whether the initial connection succeeds. * * For further details, see the documentation of [`Relay::try_connect`]. */ tryConnect(timeout: Duration): Promise<Output>; /** * Disconnect from all relays */ disconnect(): Promise<void>; /** * Subscribe to filters * * If `gossip` is enabled (see `Options]) the events will be requested also to * NIP65 relays (automatically discovered) of public keys included in filters (if any). * * ### Auto-closing subscription * * It's possible to automatically close a subscription by configuring the `SubscribeAutoCloseOptions`. */ subscribe(filter: Filter, opts?: SubscribeAutoCloseOptions | null): Promise<SubscribeOutput>; /** * Subscribe to filters with custom subscription ID * * If `gossip` is enabled (see `Options]) the events will be requested also to * NIP65 relays (automatically discovered) of public keys included in filters (if any). * * ### Auto-closing subscription * * It's possible to automatically close a subscription by configuring the `SubscribeAutoCloseOptions`. */ subscribeWithId(id: string, filter: Filter, opts?: SubscribeAutoCloseOptions | null): Promise<Output>; /** * Subscribe to filters to specific relays * * ### Auto-closing subscription * * It's possible to automatically close a subscription by configuring the `SubscribeAutoCloseOptions`. */ subscribeTo(urls: string[], filter: Filter, opts?: SubscribeAutoCloseOptions | null): Promise<SubscribeOutput>; /** * Subscribe to filters with custom subscription ID to specific relays * * ### Auto-closing subscription * * It's possible to automatically close a subscription by configuring the `SubscribeAutoCloseOptions`. */ subscribeWithIdTo(urls: string[], id: string, filter: Filter, opts?: SubscribeAutoCloseOptions | null): Promise<Output>; /** * Unsubscribe */ unsubscribe(subscription_id: string): Promise<void>; /** * Unsubscribe */ unsubscribeAll(): Promise<void>; /** * Sync events with relays (negentropy reconciliation) * * If `gossip` is enabled (see `Options`) the events will be reconciled also with * NIP65 relays (automatically discovered) of public keys included in filters (if any). * * <https://github.com/hoytech/negentropy> */ sync(filter: Filter, opts: SyncOptions): Promise<ReconciliationOutput>; /** * Fetch events from relays * * This is an auto-closing subscription and will be closed automatically on `EOSE`. * * # Gossip * * If `gossip` is enabled (see `Options`) the events will be requested also to * NIP65 relays (automatically discovered) of public keys included in filters (if any). */ fetchEvents(filter: Filter, timeout: Duration): Promise<Events>; /** * Fetch events from specific relays * * This is an auto-closing subscription and will be closed automatically on `EOSE`. */ fetchEventsFrom(urls: string[], filter: Filter, timeout: Duration): Promise<Events>; /** * Get events both from database and relays * * This is an auto-closing subscription and will be closed automatically on `EOSE`. * * You can obtain the same result by merging the `Events` from different type of sources. * * This method will be deprecated in the future! * This is a temporary solution for who still want to query events both from database and relays and merge the result. * The optimal solution is to execute a [`Client::sync`] to get all old events, [`Client::subscribe`] to get all * new future events, [`NostrDatabase::query`] to query events and [`Client::handle_notifications`] to listen-for/handle new events (i.e. to know when update the UI). * This will allow very fast queries, low bandwidth usage (depending on how many events the client have to reconcile) and a lower load on the relays. * * # Gossip * * If `gossip` is enabled (see [`Options::gossip`]) the events will be requested also to * NIP65 relays (automatically discovered) of public keys included in filters (if any). */ fetchCombinedEvents(filter: Filter, timeout: Duration): Promise<Events>; /** * Send client message to a specific relay */ sendMsgTo(urls: string[], msg: ClientMessage): Promise<Output>; /** * Send event * * Send event to all relays with `WRITE` flag. * If `gossip` is enabled (see `Options`) the event will be sent also to NIP65 relays (automatically discovered). */ sendEvent(event: Event): Promise<SendEventOutput>; /** * Send event to specific relay */ sendEventTo(urls: string[], event: Event): Promise<SendEventOutput>; /** * Signs the `EventBuilder` into an `Event` using the `NostrSigner` */ signEventBuilder(builder: EventBuilder): Promise<Event>; /** * Take an `EventBuilder`, sign it by using the `NostrSigner` and broadcast to relays (check `send_event` method for more details) * * Rise an error if the `NostrSigner` is not set. */ sendEventBuilder(builder: EventBuilder): Promise<SendEventOutput>; /** * Take an `EventBuilder`, sign it by using the `NostrSigner` and broadcast to specific relays. * * Rise an error if the `NostrSigner` is not set. */ sendEventBuilderTo(urls: string[], builder: EventBuilder): Promise<SendEventOutput>; /** * Fetch the newest public key metadata from relays. * * Returns `None` if the `Metadata` of the `PublicKey` has not been found. * * Check `Client.fetchEvents` for more details. * * If you only want to consult cached data, * consider `client.database().profile(PUBKEY)`. * * <https://github.com/nostr-protocol/nips/blob/master/01.md> */ fetchMetadata(public_key: PublicKey, timeout: Duration): Promise<Metadata | undefined>; /** * Update metadata * * <https://github.com/nostr-protocol/nips/blob/master/01.md> */ setMetadata(metadata: Metadata): Promise<SendEventOutput>; /** * Send a private direct message * * If gossip is enabled, the message will be sent to the NIP17 relays (automatically discovered). * If gossip is not enabled will be sent to all relays with WRITE` relay service flag. * * <https://github.com/nostr-protocol/nips/blob/master/17.md> */ sendPrivateMsg(receiver: PublicKey, message: string, rumor_extra_tags?: Tag[] | null): Promise<SendEventOutput>; /** * Send private direct message to specific relays * * <https://github.com/nostr-protocol/nips/blob/master/17.md> */ sendPrivateMsgTo(urls: string[], receiver: PublicKey, message: string, rumor_extra_tags?: Tag[] | null): Promise<SendEventOutput>; /** * Construct Gift Wrap and send to relays * * Check `sendEvent` method to know how sending events works. * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ giftWrap(receiver: PublicKey, rumor: UnsignedEvent, extra_tags?: Tag[] | null): Promise<SendEventOutput>; /** * Construct Gift Wrap and send to specific relays * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ giftWrapTo(urls: string[], receiver: PublicKey, rumor: UnsignedEvent, extra_tags?: Tag[] | null): Promise<SendEventOutput>; /** * Unwrap Gift Wrap event * * Internally verify the `seal` event * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ unwrapGiftWrap(gift_wrap: Event): Promise<UnwrappedGift>; /** * Handle notifications * * **This method spawn a task**, so ensure to keep up the app after calling this (if needed). * * To exit from the handle notifications loop, return `true` or call `abortable.abort();`. * * # Example * ```javascript * // Subscribe to filters * const filter = new Filter().author(keys.publicKey); * await client.subscribe([filter]); * * const handle = { * // Handle event * handleEvent: async (relayUrl, subscriptionId, event) => { * console.log("Received new event from", relayUrl); * if (event.kind == 4) { * try { * let content = nip04Decrypt(keys.secretKey, event.author, event.content); * console.log("Message:", content); * await client.sendDirectMsg(event.author, "Echo: " + content); * * if (content == "stop") { * return true; * } * } catch (error) { * console.log("Impossible to decrypt DM:", error); * } * } * }, * // Handle relay message * handleMsg: async (relayUrl, message) => { * console.log("Received message from", relayUrl, message.asJson()); * } * }; * * let abortable = client.handleNotifications(handle); * // Optionally, call `abortable.abort();` when you need to stop handle notifications task * ``` */ handleNotifications(callback: HandleNotification): AbortHandle; readonly database: NostrDatabase; } export class ClientBuilder { free(): void; /** * New client builder */ constructor(); signer(signer: NostrSigner): ClientBuilder; database(database: NostrDatabase): ClientBuilder; admitPolicy(policy: AdmitPolicy): ClientBuilder; opts(opts: ClientOptions): ClientBuilder; /** * Build `Client` * * This method **consumes** the `ClientBuilder`! */ build(): Client; } export class ClientMessage { private constructor(); free(): void; /** * Create new `EVENT` message */ static event(event: Event): ClientMessage; /** * Create new `REQ` message */ static req(subscription_id: string, filter: Filter): ClientMessage; /** * Create new `COUNT` message */ static count(subscription_id: string, filter: Filter): ClientMessage; /** * Create new `CLOSE` message */ static close(subscription_id: string): ClientMessage; /** * Create new `AUTH` message */ static auth(event: Event): ClientMessage; /** * Deserialize `ClientMessage` from JSON string * * **This method NOT verify the event signature!** */ static fromJson(json: string): ClientMessage; asJson(): string; } export class ClientOptions { free(): void; constructor(); /** * Automatically start connection with relays (default: false) * * When set to `true`, there isn't the need of calling the connect methods. */ autoconnect(val: boolean): ClientOptions; /** * Auto authenticate to relays (default: true) * * <https://github.com/nostr-protocol/nips/blob/master/42.md> */ automaticAuthentication(enabled: boolean): ClientOptions; /** * Enable gossip model (default: false) */ gossip(enable: boolean): ClientOptions; /** * Set custom relay limits */ relayLimits(limits: RelayLimits): ClientOptions; } export class Contact { free(): void; constructor(public_key: PublicKey, relay_url?: string | null, alias?: string | null); readonly alias: string | undefined; readonly publicKey: PublicKey; readonly relayUrl: string | undefined; } export class Coordinate { free(): void; constructor(kind: Kind, public_key: PublicKey, identifier?: string | null); /** * Parse coordinate from `<kind>:<pubkey>:[<d-tag>]` format, `bech32` or [NIP21](https://github.com/nostr-protocol/nips/blob/master/21.md) uri */ static parse(coordinate: string): Coordinate; /** * Check if the coordinate is valid. * * Returns `false` if: * - the `Kind` is `replaceable` and the identifier is not empty * - the `Kind` is `addressable` and the identifier is empty */ verify(): boolean; toString(): string; readonly kind: Kind; readonly publicKey: PublicKey; readonly identifier: string; } export class Duration { private constructor(); free(): void; static fromSecs(secs: number): Duration; static fromMillis(millis: bigint): Duration; asSecs(): number; asMillis(): number; } /** * Emoji * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ export class EmojiInfo { free(): void; constructor(shortcode: string, url: string); shortcode: string; url: string; } /** * User preferred emojis and pointers to emoji sets * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ export class Emojis { free(): void; constructor(); emojis: EmojiInfo[]; coordinate: Coordinate[]; } /** * Encrypted Secret Key */ export class EncryptedSecretKey { free(): void; /** * Encrypt secret key */ constructor(secret_key: SecretKey, password: string, log_n: number, key_security: KeySecurity); static fromBech32(bech32: string): EncryptedSecretKey; /** * Get encrypted secret key version */ version(): EncryptedSecretKeyVersion; /** * Get encrypted secret key security */ keySecurity(): KeySecurity; /** * Decrypt secret key */ asSecretKey(password: string): SecretKey; toBech32(): string; } export class Event { private constructor(); free(): void; /** * Verify both `EventId` and `Signature` */ verify(): boolean; /** * Verify if the `EventId` it's composed correctly */ verifyId(): boolean; /** * Verify only event `Signature` */ verifySignature(): boolean; /** * Check POW * * <https://github.com/nostr-protocol/nips/blob/master/13.md> */ checkPow(difficulty: number): boolean; /** * Returns `true` if the event has an expiration tag that is expired. * If an event has no `Expiration` tag, then it will return `false`. * * <https://github.com/nostr-protocol/nips/blob/master/40.md> */ isExpired(): boolean; /** * Returns `true` if the event has an expiration tag that is expired. * If an event has no `Expiration` tag, then it will return `false`. * * <https://github.com/nostr-protocol/nips/blob/master/40.md> */ isExpiredAt(now: Timestamp): boolean; /** * Check if it's a protected event * * <https://github.com/nostr-protocol/nips/blob/master/70.md> */ isProtected(): boolean; static fromJson(json: string): Event; asJson(): string; asPrettyJson(): string; readonly id: EventId; /** * Get event author (`pubkey` field) */ readonly author: PublicKey; readonly createdAt: Timestamp; readonly kind: Kind; readonly tags: Tags; readonly content: string; readonly signature: string; } export class EventBuilder { free(): void; constructor(kind: Kind, content: string); /** * Add tags * * This method extend the current tags (if any). */ tags(tags: Tag[]): EventBuilder; /** * Set a custom `created_at` UNIX timestamp */ customCreatedAt(created_at: Timestamp): EventBuilder; /** * Set POW difficulty * * Only values `> 0` are accepted! */ pow(difficulty: number): EventBuilder; /** * Allow self-tagging * * When this mode is enabled, any `p` tags referencing the author’s public key will not be discarded. */ allow_self_tagging(): EventBuilder; /** * Deduplicate tags * * For more details check [`Tags::dedup`]. */ dedup_tags(): EventBuilder; /** * Build, sign and return event * * Check [`EventBuilder::build`] to learn more. * * **This method consumes the builder, so it will no longer be usable!** */ sign(signer: NostrSigner): Promise<Event>; /** * Build, sign and return event using keys signer * * Check [`EventBuilder::build`] to learn more. * * **This method consumes the builder, so it will no longer be usable!** */ signWithKeys(keys: Keys): Event; /** * Build an unsigned event * * By default, this method removes any `p` tags that match the author's public key. * To allow self-tagging, call [`EventBuilder::allow_self_tagging`] first. * * **This method consumes the builder, so it will no longer be usable!** */ build(public_key: PublicKey): UnsignedEvent; /** * Profile metadata * * <https://github.com/nostr-protocol/nips/blob/master/01.md> */ static metadata(metadata: Metadata): EventBuilder; /** * Relay list metadata * * <https://github.com/nostr-protocol/nips/blob/master/65.md> */ static relayList(relays: RelayListItem[]): EventBuilder; /** * Text note * * <https://github.com/nostr-protocol/nips/blob/master/01.md> */ static textNote(content: string): EventBuilder; /** * Text note reply * * This adds only that most significant tags, like: * - `p` tag with the author of the `reply_to` and `root` events; * - `e` tag of the `reply_to` and `root` events. * * Any additional necessary tag can be added with [`EventBuilder::tag`] or [`EventBuilder::tags`]. * * <https://github.com/nostr-protocol/nips/blob/master/10.md> */ static textNoteReply(content: string, reply_to: Event, root?: Event | null, relay_url?: string | null): EventBuilder; /** * Comment * * This adds only that most significant tags, like: * - `p` tag with the author of the `comment_to` event; * - the `a`/`e` and `k` tags of the `comment_to` event; * - `P` tag with the author of the `root` event; * - the `A`/`E` and `K` tags of the `root` event. * * Any additional necessary tag can be added with [`EventBuilder::tag`] or [`EventBuilder::tags`]. * * <https://github.com/nostr-protocol/nips/blob/master/22.md> */ static comment(content: string, comment_to: Event, root?: Event | null, relay_url?: string | null): EventBuilder; /** * Long-form text note (generally referred to as "articles" or "blog posts"). * * <https://github.com/nostr-protocol/nips/blob/master/23.md> */ static longFormTextNote(content: string): EventBuilder; /** * Contact/Follow list * * <https://github.com/nostr-protocol/nips/blob/master/02.md> */ static contactList(list: Contact[]): EventBuilder; /** * Repost * * <https://github.com/nostr-protocol/nips/blob/master/18.md> */ static repost(event: Event, relay_url?: string | null): EventBuilder; /** * Event deletion * * <https://github.com/nostr-protocol/nips/blob/master/09.md> */ static delete(request: EventDeletionRequest): EventBuilder; /** * Add reaction (like/upvote, dislike/downvote or emoji) to an event */ static reaction(event: Event, reaction: string): EventBuilder; /** * Add reaction (like/upvote, dislike/downvote or emoji) to an event */ static reactionExtended(event_id: EventId, public_key: PublicKey, kind: Kind | null | undefined, reaction: string): EventBuilder; /** * Create new channel * * <https://github.com/nostr-protocol/nips/blob/master/28.md> */ static channel(metadata: Metadata): EventBuilder; /** * Channel metadata * * <https://github.com/nostr-protocol/nips/blob/master/28.md> */ static channelMetadata(channel_id: EventId, relay_url: string | null | undefined, metadata: Metadata): EventBuilder; /** * Channel message * * <https://github.com/nostr-protocol/nips/blob/master/28.md> */ static channelMsg(channel_id: EventId, relay_url: string, content: string): EventBuilder; /** * Hide message * * <https://github.com/nostr-protocol/nips/blob/master/28.md> */ static hideChannelMsg(message_id: EventId, reason?: string | null): EventBuilder; /** * Mute channel user * * <https://github.com/nostr-protocol/nips/blob/master/28.md> */ static muteChannelUser(pubkey: PublicKey, reason?: string | null): EventBuilder; /** * Authentication of clients to relays * * <https://github.com/nostr-protocol/nips/blob/master/42.md> */ static auth(challenge: string, relay: string): EventBuilder; /** * Live Event * * <https://github.com/nostr-protocol/nips/blob/master/53.md> */ static liveEvent(live_event: LiveEvent): EventBuilder; /** * Live Event Message * * <https://github.com/nostr-protocol/nips/blob/master/53.md> */ static liveEventMsg(live_event_id: string, live_event_host: PublicKey, content: string, relay_url?: string | null): EventBuilder; /** * Reporting * * <https://github.com/nostr-protocol/nips/blob/master/56.md> */ static report(tags: Tag[], content: string): EventBuilder; /** * Create **public** zap request event * * **This event MUST NOT be broadcasted to relays**, instead must be sent to a recipient's LNURL pay callback url. * * To build a **private** or **anonymous** zap request use `nip57PrivateZapRequest(...)` or `nip57AnonymousZapRequest(...)` functions. * * <https://github.com/nostr-protocol/nips/blob/master/57.md> */ static publicZapRequest(data: ZapRequestData): EventBuilder; /** * Zap Receipt * * <https://github.com/nostr-protocol/nips/blob/master/57.md> */ static zapReceipt(bolt11: string, preimage: string | null | undefined, zap_request: Event): EventBuilder; /** * Badge definition * * <https://github.com/nostr-protocol/nips/blob/master/58.md> */ static defineBadge(badge_id: string, name: string | null | undefined, description: string | null | undefined, image: string | null | undefined, image_dimensions: ImageDimensions | null | undefined, thumbnails: Thumbnails[]): EventBuilder; /** * Badge award * * <https://github.com/nostr-protocol/nips/blob/master/58.md> */ static awardBadge(badge_definition: Event, awarded_public_keys: PublicKey[]): EventBuilder; /** * Profile badges * * <https://github.com/nostr-protocol/nips/blob/master/58.md> */ static profileBadges(badge_definitions: Event[], badge_awards: Event[], pubkey_awarded: PublicKey): EventBuilder; /** * Data Vending Machine (DVM) - Job Request * * <https://github.com/nostr-protocol/nips/blob/master/90.md> */ static jobRequest(kind: Kind): EventBuilder; /** * Data Vending Machine (DVM) - Job Result * * <https://github.com/nostr-protocol/nips/blob/master/90.md> */ static jobResult(job_request: Event, payload: string, millisats: number, bolt11?: string | null): EventBuilder; /** * Data Vending Machine (DVM) - Job Feedback * * <https://github.com/nostr-protocol/nips/blob/master/90.md> */ static jobFeedback(data: JobFeedbackData): EventBuilder; /** * File metadata * * <https://github.com/nostr-protocol/nips/blob/master/94.md> */ static fileMetadata(description: string, metadata: FileMetadata): EventBuilder; /** * HTTP Auth * * <https://github.com/nostr-protocol/nips/blob/master/98.md> */ static httpAuth(data: HttpData): EventBuilder; /** * Set stall data * * <https://github.com/nostr-protocol/nips/blob/master/15.md> */ static stallData(data: StallData): EventBuilder; /** * Set product data * * <https://github.com/nostr-protocol/nips/blob/master/15.md> */ static productData(data: ProductData): EventBuilder; /** * Seal * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ static seal(signer: NostrSigner, receiver_public_key: PublicKey, rumor: UnsignedEvent): Promise<EventBuilder>; /** * Gift Wrap from seal * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ static giftWrapFromSeal(receiver: PublicKey, seal: Event, extra_tags?: Tag[] | null): Event; /** * Gift Wrap * * <https://github.com/nostr-protocol/nips/blob/master/59.md> */ static giftWrap(signer: NostrSigner, receiver: PublicKey, rumor: UnsignedEvent, extra_tags?: Tag[] | null): Promise<Event>; /** * Private Direct message rumor * * <div class="warning"> * This constructor compose ONLY the rumor for the private direct message! * NOT USE THIS IF YOU DON'T KNOW WHAT YOU ARE DOING! * </div> * * <https://github.com/nostr-protocol/nips/blob/master/17.md> */ static privateMsgRumor(receiver: PublicKey, message: string): EventBuilder; /** * Private Direct message * * <https://github.com/nostr-protocol/nips/blob/master/17.md> */ static privateMsg(signer: NostrSigner, receiver: PublicKey, message: string, rumor_extra_tags?: Tag[] | null): Promise<Event>; /** * Mute list * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static muteList(list: MuteList): EventBuilder; /** * Pinned notes * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static pinnedNotes(ids: EventId[]): EventBuilder; /** * Bookmarks * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static bookmarks(list: Bookmarks): EventBuilder; /** * Communities * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static communities(communities: Coordinate[]): EventBuilder; /** * Public chats * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static publicChats(chat: EventId[]): EventBuilder; /** * Blocked relays * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static blockedRelays(relays: string[]): EventBuilder; /** * Search relays * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static searchRelays(relays: string[]): EventBuilder; /** * Interests * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static interests(list: Interests): EventBuilder; /** * Emojis * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static emojis(list: Emojis): EventBuilder; /** * Follow set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static followSet(identifier: string, public_keys: PublicKey[]): EventBuilder; /** * Relay set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static relaySet(identifier: string, relays: string[]): EventBuilder; /** * Bookmark set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static bookmarksSet(identifier: string, list: Bookmarks): EventBuilder; /** * Article Curation set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static articlesCurationSet(identifier: string, list: ArticlesCuration): EventBuilder; /** * Videos Curation set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static videosCurationSet(identifier: string, video: Coordinate[]): EventBuilder; /** * Interest set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static interestSet(identifier: string, hashtags: string[]): EventBuilder; /** * Emoji set * * <https://github.com/nostr-protocol/nips/blob/master/51.md> */ static emojiSet(identifier: string, emoji: EmojiInfo[]): EventBuilder; /** * Label * * <https://github.com/nostr-protocol/nips/blob/master/32.md> */ static label(label_namespace: string, label: string): EventBuilder; /** * Git Repository Announcement * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ static gitRepositoryAnnouncement(data: GitRepositoryAnnouncement): EventBuilder; /** * Git Issue * * <https://github.com/nostr-protocol/nips/blob/master/34.md> */ static gitIssue(issue: GitIssue): EventBuilder; } /** * Event deletion request */ export class EventDeletionRequest { free(): void; constructor(); /** * Event IDs */ ids: EventId[]; /** * Event coordinates */ coordinates: Coordinate[]; /** * Optional reason */ get reason(): string | undefined; /** * Optional reason */ set reason(value: string | null | undefined); } export class EventId { free(): void; constructor(pubkey: PublicKey, created_at: Timestamp, kind: Kind, tags: Tags, content: string); /** * Try to parse event ID from `hex`, `bech32` or [NIP21](https://github.com/nostr-protocol/nips/blob/master/21.md) uri */ static parse(id: string): EventId; static fromSlice(bytes: Uint8Array): EventId; asBytes(): Uint8Array; toHex(): string; toBech32(): string; toNostrUri(): string; } export class Events { private constructor(); free(): void; /** * Returns the number of events in the collection. */ len(): bigint; /** * Returns the number of events in the collection. */ isEmpty(): boolean; /** * Check if contains `Event` */ contains(event: Event): boolean; /** * Merge events collections into a single one. * * Collection is converted to unbounded if one of the merge `Events` have a different hash. * In other words, the filters limit is respected only if the `Events` are related to the same * list of filters. */ merge(other: Events): Events; /** * Get first `Event` (descending order) */ first(): Event | undefined; /** * Convert collection to vector of events. */ forEach(callbackfn: (event: Event) => void): void; /** * Convert collection to vector of events. */ toVec(): Event[]; } export class FailedOutputItem { private constructor(); free(): void; url: string; error: string; } export class FileMetadata { free(): void; constructor(url: string, mime_type: string, hash: string); readonly urls: string; readonly mimeType: string; readonly hash: string; readonly aes256Gcm: Aes256Gcm | undefined; readonly size: number | undefined; readonly dim: ImageDimensions | undefined; readonly magnet: string | undefined; readonly blurhash: string | undefined; } export class Filter { free(): void; constructor(); static fromJson(json: string): Filter; asJson(): string; asPrettyJson(): string; /** * Set event ID */ id(id: EventId): Filter; /** * Set event IDs */ ids(ids: EventId[]): Filter; /** * Remove event IDs */ removeIds(ids: EventId[]): Filter; /** * Set author */ author(author: PublicKey): Filter; /** * Set authors */ authors(authors: PublicKey[]): Filter; /** * Remove authors */ rem