hopper-runtime 0.4.5

Canonical low-level runtime surface for Hopper programs: direct account memory, validation, borrow guards, CPI, and zero-copy state access.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! Manifest-backed foreign-account lenses.
//!
//! This module provides manifest-backed foreign-account lenses as a
//! verifiable alternative to ad-hoc offset-based foreign reads.
//!
//! # Problem
//!
//! Today, reading a field from an account owned by a *different* program
//! either imports the foreign program's crate (tight coupling, forces
//! version-lock) or reads raw bytes by hand-maintained offset
//! (no ABI-drift detection. if the foreign program changes its layout,
//! silent misreads result).
//!
//! # Design
//!
//! A `ForeignManifest` is an opaque witness (supplied by the caller)
//! that carries the foreign program's `wire_fp64` hash plus the layout
//! discriminator it expects for a particular `T: AccountLayout`. When
//! `ctx.foreign::<T>(idx, &manifest)?` is called:
//!
//! 1. The account's owner must match `manifest.program_id`
//! 2. The account's header discriminator must match `T::DISC` and
//!    `manifest.expected_disc`
//! 3. The header's `wire_fp64` must match `T::WIRE_FINGERPRINT` and
//!    `manifest.expected_wire_fp`
//! 4. `schema_epoch` must fall in `manifest.supported_epochs`
//!
//! Only after all four pass does the lens expose field access. Any
//! mismatch returns `ProgramError::InvalidAccountData`. never silent
//! mis-reads, never UB.
//!
//! # Manifest sourcing
//!
//! Hopper does not fetch manifests from RPC inside a program (that
//! would be round-trip CPI with no caching story). Manifests are
//! caller-supplied, typically from:
//!
//! - An embedded `const ForeignManifest` authored when the program was
//!   built (works when the foreign program's ABI is known at build time)
//! - A manifest account located at the canonical manifest PDA
//!   (`find_program_address(&[MANIFEST_SEED], &foreign_program_id)`)
//!   whose payload has already been verified by a prior instruction
//! - A Hopper IDL that emits manifest constants as part of
//!   its client-generation output

use crate::account::AccountView;
use crate::address::Address;
use crate::borrow::Ref;
use crate::crypto::{sha256_single, Sha256Hash};
use crate::error::ProgramError;
use crate::layout::{HopperHeader, LayoutContract};
use crate::zerocopy::{AccountLayout, ZeroCopy};
use crate::ProgramResult;
use core::marker::PhantomData;

/// Validation contract for known non-Hopper account layouts.
///
/// Hopper-owned layouts use Hopper headers and [`Account`](crate::Account).
/// Known foreign accounts usually do not. Implement this trait on a marker or
/// adapter type to validate owner, fixed byte prefix/discriminator, minimum
/// length, version bytes, oracle freshness gates, or any other external
/// invariant before binding an [`ExternalAccount`].
pub trait ExternalZeroCopy {
    /// Guard-owned zero-copy view returned by this external adapter.
    ///
    /// Implementations should store the supplied [`Ref<'a, [u8]>`] directly or
    /// project it into a narrower borrowed view. This keeps the account-data
    /// borrow alive for exactly as long as the external view exists.
    type View<'a>;

    /// Single expected owner program, when the adapter has one.
    const OWNER: Option<Address> = None;
    /// Optional byte prefix/discriminator at offset 0.
    const DISCRIMINATOR: Option<&'static [u8]> = None;
    /// Minimum account data length accepted by this adapter.
    const MIN_LEN: usize = 0;

    /// Validate this external account. Override for multi-owner layouts,
    /// versioned dispatch, or custom invariants.
    #[inline]
    fn validate(view: &AccountView<'_>) -> ProgramResult {
        if let Some(owner) = Self::OWNER {
            view.check_owned_by(&owner)?;
        }
        if view.data_len() < Self::MIN_LEN {
            return Err(ProgramError::AccountDataTooSmall);
        }
        if let Some(discriminator) = Self::DISCRIMINATOR {
            let data = view.try_borrow()?;
            if data.len() < discriminator.len() {
                return Err(ProgramError::AccountDataTooSmall);
            }
            if !data.starts_with(discriminator) {
                return Err(ProgramError::InvalidAccountData);
            }
        }
        Ok(())
    }

