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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#![allow(
    unsafe_code,
    reason = "Client operations require unsafe for FFI calls to xmtp_sys"
)]
//! XMTP client — the primary entry point for the SDK.

mod conversations;
mod identity;

use std::ffi::c_char;
use std::ptr;

use crate::error::{self, Result};
use crate::ffi::{
    FfiList, OwnedHandle, ffi_usize, read_borrowed_strings, take_c_string, to_c_string, to_ffi_len,
};
use crate::types::{
    AccountIdentifier, ApiStats, ConsentEntityType, ConsentState, Env, IdentifierKind,
    IdentityStats, InboxState, KeyPackageStatus, Signer,
};

/// Generate a deterministic inbox ID (no network access required).
pub fn generate_inbox_id(address: &str, kind: IdentifierKind, nonce: u64) -> Result<String> {
    let c = to_c_string(address)?;
    // SAFETY: `c` is a valid CString; FFI function has no preconditions beyond valid pointer.
    let ptr = unsafe { xmtp_sys::xmtp_generate_inbox_id(c.as_ptr(), kind as i32, nonce) };
    // SAFETY: `ptr` is a C string allocated by the FFI layer (or null, handled by `take_c_string`).
    unsafe { take_c_string(ptr) }
}

/// Look up an inbox ID for an identifier on the network.
///
/// Returns `None` if the identifier is not registered.
pub fn get_inbox_id_for_identifier(
    host: &str,
    is_secure: bool,
    address: &str,
    kind: IdentifierKind,
) -> Result<Option<String>> {
    let c_host = to_c_string(host)?;
    let c_addr = to_c_string(address)?;
    let mut out: *mut c_char = ptr::null_mut();
    // SAFETY: All CString pointers are valid; `out` is a valid mutable pointer for the result.
    let rc = unsafe {
        xmtp_sys::xmtp_get_inbox_id_for_identifier(
            c_host.as_ptr(),
            i32::from(is_secure),
            c_addr.as_ptr(),
            kind as i32,
            &raw mut out,
        )
    };
    error::check(rc)?;
    if out.is_null() {
        Ok(None)
    } else {
        // SAFETY: `out` is a non-null C string allocated by the FFI layer.
        unsafe { take_c_string(out) }.map(Some)
    }
}

/// Initialize the FFI tracing logger. Call at most once.
pub fn init_logger(level: Option<&str>) -> Result<()> {
    let c = level.map(to_c_string).transpose()?;
    // SAFETY: Optional CString pointer (or null); FFI function is safe to call once.
    error::check(unsafe {
        xmtp_sys::xmtp_init_logger(c.as_ref().map_or(ptr::null(), |s| s.as_ptr()))
    })
}

/// Get the libxmtp version string.
pub fn libxmtp_version() -> Result<String> {
    // SAFETY: Returns a C string allocated by the FFI layer.
    let ptr = unsafe { xmtp_sys::xmtp_libxmtp_version() };
    // SAFETY: `ptr` is a C string allocated by the FFI layer (or null).
    unsafe { take_c_string(ptr) }
}

/// A connected XMTP client.
pub struct Client {
    pub(crate) handle: OwnedHandle<xmtp_sys::XmtpFfiClient>,
    pub(crate) resolver: Option<Box<dyn crate::resolve::Resolver>>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("handle", &self.handle)
            .field("resolver", &self.resolver.is_some())
            .finish()
    }
}

impl Client {
    /// Create a new [`ClientBuilder`].
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// The inbox ID for this client.
    pub fn inbox_id(&self) -> Result<String> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        let ptr = unsafe { xmtp_sys::xmtp_client_inbox_id(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }
    }

    /// The hex-encoded installation ID.
    pub fn installation_id(&self) -> Result<String> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        let ptr = unsafe { xmtp_sys::xmtp_client_installation_id(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }
    }

    /// Whether this client is registered on the network.
    #[must_use]
    pub fn is_registered(&self) -> bool {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        unsafe { xmtp_sys::xmtp_client_is_registered(self.handle.as_ptr()) == 1 }
    }

    /// The account identifier used to create this client.
    pub fn account_identifier(&self) -> Result<String> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        let ptr = unsafe { xmtp_sys::xmtp_client_account_identifier(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }
    }

    /// The app version string (if set).
    pub fn app_version(&self) -> Result<String> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        let ptr = unsafe { xmtp_sys::xmtp_client_app_version(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }
    }

