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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
#![allow(
    unsafe_code,
    reason = "Conversation operations require unsafe for FFI calls to xmtp_sys"
)]
//! Conversation operations: send, messages, members, metadata, consent,
//! disappearing messages, admin management, permissions, debug info, and HMAC keys.

use std::ffi::{CStr, c_char};
use std::ptr;

use crate::error::{self, Result};
use crate::ffi::{
    FfiList, OwnedHandle, borrow_c_string, borrow_nullable_string, ffi_usize, identifiers_to_ffi,
    read_borrowed_strings, take_c_string, take_nullable_string, to_c_string, to_c_string_array,
    to_ffi_len,
};
use crate::types::{
    AccountIdentifier, ConsentState, ConversationDebugInfo, ConversationMetadata, ConversationType,
    Cursor, DeliveryStatus, DisappearingSettings, GroupPermissionsPreset, HmacKey, HmacKeyEntry,
    LastReadTime, ListMessagesOptions, MembershipState, MessageKind, MetadataField,
    PermissionLevel, PermissionPolicy, PermissionPolicySet, PermissionUpdateType, Permissions,
    SendOptions, SortDirection,
};

/// Action for updating the admin list via FFI.
#[repr(i32)]
enum AdminAction {
    Add = 0,
    Remove = 1,
    AddSuper = 2,
    RemoveSuper = 3,
}