    /// Build the adapter's typed zero-copy view from an active account-data
    /// borrow. The borrow guard is consumed so the returned view can carry it.
    fn view<'a>(data: Ref<'a, [u8]>) -> Result<Self::View<'a>, ProgramError>;
}

/// Minimal guard-owned external byte view.
///
/// Adapters that only need checked bytes can use this as their `View<'a>` while
/// richer adapters can expose accessor methods over the same borrowed data.
pub struct ExternalBytes<'a> {
    data: Ref<'a, [u8]>,
}

impl<'a> ExternalBytes<'a> {
    /// Wrap an active external account-data borrow.
    #[inline(always)]
    pub const fn new(data: Ref<'a, [u8]>) -> Self {
        Self { data }
    }

    /// Borrow the validated external bytes.
    #[inline(always)]
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }
}

impl core::ops::Deref for ExternalBytes<'_> {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &[u8] {
        self.as_bytes()
    }
}

/// Owner/discriminator-selected resolver for external account families.
///
/// Use this for account sets such as Pyth/Switchboard/custom oracle unions or
/// Token/Token-2022 interfaces where the account owner decides which zero-copy
/// view should be used at runtime.
pub trait ExternalResolve {
    /// Guard-owned resolved view.
    type Resolved<'a>;

    /// Resolve the account into one of the supported external views.
    fn resolve<'a>(view: &'a AccountView<'a>) -> Result<Self::Resolved<'a>, ProgramError>;
}

/// Adapter-specific proof verifier for known external accounts.
///
/// Proof implementations should perform one focused validation step, such as
/// "this token account has the expected mint" or "this oracle price is fresh".
/// The returned proof token can be carried into downstream APIs that should not
/// accept a merely raw or adapter-checked account. The token proves the bytes
/// observed when [`ExternalProof::verify`] ran; it must not be carried across a
/// CPI that can mutate the account. Re-run [`ExternalAccount::checked`] after
/// such a CPI. Basic adapter validation is independently repeated by every
/// subsequent safe data/view/resolve/explain access.
pub trait ExternalProof<T: ExternalZeroCopy> {
    /// Proof token produced by this verifier.
    type Proof<'a>;

    /// Verify `account` and return the proof token.
    fn verify<'a>(account: ExternalAccount<'a, T>) -> Result<Self::Proof<'a>, ProgramError>;
}

/// External account paired with an adapter-specific point-in-time proof token.
pub struct ExternalChecked<'info, T, P>
where
    T: ExternalZeroCopy,
    P: ExternalProof<T>,
{
    account: ExternalAccount<'info, T>,
    proof: P::Proof<'info>,
    _marker: PhantomData<P>,
}

impl<'info, T, P> ExternalChecked<'info, T, P>
where
    T: ExternalZeroCopy,
    P: ExternalProof<T>,
{
    /// The checked external account.
    #[inline(always)]
    pub const fn account(&self) -> ExternalAccount<'info, T> {
        self.account
    }

    /// The adapter-specific proof token.
    #[inline(always)]
    pub const fn proof(&self) -> &P::Proof<'info> {
        &self.proof
    }

    /// Borrow and decode the adapter's typed zero-copy view.
    #[inline]
    pub fn view(&self) -> Result<T::View<'info>, ProgramError> {
        self.account.view()
    }
}