    /// Release the database connection pool (for background/suspend).
    pub fn release_db(&self) -> Result<()> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        error::check(unsafe { xmtp_sys::xmtp_client_release_db_connection(self.handle.as_ptr()) })
    }

    /// Reconnect the database after a prior release.
    pub fn reconnect_db(&self) -> Result<()> {
        // SAFETY: `self.handle` is a valid FFI client pointer.
        error::check(unsafe { xmtp_sys::xmtp_client_reconnect_db(self.handle.as_ptr()) })
    }

    /// Check which identifiers can receive XMTP messages.
    pub fn can_message(&self, identifiers: &[AccountIdentifier]) -> Result<Vec<bool>> {
        if identifiers.is_empty() {
            return Ok(vec![]);
        }
        let (_owned, ptrs, kinds) = crate::ffi::identifiers_to_ffi(identifiers)?;
        let len = to_ffi_len(ptrs.len())?;
        let mut results = vec![0i32; identifiers.len()];
        // SAFETY: All FFI arrays are valid with matching lengths; `results` is pre-allocated.
        let rc = unsafe {
            xmtp_sys::xmtp_client_can_message(
                self.handle.as_ptr(),
                ptrs.as_ptr(),
                kinds.as_ptr(),
                len,
                results.as_mut_ptr(),
            )
        };
        error::check(rc)?;
        Ok(results.into_iter().map(|r| r == 1).collect())
    }

    /// Look up an inbox ID by identifier using this client's connection.
    pub fn inbox_id_for(&self, address: &str, kind: IdentifierKind) -> Result<Option<String>> {
        let c = to_c_string(address)?;
        let mut out: *mut c_char = ptr::null_mut();
        // SAFETY: Valid CString and handle pointers; `out` receives the result.
        let rc = unsafe {
            xmtp_sys::xmtp_client_get_inbox_id_by_identifier(
                self.handle.as_ptr(),
                c.as_ptr(),
                kind as i32,
                &raw mut out,
            )
        };
        error::check(rc)?;
        if out.is_null() {
            Ok(None)
        } else {
            // SAFETY: `out` is non-null, allocated by the FFI layer.
            unsafe { take_c_string(out) }.map(Some)
        }
    }

    /// Installation ID as raw bytes.
    pub fn installation_id_bytes(&self) -> Result<Vec<u8>> {
        let mut len = 0i32;
        // SAFETY: `self.handle` is a valid FFI client pointer; `len` receives the byte count.
        let ptr = unsafe {
            xmtp_sys::xmtp_client_installation_id_bytes(self.handle.as_ptr(), &raw mut len)
        };
        if ptr.is_null() || len <= 0 {
            return Err(crate::XmtpError::NullPointer);
        }
        // SAFETY: `ptr` points to `len` valid bytes allocated by the FFI layer.
        let bytes = unsafe { std::slice::from_raw_parts(ptr, len as usize) }.to_vec();
        // SAFETY: Frees the byte buffer allocated by the FFI layer.
        unsafe { xmtp_sys::xmtp_free_bytes(ptr, len) };
        Ok(bytes)
    }

    /// Get this client's inbox state. Set `refresh` to fetch from network.
    pub fn inbox_state(&self, refresh: bool) -> Result<Vec<InboxState>> {
        let mut out: *mut xmtp_sys::XmtpFfiInboxStateList = ptr::null_mut();
        // SAFETY: Valid handle pointer; `out` receives the result list.
        let rc = unsafe {
            xmtp_sys::xmtp_client_inbox_state(
                self.handle.as_ptr(),
                i32::from(refresh),
                &raw mut out,
            )
        };
        error::check(rc)?;
        read_inbox_state_list(out)
    }

    /// Fetch inbox states for multiple inbox IDs.
    pub fn inbox_states(&self, inbox_ids: &[&str], refresh: bool) -> Result<Vec<InboxState>> {
        let c_ids: Vec<_> = inbox_ids
            .iter()
            .map(|s| to_c_string(s))
            .collect::<Result<_>>()?;
        let c_ptrs: Vec<*const c_char> = c_ids.iter().map(|c| c.as_ptr()).collect();
        let len = to_ffi_len(c_ptrs.len())?;
        let mut out: *mut xmtp_sys::XmtpFfiInboxStateList = ptr::null_mut();
        // SAFETY: All CString pointers and handle are valid; `out` receives the result.
        let rc = unsafe {
            xmtp_sys::xmtp_client_fetch_inbox_states(
                self.handle.as_ptr(),
                c_ptrs.as_ptr(),
                len,
                i32::from(refresh),
                &raw mut out,
            )
        };
        error::check(rc)?;
        read_inbox_state_list(out)
    }

    /// Sign text with the client's installation key. Returns signature bytes.
    pub fn sign_with_installation_key(&self, text: &str) -> Result<Vec<u8>> {
        let c = to_c_string(text)?;
        let mut out: *mut u8 = ptr::null_mut();
        let mut out_len = 0i32;
        // SAFETY: Valid handle and CString; `out`/`out_len` receive signature bytes.
        let rc = unsafe {
            xmtp_sys::xmtp_client_sign_with_installation_key(
                self.handle.as_ptr(),
                c.as_ptr(),
                &raw mut out,
                &raw mut out_len,
            )
        };
        error::check(rc)?;
        if out.is_null() || out_len <= 0 {
            return Err(crate::XmtpError::NullPointer);
        }
        // SAFETY: `out` points to `out_len` valid bytes allocated by the FFI layer.
        let bytes = unsafe { std::slice::from_raw_parts(out, out_len as usize) }.to_vec();
        // SAFETY: Frees the byte buffer allocated by the FFI layer.
        unsafe { xmtp_sys::xmtp_free_bytes(out, out_len) };
        Ok(bytes)
    }

    /// Verify a signature produced by [`sign_with_installation_key`](Self::sign_with_installation_key).
    pub fn verify_installation_signature(&self, text: &str, signature: &[u8]) -> Result<bool> {
        let c = to_c_string(text)?;
        // SAFETY: Valid handle, CString, and byte slice with matching length.
        let rc = unsafe {
            xmtp_sys::xmtp_client_verify_signed_with_installation_key(
                self.handle.as_ptr(),
                c.as_ptr(),
                signature.as_ptr(),
                to_ffi_len(signature.len())?,
            )
        };
        Ok(rc == 0)
    }

    /// Set consent states for multiple entities.
    pub fn set_consent(&self, entries: &[(ConsentEntityType, ConsentState, &str)]) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }
        let c_strs: Vec<_> = entries
            .iter()
            .map(|(_, _, e)| to_c_string(e))
            .collect::<Result<_>>()?;
        let c_ptrs: Vec<*const c_char> = c_strs.iter().map(|c| c.as_ptr()).collect();
        let types: Vec<i32> = entries.iter().map(|(t, _, _)| *t as i32).collect();
        let states: Vec<i32> = entries.iter().map(|(_, s, _)| *s as i32).collect();
        let len = to_ffi_len(entries.len())?;
        // SAFETY: All parallel arrays are valid with matching `len`.
        error::check(unsafe {
            xmtp_sys::xmtp_client_set_consent_states(
                self.handle.as_ptr(),
                types.as_ptr(),
                states.as_ptr(),
                c_ptrs.as_ptr(),
                len,
            )
        })
    }

    /// Get consent state for a single entity.
    pub fn consent_state(
        &self,
        entity_type: ConsentEntityType,
        entity: &str,
    ) -> Result<ConsentState> {
        let c = to_c_string(entity)?;
        let mut out = 0i32;
        // SAFETY: Valid handle and CString; `out` receives the consent state.
        let rc = unsafe {
            xmtp_sys::xmtp_client_get_consent_state(
                self.handle.as_ptr(),
                entity_type as i32,
                c.as_ptr(),
                &raw mut out,
            )
        };
        error::check(rc)?;
        ConsentState::from_ffi(out)
            .ok_or_else(|| crate::XmtpError::Ffi(format!("unknown consent state: {out}")))
    }

    /// Get MLS API call statistics.
    pub fn mls_stats(&self) -> Result<ApiStats> {
        let mut out = xmtp_sys::XmtpFfiApiStats::default();
        // SAFETY: Valid handle; `out` is a stack-allocated struct for the result.
        error::check(unsafe {
            xmtp_sys::xmtp_client_api_statistics(self.handle.as_ptr(), &raw mut out)
        })?;
        Ok(ApiStats {
            upload_key_package: out.upload_key_package,
            fetch_key_package: out.fetch_key_package,
            send_group_messages: out.send_group_messages,
            send_welcome_messages: out.send_welcome_messages,
            query_group_messages: out.query_group_messages,
            query_welcome_messages: out.query_welcome_messages,
            subscribe_messages: out.subscribe_messages,
            subscribe_welcomes: out.subscribe_welcomes,
            publish_commit_log: out.publish_commit_log,
            query_commit_log: out.query_commit_log,
            get_newest_group_message: out.get_newest_group_message,
        })
    }

    /// Get identity API call statistics.
    pub fn identity_stats(&self) -> Result<IdentityStats> {
        let mut out = xmtp_sys::XmtpFfiIdentityStats::default();
        // SAFETY: Valid handle; `out` is a stack-allocated struct for the result.
        error::check(unsafe {
            xmtp_sys::xmtp_client_api_identity_statistics(self.handle.as_ptr(), &raw mut out)
        })?;
        Ok(IdentityStats {
            publish_identity_update: out.publish_identity_update,
            get_identity_updates_v2: out.get_identity_updates_v2,
            get_inbox_ids: out.get_inbox_ids,
            verify_smart_contract_wallet_signature: out.verify_smart_contract_wallet_signature,
        })
    }

    /// Get aggregate statistics as a human-readable debug string.
    pub fn aggregate_stats(&self) -> Result<String> {
        // SAFETY: Valid handle; returns a C string allocated by the FFI layer.
        let ptr = unsafe { xmtp_sys::xmtp_client_api_aggregate_statistics(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }
    }

    /// Clear all API call statistics.
    pub fn clear_stats(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe { xmtp_sys::xmtp_client_clear_all_statistics(self.handle.as_ptr()) })
    }

    /// Fetch key package statuses for a list of installation IDs (hex).
    pub fn key_package_statuses(&self, installation_ids: &[&str]) -> Result<Vec<KeyPackageStatus>> {
        let (_owned, ptrs) = crate::ffi::to_c_string_array(installation_ids)?;
        let len = to_ffi_len(ptrs.len())?;
        let mut out: *mut xmtp_sys::XmtpFfiKeyPackageStatusList = ptr::null_mut();
        // SAFETY: Valid handle and CString array with matching length; `out` receives the result.
        let rc = unsafe {
            xmtp_sys::xmtp_client_fetch_key_package_statuses(
                self.handle.as_ptr(),
                ptrs.as_ptr(),
                len,
                &raw mut out,
            )
        };
        error::check(rc)?;
        Ok(read_key_package_status_list(out))
    }

    /// Send a device sync request to retrieve records from another installation.
    pub fn request_device_sync(&self) -> Result<()> {
        let opts = xmtp_sys::XmtpFfiArchiveOptions::default();
        // SAFETY: Valid handle; `opts` is a stack-allocated default struct.
        error::check(unsafe {
            xmtp_sys::xmtp_device_sync_send_request(
                self.handle.as_ptr(),
                &raw const opts,
                ptr::null(),
            )
        })
    }
}

