hopper-native 0.1.0

Hopper's sovereign raw backend for Solana. Zero-copy account access, direct syscall layer, CPI infrastructure, PDA helpers, and entrypoint glue. no_std, no_alloc, no external runtime dependencies.
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
//! RuntimeAccount memory layout and AccountView zero-copy wrapper.
//!
//! `RuntimeAccount` maps 1:1 onto the BPF input buffer layout that the
//! Solana runtime writes for each account. `AccountView` is a thin
//! pointer to a `RuntimeAccount` in that buffer, providing safe accessors
//! for address, owner, flags, lamports, and data.

use crate::address::{address_eq, Address};
use crate::borrow::{Ref, RefMut};
use crate::error::ProgramError;
use crate::raw_account::RuntimeAccount;
use crate::{ProgramResult, MAX_PERMITTED_DATA_INCREASE, NOT_BORROWED};

// ── AccountView ──────────────────────────────────────────────────────

/// Zero-copy view over a Solana account in the BPF input buffer.
///
/// `AccountView` stores a raw pointer to the `RuntimeAccount` header.
/// All accessor methods read directly from the input buffer with no copies.
#[repr(C)]
#[cfg_attr(feature = "copy", derive(Copy))]
#[derive(Clone, PartialEq, Eq)]
pub struct AccountView {
    raw: *mut RuntimeAccount,
}

// SAFETY: AccountView is safe to send between threads in test contexts.
// On BPF there is only one thread.
unsafe impl Send for AccountView {}
unsafe impl Sync for AccountView {}

impl AccountView {
    /// Construct an AccountView from a raw pointer.
    ///
    /// # Safety
    ///
    /// `raw` must point to a valid `RuntimeAccount` in the BPF input buffer
    /// (or a test allocation with the same layout), followed by at least
    /// `(*raw).data_len` bytes of account data.
    #[inline(always)]
    pub const unsafe fn new_unchecked(raw: *mut RuntimeAccount) -> Self {
        Self { raw }
    }

    #[inline(always)]
    pub(crate) const fn raw_ptr(&self) -> *mut RuntimeAccount {
        self.raw
    }

    // ── Getters ──────────────────────────────────────────────────────

    /// The account's public key.
    #[inline(always)]
    pub fn address(&self) -> &Address {
        // SAFETY: raw always points to a valid RuntimeAccount.
        unsafe { &(*self.raw).address }
    }

    /// The owning program's address.
    ///
    /// # Safety
    ///
    /// The returned reference is invalidated if the account is assigned
    /// to a new owner or closed. The caller must ensure no concurrent
    /// mutation occurs.
    #[inline(always)]
    pub unsafe fn owner(&self) -> &Address {
        // SAFETY: raw is valid; caller promises no concurrent mutation.
        unsafe { &(*self.raw).owner }
    }

    /// Whether this account signed the transaction.
    #[inline(always)]
    pub fn is_signer(&self) -> bool {
        // SAFETY: raw is valid.
        unsafe { (*self.raw).is_signer != 0 }
    }

    /// Whether this account is writable in the transaction.
    #[inline(always)]
    pub fn is_writable(&self) -> bool {
        unsafe { (*self.raw).is_writable != 0 }
    }

    /// Whether this account contains an executable program.
    #[inline(always)]
    pub fn executable(&self) -> bool {
        unsafe { (*self.raw).executable != 0 }
    }

    /// Current data length in bytes.
    #[inline(always)]
    pub fn data_len(&self) -> usize {
        unsafe { (*self.raw).data_len as usize }
    }

    /// Resize delta (difference between current and original data length).
    #[inline(always)]
    pub fn resize_delta(&self) -> i32 {
        unsafe { (*self.raw).resize_delta }
    }

    /// Current lamport balance.
    #[inline(always)]
    pub fn lamports(&self) -> u64 {
        unsafe { (*self.raw).lamports }
    }