/// Minimal no-allocation sink for external explain adapters.
///
/// Runtime adapters can emit structured fields without depending on a concrete
/// CLI/SVM explain representation. Sinks may redact, hash, serialize, or ignore
/// fields according to their environment.
pub trait ExternalExplainSink {
    fn field_str(&mut self, name: &'static str, value: &str) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }

    fn field_bytes(&mut self, name: &'static str, value: &[u8]) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }

    fn field_address(&mut self, name: &'static str, value: &Address) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }

    fn field_u64(&mut self, name: &'static str, value: u64) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }

    fn field_i64(&mut self, name: &'static str, value: i64) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }

    fn field_bool(&mut self, name: &'static str, value: bool) -> ProgramResult {
        let _ = (name, value);
        Ok(())
    }
}

/// Optional structured explain hook for external account adapters.
pub trait ExplainExternal: ExternalZeroCopy {
    /// Emit adapter-specific explain fields.
    fn explain<S: ExternalExplainSink>(account: &AccountView<'_>, sink: &mut S) -> ProgramResult;
}

/// Copyable value that can be read from a checked external-account byte lens.
pub trait ExternalLensValue: Sized {
    /// Number of bytes consumed by this lens value.
    const SIZE: usize;

    /// Read a value from exactly [`Self::SIZE`] bytes.
    fn read(bytes: &[u8]) -> Self;
}

macro_rules! impl_external_lens_value_le {
    ($ty:ty, $size:expr) => {
        impl ExternalLensValue for $ty {
            const SIZE: usize = $size;

            #[inline(always)]
            fn read(bytes: &[u8]) -> Self {
                let mut raw = [0u8; $size];
                raw.copy_from_slice(bytes);
                <$ty>::from_le_bytes(raw)
            }
        }
    };
}

impl ExternalLensValue for u8 {
    const SIZE: usize = 1;

    #[inline(always)]
    fn read(bytes: &[u8]) -> Self {
        bytes[0]
    }
}

impl ExternalLensValue for i8 {
    const SIZE: usize = 1;

    #[inline(always)]
    fn read(bytes: &[u8]) -> Self {
        bytes[0] as i8
    }
}

impl_external_lens_value_le!(u16, 2);
impl_external_lens_value_le!(u32, 4);
impl_external_lens_value_le!(u64, 8);
impl_external_lens_value_le!(u128, 16);
impl_external_lens_value_le!(i16, 2);
impl_external_lens_value_le!(i32, 4);
impl_external_lens_value_le!(i64, 8);
impl_external_lens_value_le!(i128, 16);

impl<const N: usize> ExternalLensValue for [u8; N] {
    const SIZE: usize = N;

    #[inline(always)]
    fn read(bytes: &[u8]) -> Self {
        let mut raw = [0u8; N];
        raw.copy_from_slice(bytes);
        raw
    }
}

impl ExternalLensValue for Address {
    const SIZE: usize = 32;

    #[inline(always)]
    fn read(bytes: &[u8]) -> Self {
        let mut raw = [0u8; 32];
        raw.copy_from_slice(bytes);
        Address::new_from_array(raw)
    }
}

/// Bounds-checked zero-copy byte lens into an external account.
pub struct ExternalLens<'a, V: ExternalLensValue, const OFFSET: usize> {
    data: Ref<'a, [u8]>,
    _value: PhantomData<V>,
}

impl<'a, V: ExternalLensValue, const OFFSET: usize> ExternalLens<'a, V, OFFSET> {
    #[inline]
    fn new(data: Ref<'a, [u8]>) -> Result<Self, ProgramError> {
        let end = OFFSET
            .checked_add(V::SIZE)
            .ok_or(ProgramError::ArithmeticOverflow)?;
        if end > data.len() {
            return Err(ProgramError::AccountDataTooSmall);
        }
        Ok(Self {
            data,
            _value: PhantomData,
        })
    }

    /// Borrow the checked byte range backing this lens.
    #[inline(always)]
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[OFFSET..OFFSET + V::SIZE]
    }

    /// Read the lens value by copy.
    #[inline(always)]
    pub fn get(&self) -> V {
        V::read(self.as_bytes())
    }
}

/// Validated handle to a known external account.
///
/// This wrapper is intentionally transparent over [`AccountView`]. It proves
/// the adapter's [`ExternalZeroCopy::validate`] contract, but it does not imply
/// a Hopper header is present. Use [`ExternalAccount::data`] or adapter helper
/// methods to read bytes, and keep raw `AccountView`/`UncheckedAccount` for
/// accounts that truly have no known schema.
#[repr(transparent)]
pub struct ExternalAccount<'info, T: ExternalZeroCopy> {
    inner: &'info AccountView<'info>,
    _ty: PhantomData<T>,
}

impl<'info, T: ExternalZeroCopy> Clone for ExternalAccount<'info, T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<'info, T: ExternalZeroCopy> Copy for ExternalAccount<'info, T> {}

impl<T: ExternalZeroCopy> core::fmt::Debug for ExternalAccount<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ExternalAccount")
            .field("key", self.key())
            .field("owner", &self.owner())
            .field("data_len", &self.data_len())
            .finish()
    }
}

impl<'info, T: ExternalZeroCopy> ExternalAccount<'info, T> {
    #[inline(always)]
    fn revalidate(&self) -> ProgramResult {
        T::validate(self.inner)
    }

