xmtp 0.9.3

Safe, ergonomic Rust client SDK for the XMTP messaging protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#![allow(
    unsafe_code,
    reason = "Conversation management requires unsafe for FFI calls to xmtp_sys"
)]
//! Conversation creation, listing, synchronization, and message lookup.

use std::ptr;

use super::Client;
use crate::conversation::{
    Conversation, Message, read_conversation_list_inner, read_enriched_message_list,
    read_hmac_key_map,
};
use crate::error::{self, Result};
use crate::ffi::{
    c_str_ptr, identifiers_to_ffi, optional_c_string, to_c_string, to_c_string_array, to_ffi_len,
};
use crate::resolve::Recipient;
use crate::types::{
    AccountIdentifier, ConsentState, ConversationType, CreateDmOptions, CreateGroupOptions,
    HmacKeyEntry, IdentifierKind, ListConversationsOptions, SyncResult,
};

impl Client {
    /// Create a group with any recipient types.
    ///
    /// Accepts Ethereum addresses, inbox IDs, and ENS names (if a
    /// [`Resolver`](crate::Resolver) is configured). Mixed types are supported.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(client: &xmtp::Client) -> xmtp::Result<()> {
    /// use xmtp::{CreateGroupOptions, Recipient};
    ///
    /// let members = [
    ///     Recipient::parse("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"),
    ///     Recipient::parse("vitalik.eth"),
    /// ];
    /// let opts = CreateGroupOptions { name: Some("My Group".into()), ..Default::default() };
    /// client.group(&members, &opts)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn group(&self, members: &[Recipient], opts: &CreateGroupOptions) -> Result<Conversation> {
        let (identifiers, inbox_ids) = self.resolve_recipients(members)?;
        // Pick the most efficient FFI path.
        if inbox_ids.is_empty() {
            return self.group_by_identifiers(&identifiers, opts);
        }
        if identifiers.is_empty() {
            let ids: Vec<&str> = inbox_ids.iter().map(String::as_str).collect();
            return self.group_by_inbox_ids(&ids, opts);
        }
        // Mixed: resolve identifiers → inbox IDs, then create by inbox IDs.
        let mut all_ids = inbox_ids;
        for ident in &identifiers {
            let id = self
                .inbox_id_for(&ident.address, ident.kind)?
                .ok_or_else(|| {
                    crate::XmtpError::Resolution(format!("no inbox for {}", ident.address))
                })?;
            all_ids.push(id);
        }
        let ids: Vec<&str> = all_ids.iter().map(String::as_str).collect();
        self.group_by_inbox_ids(&ids, opts)
    }

    /// Add members to a group conversation by any recipient type.
    ///
    /// Accepts Ethereum addresses, inbox IDs, and ENS names (if a
    /// [`Resolver`](crate::Resolver) is configured).
    pub fn add_members(&self, conv: &Conversation, members: &[Recipient]) -> Result<()> {
        let (idents, inbox_ids) = self.resolve_recipients(members)?;
        if !idents.is_empty() {
            conv.add_members_by_identity(&idents)?;
        }
        if !inbox_ids.is_empty() {
            let ids: Vec<&str> = inbox_ids.iter().map(String::as_str).collect();
            conv.add_members_by_inbox_id(&ids)?;
        }
        Ok(())
    }

    /// Remove members from a group conversation by any recipient type.
    ///
    /// Accepts Ethereum addresses, inbox IDs, and ENS names (if a
    /// [`Resolver`](crate::Resolver) is configured).
    pub fn remove_members(&self, conv: &Conversation, members: &[Recipient]) -> Result<()> {
        let (idents, inbox_ids) = self.resolve_recipients(members)?;
        if !idents.is_empty() {
            conv.remove_members_by_identity(&idents)?;
        }
        if !inbox_ids.is_empty() {
            let ids: Vec<&str> = inbox_ids.iter().map(String::as_str).collect();
            conv.remove_members_by_inbox_id(&ids)?;
        }
        Ok(())
    }

    /// Check which recipients can receive XMTP messages.
    ///
    /// Returns a parallel `Vec<bool>` — one entry per recipient.
    /// Inbox-ID recipients are assumed reachable (always `true`).
    pub fn can_message_recipients(&self, recipients: &[&Recipient]) -> Result<Vec<bool>> {
        let mut results = vec![true; recipients.len()];
        // Collect address-based recipients that need an on-network check.
        let checks: Vec<(usize, AccountIdentifier)> = recipients
            .iter()
            .enumerate()
            .filter_map(|(i, r)| match r {
                Recipient::Address(a) => Some((
                    i,
                    AccountIdentifier {
                        address: a.clone(),
                        kind: IdentifierKind::Ethereum,
                    },
                )),
                Recipient::Ens(name) => self.resolve_ens(name).ok().map(|addr| {
                    (
                        i,
                        AccountIdentifier {
                            address: addr,
                            kind: IdentifierKind::Ethereum,
                        },
                    )
                }),
                Recipient::InboxId(_) => None,
            })
            .collect();
        if checks.is_empty() {
            return Ok(results);
        }
        let idents: Vec<AccountIdentifier> = checks.iter().map(|(_, id)| id.clone()).collect();
        let flags = self.can_message(&idents)?;
        for ((idx, _), reachable) in checks.into_iter().zip(flags) {
            if let Some(slot) = results.get_mut(idx) {
                *slot = reachable;
            }
        }
        Ok(results)
    }

    /// Resolve an ENS name to an Ethereum address.
    fn resolve_ens(&self, name: &str) -> Result<String> {
        self.resolver
            .as_ref()
            .ok_or(crate::XmtpError::NoResolver)?
            .resolve(name)
    }

    /// Reverse-resolve an Ethereum address to a human-readable name (e.g. ENS).
    ///
    /// Returns `None` if no resolver is configured or no reverse record exists.
    #[must_use]
    pub fn reverse_resolve(&self, address: &str) -> Option<String> {
        self.resolver
            .as_ref()
            .and_then(|r| r.reverse_resolve(address).ok().flatten())
    }

    /// Resolve recipients into identifiers and inbox IDs.
    pub(crate) fn resolve_recipients(
        &self,
        members: &[Recipient],
    ) -> Result<(Vec<AccountIdentifier>, Vec<String>)> {
        let mut idents = Vec::new();
        let mut inbox_ids = Vec::new();
        for m in members {
            match m {
                Recipient::Address(addr) => idents.push(AccountIdentifier {
                    address: addr.clone(),
                    kind: IdentifierKind::Ethereum,
                }),
                Recipient::InboxId(id) => inbox_ids.push(id.clone()),
                Recipient::Ens(name) => idents.push(AccountIdentifier {
                    address: self.resolve_ens(name)?,
                    kind: IdentifierKind::Ethereum,
                }),
            }
        }
        Ok((idents, inbox_ids))
    }

    /// Create a group without syncing (optimistic / offline).
    pub fn group_optimistic(&self, opts: &CreateGroupOptions) -> Result<Conversation> {
        with_group_ffi_opts(opts, |ffi_opts| {
            let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
            // SAFETY: Valid handle and FFI options; `out` receives the result.
            let rc = unsafe {
                xmtp_sys::xmtp_client_create_group_optimistic(
                    self.handle.as_ptr(),
                    ffi_opts,
                    &raw mut out,
                )
            };
            error::check(rc)?;
            Conversation::from_raw(out)
        })
    }

    fn group_by_inbox_ids(
        &self,
        inbox_ids: &[&str],
        opts: &CreateGroupOptions,
    ) -> Result<Conversation> {
        let (_owned, ptrs) = to_c_string_array(inbox_ids)?;
        with_group_ffi_opts(opts, |ffi_opts| {
            let ids_ptr = if ptrs.is_empty() {
                ptr::null()
            } else {
                ptrs.as_ptr()
            };
            let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
            // SAFETY: Valid handle, FFI options, and CString array with matching length.
            let rc = unsafe {
                xmtp_sys::xmtp_client_create_group(
                    self.handle.as_ptr(),
                    ffi_opts,
                    ids_ptr,
                    to_ffi_len(ptrs.len())?,
                    &raw mut out,
                )
            };
            error::check(rc)?;
            Conversation::from_raw(out)
        })
    }

    fn group_by_identifiers(
        &self,
        identifiers: &[AccountIdentifier],
        opts: &CreateGroupOptions,
    ) -> Result<Conversation> {
        let (_owned, ptrs, kinds) = identifiers_to_ffi(identifiers)?;
        with_group_ffi_opts(opts, |ffi_opts| {
            let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
            // SAFETY: Valid handle, FFI options, and identifier arrays with matching length.
            let rc = unsafe {
                xmtp_sys::xmtp_client_create_group_by_identity(
                    self.handle.as_ptr(),
                    ffi_opts,
                    ptrs.as_ptr(),
                    kinds.as_ptr(),
                    to_ffi_len(ptrs.len())?,
                    &raw mut out,
                )
            };
            error::check(rc)?;
            Conversation::from_raw(out)
        })
    }

    /// Find or create a DM with any recipient type.
    ///
    /// Accepts Ethereum addresses, inbox IDs, and ENS names (if a
    /// [`Resolver`](crate::Resolver) is configured).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(client: &xmtp::Client) -> xmtp::Result<()> {
    /// // By address
    /// client.dm(&"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045".into())?;
    /// // By inbox ID
    /// client.dm(&xmtp::Recipient::InboxId("abc123".into()))?;
    /// // By ENS (requires resolver)
    /// client.dm(&"vitalik.eth".into())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn dm(&self, to: &Recipient) -> Result<Conversation> {
        self.dm_with(to, &CreateDmOptions::default())
    }

    /// Find or create a DM with options (e.g. disappearing messages).
    pub fn dm_with(&self, to: &Recipient, opts: &CreateDmOptions) -> Result<Conversation> {
        match to {
            Recipient::Address(addr) => self.dm_by_address(addr, opts),
            Recipient::InboxId(id) => self.dm_by_inbox_id(id, opts),
            Recipient::Ens(name) => self.dm_by_address(&self.resolve_ens(name)?, opts),
        }
    }

    /// Find an existing DM by inbox ID.
    pub fn find_dm(&self, inbox_id: &str) -> Result<Option<Conversation>> {
        let c = to_c_string(inbox_id)?;
        let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
        // SAFETY: Valid handle and CString; `out` receives the conversation pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_client_find_dm_by_inbox_id(
                self.handle.as_ptr(),
                c.as_ptr(),
                &raw mut out,
            )
        };
        error::check(rc)?;
        if out.is_null() {
            Ok(None)
        } else {
            Conversation::from_raw(out).map(Some)
        }
    }

    fn dm_by_address(&self, address: &str, opts: &CreateDmOptions) -> Result<Conversation> {
        let c = to_c_string(address)?;
        let ds = opts.disappearing.unwrap_or_default();
        let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
        // SAFETY: Valid handle and CString; `out` receives the conversation pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_client_create_dm(
                self.handle.as_ptr(),
                c.as_ptr(),
                IdentifierKind::Ethereum as i32,
                ds.from_ns,
                ds.in_ns,
                &raw mut out,
            )
        };
        error::check(rc)?;
        Conversation::from_raw(out)
    }

    fn dm_by_inbox_id(&self, inbox_id: &str, opts: &CreateDmOptions) -> Result<Conversation> {
        let c = to_c_string(inbox_id)?;
        let ds = opts.disappearing.unwrap_or_default();
        let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
        // SAFETY: Valid handle and CString; `out` receives the conversation pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_client_create_dm_by_inbox_id(
                self.handle.as_ptr(),
                c.as_ptr(),
                ds.from_ns,
                ds.in_ns,
                &raw mut out,
            )
        };
        error::check(rc)?;
        Conversation::from_raw(out)
    }

    /// Get a conversation by its hex-encoded group ID.
    pub fn conversation(&self, hex_id: &str) -> Result<Option<Conversation>> {
        let c = to_c_string(hex_id)?;
        let mut out: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
        // SAFETY: Valid handle and CString; `out` receives the conversation pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_client_get_conversation_by_id(
                self.handle.as_ptr(),
                c.as_ptr(),
                &raw mut out,
            )
        };
        error::check(rc)?;
        if out.is_null() {
            Ok(None)
        } else {
            Conversation::from_raw(out).map(Some)
        }
    }

    /// List all conversations with default options.
    pub fn conversations(&self) -> Result<Vec<Conversation>> {
        self.list_conversations(&ListConversationsOptions::default())
    }

    /// List only group conversations.
    pub fn list_groups(&self) -> Result<Vec<Conversation>> {
        self.list_conversations(&ListConversationsOptions {
            conversation_type: Some(ConversationType::Group),
            ..Default::default()
        })
    }

    /// List only DM conversations.
    pub fn list_dms(&self) -> Result<Vec<Conversation>> {
        self.list_conversations(&ListConversationsOptions {
            conversation_type: Some(ConversationType::Dm),
            ..Default::default()
        })
    }

    /// List conversations with filtering options.
    pub fn list_conversations(
        &self,
        options: &ListConversationsOptions,
    ) -> Result<Vec<Conversation>> {
        let consent_i32: Vec<i32> = options.consent_states.iter().map(|s| *s as i32).collect();
        let ffi_opts = xmtp_sys::XmtpFfiListConversationsOptions {
            conversation_type: options.conversation_type.map_or(-1, |t| t as i32),
            limit: options.limit,
            created_after_ns: options.created_after_ns,
            created_before_ns: options.created_before_ns,
            last_activity_after_ns: options.last_activity_after_ns,
            last_activity_before_ns: options.last_activity_before_ns,
            consent_states: if consent_i32.is_empty() {
                ptr::null()
            } else {
                consent_i32.as_ptr()
            },
            consent_states_count: to_ffi_len(consent_i32.len()).unwrap_or(0),
            order_by: options.order_by as i32,
            include_duplicate_dms: i32::from(options.include_duplicate_dms),
        };
        let mut list: *mut xmtp_sys::XmtpFfiConversationList = ptr::null_mut();
        // SAFETY: Valid handle and fully initialized FFI options struct; `list` receives the result.
        let rc = unsafe {
            xmtp_sys::xmtp_client_list_conversations(
                self.handle.as_ptr(),
                &raw const ffi_opts,
                &raw mut list,
            )
        };
        error::check(rc)?;
        read_conversation_list_inner(list)
    }

    /// Sync welcomes (process new group invitations).
    pub fn sync_welcomes(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe { xmtp_sys::xmtp_client_sync_welcomes(self.handle.as_ptr()) })
    }

    /// Sync all conversations, optionally filtered by consent states.
    pub fn sync_all(&self, consent_states: &[ConsentState]) -> Result<SyncResult> {
        let cs: Vec<i32> = consent_states.iter().map(|s| *s as i32).collect();
        let (mut synced, mut eligible) = (0i32, 0i32);
        // SAFETY: Valid handle and consent state array (or null); output pointers are valid.
        let rc = unsafe {
            xmtp_sys::xmtp_client_sync_all(
                self.handle.as_ptr(),
                if cs.is_empty() {
                    ptr::null()
                } else {
                    cs.as_ptr()
                },
                to_ffi_len(cs.len()).unwrap_or(0),
                &raw mut synced,
                &raw mut eligible,
            )
        };
        error::check(rc)?;
        Ok(SyncResult {
            synced: synced as u32,
            eligible: eligible as u32,
        })
    }

    /// Delete a message by its hex ID. Returns the number of deleted rows.
    pub fn delete_message(&self, message_id_hex: &str) -> Result<i32> {
        let c = to_c_string(message_id_hex)?;
        let rows =
            // SAFETY: Valid handle and CString.
            unsafe { xmtp_sys::xmtp_client_delete_message_by_id(self.handle.as_ptr(), c.as_ptr()) };
        if rows < 0 {
            Err(error::last_ffi_error())
        } else {
            Ok(rows)
        }
    }

    /// Get a message by its hex-encoded ID.
    pub fn message_by_id(&self, message_id_hex: &str) -> Result<Option<Message>> {
        let c = to_c_string(message_id_hex)?;
        let mut out: *mut xmtp_sys::XmtpFfiEnrichedMessageList = ptr::null_mut();
        // SAFETY: Valid handle and CString; `out` receives the message list.
        let rc = unsafe {
            xmtp_sys::xmtp_client_get_enriched_message_by_id(
                self.handle.as_ptr(),
                c.as_ptr(),
                &raw mut out,
            )
        };
        error::check(rc)?;
        Ok(read_enriched_message_list(out).into_iter().next())
    }

    /// Sync preferences (device sync groups only).
    pub fn sync_preferences(&self) -> Result<SyncResult> {
        let (mut synced, mut eligible) = (0i32, 0i32);
        // SAFETY: Valid handle; output pointers receive sync counts.
        let rc = unsafe {
            xmtp_sys::xmtp_client_sync_preferences(
                self.handle.as_ptr(),
                &raw mut synced,
                &raw mut eligible,
            )
        };
        error::check(rc)?;
        Ok(SyncResult {
            synced: synced as u32,
            eligible: eligible as u32,
        })
    }

    /// Get HMAC keys for all conversations. For push notification verification.
    pub fn hmac_keys(&self) -> Result<Vec<HmacKeyEntry>> {
        let mut map: *mut xmtp_sys::XmtpFfiHmacKeyMap = ptr::null_mut();
        // SAFETY: Valid handle; `map` receives the HMAC key map.
        let rc = unsafe { xmtp_sys::xmtp_client_hmac_keys(self.handle.as_ptr(), &raw mut map) };
        error::check(rc)?;
        Ok(read_hmac_key_map(map))
    }
}

/// Build FFI group options and pass them to a closure. `CStrings` live on the
/// stack and are valid for the duration of `f`.
fn with_group_ffi_opts<R>(
    options: &CreateGroupOptions,
    f: impl FnOnce(&xmtp_sys::XmtpFfiCreateGroupOptions) -> Result<R>,
) -> Result<R> {
    let c_name = optional_c_string(options.name.as_deref())?;
    let c_desc = optional_c_string(options.description.as_deref())?;
    let c_img = optional_c_string(options.image_url.as_deref())?;
    let c_app = optional_c_string(options.app_data.as_deref())?;
    let ds = options.disappearing.unwrap_or_default();
    let ffi = xmtp_sys::XmtpFfiCreateGroupOptions {
        permissions: options.permissions.map_or(0, |p| p as i32),
        name: c_str_ptr(c_name.as_ref()),
        description: c_str_ptr(c_desc.as_ref()),
        image_url: c_str_ptr(c_img.as_ref()),
        app_data: c_str_ptr(c_app.as_ref()),
        message_disappear_from_ns: ds.from_ns,
        message_disappear_in_ns: ds.in_ns,
    };
    f(&ffi)
}