/// Builder for constructing a [`Client`].
#[derive(Default)]
pub struct ClientBuilder {
    env: Env,
    db_path: Option<String>,
    encryption_key: Option<Vec<u8>>,
    app_version: Option<String>,
    api_url: Option<String>,
    gateway_host: Option<String>,
    nonce: u64,
    disable_device_sync: bool,
    allow_offline: bool,
    notification_mode: bool,
    resolver: Option<Box<dyn crate::resolve::Resolver>>,
}

impl std::fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("env", &self.env)
            .field("db_path", &self.db_path)
            .field("resolver", &self.resolver.is_some())
            .finish_non_exhaustive()
    }
}

impl ClientBuilder {
    /// Set the network environment (default: [`Env::Dev`]).
    #[must_use]
    pub const fn env(mut self, env: Env) -> Self {
        self.env = env;
        self
    }

    /// Set the local database path. `None` = ephemeral (in-memory).
    #[must_use]
    pub fn db_path(mut self, p: impl Into<String>) -> Self {
        self.db_path = Some(p.into());
        self
    }

    /// Set a 32-byte encryption key for the local database.
    #[must_use]
    pub fn encryption_key(mut self, k: Vec<u8>) -> Self {
        self.encryption_key = Some(k);
        self
    }

    /// Override the API URL (instead of deriving from `env`).
    #[must_use]
    pub fn api_url(mut self, u: impl Into<String>) -> Self {
        self.api_url = Some(u.into());
        self
    }