    /// Wrap an account that has already been validated by `T`.
    #[inline(always)]
    ///
    /// # Safety
    ///
    /// Caller must have verified `T::validate(view)` for this account.
    pub unsafe fn new_unchecked(view: &'info AccountView<'info>) -> Self {
        Self {
            inner: view,
            _ty: PhantomData,
        }
    }

    /// Validate and bind a known external account.
    #[inline]
    pub fn try_new(view: &'info AccountView<'info>) -> Result<Self, ProgramError> {
        T::validate(view)?;
        Ok(Self {
            inner: view,
            _ty: PhantomData,
        })
    }

    /// The underlying account view.
    #[inline(always)]
    pub fn as_account(&self) -> &'info AccountView<'info> {
        self.inner
    }

    /// The account public key.
    #[inline(always)]
    pub fn key(&self) -> &Address {
        self.inner.address()
    }

    /// The owning program, copied out of the account header.
    #[inline(always)]
    pub fn owner(&self) -> Address {
        self.inner.read_owner()
    }

    /// Current external account data length.
    #[inline(always)]
    pub fn data_len(&self) -> usize {
        self.inner.data_len()
    }

    /// Borrow the external account bytes after adapter validation.
    #[inline(always)]
    pub fn data(&self) -> Result<Ref<'info, [u8]>, ProgramError> {
        self.revalidate()?;
        self.inner.try_borrow()
    }

    /// Borrow the bytes for the duration of a closure.
    #[inline]
    pub fn with_data<R, F>(&self, f: F) -> Result<R, ProgramError>
    where
        F: FnOnce(&[u8]) -> Result<R, ProgramError>,
    {
        let data = self.data()?;
        f(&data)
    }

    /// Borrow and decode the adapter's typed zero-copy view.
    #[inline]
    pub fn view(&self) -> Result<T::View<'info>, ProgramError> {
        T::view(self.data()?)
    }

    /// Borrow the typed zero-copy view for the duration of a closure.
    #[inline]
    pub fn with_view<R, F>(&self, f: F) -> Result<R, ProgramError>
    where
        F: FnOnce(T::View<'info>) -> Result<R, ProgramError>,
    {
        f(self.view()?)
    }

    /// Verify an adapter-specific proof and carry its token with the account.
    #[inline]
    pub fn checked<P>(self) -> Result<ExternalChecked<'info, T, P>, ProgramError>
    where
        P: ExternalProof<T>,
    {
        // A proof adapter may intentionally verify only one focused business
        // invariant and need not borrow the typed view itself. Re-establish the
        // base owner/discriminator/layout contract here so even such a narrow
        // verifier cannot mint a capability from a handle invalidated by CPI.
        self.revalidate()?;
        let proof = P::verify(self)?;
        Ok(ExternalChecked {
            account: self,
            proof,
            _marker: PhantomData,
        })
    }

    /// Require a specific owner in fluent external-account code.
    #[inline]
    pub fn require_owner(&self, owner: &Address) -> Result<&Self, ProgramError> {
        self.inner.check_owned_by(owner)?;
        Ok(self)
    }

    /// Borrow a checked offset lens into this external account's bytes.
    #[inline]
    pub fn lens<V: ExternalLensValue, const OFFSET: usize>(
        &self,
    ) -> Result<ExternalLens<'info, V, OFFSET>, ProgramError> {
        ExternalLens::new(self.data()?)
    }

    /// Hash the external account bytes for CPI/oracle consistency checks.
    #[inline]
    pub fn snapshot_hash(&self) -> Result<Sha256Hash, ProgramError> {
        let data = self.data()?;
        sha256_single(&data)
    }

    /// Verify the external account bytes still match a previous snapshot.
    #[inline]
    pub fn assert_snapshot(&self, expected: &Sha256Hash) -> ProgramResult {
        if &self.snapshot_hash()? == expected {
            Ok(())
        } else {
            Err(ProgramError::InvalidAccountData)
        }
    }

    /// Run a closure and verify this external account is unchanged afterward.
    #[inline]
    pub fn assert_unchanged_after<R, F>(&self, f: F) -> Result<R, ProgramError>
    where
        F: FnOnce() -> Result<R, ProgramError>,
    {
        let before = self.snapshot_hash()?;
        let result = f()?;
        self.assert_snapshot(&before)?;
        Ok(result)
    }
}

