Skip to main content

hopper_macros/
lib.rs

1//! # Hopper Macros (Declarative)
2//!
3//! **Support infrastructure, not the main public entry.** These
4//! `macro_rules!` macros generate layout structure, field metadata, and
5//! validation primitives at compile time. They are deliberately limited
6//! to *structure* generation: no hidden runtime logic, no surprise
7//! control flow, no validation engines.
8//!
9//! Programs that want richer DX should enable the `proc-macros` feature
10//! and reach for `#[hopper::state]`, `#[hopper::context]`, and
11//! `#[hopper::program]` in `hopper-macros-proc`. Programs that prefer a
12//! zero-tool-chain authoring path can use these declarative macros
13//! directly, both paths lower to the same runtime.
14//!
15//! ## Topical index
16//!
17//! | Section            | Macros |
18//! |--------------------|--------|
19//! | Layout             | `hopper_layout!` |
20//! | Validation         | `hopper_check!`, `hopper_error!`, `hopper_require!` |
21//! | Lifecycle          | `hopper_init!`, `hopper_close!` |
22//! | Dispatch           | `hopper_register_discs!` |
23//! | PDA                | `hopper_verify_pda!` |
24//! | Invariants         | `hopper_invariant!` |
25//! | Manifest           | `hopper_manifest!` |
26//! | Segments           | `hopper_segment!` |
27//! | Pipelines          | `hopper_validate!` |
28//! | Virtual state      | `hopper_virtual!` |
29//! | Compat / ABI       | `hopper_assert_compatible!`, `hopper_assert_fingerprint!`, `const_assert_pod!` |
30//! | Cross-program      | `hopper_interface!` |
31//! | Account structs    | `hopper_accounts!` |
32//!
33//! Every macro below is `#[macro_export]`ed and usable from the root of
34//! the `hopper-macros` crate regardless of the section banner it lives
35//! under. The banners exist only to help readers navigate the file.
36
37#![no_std]
38
39// ═════════════════════════════════════════════════════════════════════
40//  Section: Layout
41// ═════════════════════════════════════════════════════════════════════
42
43/// Define a zero-copy account layout.
44///
45/// Generates a `#[repr(C)]` struct with:
46/// - 16-byte Hopper header
47/// - Alignment-1 fields
48/// - Deterministic `LAYOUT_ID` via SHA-256
49/// - Tiered loading: `load`, `load_mut`, `load_cross_program`, `load_compatible`, `load_unverified`
50/// - Compile-time size and alignment assertions
51///
52/// # Example
53///
54/// ```ignore
55/// hopper_layout! {
56///     pub struct Vault, disc = 1, version = 1 {
57///         authority: [u8; 32]  = 32,
58///         mint:      [u8; 32]  = 32,
59///         balance:   WireU64   = 8,
60///         bump:      u8        = 1,
61///     }
62/// }
63/// ```
64#[macro_export]
65macro_rules! hopper_layout {
66    (
67        $(#[$attr:meta])*
68        pub struct $name:ident, disc = $disc:literal, version = $ver:literal
69        {
70            $(
71                $(#[$field_attr:meta])*
72                $field:ident : $fty:ty = $fsize:literal
73            ),+ $(,)?
74        }
75    ) => {
76        $(#[$attr])*
77        #[derive(Clone, Copy)]
78        #[repr(C)]
79        pub struct $name {
80            pub header: $crate::hopper_core::account::AccountHeader,
81            $(
82                $(#[$field_attr])*
83                pub $field: $fty,
84            )+
85        }
86
87        // Compile-time assertions
88        const _: () = {
89            // Size check: header + sum of field sizes
90            let expected = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
91            assert!(
92                core::mem::size_of::<$name>() == expected,
93                "Layout size mismatch: struct size != declared field sizes + header"
94            );
95            // Alignment-1 check
96            assert!(
97                core::mem::align_of::<$name>() == 1,
98                "Layout alignment must be 1 for zero-copy safety"
99            );
100        };
101
102        // Bytemuck proof (Hopper Safety Audit Must-Fix #5): every
103        // field must itself satisfy `bytemuck::Pod + Zeroable`.
104        // Hopper's Pod supertrait requires these impls; because all
105        // field types generated by `hopper_layout!` are Hopper wire
106        // types (which carry their own bytemuck impls) or byte
107        // arrays, these blanket claims are safe.
108        #[cfg(feature = "hopper-native-backend")]
109        unsafe impl $crate::hopper_runtime::__hopper_native::bytemuck::Zeroable for $name {}
110        #[cfg(feature = "hopper-native-backend")]
111        unsafe impl $crate::hopper_runtime::__hopper_native::bytemuck::Pod for $name {}
112
113        // SAFETY: #[repr(C)] over alignment-1 fields, all bit patterns valid
114        // for the constituent Pod types (header, wire integers, byte arrays).
115        unsafe impl $crate::hopper_core::account::Pod for $name {}
116
117        // Audit final-API Step 5 seal. `hopper_layout!` stamps the
118        // Hopper-authored marker so the `ZeroCopy` blanket picks up
119        // declarative layouts the same way it picks up `#[hopper::state]`
120        // ones.
121        unsafe impl $crate::hopper_runtime::__sealed::HopperZeroCopySealed for $name {}
122
123        impl $crate::hopper_core::account::FixedLayout for $name {
124            const SIZE: usize = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
125        }
126
127        impl $crate::hopper_core::field_map::FieldMap for $name {
128            const FIELDS: &'static [$crate::hopper_core::field_map::FieldInfo] = {
129                const FIELD_COUNT: usize = 0 $( + { let _ = stringify!($field); 1 } )+;
130                const NAMES: [&str; FIELD_COUNT] = [ $( stringify!($field) ),+ ];
131                const SIZES: [usize; FIELD_COUNT] = [ $( $fsize ),+ ];
132                const FIELDS: [$crate::hopper_core::field_map::FieldInfo; FIELD_COUNT] = {
133                    let mut result = [$crate::hopper_core::field_map::FieldInfo::new("", 0, 0); FIELD_COUNT];
134                    let mut offset = $crate::hopper_core::account::HEADER_LEN;
135                    let mut index = 0;
136                    while index < FIELD_COUNT {
137                        result[index] = $crate::hopper_core::field_map::FieldInfo::new(
138                            NAMES[index],
139                            offset,
140                            SIZES[index],
141                        );
142                        offset += SIZES[index];
143                        index += 1;
144                    }
145                    result
146                };
147                &FIELDS
148            };
149        }
150
151        impl $crate::hopper_runtime::LayoutContract for $name {
152            const DISC: u8 = $disc;
153            const VERSION: u8 = $ver;
154            const LAYOUT_ID: [u8; 8] = $name::LAYOUT_ID;
155            const SIZE: usize = $name::LEN;
156            const TYPE_OFFSET: usize = 0;
157        }
158
159        impl $crate::hopper_schema::SchemaExport for $name {
160            fn layout_manifest() -> $crate::hopper_schema::LayoutManifest {
161                const FIELD_COUNT: usize = 0 $( + { let _ = stringify!($field); 1 } )+;
162                const SIZES: [u16; FIELD_COUNT] = [ $( $fsize ),+ ];
163                const NAMES: [&str; FIELD_COUNT] = [ $( stringify!($field) ),+ ];
164                const TYPES: [&str; FIELD_COUNT] = [ $( stringify!($fty) ),+ ];
165                const FIELDS: [$crate::hopper_schema::FieldDescriptor; FIELD_COUNT] = {
166                    let mut result = [$crate::hopper_schema::FieldDescriptor {
167                        name: "", canonical_type: "", size: 0, offset: 0,
168                        intent: $crate::hopper_schema::FieldIntent::Custom,
169                    }; FIELD_COUNT];
170                    let mut offset = $crate::hopper_core::account::HEADER_LEN as u16;
171                    let mut index = 0;
172                    while index < FIELD_COUNT {
173                        result[index] = $crate::hopper_schema::FieldDescriptor {
174                            name: NAMES[index],
175                            canonical_type: TYPES[index],
176                            size: SIZES[index],
177                            offset,
178                            intent: $crate::hopper_schema::FieldIntent::Custom,
179                        };
180                        offset += SIZES[index];
181                        index += 1;
182                    }
183                    result
184                };
185                $crate::hopper_schema::LayoutManifest {
186                    name: stringify!($name),
187                    version: <$name>::VERSION,
188                    disc: <$name>::DISC,
189                    layout_id: <$name>::LAYOUT_ID,
190                    total_size: <$name>::LEN,
191                    field_count: FIELD_COUNT,
192                    fields: &FIELDS,
193                }
194            }
195        }
196
197        impl $name {
198            /// Total byte size of this layout.
199            pub const LEN: usize = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
200
201            /// Discriminator tag.
202            pub const DISC: u8 = $disc;
203
204            /// Layout version.
205            pub const VERSION: u8 = $ver;
206
207            /// Deterministic layout fingerprint.
208            ///
209            /// SHA-256 of: `"hopper:v1:Name:version:field:type:size,..."`
210            /// First 8 bytes for efficient comparison.
211            pub const LAYOUT_ID: [u8; 8] = {
212                // Build the canonical hash input at compile time
213                const INPUT: &str = concat!(
214                    "hopper:v1:",
215                    stringify!($name), ":",
216                    stringify!($ver), ":",
217                    $( stringify!($field), ":", stringify!($fty), ":", stringify!($fsize), ",", )+
218                );
219                const HASH: [u8; 32] = $crate::hopper_core::__sha256_const(INPUT.as_bytes());
220                [
221                    HASH[0], HASH[1], HASH[2], HASH[3],
222                    HASH[4], HASH[5], HASH[6], HASH[7],
223                ]
224            };
225
226            /// Zero-copy overlay over an already-borrowed byte slice (immutable).
227            ///
228            /// Prefer [`Self::load`] for account data so owner/header checks and
229            /// Hopper borrow tracking stay in force. Use this helper for tests,
230            /// scratch buffers, and explicitly sliced extension segments whose
231            /// surrounding account was already validated.
232            #[inline(always)]
233            pub fn overlay(data: &[u8]) -> Result<&Self, $crate::hopper_runtime::error::ProgramError> {
234                $crate::hopper_core::account::pod_from_bytes::<Self>(data)
235            }
236
237            /// Zero-copy overlay over an already-borrowed byte slice (mutable).
238            ///
239            /// Prefer [`Self::load_mut`] for account data so owner/header checks,
240            /// writable checks, and Hopper borrow tracking stay in force. Use this
241            /// helper for tests, scratch buffers, and explicitly sliced extension
242            /// segments whose surrounding account was already validated.
243            #[inline(always)]
244            pub fn overlay_mut(data: &mut [u8]) -> Result<&mut Self, $crate::hopper_runtime::error::ProgramError> {
245                $crate::hopper_core::account::pod_from_bytes_mut::<Self>(data)
246            }
247
248            /// Tier 1: Full validation load (own program accounts).
249            ///
250            /// Validates: owner + discriminator + version + layout_id + exact size.
251            #[inline]
252            pub fn load<'a>(
253                account: &'a $crate::hopper_runtime::AccountView,
254                program_id: &$crate::hopper_runtime::Address,
255            ) -> Result<
256                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
257                $crate::hopper_runtime::error::ProgramError,
258            > {
259                $crate::hopper_core::check::check_owner(account, program_id)?;
260                let data = account.try_borrow()?;
261                $crate::hopper_core::account::check_header(
262                    &*data,
263                    Self::DISC,
264                    Self::VERSION,
265                    &Self::LAYOUT_ID,
266                )?;
267                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
268                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
269            }
270
271            /// Tier 1m: Full validation load (mutable).
272            #[inline]
273            pub fn load_mut<'a>(
274                account: &'a $crate::hopper_runtime::AccountView,
275                program_id: &$crate::hopper_runtime::Address,
276            ) -> Result<
277                $crate::hopper_core::account::VerifiedAccountMut<'a, Self>,
278                $crate::hopper_runtime::error::ProgramError,
279            > {
280                $crate::hopper_core::check::check_owner(account, program_id)?;
281                $crate::hopper_core::check::check_writable(account)?;
282                let data = account.try_borrow_mut()?;
283                $crate::hopper_core::account::check_header(
284                    &*data,
285                    Self::DISC,
286                    Self::VERSION,
287                    &Self::LAYOUT_ID,
288                )?;
289                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
290                $crate::hopper_core::account::VerifiedAccountMut::from_ref_mut(data)
291            }
292
293            /// Tier 2: Foreign account load (cross-program reads).
294            ///
295            /// Validates: owner + layout_id + exact size (no disc/version check).
296            ///
297            /// **Deprecated:** Renamed to `load_cross_program()` for clarity.
298            #[deprecated(since = "0.2.0", note = "renamed to load_cross_program()")]
299            #[inline]
300            pub fn load_foreign<'a>(
301                account: &'a $crate::hopper_runtime::AccountView,
302                expected_owner: &$crate::hopper_runtime::Address,
303            ) -> Result<
304                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
305                $crate::hopper_runtime::error::ProgramError,
306            > {
307                $crate::hopper_core::check::check_owner(account, expected_owner)?;
308                let data = account.try_borrow()?;
309                let layout_id = $crate::hopper_core::account::read_layout_id(&*data)?;
310                if layout_id != Self::LAYOUT_ID {
311                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
312                }
313                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
314                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
315            }
316
317            /// Cross-program account load (reads accounts owned by other programs).
318            ///
319            /// Validates: owner + layout_id + exact size (no disc/version check).
320            /// This is the successor to `load_foreign()` with a clearer name.
321            #[inline]
322            pub fn load_cross_program<'a>(
323                account: &'a $crate::hopper_runtime::AccountView,
324                expected_owner: &$crate::hopper_runtime::Address,
325            ) -> Result<
326                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
327                $crate::hopper_runtime::error::ProgramError,
328            > {
329                $crate::hopper_core::check::check_owner(account, expected_owner)?;
330                let data = account.try_borrow()?;
331                let layout_id = $crate::hopper_core::account::read_layout_id(&*data)?;
332                if layout_id != Self::LAYOUT_ID {
333                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
334                }
335                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
336                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
337            }
338
339            /// Tier 3: Version-compatible load for migration scenarios.
340            ///
341            /// Validates: owner + discriminator + minimum version + minimum size.
342            /// Does **not** check layout_id, so it accepts any version of this
343            /// account type whose version byte is ≥ `min_version` and whose
344            /// data is at least as large as this layout.
345            ///
346            /// Use this during migration rollouts when a single instruction
347            /// must accept both old and new versions of an account.
348            ///
349            /// # Arguments
350            /// * `min_version`: lowest acceptable version byte (header byte 1).
351            ///   Pass `1` to accept V1+, `2` to accept V2+ only, etc.
352            #[inline]
353            pub fn load_compatible<'a>(
354                account: &'a $crate::hopper_runtime::AccountView,
355                program_id: &$crate::hopper_runtime::Address,
356                min_version: u8,
357            ) -> Result<
358                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
359                $crate::hopper_runtime::error::ProgramError,
360            > {
361                $crate::hopper_core::check::check_owner(account, program_id)?;
362                let data = account.try_borrow()?;
363                if data.len() < $crate::hopper_core::account::HEADER_LEN {
364                    return Err($crate::hopper_runtime::error::ProgramError::AccountDataTooSmall);
365                }
366                // Check discriminator (same account type, any version).
367                if data[0] != Self::DISC {
368                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
369                }
370                // Check minimum version.
371                if data[1] < min_version {
372                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
373                }
374                // Minimum size (account may be larger if migrated to a newer version).
375                if data.len() < Self::LEN {
376                    return Err($crate::hopper_runtime::error::ProgramError::AccountDataTooSmall);
377                }
378                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
379            }
380
381            /// Tier 3m: Version-compatible load (mutable).
382            ///
383            /// Same as [`load_compatible`] but returns a mutable overlay.
384            #[inline]
385            pub fn load_compatible_mut<'a>(
386                account: &'a $crate::hopper_runtime::AccountView,
387                program_id: &$crate::hopper_runtime::Address,
388                min_version: u8,
389            ) -> Result<
390                $crate::hopper_core::account::VerifiedAccountMut<'a, Self>,
391                $crate::hopper_runtime::error::ProgramError,
392            > {
393                $crate::hopper_core::check::check_owner(account, program_id)?;
394                $crate::hopper_core::check::check_writable(account)?;
395                let data = account.try_borrow_mut()?;
396                if data.len() < $crate::hopper_core::account::HEADER_LEN {
397                    return Err($crate::hopper_runtime::error::ProgramError::AccountDataTooSmall);
398                }
399                if data[0] != Self::DISC {
400                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
401                }
402                if data[1] < min_version {
403                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
404                }
405                if data.len() < Self::LEN {
406                    return Err($crate::hopper_runtime::error::ProgramError::AccountDataTooSmall);
407                }
408                $crate::hopper_core::account::VerifiedAccountMut::from_ref_mut(data)
409            }
410
411            /// Tier 4: Unchecked load (caller assumes all risk).
412            ///
413            /// # Safety
414            /// Caller must guarantee the data is valid for this layout.
415            ///
416            /// **Deprecated:** Use `load()` for safe access. For explicit
417            /// unsafe access, use the raw byte pointer directly.
418            #[deprecated(since = "0.2.0", note = "use load() for safe access")]
419            #[inline(always)]
420            pub unsafe fn load_unchecked(data: &[u8]) -> &Self {
421                &*(data.as_ptr() as *const Self)
422            }
423
424            /// Write the header for a freshly initialized account.
425            #[inline(always)]
426            pub fn write_init_header(data: &mut [u8]) -> Result<(), $crate::hopper_runtime::error::ProgramError> {
427                $crate::hopper_core::account::write_header(
428                    data,
429                    Self::DISC,
430                    Self::VERSION,
431                    &Self::LAYOUT_ID,
432                )
433            }
434
435            // -- BUMP_OFFSET PDA Optimization ------
436            //
437            // Scans fields for a `bump` field. If found, generates
438            // BUMP_OFFSET const and verify_pda_cached() convenience method.
439            // Saves ~344 CU per PDA check vs find_program_address.
440
441            /// Byte offset of the bump field (if present). Used by BUMP_OFFSET PDA optimization.
442            /// If no bump field exists, this is set to usize::MAX as a sentinel.
443            pub const BUMP_OFFSET: usize = {
444                let mut offset = $crate::hopper_core::account::HEADER_LEN;
445                let mut found = usize::MAX;
446                $(
447                    if $crate::hopper_core::__str_eq(stringify!($field), "bump") {
448                        found = offset;
449                    }
450                    offset += $fsize;
451                )+
452                let _ = offset;
453                found
454            };
455
456            /// Returns `true` if this layout has a bump field for PDA optimization.
457            #[inline(always)]
458            pub const fn has_bump_offset() -> bool {
459                Self::BUMP_OFFSET != usize::MAX
460            }
461
462            /// Verify a PDA using the bump stored in account data (~200 CU).
463            ///
464            /// Reads the bump from `BUMP_OFFSET`, appends it to seeds, then
465            /// uses SHA-256 verify-only. Saves ~1300 CU vs `find_program_address`.
466            ///
467            /// Only available on layouts with a `bump` field. Panics at compile
468            /// time otherwise (asserts `BUMP_OFFSET != usize::MAX`).
469            #[inline]
470            pub fn verify_pda_cached(
471                account: &$crate::hopper_runtime::AccountView,
472                seeds: &[&[u8]],
473                program_id: &$crate::hopper_runtime::Address,
474            ) -> Result<(), $crate::hopper_runtime::error::ProgramError> {
475                // BUMP_OFFSET is a const, so this comparison is optimized away.
476                if Self::BUMP_OFFSET == usize::MAX {
477                    return Err($crate::hopper_runtime::error::ProgramError::InvalidArgument);
478                }
479                $crate::hopper_runtime::pda::verify_pda_from_stored_bump(
480                    account, seeds, Self::BUMP_OFFSET, program_id,
481                )
482            }
483
484            // -- Tier 5: Unverified Overlay ------
485            //
486            // Best-effort loading for indexers and off-chain tooling.
487            // Attempts header validation but returns the overlay even on
488            // failure, with a bool indicating whether validation passed.
489
490            /// Tier 5: Unverified overlay for indexers/tooling.
491            ///
492            /// Attempts to validate the header but returns the overlay
493            /// regardless. The returned bool is `true` if validation passed.
494            ///
495            /// This is safe to call on any data -- it never panics.
496            #[inline]
497            pub fn load_unverified(data: &[u8]) -> Option<(&Self, bool)> {
498                if data.len() < Self::LEN {
499                    return None;
500                }
501                let validated = $crate::hopper_core::account::check_header(
502                    data,
503                    Self::DISC,
504                    Self::VERSION,
505                    &Self::LAYOUT_ID,
506                )
507                .is_ok();
508                // SAFETY: Size checked above. T: Pod, alignment-1.
509                let overlay = unsafe { &*(data.as_ptr() as *const Self) };
510                Some((overlay, validated))
511            }
512
513            // -- Multi-Owner Foreign Load ------
514            //
515            // Load foreign account that could be owned by any of several
516            // programs (e.g., Token vs Token-2022).
517
518            /// Tier 2m: Foreign load with multiple possible owners.
519            ///
520            /// Returns `(VerifiedAccount, owner_index)` where `owner_index`
521            /// indicates which owner matched.
522            #[inline]
523            pub fn load_foreign_multi<'a>(
524                account: &'a $crate::hopper_runtime::AccountView,
525                owners: &[&$crate::hopper_runtime::Address],
526            ) -> Result<
527                ($crate::hopper_core::account::VerifiedAccount<'a, Self>, usize),
528                $crate::hopper_runtime::error::ProgramError,
529            > {
530                let owner_idx = $crate::hopper_core::check::check_owner_multi(account, owners)?;
531                let data = account.try_borrow()?;
532                let layout_id = $crate::hopper_core::account::read_layout_id(&*data)?;
533                if layout_id != Self::LAYOUT_ID {
534                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
535                }
536                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
537                let verified = $crate::hopper_core::account::VerifiedAccount::from_ref(data)?;
538                Ok((verified, owner_idx))
539            }
540        }
541
542        // Implement HopperLayout for modifier-style wrappers.
543        impl $crate::hopper_core::check::modifier::HopperLayout for $name {
544            const DISC: u8 = $disc;
545            const VERSION: u8 = $ver;
546            const LAYOUT_ID: [u8; 8] = $name::LAYOUT_ID;
547            const LEN_WITH_HEADER: usize = $name::LEN;
548        }
549    };
550}
551
552// ═════════════════════════════════════════════════════════════════════
553//  Section: Validation (check / error / require)
554// ═════════════════════════════════════════════════════════════════════
555
556/// Composable account constraint checking.
557///
558/// ```ignore
559/// hopper_check!(vault,
560///     owner = program_id,
561///     writable,
562///     signer,
563///     disc = Vault::DISC,
564///     size >= Vault::LEN,
565/// );
566/// ```
567#[macro_export]
568macro_rules! hopper_check {
569    ($account:expr, $( $constraint:tt )+) => {{
570        $crate::_hopper_check_inner!($account, $( $constraint )+)
571    }};
572}
573
574// Internal constraint dispatcher
575#[doc(hidden)]
576#[macro_export]
577macro_rules! _hopper_check_inner {
578    // owner = $id
579    ($account:expr, owner = $id:expr $(, $($rest:tt)+ )?) => {{
580        $crate::hopper_core::check::check_owner($account, $id)?;
581        $( $crate::_hopper_check_inner!($account, $($rest)+); )?
582    }};
583    // writable
584    ($account:expr, writable $(, $($rest:tt)+ )?) => {{
585        $crate::hopper_core::check::check_writable($account)?;
586        $( $crate::_hopper_check_inner!($account, $($rest)+); )?
587    }};
588    // signer
589    ($account:expr, signer $(, $($rest:tt)+ )?) => {{
590        $crate::hopper_core::check::check_signer($account)?;
591        $( $crate::_hopper_check_inner!($account, $($rest)+); )?
592    }};
593    // disc = $d
594    ($account:expr, disc = $d:expr $(, $($rest:tt)+ )?) => {{
595        let data = $account.try_borrow()?;
596        $crate::hopper_core::check::check_discriminator(&*data, $d)?;
597        $( $crate::_hopper_check_inner!($account, $($rest)+); )?
598    }};
599    // size >= $n
600    ($account:expr, size >= $n:expr $(, $($rest:tt)+ )?) => {{
601        let data = $account.try_borrow()?;
602        $crate::hopper_core::check::check_size(&*data, $n)?;
603        $( $crate::_hopper_check_inner!($account, $($rest)+); )?
604    }};
605    // Base case
606    ($account:expr,) => {};
607}
608
609/// Generate sequential error codes.
610///
611/// ```ignore
612/// hopper_error! {
613///     base = 6000;
614///     Undercollateralized,  // 6000
615///     Expired,              // 6001
616///     InvalidOracle,        // 6002
617/// }
618/// ```
619#[macro_export]
620macro_rules! hopper_error {
621    (
622        base = $base:literal;
623        $( $name:ident ),+ $(,)?
624    ) => {
625        $crate::_hopper_error_inner!($base; $( $name ),+);
626    };
627}
628
629#[doc(hidden)]
630#[macro_export]
631macro_rules! _hopper_error_inner {
632    // Base case: single ident
633    ($code:expr; $name:ident) => {
634        pub struct $name;
635        impl $name {
636            pub const CODE: u32 = $code;
637        }
638        impl From<$name> for $crate::hopper_runtime::error::ProgramError {
639            fn from(_: $name) -> $crate::hopper_runtime::error::ProgramError {
640                $crate::hopper_runtime::error::ProgramError::Custom($code)
641            }
642        }
643    };
644    // Recursive case: first ident + rest
645    ($code:expr; $name:ident, $($rest:ident),+) => {
646        $crate::_hopper_error_inner!($code; $name);
647        $crate::_hopper_error_inner!($code + 1; $($rest),+);
648    };
649}
650
651/// Require a condition, returning a custom error if false.
652///
653/// ```ignore
654/// hopper_require!(amount > 0, ZeroAmount)?;
655/// ```
656#[macro_export]
657macro_rules! hopper_require {
658    ($cond:expr, $err:expr) => {
659        if !$cond {
660            return Err($err.into());
661        }
662    };
663}
664
665// ═════════════════════════════════════════════════════════════════════
666//  Section: Lifecycle (init / close)
667// ═════════════════════════════════════════════════════════════════════
668
669/// Initialize an account: create via CPI, zero-init, write header.
670///
671/// ```ignore
672/// hopper_init!(payer, account, system_program, program_id, Vault)?;
673/// ```
674#[macro_export]
675macro_rules! hopper_init {
676    ($payer:expr, $account:expr, $system:expr, $program_id:expr, $layout:ty) => {{
677        // Calculate rent
678        let lamports = $crate::hopper_core::check::rent_exempt_min(<$layout>::LEN);
679        let space = <$layout>::LEN as u64;
680
681        // CPI CreateAccount
682        $crate::hopper_system::CreateAccount {
683            from: $payer,
684            to: $account,
685            lamports,
686            space,
687            owner: $program_id,
688        }
689        .invoke()?;
690
691        // Zero-init and write header
692        let mut data = $account.try_borrow_mut()?;
693        $crate::hopper_core::account::zero_init(&mut *data);
694        <$layout>::write_init_header(&mut *data)
695    }};
696}
697
698/// Safely close an account with sentinel protection.
699///
700/// ```ignore
701/// hopper_close!(account, destination)?;
702/// ```
703#[macro_export]
704macro_rules! hopper_close {
705    ($account:expr, $destination:expr) => {
706        $crate::hopper_core::account::safe_close_with_sentinel($account, $destination)
707    };
708}
709
710// ═════════════════════════════════════════════════════════════════════
711//  Section: Dispatch (discriminator registry)
712// ═════════════════════════════════════════════════════════════════════
713
714/// Discriminator registry -- compile-time uniqueness enforcement.
715///
716/// Lists all account types for a program and asserts that no two share
717/// a discriminator. This prevents silent bugs where `Vault::load()` could
718/// accidentally succeed on a `Pool` account.
719///
720/// ```ignore
721/// hopper_register_discs! {
722///     Vault,
723///     Pool,
724///     Position,
725/// }
726/// ```
727///
728/// Fails at compile time if any two types share the same DISC value.
729#[macro_export]
730macro_rules! hopper_register_discs {
731    ( $( $layout:ty ),+ $(,)? ) => {
732        const _: () = {
733            let discs: &[u8] = &[ $( <$layout>::DISC, )+ ];
734            let names: &[&str] = &[ $( stringify!($layout), )+ ];
735            let n = discs.len();
736            let mut i = 0;
737            while i < n {
738                let mut j = i + 1;
739                while j < n {
740                    assert!(
741                        discs[i] != discs[j],
742                        // Can't format at const time, but this gives a clear enough message
743                        "Duplicate discriminator detected in hopper_register_discs!"
744                    );
745                    j += 1;
746                }
747                i += 1;
748            }
749            let _ = names; // consumed for error messages in non-const contexts
750        };
751    };
752}
753
754// ═════════════════════════════════════════════════════════════════════
755//  Section: PDA
756// ═════════════════════════════════════════════════════════════════════
757
758/// PDA verification with BUMP_OFFSET optimization.
759///
760/// If the layout has a bump field, reads bump from account data and uses
761/// `create_program_address` (~200 CU). Otherwise falls back to
762/// `find_program_address` (~544 CU).
763///
764/// ```ignore
765/// hopper_verify_pda!(vault_account, &[b"vault", authority.as_ref()], program_id, Vault)?;
766/// ```
767#[macro_export]
768macro_rules! hopper_verify_pda {
769    ($account:expr, $seeds:expr, $program_id:expr, $layout:ty) => {{
770        if <$layout>::has_bump_offset() {
771            $crate::hopper_core::check::verify_pda_cached(
772                $account,
773                $seeds,
774                <$layout>::BUMP_OFFSET,
775                $program_id,
776            )
777        } else {
778            // Fallback: no bump field, use regular verify
779            match $crate::hopper_core::check::find_and_verify_pda($account, $seeds, $program_id) {
780                Ok(_bump) => Ok(()),
781                Err(e) => Err(e),
782            }
783        }
784    }};
785}
786
787// ═════════════════════════════════════════════════════════════════════
788//  Section: Invariants
789// ═════════════════════════════════════════════════════════════════════
790
791/// Invariant checking macro.
792///
793/// Defines a set of invariants for an instruction that run after mutation.
794/// Each invariant is a closure over account data that returns `ProgramResult`.
795///
796/// ```ignore
797/// hopper_invariant! {
798///     "balance_conserved" => |vault: &Vault| {
799///         let bal = vault.balance.get();
800///         hopper_require!(bal <= MAX_SUPPLY, BalanceOverflow);
801///         Ok(())
802///     },
803///     "authority_unchanged" => |vault: &Vault, old: &Vault| {
804///         hopper_require!(vault.authority == old.authority, AuthorityChanged);
805///         Ok(())
806///     },
807/// }
808/// ```
809///
810/// Generates an inline invariant runner that returns the first failure.
811#[macro_export]
812macro_rules! hopper_invariant {
813    ( $( $label:literal => $check:expr ),+ $(,)? ) => {{
814        let mut _result: $crate::hopper_runtime::ProgramResult = Ok(());
815        $(
816            if _result.is_ok() {
817                _result = $check;
818            }
819        )+
820        _result
821    }};
822}
823
824// ═════════════════════════════════════════════════════════════════════
825//  Section: Manifest (schema export)
826// ═════════════════════════════════════════════════════════════════════
827
828/// Generate a layout manifest for schema tooling.
829///
830/// Produces a `const LayoutManifest` for a layout type, with field
831/// descriptors suitable for off-chain tooling, indexers, and migration
832/// compatibility checks.
833///
834/// ```ignore
835/// hopper_manifest! {
836///     VAULT_MANIFEST = Vault {
837///         authority: [u8; 32]  = 32,
838///         mint:      [u8; 32]  = 32,
839///         balance:   WireU64   = 8,
840///         bump:      u8        = 1,
841///     }
842/// }
843/// ```
844///
845/// Generates: `pub const VAULT_MANIFEST: hopper_schema::LayoutManifest`
846#[macro_export]
847macro_rules! hopper_manifest {
848    (
849        $const_name:ident = $name:ident {
850            $( $field:ident : $fty:ty = $fsize:literal ),+ $(,)?
851        }
852    ) => {
853        pub const $const_name: $crate::hopper_schema::LayoutManifest = {
854            const FIELD_COUNT: usize = 0 $( + { let _ = stringify!($field); 1 } )+;
855            const SIZES: [u16; FIELD_COUNT] = [ $( $fsize ),+ ];
856            const NAMES: [&str; FIELD_COUNT] = [ $( stringify!($field) ),+ ];
857            const TYPES: [&str; FIELD_COUNT] = [ $( stringify!($fty) ),+ ];
858            const FIELDS: [$crate::hopper_schema::FieldDescriptor; FIELD_COUNT] = {
859                let h = $crate::hopper_core::account::HEADER_LEN as u16;
860                let mut result = [$crate::hopper_schema::FieldDescriptor {
861                    name: "", canonical_type: "", size: 0, offset: 0,
862                    intent: $crate::hopper_schema::FieldIntent::Custom,
863                }; FIELD_COUNT];
864                let mut offset = h;
865                let mut i = 0;
866                while i < FIELD_COUNT {
867                    result[i] = $crate::hopper_schema::FieldDescriptor {
868                        name: NAMES[i],
869                        canonical_type: TYPES[i],
870                        size: SIZES[i],
871                        offset,
872                        intent: $crate::hopper_schema::FieldIntent::Custom,
873                    };
874                    offset += SIZES[i];
875                    i += 1;
876                }
877                result
878            };
879            $crate::hopper_schema::LayoutManifest {
880                name: stringify!($name),
881                version: <$name>::VERSION,
882                disc: <$name>::DISC,
883                layout_id: <$name>::LAYOUT_ID,
884                total_size: <$name>::LEN,
885                field_count: FIELD_COUNT,
886                fields: &FIELDS,
887            }
888        };
889    };
890}
891
892// ═════════════════════════════════════════════════════════════════════
893//  Section: Segmented accounts
894// ═════════════════════════════════════════════════════════════════════
895
896/// Declare a segmented account with typed segments.
897///
898/// Generates:
899/// - Segment ID constants (FNV-1a)
900/// - A `register_segments` function that initializes the segment registry
901/// - Per-segment accessor methods on a generated context struct
902///
903/// ```ignore
904/// hopper_segment! {
905///     pub struct Treasury, disc = 3 {
906///         core:        TreasuryCore        = 128,
907///         permissions: PermissionsTable     = 256,
908///         history:     HistoryLog           = 512,
909///     }
910/// }
911///
912/// // Initialize:
913/// Treasury::init_segments(data)?;
914///
915/// // Read:
916/// let core: &TreasuryCore = Treasury::load_segment::<TreasuryCore>(data, Treasury::CORE_ID)?;
917/// ```
918#[macro_export]
919macro_rules! hopper_segment {
920    (
921        $(#[$attr:meta])*
922        pub struct $name:ident, disc = $disc:literal
923        {
924            $( $seg:ident : $sty:ty = $ssize:literal ),+ $(,)?
925        }
926    ) => {
927        $(#[$attr])*
928        pub struct $name;
929
930        impl $name {
931            pub const DISC: u8 = $disc;
932
933            // Generate segment ID constants
934            $crate::_hopper_segment_ids!($( $seg ),+);
935
936            // Segment count
937            pub const SEGMENT_COUNT: usize = $crate::_hopper_segment_count!($( $seg ),+);
938
939            /// Total account size: header + registry header + entries + segment data.
940            pub const TOTAL_SIZE: usize = {
941                let registry_size = $crate::hopper_core::account::registry::REGISTRY_HEADER_SIZE
942                    + (Self::SEGMENT_COUNT * $crate::hopper_core::account::registry::SEGMENT_ENTRY_SIZE);
943                $crate::hopper_core::account::HEADER_LEN
944                    + registry_size
945                    $( + $ssize )+
946            };
947
948            /// Initialize the segment registry with all declared segments.
949            #[inline]
950            pub fn init_segments(data: &mut [u8]) -> Result<(), $crate::hopper_runtime::error::ProgramError> {
951                let specs: &[($crate::hopper_core::account::registry::SegmentId, u32, u8)] = &[
952                    $(
953                        (
954                            $crate::hopper_core::account::registry::segment_id(stringify!($seg)),
955                            $ssize as u32,
956                            1u8,
957                        ),
958                    )+
959                ];
960                $crate::hopper_core::account::SegmentRegistryMut::init(data, specs)
961            }
962
963            /// Load a typed overlay from a named segment (immutable).
964            #[inline]
965            pub fn load_segment<T: $crate::hopper_core::account::Pod + $crate::hopper_core::account::FixedLayout>(
966                data: &[u8],
967                seg_id: &$crate::hopper_core::account::registry::SegmentId,
968            ) -> Result<&T, $crate::hopper_runtime::error::ProgramError> {
969                let registry = $crate::hopper_core::account::SegmentRegistry::from_account(data)?;
970                registry.segment_overlay::<T>(seg_id)
971            }
972
973            /// Load a typed overlay from a named segment (mutable).
974            #[inline]
975            pub fn load_segment_mut<T: $crate::hopper_core::account::Pod + $crate::hopper_core::account::FixedLayout>(
976                data: &mut [u8],
977                seg_id: &$crate::hopper_core::account::registry::SegmentId,
978            ) -> Result<&mut T, $crate::hopper_runtime::error::ProgramError> {
979                let mut registry = $crate::hopper_core::account::SegmentRegistryMut::from_account_mut(data)?;
980                registry.segment_overlay_mut::<T>(seg_id)
981            }
982        }
983    };
984}
985
986/// Generate uppercase segment ID constants from field names.
987#[doc(hidden)]
988#[macro_export]
989macro_rules! _hopper_segment_ids {
990    ( $( $seg:ident ),+ ) => {
991        $(
992            // Use paste-style approach: just use the name directly as a const
993            // The user references it as TypeName::SEGNAME_ID
994            $crate::_hopper_segment_id_const!($seg);
995        )+
996    };
997}
998
999/// Generate a single segment ID constant.
1000///
1001/// Produces `pub const {NAME}_ID: SegmentId = segment_id("name");`
1002/// Due to macro_rules limitations we use the exact field name in
1003/// uppercase manually. This generates as-is with _ID suffix.
1004#[doc(hidden)]
1005#[macro_export]
1006macro_rules! _hopper_segment_id_const {
1007    ($seg:ident) => {
1008        #[doc = concat!("Segment ID for `", stringify!($seg), "`.")]
1009        #[allow(non_upper_case_globals)]
1010        pub const $seg: $crate::hopper_core::account::registry::SegmentId =
1011            $crate::hopper_core::account::registry::segment_id(stringify!($seg));
1012    };
1013}
1014
1015/// Count segments.
1016#[doc(hidden)]
1017#[macro_export]
1018macro_rules! _hopper_segment_count {
1019    ( $( $seg:ident ),+ ) => {
1020        {
1021            let mut _n = 0usize;
1022            $( let _ = stringify!($seg); _n += 1; )+
1023            _n
1024        }
1025    };
1026}
1027
1028// ═════════════════════════════════════════════════════════════════════
1029//  Section: Validation pipeline builder
1030// ═════════════════════════════════════════════════════════════════════
1031
1032/// Build a validation pipeline declaratively.
1033///
1034/// Each rule is a combinator that returns `impl Fn(&ValidationContext) -> ProgramResult`.
1035/// The macro creates a context, enforces unique writable accounts by default,
1036/// and then invokes each rule in order (fail-fast).
1037#[macro_export]
1038macro_rules! hopper_validate {
1039    (
1040        accounts = $accounts:expr,
1041        program_id = $program_id:expr,
1042        data = $data:expr,
1043        rules {
1044            $( $rule:expr ),+ $(,)?
1045        }
1046    ) => {{
1047        let _vctx = $crate::hopper_core::check::graph::ValidationContext::new(
1048            $program_id,
1049            $accounts,
1050            $data,
1051        );
1052        $crate::hopper_core::check::graph::require_unique_writable_accounts()(&_vctx)?;
1053        $( ($rule)(&_vctx)?; )+
1054        Ok::<(), $crate::hopper_runtime::error::ProgramError>(())
1055    }};
1056}
1057
1058// ═════════════════════════════════════════════════════════════════════
1059//  Section: Virtual state (multi-account mapping)
1060// ═════════════════════════════════════════════════════════════════════
1061
1062/// Declare a multi-account virtual state mapping.
1063///
1064/// ```ignore
1065/// let market = hopper_virtual! {
1066///     slots = 3,
1067///     map {
1068///         0 => account_index: 1, owned, writable,
1069///         1 => account_index: 2, owned,
1070///         2 => account_index: 3,
1071///     }
1072/// };
1073///
1074/// market.validate(accounts, program_id)?;
1075/// let core: &MarketCore = market.overlay::<MarketCore>(accounts, 0)?;
1076/// ```
1077#[macro_export]
1078macro_rules! hopper_virtual {
1079    (
1080        slots = $n:literal,
1081        map {
1082            $( $slot:literal => account_index: $idx:literal
1083                $(, owned $( = $owner:expr )? )?
1084                $(, writable )?
1085            ),+ $(,)?
1086        }
1087    ) => {{
1088        let mut vs = $crate::hopper_core::virtual_state::VirtualState::<$n>::new();
1089        $(
1090            vs = $crate::_hopper_virtual_slot!(vs, $slot, $idx
1091                $(, owned $( = $owner )? )?
1092                $(, writable )?
1093            );
1094        )+
1095        vs
1096    }};
1097}
1098
1099/// Apply a single virtual slot mapping.
1100#[doc(hidden)]
1101#[macro_export]
1102macro_rules! _hopper_virtual_slot {
1103    // owned + writable
1104    ($vs:expr, $slot:literal, $idx:literal, owned, writable) => {
1105        $vs.map_mut($slot, $idx)
1106    };
1107    // owned only
1108    ($vs:expr, $slot:literal, $idx:literal, owned) => {
1109        $vs.map($slot, $idx)
1110    };
1111    // writable only (no owner check)
1112    ($vs:expr, $slot:literal, $idx:literal, writable) => {
1113        $vs.set_slot(
1114            $slot,
1115            $crate::hopper_core::virtual_state::VirtualSlot {
1116                account_index: $idx,
1117                require_owned: false,
1118                require_writable: true,
1119            },
1120        )
1121    };
1122    // bare (no constraints)
1123    ($vs:expr, $slot:literal, $idx:literal) => {
1124        $vs.map_foreign($slot, $idx)
1125    };
1126}
1127
1128// ═════════════════════════════════════════════════════════════════════
1129//  Section: Compile-time compatibility & ABI assertions
1130// ═════════════════════════════════════════════════════════════════════
1131
1132/// Assert that two layout versions have compatible fingerprints.
1133///
1134/// Fails at compile time if the assertion doesn't hold.
1135/// Use this in tests and CI to catch accidental schema breaks.
1136///
1137/// ```ignore
1138/// // Assert V2 is a strict superset of V1 (append-only):
1139/// hopper_assert_compatible!(VaultV1, VaultV2, append);
1140///
1141/// // Assert two layouts have different fingerprints (version bump required):
1142/// hopper_assert_compatible!(VaultV1, VaultV2, differs);
1143/// ```
1144#[macro_export]
1145macro_rules! hopper_assert_compatible {
1146    // Assert V2 is append-compatible with V1: different fingerprint + larger size + same disc
1147    ($old:ty, $new:ty, append) => {
1148        const _: () = {
1149            assert!(
1150                <$new>::LEN > <$old>::LEN,
1151                "New layout must be larger than old for append compatibility"
1152            );
1153            assert!(
1154                <$new>::DISC == <$old>::DISC,
1155                "Discriminator must remain the same across versions"
1156            );
1157            assert!(
1158                <$new>::VERSION > <$old>::VERSION,
1159                "New version must be strictly greater"
1160            );
1161            // Layout IDs must differ (field set changed)
1162            let old_id = <$old>::LAYOUT_ID;
1163            let new_id = <$new>::LAYOUT_ID;
1164            let mut same = true;
1165            let mut i = 0;
1166            while i < 8 {
1167                if old_id[i] != new_id[i] {
1168                    same = false;
1169                }
1170                i += 1;
1171            }
1172            assert!(!same, "Layout IDs must differ between versions");
1173        };
1174    };
1175    // Assert two layouts have different fingerprints
1176    ($old:ty, $new:ty, differs) => {
1177        const _: () = {
1178            let old_id = <$old>::LAYOUT_ID;
1179            let new_id = <$new>::LAYOUT_ID;
1180            let mut same = true;
1181            let mut i = 0;
1182            while i < 8 {
1183                if old_id[i] != new_id[i] {
1184                    same = false;
1185                }
1186                i += 1;
1187            }
1188            assert!(!same, "Layout IDs must differ between versions");
1189        };
1190    };
1191}
1192
1193/// Assert that a layout's fingerprint matches an expected value.
1194///
1195/// Use this to pin a layout's fingerprint in tests. If someone changes the
1196/// layout fields, this assertion catches the ABI break at compile time.
1197///
1198/// ```ignore
1199/// hopper_assert_fingerprint!(Vault, [0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x70, 0x81]);
1200/// ```
1201#[macro_export]
1202macro_rules! hopper_assert_fingerprint {
1203    ($layout:ty, $expected:expr) => {
1204        const _: () = {
1205            let actual = <$layout>::LAYOUT_ID;
1206            let expected: [u8; 8] = $expected;
1207            let mut i = 0;
1208            while i < 8 {
1209                assert!(
1210                    actual[i] == expected[i],
1211                    "Layout fingerprint doesn't match expected value -- ABI may have changed"
1212                );
1213                i += 1;
1214            }
1215        };
1216    };
1217}
1218
1219// Re-export dispatch from core
1220pub use hopper_core;
1221pub use hopper_runtime;
1222pub use hopper_schema;
1223pub use hopper_system;
1224
1225/// Compile-time assertion for safe manual `Pod` implementations.
1226///
1227/// Verifies that a type meets all Pod requirements:
1228/// - `align_of == 1` (required for zero-copy overlay at any offset)
1229/// - `size_of == SIZE` matches declared SIZE
1230///
1231/// Use this when implementing `Pod` manually (outside of `hopper_layout!`).
1232///
1233/// ```ignore
1234/// #[repr(C)]
1235/// #[derive(Clone, Copy)]
1236/// pub struct MyEntry {
1237///     pub key: [u8; 32],
1238///     pub value: WireU64,
1239/// }
1240///
1241/// const_assert_pod!(MyEntry, 40);
1242/// unsafe impl Pod for MyEntry {}
1243/// ```
1244#[macro_export]
1245macro_rules! const_assert_pod {
1246    ($ty:ty, $size:expr) => {
1247        const _: () = assert!(
1248            core::mem::align_of::<$ty>() == 1,
1249            concat!(
1250                "Pod type `",
1251                stringify!($ty),
1252                "` must have alignment 1 for zero-copy safety. ",
1253                "Ensure all fields use alignment-1 wire types ([u8; N], WireU64, etc.)."
1254            )
1255        );
1256        const _: () = assert!(
1257            core::mem::size_of::<$ty>() == $size,
1258            concat!(
1259                "Pod type `",
1260                stringify!($ty),
1261                "` size mismatch: ",
1262                "expected ",
1263                stringify!($size),
1264                " bytes"
1265            )
1266        );
1267    };
1268}
1269
1270// ═════════════════════════════════════════════════════════════════════
1271//  Section: Cross-program interface
1272// ═════════════════════════════════════════════════════════════════════
1273
1274/// Declare a cross-program interface view.
1275///
1276/// Generates a read-only overlay struct for reading accounts owned by
1277/// another program **without any crate dependency**. The interface is
1278/// pinned by `LAYOUT_ID` -- the same deterministic SHA-256 fingerprint
1279/// used by `hopper_layout!`. If the originating program changes its
1280/// layout, the fingerprint will differ and `load_foreign()` will reject
1281/// the account at runtime.
1282///
1283/// The generated struct includes:
1284/// - `#[repr(C)]` zero-copy overlay with alignment-1 guarantee
1285/// - Deterministic `LAYOUT_ID` matching the originating layout
1286/// - `load_foreign(account, expected_owner)` for Tier-2 cross-program reads
1287/// - `load_foreign_multi(account, owners)` for multi-owner scenarios
1288/// - `load_with_profile(account, TrustProfile)` for configurable trust
1289/// - Compile-time size and alignment assertions
1290///
1291/// # Example
1292///
1293/// Program A defines a Vault:
1294/// ```ignore
1295/// hopper_layout! {
1296///     pub struct Vault, disc = 1, version = 1 {
1297///         authority: TypedAddress<Authority> = 32,
1298///         balance:   WireU64                = 8,
1299///         bump:      u8                     = 1,
1300///     }
1301/// }
1302/// ```
1303///
1304/// Program B reads it **without importing Program A**:
1305/// ```ignore
1306/// hopper_interface! {
1307///     /// Read-only view of Program A's Vault.
1308///     pub struct VaultView, disc = 1, version = 1 {
1309///         authority: TypedAddress<Authority> = 32,
1310///         balance:   WireU64                = 8,
1311///         bump:      u8                     = 1,
1312///     }
1313/// }
1314///
1315/// let verified = VaultView::load_foreign(vault_account, &PROGRAM_A_ID)?;
1316/// let balance = verified.get().balance.get();
1317/// ```
1318///
1319/// If the fields match Program A's Vault exactly, the LAYOUT_IDs will
1320/// be identical and `load_foreign` succeeds. Any structural divergence
1321/// produces a different hash and the load fails.
1322#[macro_export]
1323macro_rules! hopper_interface {
1324    (
1325        $(#[$attr:meta])*
1326        pub struct $name:ident, disc = $disc:literal, version = $ver:literal
1327        {
1328            $(
1329                $(#[$field_attr:meta])*
1330                $field:ident : $fty:ty = $fsize:literal
1331            ),+ $(,)?
1332        }
1333    ) => {
1334        $(#[$attr])*
1335        #[derive(Clone, Copy)]
1336        #[repr(C)]
1337        pub struct $name {
1338            pub header: $crate::hopper_core::account::AccountHeader,
1339            $(
1340                $(#[$field_attr])*
1341                pub $field: $fty,
1342            )+
1343        }
1344
1345        // Compile-time assertions
1346        const _: () = {
1347            let expected = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
1348            assert!(
1349                core::mem::size_of::<$name>() == expected,
1350                "Interface size mismatch: struct size != declared field sizes + header"
1351            );
1352            assert!(
1353                core::mem::align_of::<$name>() == 1,
1354                "Interface alignment must be 1 for zero-copy safety"
1355            );
1356        };
1357
1358        // Bytemuck proof (Hopper Safety Audit Must-Fix #5), same
1359        // justification as `hopper_layout!`: `#[repr(C)]` over Hopper
1360        // wire types is bytemuck-safe by construction.
1361        #[cfg(feature = "hopper-native-backend")]
1362        unsafe impl $crate::hopper_runtime::__hopper_native::bytemuck::Zeroable for $name {}
1363        #[cfg(feature = "hopper-native-backend")]
1364        unsafe impl $crate::hopper_runtime::__hopper_native::bytemuck::Pod for $name {}
1365
1366        // SAFETY: #[repr(C)] over alignment-1 fields, all bit patterns valid.
1367        unsafe impl $crate::hopper_core::account::Pod for $name {}
1368
1369        // Audit final-API Step 5 seal (second declarative-macro form).
1370        unsafe impl $crate::hopper_runtime::__sealed::HopperZeroCopySealed for $name {}
1371
1372        impl $crate::hopper_core::account::FixedLayout for $name {
1373            const SIZE: usize = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
1374        }
1375
1376        impl $crate::hopper_core::field_map::FieldMap for $name {
1377            const FIELDS: &'static [$crate::hopper_core::field_map::FieldInfo] = {
1378                const FIELD_COUNT: usize = 0 $( + { let _ = stringify!($field); 1 } )+;
1379                const NAMES: [&str; FIELD_COUNT] = [ $( stringify!($field) ),+ ];
1380                const SIZES: [usize; FIELD_COUNT] = [ $( $fsize ),+ ];
1381                const FIELDS: [$crate::hopper_core::field_map::FieldInfo; FIELD_COUNT] = {
1382                    let mut result = [$crate::hopper_core::field_map::FieldInfo::new("", 0, 0); FIELD_COUNT];
1383                    let mut offset = $crate::hopper_core::account::HEADER_LEN;
1384                    let mut index = 0;
1385                    while index < FIELD_COUNT {
1386                        result[index] = $crate::hopper_core::field_map::FieldInfo::new(
1387                            NAMES[index],
1388                            offset,
1389                            SIZES[index],
1390                        );
1391                        offset += SIZES[index];
1392                        index += 1;
1393                    }
1394                    result
1395                };
1396                &FIELDS
1397            };
1398        }
1399
1400        impl $crate::hopper_runtime::LayoutContract for $name {
1401            const DISC: u8 = $disc;
1402            const VERSION: u8 = $ver;
1403            const LAYOUT_ID: [u8; 8] = $name::LAYOUT_ID;
1404            const SIZE: usize = $name::LEN;
1405            const TYPE_OFFSET: usize = 0;
1406        }
1407
1408        impl $crate::hopper_schema::SchemaExport for $name {
1409            fn layout_manifest() -> $crate::hopper_schema::LayoutManifest {
1410                const FIELD_COUNT: usize = 0 $( + { let _ = stringify!($field); 1 } )+;
1411                const SIZES: [u16; FIELD_COUNT] = [ $( $fsize ),+ ];
1412                const NAMES: [&str; FIELD_COUNT] = [ $( stringify!($field) ),+ ];
1413                const TYPES: [&str; FIELD_COUNT] = [ $( stringify!($fty) ),+ ];
1414                const FIELDS: [$crate::hopper_schema::FieldDescriptor; FIELD_COUNT] = {
1415                    let mut result = [$crate::hopper_schema::FieldDescriptor {
1416                        name: "", canonical_type: "", size: 0, offset: 0,
1417                        intent: $crate::hopper_schema::FieldIntent::Custom,
1418                    }; FIELD_COUNT];
1419                    let mut offset = $crate::hopper_core::account::HEADER_LEN as u16;
1420                    let mut index = 0;
1421                    while index < FIELD_COUNT {
1422                        result[index] = $crate::hopper_schema::FieldDescriptor {
1423                            name: NAMES[index],
1424                            canonical_type: TYPES[index],
1425                            size: SIZES[index],
1426                            offset,
1427                            intent: $crate::hopper_schema::FieldIntent::Custom,
1428                        };
1429                        offset += SIZES[index];
1430                        index += 1;
1431                    }
1432                    result
1433                };
1434                $crate::hopper_schema::LayoutManifest {
1435                    name: stringify!($name),
1436                    version: <$name>::VERSION,
1437                    disc: <$name>::DISC,
1438                    layout_id: <$name>::LAYOUT_ID,
1439                    total_size: <$name>::LEN,
1440                    field_count: FIELD_COUNT,
1441                    fields: &FIELDS,
1442                }
1443            }
1444        }
1445
1446        impl $name {
1447            /// Total byte size of this interface view.
1448            pub const LEN: usize = $crate::hopper_core::account::HEADER_LEN $( + $fsize )+;
1449
1450            /// Expected discriminator of the originating layout.
1451            pub const DISC: u8 = $disc;
1452
1453            /// Expected version of the originating layout.
1454            pub const VERSION: u8 = $ver;
1455
1456            /// Deterministic layout fingerprint.
1457            ///
1458            /// Matches the originating layout's `LAYOUT_ID` if the field
1459            /// names, types, sizes, and ordering are identical.
1460            pub const LAYOUT_ID: [u8; 8] = {
1461                const INPUT: &str = concat!(
1462                    "hopper:v1:",
1463                    stringify!($name), ":",
1464                    stringify!($ver), ":",
1465                    $( stringify!($field), ":", stringify!($fty), ":", stringify!($fsize), ",", )+
1466                );
1467                const HASH: [u8; 32] = $crate::hopper_core::__sha256_const(INPUT.as_bytes());
1468                [
1469                    HASH[0], HASH[1], HASH[2], HASH[3],
1470                    HASH[4], HASH[5], HASH[6], HASH[7],
1471                ]
1472            };
1473
1474            /// Read-only overlay (immutable).
1475            #[inline(always)]
1476            pub fn overlay(data: &[u8]) -> Result<&Self, $crate::hopper_runtime::error::ProgramError> {
1477                $crate::hopper_core::account::pod_from_bytes::<Self>(data)
1478            }
1479
1480            /// Tier 2: Cross-program foreign load (read-only).
1481            ///
1482            /// Validates: owner + layout_id + exact size.
1483            /// No discriminator or version check -- the layout_id is the ABI proof.
1484            ///
1485            /// **Deprecated:** Renamed to `load_cross_program()` for clarity.
1486            #[deprecated(since = "0.2.0", note = "renamed to load_cross_program()")]
1487            #[inline]
1488            pub fn load_foreign<'a>(
1489                account: &'a $crate::hopper_runtime::AccountView,
1490                expected_owner: &$crate::hopper_runtime::Address,
1491            ) -> Result<
1492                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
1493                $crate::hopper_runtime::error::ProgramError,
1494            > {
1495                Self::load_cross_program(account, expected_owner)
1496            }
1497
1498            /// Tier 2: Cross-program load (read-only).
1499            ///
1500            /// Validates: owner + layout_id + exact size.
1501            /// The layout_id is the ABI proof, so no discriminator or version check is needed.
1502            #[inline]
1503            pub fn load_cross_program<'a>(
1504                account: &'a $crate::hopper_runtime::AccountView,
1505                expected_owner: &$crate::hopper_runtime::Address,
1506            ) -> Result<
1507                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
1508                $crate::hopper_runtime::error::ProgramError,
1509            > {
1510                $crate::hopper_core::check::check_owner(account, expected_owner)?;
1511                let data = account.try_borrow()?;
1512                let layout_id = $crate::hopper_core::account::read_layout_id(&*data)?;
1513                if layout_id != Self::LAYOUT_ID {
1514                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
1515                }
1516                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
1517                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
1518            }
1519
1520            /// Tier 2m: Foreign load with multiple possible owners.
1521            ///
1522            /// Returns `(VerifiedAccount, owner_index)` where `owner_index`
1523            /// indicates which expected owner matched.
1524            #[inline]
1525            pub fn load_foreign_multi<'a>(
1526                account: &'a $crate::hopper_runtime::AccountView,
1527                owners: &[&$crate::hopper_runtime::Address],
1528            ) -> Result<
1529                ($crate::hopper_core::account::VerifiedAccount<'a, Self>, usize),
1530                $crate::hopper_runtime::error::ProgramError,
1531            > {
1532                let owner_idx = $crate::hopper_core::check::check_owner_multi(account, owners)?;
1533                let data = account.try_borrow()?;
1534                let layout_id = $crate::hopper_core::account::read_layout_id(&*data)?;
1535                if layout_id != Self::LAYOUT_ID {
1536                    return Err($crate::hopper_runtime::error::ProgramError::InvalidAccountData);
1537                }
1538                $crate::hopper_core::check::check_size(&*data, Self::LEN)?;
1539                let verified = $crate::hopper_core::account::VerifiedAccount::from_ref(data)?;
1540                Ok((verified, owner_idx))
1541            }
1542
1543            /// Load with a TrustProfile for configurable cross-program validation.
1544            ///
1545            /// Supports Strict, Compatible, and Observational trust levels.
1546            #[inline]
1547            pub fn load_with_profile<'a>(
1548                account: &'a $crate::hopper_runtime::AccountView,
1549                profile: &$crate::hopper_core::check::trust::TrustProfile<'a>,
1550            ) -> Result<
1551                $crate::hopper_core::account::VerifiedAccount<'a, Self>,
1552                $crate::hopper_runtime::error::ProgramError,
1553            > {
1554                let data = profile.load(account)?;
1555                $crate::hopper_core::account::VerifiedAccount::from_ref(data)
1556            }
1557
1558            /// Tier 5: Unverified overlay for indexers/tooling.
1559            #[inline]
1560            pub fn load_unverified(data: &[u8]) -> Option<(&Self, bool)> {
1561                if data.len() < Self::LEN {
1562                    return None;
1563                }
1564                let validated = $crate::hopper_core::account::check_header(
1565                    data,
1566                    Self::DISC,
1567                    Self::VERSION,
1568                    &Self::LAYOUT_ID,
1569                )
1570                .is_ok();
1571                // SAFETY: Size checked above. T: Pod, alignment-1.
1572                let overlay = unsafe { &*(data.as_ptr() as *const Self) };
1573                Some((overlay, validated))
1574            }
1575        }
1576    };
1577}
1578
1579// ═════════════════════════════════════════════════════════════════════
1580//  Section: Typed account-struct context generation
1581// ═════════════════════════════════════════════════════════════════════
1582
1583/// Generate a typed instruction context struct with validated account parsing.
1584///
1585/// Produces:
1586/// - The account struct itself
1587/// - A `Bumps` struct for PDA bump storage
1588/// - A `HopperAccounts` impl with `try_from_accounts`
1589/// - A static `ContextDescriptor` for schema/explain
1590///
1591/// # Account kinds
1592///
1593/// Each field specifies a `kind` wrapped in parentheses, with optional modifiers:
1594///
1595/// | Kind                 | Description                     | Writable | Signer |
1596/// |----------------------|---------------------------------|----------|--------|
1597/// | `(signer)`           | Verified signer (SignerAccount) | no       | yes    |
1598/// | `(mut signer)`       | Mutable + signer                | yes      | yes    |
1599/// | `(account<T>)`       | Layout-bound HopperAccount      | no       | no     |
1600/// | `(mut account<T>)`   | Mutable layout-bound account    | yes      | no     |
1601/// | `(program)`          | Verified executable (ProgramRef)| no       | no     |
1602/// | `(unchecked)`        | No-validation passthrough       | no       | no     |
1603/// | `(mut unchecked)`    | Mutable unchecked passthrough   | yes      | no     |
1604///
1605/// # Example
1606///
1607/// ```ignore
1608/// hopper_accounts! {
1609///     pub struct Deposit {
1610///         authority: (mut signer),
1611///         vault: (mut account<VaultState>),
1612///         system_program: (program),
1613///     }
1614/// }
1615/// ```
1616///
1617/// Then use with `hopper_entry`:
1618///
1619/// ```ignore
1620/// hopper_entry::<DepositIx, _>(program_id, accounts, data, |ctx, args| {
1621///     let vault = ctx.accounts.vault.write()?;
1622///     // ...
1623///     Ok(())
1624/// })
1625/// ```
1626#[macro_export]
1627macro_rules! hopper_accounts {
1628    // Main entry: parse struct with field list
1629    (
1630        $(#[$attr:meta])*
1631        pub struct $name:ident {
1632            $( $field:ident : ( $($kind:tt)+ ) ),+ $(,)?
1633        }
1634    ) => {
1635        // Wrap each kind in parens so it becomes a single tt group,
1636        // which eliminates the greedy-tt ambiguity in the inner macro.
1637        $crate::_hopper_accounts_struct!($name; $( $field: ($($kind)+) ; )+);
1638    };
1639}
1640
1641/// Internal: parse each field's kind and generate the struct + impls.
1642///
1643/// Each `$kind` is a single parenthesised token tree, e.g. `(mut signer)`.
1644#[doc(hidden)]
1645#[macro_export]
1646macro_rules! _hopper_accounts_struct {
1647    ($name:ident; $( $field:ident : $kind:tt ; )+) => {
1648
1649        // --- Context struct ---
1650        pub struct $name<'a> {
1651            $(
1652                pub $field: $crate::_hopper_field_type!($kind),
1653            )+
1654        }
1655
1656        // --- HopperAccounts impl ---
1657        impl<'a> $crate::hopper_core::accounts::HopperAccounts<'a> for $name<'a> {
1658            type Bumps = ();
1659
1660            const ACCOUNT_COUNT: usize = {
1661                // Count fields at compile time using the array-length trick.
1662                #[allow(unused)]
1663                const N: usize = [$( { let _ = stringify!($field); 0u8 }, )+].len();
1664                N
1665            };
1666
1667            fn try_from_accounts(
1668                program_id: &'a $crate::hopper_runtime::Address,
1669                accounts: &'a [$crate::hopper_runtime::AccountView],
1670                _instruction_data: &'a [u8],
1671            ) -> Result<(Self, Self::Bumps), $crate::hopper_runtime::error::ProgramError> {
1672                let mut _idx: usize = 0;
1673                $(
1674                    if _idx >= accounts.len() {
1675                        return Err($crate::hopper_runtime::error::ProgramError::NotEnoughAccountKeys);
1676                    }
1677                    let $field = $crate::_hopper_field_parse!(
1678                        &accounts[_idx], program_id, $kind
1679                    )?;
1680                    _idx += 1;
1681                )+
1682                Ok((Self { $( $field, )+ }, ()))
1683            }
1684
1685            #[cfg(feature = "explain")]
1686            fn context_schema() -> Option<
1687                &'static $crate::hopper_core::accounts::explain::ContextSchema
1688            > {
1689                static FIELDS: &[$crate::hopper_core::accounts::explain::AccountFieldSchema] = &[
1690                    $(
1691                        $crate::hopper_core::accounts::explain::AccountFieldSchema {
1692                            name: stringify!($field),
1693                            kind: $crate::_hopper_field_kind_name!($kind),
1694                            mutable: $crate::_hopper_field_is_mut!($kind),
1695                            signer: $crate::_hopper_field_is_signer!($kind),
1696                            layout: $crate::_hopper_field_layout_name!($kind),
1697                            policy: None,
1698                            seeds: &[],
1699                            optional: false,
1700                        },
1701                    )+
1702                ];
1703                static SCHEMA: $crate::hopper_core::accounts::explain::ContextSchema =
1704                    $crate::hopper_core::accounts::explain::ContextSchema {
1705                        name: stringify!($name),
1706                        fields: FIELDS,
1707                        policy_names: &[],
1708                        receipts_expected: false,
1709                        mutation_classes: &[],
1710                    };
1711                Some(&SCHEMA)
1712            }
1713        }
1714    };
1715}
1716
1717// --- Field type resolution ---
1718
1719#[doc(hidden)]
1720#[macro_export]
1721macro_rules! _hopper_field_type {
1722    ((mut signer)) => { $crate::hopper_core::accounts::SignerAccount<'a> };
1723    ((signer)) => { $crate::hopper_core::accounts::SignerAccount<'a> };
1724    ((mut account < $layout:ty >)) => { $crate::hopper_core::accounts::HopperAccount<'a, $layout> };
1725    ((account < $layout:ty >)) => { $crate::hopper_core::accounts::HopperAccount<'a, $layout> };
1726    ((program)) => { $crate::hopper_core::accounts::ProgramRef<'a> };
1727    ((unchecked)) => { $crate::hopper_core::accounts::UncheckedAccount<'a> };
1728    ((mut unchecked)) => { $crate::hopper_core::accounts::UncheckedAccount<'a> };
1729}
1730
1731// --- Field parsing at runtime ---
1732
1733#[doc(hidden)]
1734#[macro_export]
1735macro_rules! _hopper_field_parse {
1736    ($account:expr, $program_id:expr, (mut signer)) => {{
1737        $crate::hopper_core::check::check_writable($account)?;
1738        $crate::hopper_core::accounts::SignerAccount::from_account($account)
1739    }};
1740    ($account:expr, $program_id:expr, (signer)) => {
1741        $crate::hopper_core::accounts::SignerAccount::from_account($account)
1742    };
1743    ($account:expr, $program_id:expr, (mut account < $layout:ty >)) => {
1744        $crate::hopper_core::accounts::HopperAccount::<$layout>::from_account_mut(
1745            $account,
1746            $program_id,
1747        )
1748    };
1749    ($account:expr, $program_id:expr, (account < $layout:ty >)) => {
1750        $crate::hopper_core::accounts::HopperAccount::<$layout>::from_account($account, $program_id)
1751    };
1752    ($account:expr, $program_id:expr, (program)) => {
1753        $crate::hopper_core::accounts::ProgramRef::from_account($account)
1754    };
1755    ($account:expr, $program_id:expr, (unchecked)) => {
1756        Ok::<_, $crate::hopper_runtime::error::ProgramError>(
1757            $crate::hopper_core::accounts::UncheckedAccount::new($account),
1758        )
1759    };
1760    ($account:expr, $program_id:expr, (mut unchecked)) => {{
1761        $crate::hopper_core::check::check_writable($account)?;
1762        Ok::<_, $crate::hopper_runtime::error::ProgramError>(
1763            $crate::hopper_core::accounts::UncheckedAccount::new($account),
1764        )
1765    }};
1766}
1767
1768// --- Static metadata helpers ---
1769
1770#[doc(hidden)]
1771#[macro_export]
1772macro_rules! _hopper_field_kind_name {
1773    ((mut signer)) => {
1774        "Signer"
1775    };
1776    ((signer)) => {
1777        "Signer"
1778    };
1779    ((mut account < $layout:ty >)) => {
1780        "HopperAccount"
1781    };
1782    ((account < $layout:ty >)) => {
1783        "HopperAccount"
1784    };
1785    ((program)) => {
1786        "ProgramRef"
1787    };
1788    ((unchecked)) => {
1789        "Unchecked"
1790    };
1791    ((mut unchecked)) => {
1792        "Unchecked"
1793    };
1794}
1795
1796#[doc(hidden)]
1797#[macro_export]
1798macro_rules! _hopper_field_is_mut {
1799    ((mut signer)) => {
1800        true
1801    };
1802    ((signer)) => {
1803        false
1804    };
1805    ((mut account < $layout:ty >)) => {
1806        true
1807    };
1808    ((account < $layout:ty >)) => {
1809        false
1810    };
1811    ((program)) => {
1812        false
1813    };
1814    ((unchecked)) => {
1815        false
1816    };
1817    ((mut unchecked)) => {
1818        true
1819    };
1820}
1821
1822#[doc(hidden)]
1823#[macro_export]
1824macro_rules! _hopper_field_is_signer {
1825    ((mut signer)) => {
1826        true
1827    };
1828    ((signer)) => {
1829        true
1830    };
1831    ((mut account < $layout:ty >)) => {
1832        false
1833    };
1834    ((account < $layout:ty >)) => {
1835        false
1836    };
1837    ((program)) => {
1838        false
1839    };
1840    ((unchecked)) => {
1841        false
1842    };
1843    ((mut unchecked)) => {
1844        false
1845    };
1846}
1847
1848#[doc(hidden)]
1849#[macro_export]
1850macro_rules! _hopper_field_layout_name {
1851    ((mut signer)) => {
1852        None
1853    };
1854    ((signer)) => {
1855        None
1856    };
1857    ((mut account < $layout:ty >)) => {
1858        Some(stringify!($layout))
1859    };
1860    ((account < $layout:ty >)) => {
1861        Some(stringify!($layout))
1862    };
1863    ((program)) => {
1864        None
1865    };
1866    ((unchecked)) => {
1867        None
1868    };
1869    ((mut unchecked)) => {
1870        None
1871    };
1872}