    /// Set the gateway host URL for decentralized API.
    #[must_use]
    pub fn gateway_host(mut self, h: impl Into<String>) -> Self {
        self.gateway_host = Some(h.into());
        self
    }

    /// Set a custom app version string.
    #[must_use]
    pub fn app_version(mut self, v: impl Into<String>) -> Self {
        self.app_version = Some(v.into());
        self
    }

    /// Set the nonce for inbox ID generation (default: 0, which FFI treats as 1).
    #[must_use]
    pub const fn nonce(mut self, n: u64) -> Self {
        self.nonce = n;
        self
    }

    /// Disable the device sync worker.
    #[must_use]
    pub const fn disable_device_sync(mut self) -> Self {
        self.disable_device_sync = true;
        self
    }

    /// Allow creating the client while offline. The client will sync when
    /// connectivity is restored.
    #[must_use]
    pub const fn allow_offline(mut self) -> Self {
        self.allow_offline = true;
        self
    }

    /// Use notification (read-only) mode. The client will not send messages
    /// or modify state, only receive push notifications.
    #[must_use]
    pub const fn notification_mode(mut self) -> Self {
        self.notification_mode = true;
        self
    }

    /// Set the identity resolver for ENS names and other external identities.
    ///
    /// Without a resolver, [`Recipient::Ens`](crate::Recipient::Ens) variants
    /// will return [`Error::NoResolver`](crate::XmtpError::NoResolver).
    #[must_use]
    pub fn resolver(mut self, r: impl crate::resolve::Resolver + 'static) -> Self {
        self.resolver = Some(Box::new(r));
        self
    }