impl<'info, T> ExternalAccount<'info, T>
where
    T: ExplainExternal,
{
    /// Emit structured external explain fields through the supplied sink.
    #[inline]
    pub fn explain<S: ExternalExplainSink>(&self, sink: &mut S) -> ProgramResult {
        self.revalidate()?;
        T::explain(self.inner, sink)
    }
}

impl<'info, T> ExternalAccount<'info, T>
where
    T: ExternalZeroCopy + ExternalResolve,
{
    /// Resolve this external account into an owner-selected view family.
    #[inline]
    pub fn resolve(&self) -> Result<T::Resolved<'info>, ProgramError> {
        self.revalidate()?;
        T::resolve(self.inner)
    }
}

impl<'info, T: ExternalZeroCopy> core::ops::Deref for ExternalAccount<'info, T> {
    type Target = AccountView<'info>;

    #[inline(always)]
    fn deref(&self) -> &AccountView<'info> {
        self.inner
    }
}

/// Opaque witness to a foreign program's layout ABI.
///
/// Callers construct this once per foreign program they want to read
/// from, typically as a `const` from build-time-embedded metadata or
/// from the foreign program's Hopper manifest account.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForeignManifest {
    /// Owner program that authored the layout. The account's owner
    /// must match this address exactly.
    pub program_id: Address,
    /// Discriminator byte the foreign layout expects.
    pub expected_disc: u8,
    /// Canonical wire-fingerprint hash from the foreign program's
    /// schema manifest. Matches `AccountLayout::WIRE_FINGERPRINT` on
    /// the reader side.
    pub expected_wire_fp: u64,
    /// Inclusive range of `schema_epoch` values the reader supports.
    /// Accounts outside this range fail verification. the caller can
    /// then fall back to a migration path or a different manifest.
    pub supported_epochs: core::ops::RangeInclusive<u32>,
}

impl ForeignManifest {
    /// Build a single-epoch manifest covering `expected_wire_fp` for
    /// `program_id` at exactly the given schema epoch.
    pub const fn single_epoch(
        program_id: Address,
        expected_disc: u8,
        expected_wire_fp: u64,
        epoch: u32,
    ) -> Self {
        Self {
            program_id,
            expected_disc,
            expected_wire_fp,
            supported_epochs: epoch..=epoch,
        }
    }
}

/// A verified read-only handle into a foreign account.
///
/// `ForeignLens<'a, T>` borrows the underlying account data for its
/// lifetime. Field access (`.get()`, `.field::<F, OFFSET>()`) performs
/// only pointer arithmetic. no further verification, because all
/// cross-program invariants were pinned at construction.
pub struct ForeignLens<'a, T: AccountLayout + LayoutContract> {
    inner: Ref<'a, T>,
}