/// Generate a nullable-string getter method on `Conversation`.
macro_rules! metadata_getter {
    ($(#[$m:meta])* $name:ident, $ffi_fn:path) => {
        $(#[$m])*
        pub fn $name(&self) -> Option<String> {
            // SAFETY: `self.handle` is a valid FFI conversation pointer.
            unsafe { take_nullable_string($ffi_fn(self.handle.as_ptr())) }
        }
    };
}

/// Generate a string setter method on `Conversation`.
macro_rules! metadata_setter {
    ($(#[$m:meta])* $name:ident, $ffi_fn:path) => {
        $(#[$m])*
        pub fn $name(&self, value: &str) -> Result<()> {
            let c = to_c_string(value)?;
            // SAFETY: Valid handle and CString.
            error::check(unsafe { $ffi_fn(self.handle.as_ptr(), c.as_ptr()) })
        }
    };
}

/// An enriched message from a conversation.
#[derive(Debug, Clone)]
pub struct Message {
    /// Hex-encoded message ID.
    pub id: String,
    /// Hex-encoded group/conversation ID.
    pub conversation_id: String,
    /// Sender's inbox ID.
    pub sender_inbox_id: String,
    /// Sender's installation ID (hex).
    pub sender_installation_id: String,
    /// Sent timestamp in nanoseconds.
    pub sent_at_ns: i64,
    /// Inserted-into-DB timestamp in nanoseconds.
    pub inserted_at_ns: i64,
    /// Message kind.
    pub kind: MessageKind,
    /// Delivery status.
    pub delivery_status: DeliveryStatus,
    /// Content type ID (e.g. `"xmtp.org/text:1.0"`).
    pub content_type: Option<String>,
    /// Fallback text for unsupported content types.
    pub fallback: Option<String>,
    /// Raw decrypted content bytes (protobuf-encoded `EncodedContent`).
    pub content: Vec<u8>,
    /// Expiration timestamp in nanoseconds (0 = no expiration).
    pub expires_at_ns: i64,
    /// Number of reactions to this message.
    pub num_reactions: i32,
    /// Number of replies to this message.
    pub num_replies: i32,
}

/// A member of a group conversation.
#[derive(Debug, Clone)]
pub struct GroupMember {
    /// Member's inbox ID.
    pub inbox_id: String,
    /// Permission level within the group.
    pub permission_level: PermissionLevel,
    /// Consent state.
    pub consent_state: ConsentState,
    /// Associated account identifiers (addresses).
    pub account_identifiers: Vec<String>,
    /// Installation IDs (hex).
    pub installation_ids: Vec<String>,
}

/// A conversation handle (DM or group).
#[derive(Debug)]
pub struct Conversation {
    handle: OwnedHandle<xmtp_sys::XmtpFfiConversation>,
}

impl Conversation {
    /// Wrap a raw FFI conversation pointer. Takes ownership.
    pub(crate) fn from_raw(ptr: *mut xmtp_sys::XmtpFfiConversation) -> Result<Self> {
        OwnedHandle::new(ptr, xmtp_sys::xmtp_conversation_free).map(|h| Self { handle: h })
    }

    /// Raw const pointer for the stream module.
    pub(crate) const fn handle_ptr(&self) -> *const xmtp_sys::XmtpFfiConversation {
        self.handle.as_ptr()
    }

    /// Hex-encoded group ID.
    #[must_use]
    pub fn id(&self) -> String {
        // SAFETY: `self.handle` is a valid FFI conversation pointer.
        let ptr = unsafe { xmtp_sys::xmtp_conversation_id(self.handle.as_ptr()) };
        // SAFETY: `ptr` is a C string allocated by the FFI layer.
        unsafe { take_c_string(ptr) }.unwrap_or_default()
    }

    /// Conversation type (DM, Group, etc.).
    #[must_use]
    pub fn conversation_type(&self) -> Option<ConversationType> {
        // SAFETY: `self.handle` is a valid FFI conversation pointer.
        ConversationType::from_ffi(unsafe {
            xmtp_sys::xmtp_conversation_type(self.handle.as_ptr())
        })
    }

    /// Created-at timestamp in nanoseconds.
    #[must_use]
    pub fn created_at_ns(&self) -> i64 {
        // SAFETY: `self.handle` is a valid FFI conversation pointer.
        unsafe { xmtp_sys::xmtp_conversation_created_at_ns(self.handle.as_ptr()) }
    }

    /// Whether the conversation is active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        // SAFETY: `self.handle` is a valid FFI conversation pointer.
        unsafe { xmtp_sys::xmtp_conversation_is_active(self.handle.as_ptr()) == 1 }
    }

    /// Current membership state of this client in the conversation.
    #[must_use]
    pub fn membership_state(&self) -> Option<MembershipState> {
        // SAFETY: `self.handle` is a valid FFI conversation pointer.
        MembershipState::from_ffi(unsafe {
            xmtp_sys::xmtp_conversation_membership_state(self.handle.as_ptr())
        })
    }

    metadata_getter!(/// DM peer's inbox ID. Returns `None` if not a DM.
        dm_peer_inbox_id, xmtp_sys::xmtp_conversation_dm_peer_inbox_id);
    metadata_getter!(/// Inbox ID of the member who added this client.
        added_by_inbox_id, xmtp_sys::xmtp_conversation_added_by_inbox_id);
    metadata_getter!(/// Get the group name.
        name, xmtp_sys::xmtp_conversation_group_name);
    metadata_setter!(/// Set the group name.
        set_name, xmtp_sys::xmtp_conversation_update_group_name);
    metadata_getter!(/// Get the group description.
        description, xmtp_sys::xmtp_conversation_group_description);
    metadata_setter!(/// Set the group description.
        set_description, xmtp_sys::xmtp_conversation_update_group_description);
    metadata_getter!(/// Get the group image URL.
        image_url, xmtp_sys::xmtp_conversation_group_image_url);
    metadata_setter!(/// Set the group image URL.
        set_image_url, xmtp_sys::xmtp_conversation_update_group_image_url);
    metadata_getter!(/// Get app data string.
        app_data, xmtp_sys::xmtp_conversation_app_data);
    metadata_setter!(/// Set app data (max 8192 bytes).
        set_app_data, xmtp_sys::xmtp_conversation_update_app_data);

    /// Check if conversation is paused for a version upgrade.
    pub fn paused_for_version(&self) -> Result<Option<String>> {
        let mut out: *mut c_char = ptr::null_mut();
        // SAFETY: Valid handle; `out` receives a nullable C string.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_paused_for_version(self.handle.as_ptr(), &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)
        }
    }

    /// Get the conversation metadata (creator inbox ID + type).
    pub fn metadata(&self) -> Result<ConversationMetadata> {
        let mut out: *mut xmtp_sys::XmtpFfiGroupMetadata = ptr::null_mut();
        // SAFETY: Valid handle; `out` receives the metadata pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_group_metadata(self.handle.as_ptr(), &raw mut out)
        };
        error::check(rc)?;
        if out.is_null() {
            return Err(crate::XmtpError::NullPointer);
        }
        // SAFETY: `out` is non-null and points to a valid FFI struct.
        let meta = unsafe { &*out };
        // SAFETY: `creator_inbox_id` is a C string field in the FFI struct.
        let creator = unsafe { take_c_string(meta.creator_inbox_id) }.unwrap_or_default();
        let conv_type = ConversationType::from_ffi(meta.conversation_type as i32)
            .unwrap_or(ConversationType::Group);
        // SAFETY: `out` was allocated by the FFI layer and must be freed.
        unsafe { xmtp_sys::xmtp_group_metadata_free(out) };
        Ok(ConversationMetadata {
            creator_inbox_id: creator,
            conversation_type: conv_type,
        })
    }

    /// Get the group permissions (preset + full policy set).
    pub fn permissions(&self) -> Result<Permissions> {
        let mut out: *mut xmtp_sys::XmtpFfiGroupPermissions = ptr::null_mut();
        // SAFETY: Valid handle; `out` receives the permissions pointer.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_group_permissions(self.handle.as_ptr(), &raw mut out)
        };
        error::check(rc)?;
        if out.is_null() {
            return Err(crate::XmtpError::NullPointer);
        }
        // SAFETY: `out` is non-null and points to a valid FFI struct.
        let perms = unsafe { &*out };
        let result = read_permissions(perms);
        // SAFETY: `out` was allocated by the FFI layer and must be freed.
        unsafe { xmtp_sys::xmtp_group_permissions_free(out) };
        Ok(result)
    }

    /// Sync this conversation with the network.
    pub fn sync(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe { xmtp_sys::xmtp_conversation_sync(self.handle.as_ptr()) })
    }

    /// Send raw encoded content bytes. Returns the hex-encoded message ID.
    pub fn send(&self, content: &[u8]) -> Result<String> {
        self.send_inner(content, ptr::null(), xmtp_sys::xmtp_conversation_send)
    }

    /// Send with options. Returns the hex-encoded message ID.
    pub fn send_with(&self, content: &[u8], opts: &SendOptions) -> Result<String> {
        let ffi = send_opts_to_ffi(*opts);
        self.send_inner(content, &raw const ffi, xmtp_sys::xmtp_conversation_send)
    }

    /// Send optimistically (returns immediately, publishes in background).
    pub fn send_optimistic(&self, content: &[u8]) -> Result<String> {
        self.send_inner(
            content,
            ptr::null(),
            xmtp_sys::xmtp_conversation_send_optimistic,
        )
    }

    /// Send optimistically with options.
    pub fn send_optimistic_with(&self, content: &[u8], opts: &SendOptions) -> Result<String> {
        let ffi = send_opts_to_ffi(*opts);
        self.send_inner(
            content,
            &raw const ffi,
            xmtp_sys::xmtp_conversation_send_optimistic,
        )
    }

    /// Shared send implementation.
    fn send_inner(
        &self,
        content: &[u8],
        opts: *const xmtp_sys::XmtpFfiSendOpts,
        ffi_fn: unsafe extern "C" fn(
            *const xmtp_sys::XmtpFfiConversation,
            *const u8,
            i32,
            *const xmtp_sys::XmtpFfiSendOpts,
            *mut *mut c_char,
        ) -> i32,
    ) -> Result<String> {
        let len = to_ffi_len(content.len())?;
        let mut out: *mut c_char = ptr::null_mut();
        // SAFETY: Valid handle, content buffer, and FFI options; `out` receives the message ID.
        let rc = unsafe {
            ffi_fn(
                self.handle.as_ptr(),
                content.as_ptr(),
                len,
                opts,
                &raw mut out,
            )
        };
        error::check(rc)?;
        // SAFETY: `out` is a C string allocated by the FFI layer.
        unsafe { take_c_string(out) }
    }

    /// Publish all queued (unpublished) messages.
    pub fn publish_messages(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe { xmtp_sys::xmtp_conversation_publish_messages(self.handle.as_ptr()) })
    }

    /// List all messages with default options.
    pub fn messages(&self) -> Result<Vec<Message>> {
        self.list_messages(&ListMessagesOptions::default())
    }

    /// List messages with filtering options.
    pub fn list_messages(&self, options: &ListMessagesOptions) -> Result<Vec<Message>> {
        let ffi_opts = msg_opts_to_ffi(options);
        let mut list: *mut xmtp_sys::XmtpFfiEnrichedMessageList = ptr::null_mut();
        // SAFETY: Valid handle and FFI options; `list` receives the message list.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_list_enriched_messages(
                self.handle.as_ptr(),
                &raw const ffi_opts,
                &raw mut list,
            )
        };
        error::check(rc)?;
        Ok(read_enriched_message_list(list))
    }

    /// Count messages matching filter options.
    #[must_use]
    pub fn count_messages(&self, options: &ListMessagesOptions) -> i64 {
        let ffi_opts = msg_opts_to_ffi(options);
        // SAFETY: Valid handle and FFI options struct.
        unsafe {
            xmtp_sys::xmtp_conversation_count_messages(self.handle.as_ptr(), &raw const ffi_opts)
        }
    }

    /// List members of this conversation.
    pub fn members(&self) -> Result<Vec<GroupMember>> {
        let mut list: *mut xmtp_sys::XmtpFfiGroupMemberList = ptr::null_mut();
        // SAFETY: Valid handle; `list` receives the member list.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_list_members(self.handle.as_ptr(), &raw mut list)
        };
        error::check(rc)?;
        read_member_list(list)
    }

    /// Add members by inbox IDs.
    pub fn add_members_by_inbox_id(&self, inbox_ids: &[&str]) -> Result<()> {
        let (_owned, ptrs) = to_c_string_array(inbox_ids)?;
        let len = to_ffi_len(ptrs.len())?;
        // SAFETY: Valid handle and CString array with matching length.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_add_members(self.handle.as_ptr(), ptrs.as_ptr(), len)
        })
    }

    /// Remove members by inbox IDs.
    pub fn remove_members_by_inbox_id(&self, inbox_ids: &[&str]) -> Result<()> {
        let (_owned, ptrs) = to_c_string_array(inbox_ids)?;
        let len = to_ffi_len(ptrs.len())?;
        // SAFETY: Valid handle and CString array with matching length.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_remove_members(self.handle.as_ptr(), ptrs.as_ptr(), len)
        })
    }

    /// Add members by external identifiers (address + kind).
    pub fn add_members_by_identity(&self, identifiers: &[AccountIdentifier]) -> Result<()> {
        let (_owned, ptrs, kinds) = identifiers_to_ffi(identifiers)?;
        let len = to_ffi_len(ptrs.len())?;
        // SAFETY: Valid handle and identifier arrays with matching length.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_add_members_by_identity(
                self.handle.as_ptr(),
                ptrs.as_ptr(),
                kinds.as_ptr(),
                len,
            )
        })
    }

    /// Remove members by external identifiers (address + kind).
    pub fn remove_members_by_identity(&self, identifiers: &[AccountIdentifier]) -> Result<()> {
        let (_owned, ptrs, kinds) = identifiers_to_ffi(identifiers)?;
        let len = to_ffi_len(ptrs.len())?;
        // SAFETY: Valid handle and identifier arrays with matching length.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_remove_members_by_identity(
                self.handle.as_ptr(),
                ptrs.as_ptr(),
                kinds.as_ptr(),
                len,
            )
        })
    }

    /// Leave this group conversation.
    pub fn leave(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe { xmtp_sys::xmtp_conversation_leave(self.handle.as_ptr()) })
    }

    /// Get the consent state for this conversation.
    pub fn consent_state(&self) -> Result<ConsentState> {
        let mut out = 0i32;
        // SAFETY: Valid handle; `out` receives the consent state.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_consent_state(self.handle.as_ptr(), &raw mut out)
        };
        error::check(rc)?;
        ConsentState::from_ffi(out)
            .ok_or_else(|| crate::XmtpError::Ffi(format!("unknown consent state: {out}")))
    }

    /// Set the consent state for this conversation.
    pub fn set_consent(&self, state: ConsentState) -> Result<()> {
        // SAFETY: Valid handle and consent state value.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_update_consent_state(self.handle.as_ptr(), state as i32)
        })
    }

    /// Get the current disappearing message settings.
    #[must_use]
    pub fn disappearing_settings(&self) -> Option<DisappearingSettings> {
        let mut out = xmtp_sys::XmtpFfiDisappearingSettings::default();
        // SAFETY: Valid handle; `out` is a stack-allocated struct for the result.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_disappearing_settings(self.handle.as_ptr(), &raw mut out)
        };
        if rc == 0 {
            Some(DisappearingSettings {
                from_ns: out.from_ns,
                in_ns: out.in_ns,
            })
        } else {
            None
        }
    }

    /// Set disappearing message settings.
    pub fn set_disappearing(&self, settings: DisappearingSettings) -> Result<()> {
        let ffi = xmtp_sys::XmtpFfiDisappearingSettings {
            from_ns: settings.from_ns,
            in_ns: settings.in_ns,
        };
        // SAFETY: Valid handle and FFI settings struct.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_update_disappearing_settings(
                self.handle.as_ptr(),
                &raw const ffi,
            )
        })
    }

    /// Clear disappearing message settings.
    pub fn clear_disappearing(&self) -> Result<()> {
        // SAFETY: Valid handle pointer.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_remove_disappearing_settings(self.handle.as_ptr())
        })
    }

    /// Whether disappearing messages are enabled.
    #[must_use]
    pub fn is_disappearing_enabled(&self) -> bool {
        // SAFETY: Valid handle pointer.
        unsafe { xmtp_sys::xmtp_conversation_is_disappearing_enabled(self.handle.as_ptr()) == 1 }
    }

    /// Set a permission policy on this conversation.
    ///
    /// The `metadata_field` is only used when `update_type` is
    /// [`PermissionUpdateType::UpdateMetadata`].
    pub fn set_permission_policy(
        &self,
        update_type: PermissionUpdateType,
        policy: PermissionPolicy,
        metadata_field: Option<MetadataField>,
    ) -> Result<()> {
        let c_field = metadata_field
            .map(|f| to_c_string(f.as_str()))
            .transpose()?;
        // SAFETY: Valid handle, update type, policy, and optional CString field.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_update_permission_policy(
                self.handle.as_ptr(),
                update_type as i32,
                policy.to_write_i32(),
                c_field.as_ref().map_or(ptr::null(), |c| c.as_ptr()),
            )
        })
    }

    /// Get the last message in this conversation, if any.
    pub fn last_message(&self) -> Result<Option<Message>> {
        let opts = ListMessagesOptions {
            limit: 1,
            direction: Some(SortDirection::Descending),
            ..Default::default()
        };
        Ok(self.list_messages(&opts)?.into_iter().next())
    }

    /// Add an admin.
    pub fn add_admin(&self, inbox_id: &str) -> Result<()> {
        self.update_admin_list(inbox_id, AdminAction::Add)
    }

    /// Remove an admin.
    pub fn remove_admin(&self, inbox_id: &str) -> Result<()> {
        self.update_admin_list(inbox_id, AdminAction::Remove)
    }

    /// Add a super admin.
    pub fn add_super_admin(&self, inbox_id: &str) -> Result<()> {
        self.update_admin_list(inbox_id, AdminAction::AddSuper)
    }

    /// Remove a super admin.
    pub fn remove_super_admin(&self, inbox_id: &str) -> Result<()> {
        self.update_admin_list(inbox_id, AdminAction::RemoveSuper)
    }

    /// Low-level admin list update.
    fn update_admin_list(&self, inbox_id: &str, action: AdminAction) -> Result<()> {
        let c = to_c_string(inbox_id)?;
        // SAFETY: Valid handle, CString, and action code.
        error::check(unsafe {
            xmtp_sys::xmtp_conversation_update_admin_list(
                self.handle.as_ptr(),
                c.as_ptr(),
                action as i32,
            )
        })
    }

    /// Admin inbox IDs.
    #[must_use]
    pub fn admins(&self) -> Vec<String> {
        let mut count = 0i32;
        // SAFETY: Valid handle; `count` receives the array length.
        let ptr = unsafe {
            xmtp_sys::xmtp_conversation_list_admins(self.handle.as_ptr(), &raw mut count)
        };
        // SAFETY: `ptr` points to `count` borrowed C strings.
        unsafe { read_borrowed_strings(ptr.cast_const(), count) }
    }

    /// Super admin inbox IDs.
    #[must_use]
    pub fn super_admins(&self) -> Vec<String> {
        let mut count = 0i32;
        // SAFETY: Valid handle; `count` receives the array length.
        let ptr = unsafe {
            xmtp_sys::xmtp_conversation_list_super_admins(self.handle.as_ptr(), &raw mut count)
        };
        // SAFETY: `ptr` points to `count` borrowed C strings.
        unsafe { read_borrowed_strings(ptr.cast_const(), count) }
    }

    /// Check if the given inbox ID is an admin.
    #[must_use]
    pub fn is_admin(&self, inbox_id: &str) -> bool {
        // SAFETY: Valid handle and CString.
        to_c_string(inbox_id).is_ok_and(|c| unsafe {
            xmtp_sys::xmtp_conversation_is_admin(self.handle.as_ptr(), c.as_ptr()) == 1
        })
    }

    /// Check if the given inbox ID is a super admin.
    #[must_use]
    pub fn is_super_admin(&self, inbox_id: &str) -> bool {
        // SAFETY: Valid handle and CString.
        to_c_string(inbox_id).is_ok_and(|c| unsafe {
            xmtp_sys::xmtp_conversation_is_super_admin(self.handle.as_ptr(), c.as_ptr()) == 1
        })
    }

    /// Find duplicate DM conversations for this DM.
    pub fn duplicate_dms(&self) -> Result<Vec<Self>> {
        let mut list: *mut xmtp_sys::XmtpFfiConversationList = ptr::null_mut();
        // SAFETY: Valid handle; `list` receives the conversation list.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_duplicate_dms(self.handle.as_ptr(), &raw mut list)
        };
        error::check(rc)?;
        read_conversation_list_inner(list)
    }

    /// Get debug information for this conversation.
    pub fn debug_info(&self) -> Result<ConversationDebugInfo> {
        let mut out = xmtp_sys::XmtpFfiConversationDebugInfo::default();
        let rc =
            // SAFETY: Valid handle; `out` is a stack-allocated struct for the result.
            unsafe { xmtp_sys::xmtp_conversation_debug_info(self.handle.as_ptr(), &raw mut out) };
        error::check(rc)?;
        let info = read_debug_info(&out);
        // SAFETY: `out` contains FFI-allocated fields that must be freed.
        unsafe { xmtp_sys::xmtp_conversation_debug_info_free(&raw mut out) };
        Ok(info)
    }

    /// Get per-inbox last-read timestamps.
    pub fn last_read_times(&self) -> Result<Vec<LastReadTime>> {
        let mut list: *mut xmtp_sys::XmtpFfiLastReadTimeList = ptr::null_mut();
        // SAFETY: Valid handle; `list` receives the last-read-time list.
        let rc = unsafe {
            xmtp_sys::xmtp_conversation_last_read_times(self.handle.as_ptr(), &raw mut list)
        };
        error::check(rc)?;
        Ok(read_last_read_times(list))
    }

    /// Get HMAC keys for this conversation (including duplicate DMs).
    pub fn hmac_keys(&self) -> Result<Vec<HmacKeyEntry>> {
        let mut map: *mut xmtp_sys::XmtpFfiHmacKeyMap = ptr::null_mut();
        let rc =
            // SAFETY: Valid handle; `map` receives the HMAC key map.
            unsafe { xmtp_sys::xmtp_conversation_hmac_keys(self.handle.as_ptr(), &raw mut map) };
        error::check(rc)?;
        Ok(read_hmac_key_map(map))
    }
}