    /// Whether the account data is empty (data_len == 0).
    #[inline(always)]
    pub fn is_data_empty(&self) -> bool {
        self.data_len() == 0
    }

    /// Set the lamport balance.
    #[inline(always)]
    pub fn set_lamports(&self, lamports: u64) {
        unsafe {
            (*self.raw).lamports = lamports;
        }
    }

    // ── Ownership ────────────────────────────────────────────────────

    /// Check whether this account is owned by the given program.
    #[inline(always)]
    pub fn owned_by(&self, program: &Address) -> bool {
        // SAFETY: owner field is valid for the lifetime of the input buffer.
        unsafe { address_eq(&(*self.raw).owner, program) }
    }

    /// Assign a new owner.
    ///
    /// # Safety
    ///
    /// The caller must ensure the account is writable and that ownership
    /// transfer is authorized by the current owner program.
    #[inline(always)]
    pub unsafe fn assign(&self, new_owner: &Address) {
        unsafe {
            (*self.raw).owner = new_owner.clone();
        }
    }

    // ── Borrow tracking ─────────────────────────────────────────────

    /// Whether the account data is currently borrowed (shared or exclusive).
    #[inline(always)]
    pub fn is_borrowed(&self) -> bool {
        unsafe { (*self.raw).borrow_state != NOT_BORROWED }
    }

    /// Whether the account data is exclusively (mutably) borrowed.
    #[inline(always)]
    pub fn is_borrowed_mut(&self) -> bool {
        unsafe { (*self.raw).borrow_state == 0 }
    }

    /// Check that the account can be shared-borrowed.
    #[inline(always)]
    pub fn check_borrow(&self) -> Result<(), ProgramError> {
        let state = unsafe { (*self.raw).borrow_state };
        if state == 0 {
            // Exclusively borrowed -- cannot share.
            Err(ProgramError::AccountBorrowFailed)
        } else {
            Ok(())
        }
    }

    /// Check that the account can be exclusively borrowed.
    #[inline(always)]
    pub fn check_borrow_mut(&self) -> Result<(), ProgramError> {
        let state = unsafe { (*self.raw).borrow_state };
        if state != NOT_BORROWED {
            // Already borrowed (shared or exclusive).
            Err(ProgramError::AccountBorrowFailed)
        } else {
            Ok(())
        }
    }

    // ── Unchecked data access ────────────────────────────────────────

    /// Borrow account data without borrow tracking.
    ///
    /// # Safety
    ///
    /// The caller must ensure no mutable borrow is active.
    #[inline(always)]
    pub unsafe fn borrow_unchecked(&self) -> &[u8] {
        let data_ptr = self.data_ptr_unchecked();
        let len = self.data_len();
        unsafe { core::slice::from_raw_parts(data_ptr, len) }
    }

    /// Mutably borrow account data without borrow tracking.
    ///
    /// # Safety
    ///
    /// The caller must ensure no other borrows (shared or exclusive) are active.
    #[inline(always)]
    pub unsafe fn borrow_unchecked_mut(&self) -> &mut [u8] {
        let data_ptr = self.data_ptr_unchecked();
        let len = self.data_len();
        unsafe { core::slice::from_raw_parts_mut(data_ptr, len) }
    }

    // ── Checked data access ──────────────────────────────────────────