    /// Build the client, registering identity with `signer` if needed.
    pub fn build(self, signer: &dyn Signer) -> Result<Client> {
        let ident = signer.identifier();
        let client = self.build_inner(&ident.address, ident.kind)?;
        if !client.is_registered() {
            register_identity(&client, signer)?;
        }
        Ok(client)
    }

    /// Build a client for an already-registered identity **without** a signer.
    ///
    /// This is equivalent to Node SDK's `Client.build(identifier)`. The
    /// identity must have been previously registered; no registration attempt
    /// will be made.
    pub fn build_existing(self, address: &str, kind: IdentifierKind) -> Result<Client> {
        self.build_inner(address, kind)
    }

    /// Shared client creation logic.
    fn build_inner(self, address: &str, kind: IdentifierKind) -> Result<Client> {
        let host = self.api_url.as_deref().unwrap_or_else(|| self.env.url());
        let c_host = to_c_string(host)?;
        let c_gateway = self.gateway_host.as_deref().map(to_c_string).transpose()?;
        let c_db = self.db_path.as_deref().map(to_c_string).transpose()?;
        let c_account = to_c_string(address)?;
        let nonce = if self.nonce == 0 { 1 } else { self.nonce };
        let inbox_id = generate_inbox_id(address, kind, nonce)?;
        let c_inbox = to_c_string(&inbox_id)?;
        let c_app = self.app_version.as_deref().map(to_c_string).transpose()?;

        let opts = xmtp_sys::XmtpFfiClientOptions {
            host: c_host.as_ptr(),
            gateway_host: c_gateway.as_ref().map_or(ptr::null(), |c| c.as_ptr()),
            is_secure: i32::from(host.starts_with("https")),
            db_path: c_db.as_ref().map_or(ptr::null(), |c| c.as_ptr()),
            encryption_key: self
                .encryption_key
                .as_deref()
                .map_or(ptr::null(), <[u8]>::as_ptr),
            inbox_id: c_inbox.as_ptr(),
            account_identifier: c_account.as_ptr(),
            identifier_kind: kind as i32,
            nonce,
            auth_handle: ptr::null(),
            app_version: c_app.as_ref().map_or(ptr::null(), |c| c.as_ptr()),
            device_sync_worker_mode: i32::from(self.disable_device_sync),
            allow_offline: i32::from(self.allow_offline),
            client_mode: i32::from(self.notification_mode),
            max_db_pool_size: 0,
            min_db_pool_size: 0,
        };

        let mut raw: *mut xmtp_sys::XmtpFfiClient = ptr::null_mut();
        // SAFETY: `opts` is a fully initialized struct with valid CString pointers that outlive this call.
        error::check(unsafe { xmtp_sys::xmtp_client_create(&raw const opts, &raw mut raw) })?;
        let handle = OwnedHandle::new(raw, xmtp_sys::xmtp_client_free)?;
        Ok(Client {
            handle,
            resolver: self.resolver,
        })
    }
}