/// Convert `SendOptions` to the FFI struct.
fn send_opts_to_ffi(opts: SendOptions) -> xmtp_sys::XmtpFfiSendOpts {
    xmtp_sys::XmtpFfiSendOpts {
        should_push: i32::from(opts.should_push),
    }
}

/// Convert `ListMessagesOptions` to the FFI struct.
pub(crate) fn msg_opts_to_ffi(
    options: &ListMessagesOptions,
) -> xmtp_sys::XmtpFfiListMessagesOptions {
    xmtp_sys::XmtpFfiListMessagesOptions {
        sent_after_ns: options.sent_after_ns,
        sent_before_ns: options.sent_before_ns,
        limit: options.limit,
        delivery_status: options.delivery_status.map_or(-1, |d| d as i32),
        kind: options.kind.map_or(-1, |k| k as i32),
        direction: options.direction.map_or(0, |d| d as i32),
        ..Default::default()
    }
}

/// Read enriched messages from an FFI list into a `Vec<Message>`.
pub(crate) fn read_enriched_message_list(
    ptr: *mut xmtp_sys::XmtpFfiEnrichedMessageList,
) -> Vec<Message> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_enriched_message_list_len,
        xmtp_sys::xmtp_enriched_message_list_free,
    );
    let mut msgs = 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_enriched_message_list_get(list.as_ptr(), i) };
        if p.is_null() {
            continue;
        }
        // SAFETY: `p` is non-null and points to a valid FFI struct.
        let m = unsafe { &*p };
        let content = if m.content_bytes.is_null() || m.content_bytes_len <= 0 {
            Vec::new()
        } else {
            // SAFETY: `content_bytes` is non-null with `content_bytes_len` valid bytes.
            unsafe { std::slice::from_raw_parts(m.content_bytes, ffi_usize(m.content_bytes_len)) }
                .to_vec()
        };
        msgs.push(Message {
            // SAFETY: Borrowed C string field in the FFI struct.
            id: unsafe { borrow_c_string(m.id) },
            // SAFETY: Borrowed C string field in the FFI struct.
            conversation_id: unsafe { borrow_c_string(m.group_id) },
            // SAFETY: Borrowed C string field in the FFI struct.
            sender_inbox_id: unsafe { borrow_c_string(m.sender_inbox_id) },
            // SAFETY: Borrowed C string field in the FFI struct.
            sender_installation_id: unsafe { borrow_c_string(m.sender_installation_id) },
            sent_at_ns: m.sent_at_ns,
            inserted_at_ns: m.inserted_at_ns,
            kind: MessageKind::from_ffi(m.kind as i32).unwrap_or(MessageKind::Application),
            delivery_status: DeliveryStatus::from_ffi(m.delivery_status as i32)
                .unwrap_or(DeliveryStatus::Unpublished),
            // SAFETY: Nullable borrowed C string field.
            content_type: unsafe { borrow_nullable_string(m.content_type) },
            // SAFETY: Nullable borrowed C string field.
            fallback: unsafe { borrow_nullable_string(m.fallback_text) },
            content,
            expires_at_ns: m.expires_at_ns,
            num_reactions: m.num_reactions,
            num_replies: m.num_replies,
        });
    }
    msgs
}