    /// Try to obtain a shared borrow of the account data.
    ///
    /// Returns `Err(AccountBorrowFailed)` if the data is exclusively borrowed.
    #[inline(always)]
    pub fn try_borrow(&self) -> Result<Ref<'_, [u8]>, ProgramError> {
        self.check_borrow()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        let state = unsafe { *state_ptr };
        let new_state = if state == NOT_BORROWED { 1 } else { state + 1 };
        if new_state == 0 {
            // Overflow into exclusive-borrow sentinel.
            return Err(ProgramError::AccountBorrowFailed);
        }
        unsafe {
            *state_ptr = new_state;
        }
        let data = unsafe { self.borrow_unchecked() };
        Ok(Ref::new(data, state_ptr))
    }

    /// Try to obtain an exclusive (mutable) borrow of the account data.
    ///
    /// Returns `Err(AccountBorrowFailed)` if the data is already borrowed.
    #[inline(always)]
    pub fn try_borrow_mut(&self) -> Result<RefMut<'_, [u8]>, ProgramError> {
        self.check_borrow_mut()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        unsafe {
            *state_ptr = 0;
        } // Mark exclusive.
        let data = unsafe { self.borrow_unchecked_mut() };
        Ok(RefMut::new(data, state_ptr))
    }

    // ── Typed segment and raw access ───────────────────────────────

    /// Project a typed segment from account data with native borrow tracking.
    #[inline(always)]
    pub fn segment_ref<T: crate::pod::Pod>(
        &self,
        offset: u32,
        size: u32,
    ) -> Result<Ref<'_, T>, ProgramError> {
        let expected_size = core::mem::size_of::<T>() as u32;
        if size != expected_size {
            return Err(ProgramError::InvalidArgument);
        }

        let end = offset
            .checked_add(size)
            .ok_or(ProgramError::ArithmeticOverflow)?;
        if end as usize > self.data_len() {
            return Err(ProgramError::AccountDataTooSmall);
        }

        self.check_borrow()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        let state = unsafe { *state_ptr };
        let new_state = if state == NOT_BORROWED { 1 } else { state + 1 };
        if new_state == 0 {
            return Err(ProgramError::AccountBorrowFailed);
        }
        unsafe {
            *state_ptr = new_state;
        }

        let ptr = unsafe { self.data_ptr_unchecked().add(offset as usize) as *const T };
        Ok(Ref::new(unsafe { &*ptr }, state_ptr))
    }

    /// Acquire a shared segment borrow without size/bounds validation.
    ///
    /// # Safety
    ///
    /// The caller must have already verified:
    /// - `offset + size_of::<T>()` does not overflow
    /// - `offset + size_of::<T>() <= data_len()`
    #[inline(always)]
    pub unsafe fn segment_ref_unchecked<T: crate::pod::Pod>(
        &self,
        offset: u32,
    ) -> Result<Ref<'_, T>, ProgramError> {
        self.check_borrow()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        let state = unsafe { *state_ptr };
        let new_state = if state == NOT_BORROWED { 1 } else { state + 1 };
        if new_state == 0 {
            return Err(ProgramError::AccountBorrowFailed);
        }
        unsafe {
            *state_ptr = new_state;
        }

        let ptr = unsafe { self.data_ptr_unchecked().add(offset as usize) as *const T };
        Ok(Ref::new(unsafe { &*ptr }, state_ptr))
    }

    /// Project a mutable typed segment from account data with native borrow tracking.
    #[inline(always)]
    pub fn segment_mut<T: crate::pod::Pod>(
        &self,
        offset: u32,
        size: u32,
    ) -> Result<RefMut<'_, T>, ProgramError> {
        self.require_writable()?;

        let expected_size = core::mem::size_of::<T>() as u32;
        if size != expected_size {
            return Err(ProgramError::InvalidArgument);
        }

        let end = offset
            .checked_add(size)
            .ok_or(ProgramError::ArithmeticOverflow)?;
        if end as usize > self.data_len() {
            return Err(ProgramError::AccountDataTooSmall);
        }

        self.check_borrow_mut()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        unsafe {
            *state_ptr = 0;
        }

        let ptr = unsafe { self.data_ptr_unchecked().add(offset as usize) as *mut T };
        Ok(RefMut::new(unsafe { &mut *ptr }, state_ptr))
    }

    /// Acquire an exclusive segment borrow without size/bounds/writable validation.
    ///
    /// # Safety
    ///
    /// The caller must have already verified:
    /// - The account is writable
    /// - `offset + size_of::<T>()` does not overflow
    /// - `offset + size_of::<T>() <= data_len()`
    #[inline(always)]
    pub unsafe fn segment_mut_unchecked<T: crate::pod::Pod>(
        &self,
        offset: u32,
    ) -> Result<RefMut<'_, T>, ProgramError> {
        self.check_borrow_mut()?;
        let state_ptr = unsafe { &mut (*self.raw).borrow_state as *mut u8 };
        unsafe {
            *state_ptr = 0;
        }

        let ptr = unsafe { self.data_ptr_unchecked().add(offset as usize) as *mut T };
        Ok(RefMut::new(unsafe { &mut *ptr }, state_ptr))
    }

    /// Explicit raw typed read of the account buffer.
    #[inline(always)]
    pub unsafe fn raw_ref<T: crate::pod::Pod>(&self) -> Result<Ref<'_, T>, ProgramError> {
        self.segment_ref::<T>(0, core::mem::size_of::<T>() as u32)
    }

    /// Explicit raw typed write of the account buffer.
    #[inline(always)]
    pub unsafe fn raw_mut<T: crate::pod::Pod>(&self) -> Result<RefMut<'_, T>, ProgramError> {
        self.segment_mut::<T>(0, core::mem::size_of::<T>() as u32)
    }

    // ── Resize ───────────────────────────────────────────────────────

    /// Resize the account data to `new_len` bytes.
    ///
    /// Returns `Err(InvalidRealloc)` if the new length exceeds the
    /// permitted increase from the original allocation.
    #[inline(always)]
    pub fn resize(&self, new_len: usize) -> Result<(), ProgramError> {
        let original_len = (self.data_len() as i64 - self.resize_delta() as i64) as usize;
        if new_len > original_len + MAX_PERMITTED_DATA_INCREASE {
            return Err(ProgramError::InvalidRealloc);
        }
        let delta = new_len as i64 - original_len as i64;
        unsafe {
            (*self.raw).data_len = new_len as u64;
            (*self.raw).resize_delta = delta as i32;
        }
        Ok(())
    }

    /// Resize without bounds checking.
    ///
    /// # Safety
    ///
    /// The caller must guarantee `new_len <= original_len + MAX_PERMITTED_DATA_INCREASE`.
    #[inline(always)]
    pub unsafe fn resize_unchecked(&self, new_len: usize) {
        let original_len = (self.data_len() as i64 - self.resize_delta() as i64) as usize;
        let delta = new_len as i64 - original_len as i64;
        unsafe {
            (*self.raw).data_len = new_len as u64;
            (*self.raw).resize_delta = delta as i32;
        }
    }

    // ── Close ────────────────────────────────────────────────────────

    /// Solana System Program address (all-zero pubkey).
    ///
    /// Closing an account transfers ownership back to the System
    /// Program, which is the canonical "no-owner" state on Solana.
    /// The byte value `[0u8; 32]` and `Address::default()` are
    /// equivalent, but using this named constant makes the intent
    /// explicit, per the Hopper Safety Audit which flagged the
    /// `Address::default()` spelling as documentation drift.
    pub const SYSTEM_PROGRAM_ID: Address = Address::new_from_array([0u8; 32]);

    /// Close the account: zero lamports and data, reassign owner to
    /// the System Program.
    ///
    /// # Caveat
    ///
    /// This low-level routine does **not** verify the caller has
    /// authority to close the account, Solana's runtime enforces
    /// owner/writable rules at transaction commit time regardless, but
    /// higher-level APIs (e.g. `hopper_runtime::AccountView::close_to`)
    /// should pre-check those rules. See `account.rs::close_to` for
    /// the safe wrapper.
    #[inline(always)]
    pub fn close(&self) -> ProgramResult {
        self.set_lamports(0);
        unsafe {
            let len = self.data_len();
            if len > 0 {
                // Use the SVM's JIT-compiled memset for optimal CU cost.
                crate::mem::memset(self.data_ptr_unchecked(), 0, len);
            }
            (*self.raw).data_len = 0;
            (*self.raw).owner = Self::SYSTEM_PROGRAM_ID;
        }
        Ok(())
    }

    /// Close without borrow checks.
    ///
    /// # Safety
    ///
    /// The caller must ensure no active borrows exist.
    #[inline(always)]
    pub unsafe fn close_unchecked(&self) {
        unsafe {
            (*self.raw).lamports = 0;
            (*self.raw).data_len = 0;
            (*self.raw).owner = Self::SYSTEM_PROGRAM_ID;
        }
    }

    // ── Raw pointers ─────────────────────────────────────────────────

    /// Raw pointer to the `RuntimeAccount` header.
    #[inline(always)]
    pub const fn account_ptr(&self) -> *const RuntimeAccount {
        self.raw as *const RuntimeAccount
    }

    /// Raw pointer to the first byte of account data.
    ///
    /// The data starts immediately after the 88-byte `RuntimeAccount` header.
    /// This is an expert-only substrate escape hatch: constructing the pointer
    /// is safe, but dereferencing it is unsafe and bypasses Hopper Native's
    /// borrow-state checks, segment registry, and writable checks. Normal code
    /// should use `try_borrow`, `try_borrow_mut`, `segment_ref`, or
    /// `segment_mut`. Framework code should route user-facing raw access
    /// through the documented unsafe runtime APIs (`Context::as_mut_ptr` /
    /// `Context::as_ptr`) instead of exposing this method directly.
    #[doc(hidden)]
    #[inline(always)]
    pub fn data_ptr_unchecked(&self) -> *mut u8 {
        // SAFETY: Adding the struct size to the base pointer yields the
        // first data byte. The runtime guarantees this memory is valid.
        unsafe { (self.raw as *mut u8).add(core::mem::size_of::<RuntimeAccount>()) }
    }

    // ── Hopper Innovations ───────────────────────────────────────────

    /// Validate that this account is a signer, returning a typed error.
    #[inline(always)]
    pub fn require_signer(&self) -> ProgramResult {
        if self.is_signer() {
            Ok(())
        } else {
            Err(ProgramError::MissingRequiredSignature)
        }
    }

    /// Validate that this account is writable.
    #[inline(always)]
    pub fn require_writable(&self) -> ProgramResult {
        if self.is_writable() {
            Ok(())
        } else {
            Err(ProgramError::Immutable)
        }
    }

    /// Validate that this account is owned by the given program.
    #[inline(always)]
    pub fn require_owned_by(&self, program: &Address) -> ProgramResult {
        if self.owned_by(program) {
            Ok(())
        } else {
            Err(ProgramError::IncorrectProgramId)
        }
    }

    /// Validate signer + writable (common "payer" pattern).
    #[inline(always)]
    pub fn require_payer(&self) -> ProgramResult {
        self.require_signer()?;
        self.require_writable()
    }

    /// Read the Hopper account discriminator (first byte of data).
    ///
    /// Returns 0 if the account has no data.
    #[inline(always)]
    pub fn disc(&self) -> u8 {
        if self.data_len() == 0 {
            return 0;
        }
        unsafe { *self.data_ptr_unchecked() }
    }

    /// Read the Hopper account version (second byte of data).
    ///
    /// Returns 0 if the account has fewer than 2 bytes.
    #[inline(always)]
    pub fn version(&self) -> u8 {
        if self.data_len() < 2 {
            return 0;
        }
        unsafe { *self.data_ptr_unchecked().add(1) }
    }

    /// Read the 8-byte layout_id from the Hopper account header
    /// (bytes 4..12 of account data, per the canonical header format).
    ///
    /// Returns `None` if the account has fewer than 12 bytes.
    #[inline(always)]
    pub fn layout_id(&self) -> Option<&[u8; 8]> {
        if self.data_len() < 12 {
            return None;
        }
        unsafe { Some(&*(self.data_ptr_unchecked().add(4) as *const [u8; 8])) }
    }

    /// Verify that this account has the given discriminator.
    #[inline(always)]
    pub fn require_disc(&self, expected: u8) -> ProgramResult {
        if self.disc() == expected {
            Ok(())
        } else {
            Err(ProgramError::InvalidAccountData)
        }
    }

    // -- Chainable validation (Steel-inspired, improved) ---------------
    //
    // Return `Result<&Self>` so callers can chain:
    //
    //   account
    //       .check_signer()?
    //       .check_writable()?
    //       .check_owned_by(&MY_PROGRAM_ID)?;
    //
    // Validated once, used everywhere. This pattern exists in Steel but
    // not in pinocchio, Anchor, or Quasar.

    /// Chainable signer check.
    #[inline(always)]
    pub fn check_signer(&self) -> Result<&Self, ProgramError> {
        if self.is_signer() {
            Ok(self)
        } else {
            Err(ProgramError::MissingRequiredSignature)
        }
    }

    /// Chainable writable check.
    #[inline(always)]
    pub fn check_writable(&self) -> Result<&Self, ProgramError> {
        if self.is_writable() {
            Ok(self)
        } else {
            Err(ProgramError::Immutable)
        }
    }

    /// Chainable ownership check.
    #[inline(always)]
    pub fn check_owned_by(&self, program: &Address) -> Result<&Self, ProgramError> {
        if self.owned_by(program) {
            Ok(self)
        } else {
            Err(ProgramError::IncorrectProgramId)
        }
    }

    /// Chainable discriminator check.
    #[inline(always)]
    pub fn check_disc(&self, expected: u8) -> Result<&Self, ProgramError> {
        if self.disc() == expected {
            Ok(self)
        } else {
            Err(ProgramError::InvalidAccountData)
        }
    }

    /// Chainable non-empty data check.
    #[inline(always)]
    pub fn check_has_data(&self) -> Result<&Self, ProgramError> {
        if !self.is_data_empty() {
            Ok(self)
        } else {
            Err(ProgramError::AccountDataTooSmall)
        }
    }

    /// Chainable executable check.
    #[inline(always)]
    pub fn check_executable(&self) -> Result<&Self, ProgramError> {
        if self.executable() {
            Ok(self)
        } else {
            Err(ProgramError::InvalidArgument)
        }
    }

    /// Chainable address check.
    #[inline(always)]
    pub fn check_address(&self, expected: &Address) -> Result<&Self, ProgramError> {
        if address_eq(self.address(), expected) {
            Ok(self)
        } else {
            Err(ProgramError::InvalidArgument)
        }
    }

    /// Chainable minimum data length check.
    #[inline(always)]
    pub fn check_data_len(&self, min_len: usize) -> Result<&Self, ProgramError> {
        if self.data_len() >= min_len {
            Ok(self)
        } else {
            Err(ProgramError::AccountDataTooSmall)
        }
    }

    // -- Safe owner access ---------------------------------------------

    /// Read the owner address as a copy (32-byte value).
    ///
    /// Unlike `owner()` (which is unsafe due to reference invalidation
    /// if `assign()` is called), this returns a copy that is always safe.
    /// Costs 32 bytes of stack space but eliminates aliasing hazards.
    #[inline(always)]
    pub fn read_owner(&self) -> Address {
        unsafe { (*self.raw).owner.clone() }
    }

    // -- Packed flags --------------------------------------------------

    /// Read the first 4 bytes of the account header as a single u32.
    ///
    /// Layout (little-endian): `[borrow_state, is_signer, is_writable, executable]`
    ///
    /// This is the fastest way to extract multiple account properties at once
    ///, a single aligned u32 read instead of 3-4 separate byte loads.
    #[inline(always)]
    fn header_u32(&self) -> u32 {
        // SAFETY: RuntimeAccount is #[repr(C)] with first 4 fields as u8,
        // totalling 4 bytes at the start. Reading as u32 is safe because
        // the struct is at least 88 bytes and the BPF input buffer is
        // sufficiently aligned.
        unsafe { *(self.raw as *const u32) }
    }

    /// Pack the account's boolean flags into a single byte for fast
    /// comparison.
    ///
    /// Bit layout:
    /// - bit 0: is_signer
    /// - bit 1: is_writable
    /// - bit 2: executable
    /// - bit 3: has data (data_len > 0)
    ///
    /// Use with `expect_flags()` for single-instruction multi-check:
    ///
    /// ```ignore
    /// // Require: signer + writable + has data
    /// account.expect_flags(0b1011)?;
    /// ```
    #[inline(always)]
    pub fn flags(&self) -> u8 {
        // Single u32 read extracts [borrow_state, is_signer, is_writable, executable].
        // On little-endian: is_signer = bits 8-15, is_writable = bits 16-23, executable = bits 24-31.
        let h = self.header_u32();
        let mut f: u8 = 0;
        if h & 0x0000_FF00 != 0 {
            f |= 0b0001;
        } // is_signer
        if h & 0x00FF_0000 != 0 {
            f |= 0b0010;
        } // is_writable
        if h & 0xFF00_0000 != 0 {
            f |= 0b0100;
        } // executable
        if !self.is_data_empty() {
            f |= 0b1000;
        }
        f
    }

    /// Check that the account's flags contain all the required bits.
    ///
    /// `required` is a bitmask of flags that must be set. See `flags()`.
    #[inline(always)]
    pub fn expect_flags(&self, required: u8) -> ProgramResult {
        if self.flags() & required == required {
            Ok(())
        } else {
            Err(ProgramError::InvalidArgument)
        }
    }
}