impl<'a, T: AccountLayout + LayoutContract> ForeignLens<'a, T> {
    /// Verify a foreign account against the supplied manifest and, on
    /// success, return a read-only lens into its body.
    ///
    /// The four verification steps correspond one-to-one with the
    /// checked-lens requirements:
    ///
    /// 1. owner match
    /// 2. discriminator match (both `T::DISC` *and* `manifest.expected_disc`)
    /// 3. wire-fingerprint match
    /// 4. schema_epoch in supported range
    #[inline]
    pub fn open(
        account: &'a AccountView<'a>,
        manifest: &ForeignManifest,
    ) -> Result<Self, ProgramError> {
        // 1. Owner match. `check_owned_by` compares address bytes.
        account.check_owned_by(&manifest.program_id)?;

        // 2-4. Header inspection. must happen behind a byte borrow
        //     so the data can't mutate underneath us. We use the same
        //     load path authored accounts use, which verifies the
        //     discriminator too. That closes #2.
        let loaded: Ref<'a, T> = account.load::<T>()?;
        if <T as AccountLayout>::DISC != manifest.expected_disc {
            return Err(ProgramError::InvalidAccountData);
        }

        // Re-read the header bytes directly so we can match the
        // manifest's wire-fingerprint and epoch fields. The load
        // above already verified disc/version, so this step only
        // checks the manifest-specific fields. HopperHeader is
        // `#[repr(C, packed)]` at 16 bytes. `from_bytes` returns a
        // properly bounds-checked reference without touching unaligned
        // primitives (we copy packed fields out by value below).
        let data = account.try_borrow()?;
        let header = HopperHeader::from_bytes(&data).ok_or(ProgramError::AccountDataTooSmall)?;
        // Packed-field reads must go through a local copy.
        let layout_id = header.layout_id;
        let schema_epoch = header.schema_epoch;
        let actual_wire_fp = u64::from_le_bytes(layout_id);
        if actual_wire_fp != manifest.expected_wire_fp {
            return Err(ProgramError::InvalidAccountData);
        }
        if actual_wire_fp != <T as AccountLayout>::WIRE_FINGERPRINT {
            return Err(ProgramError::InvalidAccountData);
        }
        if !manifest.supported_epochs.contains(&schema_epoch) {
            return Err(ProgramError::InvalidAccountData);
        }

        // Explicit drop so the re-borrow guard releases before we
        // hand out `loaded`, which already pins its own guard.
        drop(data);

        Ok(Self { inner: loaded })
    }

    /// The full verified layout. Field access through this path is
    /// zero-cost; no further checks fire.
    #[inline(always)]
    pub fn get(&self) -> &T {
        &self.inner
    }