/// Read all members from an FFI group member list.
fn read_member_list(ptr: *mut xmtp_sys::XmtpFfiGroupMemberList) -> Result<Vec<GroupMember>> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_group_member_list_len,
        xmtp_sys::xmtp_group_member_list_free,
    );
    let mut members = 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 p = unsafe { xmtp_sys::xmtp_group_member_inbox_id(lp, i) };
        // SAFETY: `p` is a C string allocated by the FFI layer.
        let inbox_id = unsafe { take_c_string(p) }?;
        // SAFETY: `lp` is a valid FFI list and `i` is within bounds.
        let permission_level = PermissionLevel::from_ffi(unsafe {
            xmtp_sys::xmtp_group_member_permission_level(lp, i)
        })
        .unwrap_or(PermissionLevel::Member);
        // SAFETY: `lp` is a valid FFI list and `i` is within bounds.
        let consent_state =
            ConsentState::from_ffi(unsafe { xmtp_sys::xmtp_group_member_consent_state(lp, i) })
                .unwrap_or(ConsentState::Unknown);

        let mut acct_count = 0i32;
        // SAFETY: `lp` is valid; `acct_count` receives the array length.
        let acct_ptr =
            unsafe { xmtp_sys::xmtp_group_member_account_identifiers(lp, i, &raw mut acct_count) };
        // SAFETY: `acct_ptr` points to `acct_count` borrowed C strings.
        let account_identifiers = unsafe { read_borrowed_strings(acct_ptr, acct_count) };

        let mut inst_count = 0i32;
        // SAFETY: `lp` is valid; `inst_count` receives the array length.
        let inst_ptr =
            unsafe { xmtp_sys::xmtp_group_member_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) };

        members.push(GroupMember {
            inbox_id,
            permission_level,
            consent_state,
            account_identifiers,
            installation_ids,
        });
    }
    Ok(members)
}