impl core::fmt::Debug for AccountView {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("AccountView")
            .field("address", self.address())
            .field("lamports", &self.lamports())
            .field("data_len", &self.data_len())
            .field("is_signer", &self.is_signer())
            .field("is_writable", &self.is_writable())
            .finish()
    }
}

// ── RemainingAccounts ────────────────────────────────────────────────

/// Iterator over remaining (unstructured) accounts after the known ones.
pub struct RemainingAccounts<'a> {
    accounts: &'a [AccountView],
    cursor: usize,
}

impl<'a> RemainingAccounts<'a> {
    /// Create from a slice of the remaining accounts.
    #[inline(always)]
    pub fn new(accounts: &'a [AccountView]) -> Self {
        Self {
            accounts,
            cursor: 0,
        }
    }

    /// Number of accounts remaining.
    #[inline(always)]
    pub fn remaining(&self) -> usize {
        self.accounts.len() - self.cursor
    }

    /// Take the next account, or return `NotEnoughAccountKeys`.
    #[inline(always)]
    pub fn next(&mut self) -> Result<&'a AccountView, ProgramError> {
        if self.cursor >= self.accounts.len() {
            return Err(ProgramError::NotEnoughAccountKeys);
        }
        let account = &self.accounts[self.cursor];
        self.cursor += 1;
        Ok(account)
    }

    /// Take the next account that is a signer.
    #[inline(always)]
    pub fn next_signer(&mut self) -> Result<&'a AccountView, ProgramError> {
        let account = self.next()?;
        account.require_signer()?;
        Ok(account)
    }

    /// Take the next account that is writable.
    #[inline(always)]
    pub fn next_writable(&mut self) -> Result<&'a AccountView, ProgramError> {
        let account = self.next()?;
        account.require_writable()?;
        Ok(account)
    }

    /// Take the next account owned by the given program.
    #[inline(always)]
    pub fn next_owned_by(&mut self, program: &Address) -> Result<&'a AccountView, ProgramError> {
        let account = self.next()?;
        account.require_owned_by(program)?;
        Ok(account)
    }
}