/// Sign a signature request using the given signer.
pub(crate) fn sign_request(
    sig_req: &OwnedHandle<xmtp_sys::XmtpFfiSignatureRequest>,
    signer: &dyn Signer,
) -> Result<()> {
    // SAFETY: `sig_req` is a valid signature request handle.
    let ptr = unsafe { xmtp_sys::xmtp_signature_request_text(sig_req.as_ptr()) };
    // SAFETY: `ptr` is a C string allocated by the FFI layer.
    let text = unsafe { take_c_string(ptr) }?;
    let signature = signer.sign(&text)?;
    if signer.is_smart_wallet() {
        let ident = signer.identifier();
        let c_addr = to_c_string(&ident.address)?;
        let sig_len = to_ffi_len(signature.len())?;
        // SAFETY: Valid signature request handle, CString, and byte slice.
        error::check(unsafe {
            xmtp_sys::xmtp_signature_request_add_scw(
                sig_req.as_ptr(),
                c_addr.as_ptr(),
                signature.as_ptr(),
                sig_len,
                signer.chain_id(),
                signer.block_number(),
            )
        })
    } else {
        let sig_len = to_ffi_len(signature.len())?;
        // SAFETY: Valid signature request handle and byte slice with matching length.
        error::check(unsafe {
            xmtp_sys::xmtp_signature_request_add_ecdsa(
                sig_req.as_ptr(),
                signature.as_ptr(),
                sig_len,
            )
        })
    }
}

/// Apply a completed signature request to the client.
pub(crate) fn apply_signature_request(
    client: &Client,
    sig_req: &OwnedHandle<xmtp_sys::XmtpFfiSignatureRequest>,
) -> Result<()> {
    // SAFETY: Both handles are valid FFI pointers.
    error::check(unsafe {
        xmtp_sys::xmtp_client_apply_signature_request(client.handle.as_ptr(), sig_req.as_ptr())
    })
}

fn register_identity(client: &Client, signer: &dyn Signer) -> Result<()> {
    let mut raw: *mut xmtp_sys::XmtpFfiSignatureRequest = ptr::null_mut();
    // SAFETY: Valid handle; `raw` receives the signature request pointer.
    error::check(unsafe {
        xmtp_sys::xmtp_client_create_inbox_signature_request(client.handle.as_ptr(), &raw mut raw)
    })?;
    if raw.is_null() {
        return Ok(());
    }
    let sig_req = OwnedHandle::new(raw, xmtp_sys::xmtp_signature_request_free)?;
    sign_request(&sig_req, signer)?;
    // register_identity publishes the identity update AND uploads key packages.
    // Do NOT call apply_signature_request separately or the identity update will
    // be published twice, causing "Multiple create operations detected".
    // SAFETY: Both handles are valid FFI pointers.
    error::check(unsafe {
        xmtp_sys::xmtp_client_register_identity(client.handle.as_ptr(), sig_req.as_ptr())
    })
}

/// Verify a signature produced by `sign_with_installation_key` using a public key.
/// No client handle required.
pub fn verify_signed_with_public_key(
    text: &str,
    signature: &[u8],
    public_key: &[u8],
) -> Result<bool> {
    let c = to_c_string(text)?;
    let sig_len = to_ffi_len(signature.len())?;
    let key_len = to_ffi_len(public_key.len())?;
    // SAFETY: Valid CString and byte slices with matching lengths.
    let rc = unsafe {
        xmtp_sys::xmtp_verify_signed_with_public_key(
            c.as_ptr(),
            signature.as_ptr(),
            sig_len,
            public_key.as_ptr(),
            key_len,
        )
    };
    Ok(rc == 0)
}

/// Check whether an Ethereum address belongs to an inbox. No client required.
pub fn is_address_authorized(env: Env, inbox_id: &str, address: &str) -> Result<bool> {
    let c_url = to_c_string(env.url())?;
    let c_inbox = to_c_string(inbox_id)?;
    let c_addr = to_c_string(address)?;
    let mut out = 0i32;
    // SAFETY: All CStrings are valid; `out` receives the boolean result.
    let rc = unsafe {
        xmtp_sys::xmtp_is_address_authorized(
            c_url.as_ptr(),
            i32::from(env.is_secure()),
            c_inbox.as_ptr(),
            c_addr.as_ptr(),
            &raw mut out,
        )
    };
    error::check(rc)?;
    Ok(out == 1)
}