/// Read a conversation list into a `Vec<Conversation>`.
pub(crate) fn read_conversation_list_inner(
    ptr: *mut xmtp_sys::XmtpFfiConversationList,
) -> Result<Vec<Conversation>> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_conversation_list_len,
        xmtp_sys::xmtp_conversation_list_free,
    );
    let mut convs = Vec::with_capacity(ffi_usize(list.len()));
    for i in 0..list.len() {
        let mut conv: *mut xmtp_sys::XmtpFfiConversation = ptr::null_mut();
        // SAFETY: `list` is a valid FFI list and `i` is within bounds.
        let rc = unsafe { xmtp_sys::xmtp_conversation_list_get(list.as_ptr(), i, &raw mut conv) };
        if rc == 0 && !conv.is_null() {
            convs.push(Conversation::from_raw(conv)?);
        }
    }
    Ok(convs)
}

/// Read permissions from an FFI struct.
fn read_permissions(p: &xmtp_sys::XmtpFfiGroupPermissions) -> Permissions {
    let ps = &p.policy_set;
    let policy = |v: xmtp_sys::XmtpFfiPermissionPolicy| -> PermissionPolicy {
        PermissionPolicy::from_ffi(v as i32).unwrap_or(PermissionPolicy::Deny)
    };
    Permissions {
        preset: GroupPermissionsPreset::from_ffi(p.policy_type as i32)
            .unwrap_or(GroupPermissionsPreset::Custom),
        policies: PermissionPolicySet {
            add_member: policy(ps.add_member_policy),
            remove_member: policy(ps.remove_member_policy),
            add_admin: policy(ps.add_admin_policy),
            remove_admin: policy(ps.remove_admin_policy),
            update_group_name: policy(ps.update_group_name_policy),
            update_group_description: policy(ps.update_group_description_policy),
            update_group_image_url: policy(ps.update_group_image_url_square_policy),
            update_message_disappearing: policy(ps.update_message_disappearing_policy),
            update_app_data: policy(ps.update_app_data_policy),
        },
    }
}