    /// Project a typed field by byte offset. Returns a pointer-cast
    /// reference with the lens's lifetime.
    ///
    /// `OFFSET` must be the field's offset *within the layout body*
    /// (i.e. already past the 16-byte Hopper header). Callers should
    /// prefer the auto-emitted `{FIELD}_OFFSET` constants from
    /// `#[hopper::state]`.
    #[inline(always)]
    pub fn field<F: ZeroCopy, const OFFSET: usize>(&self) -> Result<&F, ProgramError> {
        let body_size = core::mem::size_of::<T>();
        let field_size = core::mem::size_of::<F>();
        if OFFSET
            .checked_add(field_size)
            .map(|end| end > body_size)
            .unwrap_or(true)
        {
            return Err(ProgramError::AccountDataTooSmall);
        }
        // SAFETY: We checked the byte range lies entirely inside the
        // body. The layout is `Pod` (from `T: AccountLayout: ZeroCopy`),
        // so every byte pattern is valid for `F: ZeroCopy`. The
        // returned reference inherits the lens's lifetime and thus
        // cannot outlive the underlying borrow guard.
        // `Ref<T>` derefs to `T`; the `&T` annotation drives the coercion.
        let layout_ref: &T = &self.inner;
        // SAFETY: This block is part of Hopper's reviewed zero-copy/backend boundary; surrounding checks and caller contracts uphold the required raw-pointer, layout, and aliasing invariants.
        unsafe {
            let base = layout_ref as *const T as *const u8;
            let field_ptr = base.add(OFFSET) as *const F;
            Ok(&*field_ptr)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hopper_native::{
        AccountView as NativeAccountView, Address as NativeAddress, RuntimeAccount, NOT_BORROWED,
    };
    const EXTERNAL_OWNER: Address = Address::new_from_array([7; 32]);
    struct SampleExternal;
    impl ExternalZeroCopy for SampleExternal {
        type View<'a> = SampleExternalView<'a>;

        const OWNER: Option<Address> = Some(EXTERNAL_OWNER);
        const DISCRIMINATOR: Option<&'static [u8]> = Some(b"PX");
        const MIN_LEN: usize = 4;

        fn view<'a>(data: Ref<'a, [u8]>) -> Result<Self::View<'a>, ProgramError> {
            Ok(SampleExternalView { data })
        }
    }
    struct SampleExternalView<'a> {
        data: Ref<'a, [u8]>,
    }
    impl SampleExternalView<'_> {
        fn tag(&self) -> &[u8] {
            &self.data[..2]
        }

        fn value(&self) -> u16 {
            u16::from_le_bytes([self.data[2], self.data[3]])
        }
    }
    enum SampleResolved<'a> {
        Price(SampleExternalView<'a>),
    }
    impl ExternalResolve for SampleExternal {
        type Resolved<'a> = SampleResolved<'a>;

        fn resolve<'a>(view: &'a AccountView<'a>) -> Result<Self::Resolved<'a>, ProgramError> {
            Ok(SampleResolved::Price(
                ExternalAccount::<SampleExternal>::try_new(view)?.view()?,
            ))
        }
    }
    struct SampleValueProof;
    struct BlindProof;
    struct SampleValueChecked {
        value: u16,
    }
    impl ExternalProof<SampleExternal> for BlindProof {
        type Proof<'a> = ();

        fn verify<'a>(
            _account: ExternalAccount<'a, SampleExternal>,
        ) -> Result<Self::Proof<'a>, ProgramError> {
            Ok(())
        }
    }
    impl ExternalProof<SampleExternal> for SampleValueProof {
        type Proof<'a> = SampleValueChecked;

        fn verify<'a>(
            account: ExternalAccount<'a, SampleExternal>,
        ) -> Result<Self::Proof<'a>, ProgramError> {
            let value = account.view()?.value();
            if value == view_u16(b"12") {
                Ok(SampleValueChecked { value })
            } else {
                Err(ProgramError::InvalidAccountData)
            }
        }
    }
    impl ExplainExternal for SampleExternal {
        fn explain<S: ExternalExplainSink>(
            account: &AccountView<'_>,
            sink: &mut S,
        ) -> ProgramResult {
            let external = ExternalAccount::<SampleExternal>::try_new(account)?;
            external.with_view(|view| {
                sink.field_str("adapter", "SampleExternal")?;
                sink.field_u64("value", view.value() as u64)
            })
        }
    }
    #[derive(Default)]
    struct CountingExplainSink {
        fields: usize,
    }
    impl ExternalExplainSink for CountingExplainSink {
        fn field_str(&mut self, _name: &'static str, _value: &str) -> ProgramResult {
            self.fields += 1;
            Ok(())
        }

        fn field_u64(&mut self, _name: &'static str, _value: u64) -> ProgramResult {
            self.fields += 1;
            Ok(())
        }
    }
    fn make_external_account(
        owner: Address,
        data: &[u8],
    ) -> (std::vec::Vec<u64>, AccountView<'static>) {
        let mut backing = std::vec![0u64; (RuntimeAccount::SIZE + data.len()).div_ceil(8)];
        let raw = backing.as_mut_ptr() as *mut RuntimeAccount;
        // SAFETY: Test helper initializes a valid RuntimeAccount header and
        // copies `data` into the owned backing buffer at the payload offset.
        unsafe {
            raw.write(RuntimeAccount {
                borrow_state: NOT_BORROWED,
                is_signer: 0,
                is_writable: 0,
                executable: 0,
                resize_delta: 0,
                address: NativeAddress::new_from_array([3; 32]),
                owner: NativeAddress::new_from_array(owner.to_bytes()),
                lamports: 1,
                data_len: data.len() as u64,
            });
            let data_ptr = (backing.as_mut_ptr() as *mut u8).add(RuntimeAccount::SIZE);
            core::ptr::copy_nonoverlapping(data.as_ptr(), data_ptr, data.len());
        }
        // SAFETY: `raw` points at the RuntimeAccount header initialized above.
        let backend = unsafe { NativeAccountView::new_unchecked(raw) };
        (backing, AccountView::from_backend(backend))
    }

    #[test]
    fn manifest_single_epoch_is_inclusive_single_value() {
        let program = Address::new_from_array([7u8; 32]);
        let m = ForeignManifest::single_epoch(program, 42, 0xDEAD_BEEF_1234_5678, 3);
        assert!(m.supported_epochs.contains(&3));
        assert!(!m.supported_epochs.contains(&2));
        assert!(!m.supported_epochs.contains(&4));
        assert_eq!(m.expected_disc, 42);
        assert_eq!(m.expected_wire_fp, 0xDEAD_BEEF_1234_5678);
    }

    #[test]
    fn manifest_range_spans_inclusive() {
        let program = Address::new_from_array([0u8; 32]);
        let m = ForeignManifest {
            program_id: program,
            expected_disc: 1,
            expected_wire_fp: 0,
            supported_epochs: 2..=5,
        };
        for ok in [2u32, 3, 4, 5] {
            assert!(m.supported_epochs.contains(&ok), "{ok}");
        }
        for fail in [0u32, 1, 6, 100] {
            assert!(!m.supported_epochs.contains(&fail), "{fail}");
        }
    }
    #[test]
    fn external_account_validates_owner_discriminator_and_length() {
        let (_backing, account) = make_external_account(EXTERNAL_OWNER, b"PX12");
        let external = ExternalAccount::<SampleExternal>::try_new(&account).unwrap();
        assert_eq!(external.owner(), EXTERNAL_OWNER);
        assert_eq!(external.data_len(), 4);
        external
            .with_data(|data| {
                assert_eq!(data, b"PX12");
                Ok(())
            })
            .unwrap();
        external
            .with_view(|view| {
                assert_eq!(view.tag(), b"PX");
                assert_eq!(view.value(), u16::from_le_bytes(*b"12"));
                Ok(())
            })
            .unwrap();
        assert_eq!(external.lens::<u16, 2>().unwrap().get(), view_u16(b"12"));
        let snapshot = external.snapshot_hash().unwrap();
        external.assert_snapshot(&snapshot).unwrap();
        let resolved = external.resolve().unwrap();
        match resolved {
            SampleResolved::Price(view) => assert_eq!(view.value(), view_u16(b"12")),
        }
        let checked = external.checked::<SampleValueProof>().unwrap();
        assert_eq!(checked.proof().value, view_u16(b"12"));
        let mut sink = CountingExplainSink::default();
        external.explain(&mut sink).unwrap();
        assert_eq!(sink.fields, 2);
    }
    fn view_u16(bytes: &[u8; 2]) -> u16 {
        u16::from_le_bytes(*bytes)
    }
    #[test]
    fn external_account_rejects_wrong_owner_or_prefix() {
        let (_wrong_owner_backing, wrong_owner) =
            make_external_account(Address::new_from_array([8; 32]), b"PX12");
        assert_eq!(
            ExternalAccount::<SampleExternal>::try_new(&wrong_owner).unwrap_err(),
            ProgramError::IncorrectProgramId
        );

        let (_wrong_prefix_backing, wrong_prefix) = make_external_account(EXTERNAL_OWNER, b"NO12");
        assert_eq!(
            ExternalAccount::<SampleExternal>::try_new(&wrong_prefix).unwrap_err(),
            ProgramError::InvalidAccountData
        );

        let (_short_backing, short) = make_external_account(EXTERNAL_OWNER, b"PX");
        assert_eq!(
            ExternalAccount::<SampleExternal>::try_new(&short).unwrap_err(),
            ProgramError::AccountDataTooSmall
        );
    }

    #[test]
    fn external_account_revalidates_owner_and_discriminator_after_binding() {
        let (_owner_backing, owner_changed) = make_external_account(EXTERNAL_OWNER, b"PX12");
        let external = ExternalAccount::<SampleExternal>::try_new(&owner_changed).unwrap();
        let checked = external.checked::<BlindProof>().unwrap();
        // SAFETY: this test owns the synthetic account and models its original
        // owner reassigning it during a writable CPI.
        unsafe {
            owner_changed.assign(&Address::new_from_array([8; 32]));
        }
        assert!(matches!(
            external.view(),
            Err(ProgramError::IncorrectProgramId)
        ));
        assert!(matches!(
            checked.view(),
            Err(ProgramError::IncorrectProgramId)
        ));
        assert!(matches!(
            external.checked::<BlindProof>(),
            Err(ProgramError::IncorrectProgramId)
        ));

        let (_disc_backing, discriminator_changed) = make_external_account(EXTERNAL_OWNER, b"PX12");
        let external = ExternalAccount::<SampleExternal>::try_new(&discriminator_changed).unwrap();
        let checked = external.checked::<BlindProof>().unwrap();
        {
            let mut data = discriminator_changed.try_borrow_mut().unwrap();
            data[..2].copy_from_slice(b"NO");
        }
        assert!(matches!(
            external.view(),
            Err(ProgramError::InvalidAccountData)
        ));
        assert!(matches!(
            checked.view(),
            Err(ProgramError::InvalidAccountData)
        ));
        assert!(matches!(
            external.checked::<BlindProof>(),
            Err(ProgramError::InvalidAccountData)
        ));
    }
}