/// Check whether an installation (public key bytes) belongs to an inbox. No client required.
pub fn is_installation_authorized(
    env: Env,
    inbox_id: &str,
    installation_id: &[u8],
) -> Result<bool> {
    let c_url = to_c_string(env.url())?;
    let c_inbox = to_c_string(inbox_id)?;
    let mut out = 0i32;
    // SAFETY: Valid CStrings and byte slice with matching length; `out` receives the result.
    let rc = unsafe {
        xmtp_sys::xmtp_is_installation_authorized(
            c_url.as_ptr(),
            i32::from(env.is_secure()),
            c_inbox.as_ptr(),
            installation_id.as_ptr(),
            to_ffi_len(installation_id.len())?,
            &raw mut out,
        )
    };
    error::check(rc)?;
    Ok(out == 1)
}

/// Read an FFI key package status list.
fn read_key_package_status_list(
    ptr: *mut xmtp_sys::XmtpFfiKeyPackageStatusList,
) -> Vec<KeyPackageStatus> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_key_package_status_list_len,
        xmtp_sys::xmtp_key_package_status_list_free,
    );
    let mut statuses = Vec::with_capacity(ffi_usize(list.len()));
    for i in 0..list.len() {
        // SAFETY: `list` is a valid FFI list and `i` is within bounds.
        let p = unsafe { xmtp_sys::xmtp_key_package_status_list_get(list.as_ptr(), i) };
        if p.is_null() {
            continue;
        }
        // SAFETY: `p` is non-null and points to a valid FFI struct.
        let s = unsafe { &*p };
        // SAFETY: `installation_id` is a C string field in the FFI struct.
        let installation_id = unsafe { take_c_string(s.installation_id) }.unwrap_or_default();
        let validation_error = if s.validation_error.is_null() {
            None
        } else {
            // SAFETY: Non-null C string field in the FFI struct.
            unsafe { take_c_string(s.validation_error) }.ok()
        };
        statuses.push(KeyPackageStatus {
            installation_id,
            valid: s.valid == 1,
            not_before: s.not_before,
            not_after: s.not_after,
            validation_error,
        });
    }
    statuses
}

/// Read an FFI inbox state list into `Vec<InboxState>`.
fn read_inbox_state_list(ptr: *mut xmtp_sys::XmtpFfiInboxStateList) -> Result<Vec<InboxState>> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_inbox_state_list_len,
        xmtp_sys::xmtp_inbox_state_list_free,
    );
    let mut states = Vec::with_capacity(ffi_usize(list.len()));
    for i in 0..list.len() {
        let lp = list.as_ptr();
        // SAFETY: `lp` is a valid FFI list and `i` is within bounds.
        let p1 = unsafe { xmtp_sys::xmtp_inbox_state_inbox_id(lp, i) };
        // SAFETY: `p1` is a C string allocated by the FFI layer.
        let inbox_id = unsafe { take_c_string(p1) }?;
        // SAFETY: `lp` is a valid FFI list and `i` is within bounds.
        let p2 = unsafe { xmtp_sys::xmtp_inbox_state_recovery_identifier(lp, i) };
        // SAFETY: `p2` is a C string allocated by the FFI layer.
        let recovery_identifier = unsafe { take_c_string(p2) }?;
        let mut ident_count = 0i32;
        // SAFETY: `lp` is valid; `ident_count` receives the array length.
        let ident_ptr =
            unsafe { xmtp_sys::xmtp_inbox_state_identifiers(lp, i, &raw mut ident_count) };
        // SAFETY: `ident_ptr` points to `ident_count` borrowed C strings.
        let identifiers = unsafe { read_borrowed_strings(ident_ptr, ident_count) };
        let mut inst_count = 0i32;
        // SAFETY: `lp` is valid; `inst_count` receives the array length.
        let inst_ptr =
            unsafe { xmtp_sys::xmtp_inbox_state_installation_ids(lp, i, &raw mut inst_count) };
        // SAFETY: `inst_ptr` points to `inst_count` borrowed C strings.
        let installation_ids = unsafe { read_borrowed_strings(inst_ptr, inst_count) };
        states.push(InboxState {
            inbox_id,
            recovery_identifier,
            identifiers,
            installation_ids,
        });
    }
    Ok(states)
}