/// Read debug info from an FFI struct.
fn read_debug_info(d: &xmtp_sys::XmtpFfiConversationDebugInfo) -> ConversationDebugInfo {
    let cursors = if d.cursors.is_null() || d.cursors_count <= 0 {
        vec![]
    } else {
        // SAFETY: `cursors` is non-null with `cursors_count` valid elements.
        let slice = unsafe {
            std::slice::from_raw_parts(d.cursors, d.cursors_count.unsigned_abs() as usize)
        };
        slice
            .iter()
            .map(|c| Cursor {
                originator_id: c.originator_id,
                sequence_id: c.sequence_id,
            })
            .collect()
    };
    ConversationDebugInfo {
        epoch: d.epoch,
        maybe_forked: d.maybe_forked != 0,
        // SAFETY: Nullable borrowed C string fields in the FFI struct.
        fork_details: unsafe { borrow_nullable_string(d.fork_details) },
        is_commit_log_forked: match d.is_commit_log_forked {
            0 => Some(false),
            1 => Some(true),
            _ => None,
        },
        // SAFETY: Nullable borrowed C string field.
        local_commit_log: unsafe { borrow_nullable_string(d.local_commit_log) },
        // SAFETY: Nullable borrowed C string field.
        remote_commit_log: unsafe { borrow_nullable_string(d.remote_commit_log) },
        cursors,
    }
}

/// Read last-read timestamps from an FFI list.
fn read_last_read_times(ptr: *mut xmtp_sys::XmtpFfiLastReadTimeList) -> Vec<LastReadTime> {
    let list = FfiList::new(
        ptr,
        xmtp_sys::xmtp_last_read_time_list_len,
        xmtp_sys::xmtp_last_read_time_list_free,
    );
    let mut result = 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_last_read_time_list_get(list.as_ptr(), i) };
        if p.is_null() {
            continue;
        }
        // SAFETY: `p` is non-null and points to a valid FFI struct.
        let entry = unsafe { &*p };
        result.push(LastReadTime {
            // SAFETY: Borrowed C string field in the FFI struct.
            inbox_id: unsafe { borrow_c_string(entry.inbox_id) },
            timestamp_ns: entry.timestamp_ns,
        });
    }
    result
}

/// Read HMAC key map from an FFI handle.
pub(crate) fn read_hmac_key_map(ptr: *mut xmtp_sys::XmtpFfiHmacKeyMap) -> Vec<HmacKeyEntry> {
    let map = FfiList::new(
        ptr,
        xmtp_sys::xmtp_hmac_key_map_len,
        xmtp_sys::xmtp_hmac_key_map_free,
    );
    let mut entries = Vec::with_capacity(ffi_usize(map.len()));
    for i in 0..map.len() {
        let mp = map.as_ptr();
        // SAFETY: `mp` is a valid FFI map handle and `i` is within bounds.
        let gid_ptr = unsafe { xmtp_sys::xmtp_hmac_key_map_group_id(mp, i) };
        let group_id = if gid_ptr.is_null() {
            String::new()
        } else {
            // SAFETY: `gid_ptr` is a non-null borrowed C string.
            unsafe { CStr::from_ptr(gid_ptr) }
                .to_str()
                .unwrap_or_default()
                .to_owned()
        };
        let mut key_count = 0i32;
        // SAFETY: `mp` is valid; `key_count` receives the array length.
        let keys_ptr = unsafe { xmtp_sys::xmtp_hmac_key_map_keys(mp, i, &raw mut key_count) };
        let keys = read_hmac_keys_inner(keys_ptr, key_count);
        entries.push(HmacKeyEntry { group_id, keys });
    }
    entries
}

/// Read HMAC keys from a raw FFI key array pointer.
fn read_hmac_keys_inner(keys_ptr: *const xmtp_sys::XmtpFfiHmacKey, key_count: i32) -> Vec<HmacKey> {
    if keys_ptr.is_null() || key_count <= 0 {
        return vec![];
    }
    // SAFETY: `keys_ptr` points to `key_count` valid FFI key structs.
    let slice = unsafe { std::slice::from_raw_parts(keys_ptr, ffi_usize(key_count)) };
    slice
        .iter()
        .map(|k| {
            let key = if k.key.is_null() || k.key_len <= 0 {
                vec![]
            } else {
                // SAFETY: `k.key` is non-null with `k.key_len` valid bytes.
                unsafe { std::slice::from_raw_parts(k.key, ffi_usize(k.key_len)) }.to_vec()
            };
            HmacKey {
                key,
                epoch: k.epoch,
            }
        })
        .collect()
}