hopper-runtime 0.3.1

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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! Hopper Runtime -- canonical semantic runtime surface.
//!
//! Hopper Runtime owns the public rules, validation, typed loading, CPI
//! semantics, and execution context that authored Hopper code targets.
//! Hopper Native owns the raw execution boundary.

#![no_std]
#![deny(unsafe_op_in_unsafe_fn)]
// The backend `AccountView` is `Copy` only under the `copy` feature. The
// `.clone()` in our manual `Clone` impl is required in the default lane, so we
// silence `clone_on_copy` only in the lane where the type is actually `Copy`.
#![cfg_attr(feature = "copy", allow(clippy::clone_on_copy))]

#[cfg(any(test, feature = "thread-local-registry"))]
extern crate std;

#[doc(hidden)]
pub mod native_boundary;

pub mod account;
pub mod account_wrappers;
pub mod address;
pub mod audit;
pub mod behavior;
pub mod borrow;
pub(crate) mod borrow_registry;
pub mod compact;
#[cfg(any(not(target_os = "solana"), feature = "remaining-compute-units-syscall"))]
pub mod compute;
pub mod cpi;
pub mod cpi_event;
pub mod crank;
pub mod crypto;
pub mod dyn_cpi;
pub mod error;
pub mod field_map;
pub mod foreign;
pub mod interop;
pub mod lamports;
pub mod lazy;
pub mod log;
pub mod memory;
pub mod migrate;
pub mod pod;
pub mod policy;
pub mod proof;
pub mod ref_only;
pub mod result;
pub mod segment;
pub mod tail;
pub mod utils;
pub mod zerocopy;
// Re-export the sealed marker module at the crate root so macro
// codegen can address it as `::hopper_runtime::__sealed::...`. It's
// doc-hidden because it is the sealed enforcement surface,
// not a normal-user-facing API.
#[doc(hidden)]
pub use zerocopy::__sealed;
pub mod context;
pub mod instruction;
pub mod layout;
pub mod option_byte;
pub mod pda;
pub mod remaining;
pub mod rent;
pub mod return_data;
pub mod segment_borrow;
pub mod segment_lease;
pub mod syscall;
pub mod syscalls;
pub mod system;
pub mod token;
pub mod token_2022_ext;
pub mod token_mint;
pub mod write_policy;

pub use account::AccountView;
pub use account_wrappers::{
    Account, InitAccount, Interface, InterfaceAccount, InterfaceAccountLayout,
    InterfaceAccountResolve, InterfaceSpec, Program, ProgramId, Signer as HopperSigner,
    SystemAccount, SystemId, UncheckedAccount,
};
pub use address::Address;
pub use audit::{AccountAudit, DuplicateAccount};
pub use behavior::{BehaviorChecked, BehaviorWrite, HopperBehavior};
pub use borrow::{Ref, RefMut};
pub use compact::{CompactDynamicLayout, CompactLayout, COMPACT_BODY_OFFSET};
#[cfg(any(not(target_os = "solana"), feature = "remaining-compute-units-syscall"))]
pub use compute::{check_compute_units, remaining_compute_units, require_compute_units};
pub use context::{Context, ScopedContext};
pub use cpi::{invoke, invoke_checked, invoke_signed, invoke_signed_checked};
#[cfg(feature = "crypto-big-mod-exp")]
pub use crypto::big_mod_exp;
#[cfg(feature = "crypto-bn254")]
pub use crypto::{
    alt_bn128_add, alt_bn128_g1_addition_be, alt_bn128_g1_compress_be, alt_bn128_g1_decompress_be,
    alt_bn128_g1_multiplication_be, alt_bn128_g2_compress_be, alt_bn128_g2_decompress_be,
    alt_bn128_mul, alt_bn128_pairing, alt_bn128_pairing_be,
};
pub use crypto::{
    blake3, blake3_single, keccak256, keccak256_single, recover_ethereum_address,
    secp256k1_recover, sha256, sha256_single,
};
#[cfg(feature = "crypto-curve")]
pub use crypto::{curve_group_add, curve_group_mul, curve_group_sub, curve_multiscalar_mul};
#[cfg(feature = "crypto-poseidon")]
pub use crypto::{poseidon_bn254_x5, poseidon_hash, poseidon_hashv};
pub use error::ProgramError;
pub use field_map::{FieldInfo, FieldMap};
pub use foreign::{
    ExplainExternal, ExternalAccount, ExternalBytes, ExternalChecked, ExternalExplainSink,
    ExternalLens, ExternalLensValue, ExternalProof, ExternalResolve, ExternalZeroCopy, ForeignLens,
    ForeignManifest,
};
pub use interop::TransparentAddress;
pub use lamports::transfer_lamports;
pub use lazy::LazyContext;
pub use migrate::{
    apply_pending_migrations, ensure_fits_with_rent, migrate_layout, migrate_layout_resizing,
    validate_header_for_epoch_migration, LayoutMigration, MigrationEdge,
};
pub use policy::{HopperInstructionPolicy, HopperProgramPolicy, HopperProgramProfile};
pub use proof::{
    AccountProof, ExecutableChecked, HasOneChecked, LayoutChecked, OwnerChecked, SeedsChecked,
    SignerChecked, TokenExtensionsChecked, Unchecked, WritableChecked,
};
pub use ref_only::HopperRefOnly;
pub use remaining::{
    RemainingAccountViews, RemainingAccounts, RemainingError, RemainingExternalAccounts,
    RemainingGroup, RemainingLazy, RemainingLazySlot, RemainingMode, RemainingSigners,
    RemainingTyped, MAX_REMAINING_ACCOUNTS,
};
pub use return_data::{get_return_data, set_return_data, try_set_return_data, ReturnData};
pub use tail::{
    borrow_address_slice, borrow_bounded_str, read_tail, read_tail_len, seq_capacity_for,
    seq_region_bytes_for, tail_capacity, tail_payload, write_tail, write_tail_payload,
    BoundedString, BoundedVec, HopperString, HopperVec, SeqElement, SeqTailRead, SeqTailWrite,
    TailBytes, TailCodec, TailElement, TailSeq, TailSeqIter, TailSeqMut, TailStr, SEQ_LEN_PREFIX,
};

/// Compose a layout's `LayoutMigration::MIGRATIONS` chain from a list
/// of `#[hopper::migrate]`-emitted edge constants.
///
/// ```ignore
/// #[hopper::migrate(from = 1, to = 2)]
/// pub fn vault_v1_to_v2(body: &mut [u8]) -> ProgramResult { Ok(()) }
///
/// hopper::layout_migrations! {
///     Vault = [VAULT_V1_TO_V2_EDGE, VAULT_V2_TO_V3_EDGE],
/// }
/// ```
///
/// Emits `impl LayoutMigration for Vault { const MIGRATIONS = .. }`.
/// Each list entry must evaluate to a
/// [`MigrationEdge`](crate::migrate::MigrationEdge). typically the
/// `<UPPER_SNAKE_FN_NAME>_EDGE` constant that
/// `#[hopper::migrate]` emits alongside each migration function.
/// Chain continuity (every adjacent pair must satisfy
/// `a.to_epoch == b.from_epoch`) is enforced at runtime by
/// [`apply_pending_migrations`].
#[macro_export]
macro_rules! layout_migrations {
    ( $layout:ty = [ $( $edge:expr ),+ $(,)? ] $(,)? ) => {
        impl $crate::migrate::LayoutMigration for $layout {
            const MIGRATIONS: &'static [$crate::migrate::MigrationEdge] = &[
                $( $edge ),+
            ];
        }
    };
}
pub use instruction::CpiAccount;
pub use instruction::{
    InstructionAccount, InstructionView, Seed, Signer, StoredAccountMeta, StoredInstruction,
};
pub use layout::{HopperHeader, LayoutContract, LayoutInfo};
pub use pod::{read_unaligned_value, Pod, ValuePod, Zeroable};
pub use result::ProgramResult;
pub use segment::{
    FieldCapability, Segment, TypedSegment, FIELD_POLICY_AUTHORITY_GATED,
    FIELD_POLICY_CHECKED_MATH, FIELD_POLICY_IMMUTABLE_AFTER_INIT, FIELD_ROLE_AUTHORITY,
    FIELD_ROLE_BALANCE, FIELD_ROLE_DATA, FIELD_ROLE_VERSION,
};
pub use segment_borrow::{AccessKind, SegmentBorrow, SegmentBorrowGuard, SegmentBorrowRegistry};
pub use segment_lease::{SegRef, SegRefMut, SegmentLease, SegmentsMut};
pub use write_policy::{
    ParametricWriteRange, WritePolicy, WriteRange, WRITE_POLICY_VIOLATION_PAGE,
};
pub use zerocopy::{AccountLayout, WireLayout, ZeroCopy};

pub const MAX_TX_ACCOUNTS: usize = native_boundary::BACKEND_MAX_TX_ACCOUNTS;
pub const SUCCESS: u64 = native_boundary::BACKEND_SUCCESS;

#[doc(hidden)]
pub use hopper_native as __hopper_native;
pub use hopper_native::sha256;

#[doc(hidden)]
pub use hopper_native::address::decode_base58_32 as __decode_base58_32;

/// Compile-time base58 address literal.
#[macro_export]
macro_rules! address {
    ( $literal:expr ) => {
        $crate::Address::new_from_array($crate::__decode_base58_32($literal))
    };
}

/// Declare a program's on-chain id, mirroring the `declare_id!` convention
/// every other Solana framework ships (Anchor, Pinocchio, Quasar).
///
/// Expands to a `pub const ID: Address` decoded at compile time, a
/// `pub const fn id() -> Address` accessor, and a `pub fn check_id(&Address)
/// -> bool` guard. Programs that pin their own id for self-PDA derivation,
/// CPI-guard checks, or `require_keys_eq!(program.key(), &crate::ID)` use this
/// instead of hand-rolling an [`address!`] constant.
///
/// ```ignore
/// hopper::declare_id!("D8UGWDX5QRwEkKs2J9Sweabf4zd6hzdLqv7CB11SF91F");
/// assert!(crate::check_id(&crate::ID));
/// ```
#[macro_export]
macro_rules! declare_id {
    ( $literal:expr ) => {
        /// The program's on-chain address, decoded at compile time.
        pub const ID: $crate::Address = $crate::address!($literal);

        /// Return the program's declared id.
        #[inline]
        pub const fn id() -> $crate::Address {
            ID
        }

        /// Return true if `other` equals the declared program id.
        #[inline]
        pub fn check_id(other: &$crate::Address) -> bool {
            *other == ID
        }
    };
}

/// A program-derived address evaluated at compile time:
/// `const_pda!(PROGRAM_ID, [seed, ...], bump)` is
/// [`pda::const_program_address`] with the seed list spelled inline (each
/// seed anything that casts to `&[u8]`: a byte-string literal, an
/// `Address::as_array()`, a `&[u8; N]`). See that function for the bump
/// contract and the soundness note.
///
/// ```ignore
/// hopper::declare_id!("F4Um7PWsnZfN7y8WFzu1aPYJwqGduJTa4zuCGY9EUqMy");
/// pub const VAULT: hopper::Address = hopper::const_pda!(ID, [b"vault", ID.as_array()], 255);
/// ```
#[macro_export]
macro_rules! const_pda {
    ( $program_id:expr, [ $( $seed:expr ),* $(,)? ], $bump:expr ) => {
        $crate::pda::const_program_address(&$program_id, &[ $( $seed as &[u8] ),* ], $bump)
    };
}

/// Early-return with an error if the condition is false.
#[macro_export]
macro_rules! require {
    ( $cond:expr, $err:expr ) => {
        if !($cond) {
            return Err($err);
        }
    };
    ( $cond:expr ) => {
        if !($cond) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Assert two values are equal, returning an error on mismatch.
#[macro_export]
macro_rules! require_eq {
    ( $left:expr, $right:expr, $err:expr ) => {
        if ($left) != ($right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if ($left) != ($right) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Assert two values are not equal. Early-returns with the supplied
/// error on match (or `ProgramError::InvalidArgument` in the short
/// form). Symmetric with [`require_eq!`].
#[macro_export]
macro_rules! require_neq {
    ( $left:expr, $right:expr, $err:expr ) => {
        if ($left) == ($right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if ($left) == ($right) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Assert two public keys (or any byte slices convertible via
/// [`AsRef<[u8; 32]>`]) are equal. Narrower than [`require_eq!`] but
/// matches the ergonomic spelling ecosystem migrators coming from
/// Anchor / Jiminy are familiar with.
///
/// ```ignore
/// hopper::require_keys_eq!(
///     vault.authority,
///     ctx.signer.address(),
///     ProgramError::InvalidAccountData,
/// );
/// ```
#[macro_export]
macro_rules! require_keys_eq {
    ( $left:expr, $right:expr, $err:expr ) => {
        if !$crate::address::keys_eq(
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$left),
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$right),
        ) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if !$crate::address::keys_eq(
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$left),
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$right),
        ) {
            return Err($crate::ProgramError::InvalidAccountData);
        }
    };
}

/// Assert two public keys are *not* equal. Used for pinning distinct
/// accounts (authority != user, source != destination). Same coercion
/// and error semantics as [`require_keys_eq!`].
#[macro_export]
macro_rules! require_keys_neq {
    ( $left:expr, $right:expr, $err:expr ) => {
        if $crate::address::keys_eq(
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$left),
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$right),
        ) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if $crate::address::keys_eq(
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$left),
            ::core::convert::AsRef::<[u8; 32]>::as_ref(&$right),
        ) {
            return Err($crate::ProgramError::InvalidAccountData);
        }
    };
}

/// Assert `left >= right`, returning the supplied error on underrun.
/// Useful for lamport / balance checks.
#[macro_export]
macro_rules! require_gte {
    ( $left:expr, $right:expr, $err:expr ) => {
        if !($left >= $right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if !($left >= $right) {
            return Err($crate::ProgramError::InsufficientFunds);
        }
    };
}

/// Assert `left > right` strictly.
#[macro_export]
macro_rules! require_gt {
    ( $left:expr, $right:expr, $err:expr ) => {
        if !($left > $right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if !($left > $right) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Assert `left < right` strictly. Anchor-parity sibling of
/// [`require_gt!`]. Default error is `ProgramError::InvalidArgument`
/// because a failed ordering check most often flags a bad user input.
#[macro_export]
macro_rules! require_lt {
    ( $left:expr, $right:expr, $err:expr ) => {
        if !($left < $right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if !($left < $right) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Assert `left <= right`. Anchor-parity sibling of [`require_gte!`].
#[macro_export]
macro_rules! require_lte {
    ( $left:expr, $right:expr, $err:expr ) => {
        if !($left <= $right) {
            return Err($err);
        }
    };
    ( $left:expr, $right:expr ) => {
        if !($left <= $right) {
            return Err($crate::ProgramError::InvalidArgument);
        }
    };
}

/// Return an error immediately. Parallel to Anchor's `err!`.
///
/// The macro expands to a bare `return Err(...)`, so the call site
/// reads like a control-flow keyword rather than an expression. The
/// argument is evaluated as an expression so either a Hopper-generated
/// error code or a raw `ProgramError` works.
///
/// ```ignore
/// if amount == 0 {
///     return err!(VaultError::ZeroDeposit);
/// }
/// ```
#[macro_export]
macro_rules! err {
    ( $e:expr ) => {
        return ::core::result::Result::Err($crate::ProgramError::from($e))
    };
}

/// Alias for [`err!`]. Anchor-style spelling for ported code. Functionally
/// identical.
#[macro_export]
macro_rules! error {
    ( $e:expr ) => {
        return ::core::result::Result::Err($crate::ProgramError::from($e))
    };
}

/// Auditable raw-pointer boundary.
///
/// Wraps a block that needs `unsafe` in a named Hopper macro so an
/// auditor can grep `hopper_unsafe_region!` and find every raw
/// reinterpretation in the tree with one command. The macro expands
/// to a plain `unsafe { ... }` block: zero runtime cost, identical
/// codegen, but the invocation site is nameable and documented.
///
/// Usage:
///
/// ```ignore
/// let cleared = hopper::hopper_unsafe_region!("clear rewards via raw ptr", {
///     let ptr = ctx.as_mut_ptr(0)?;
///     (ptr.add(24) as *mut u64).write_unaligned(0);
///     0u64
/// });
/// ```
///
/// The label is a compile-time string literal. It is discarded by
/// the expansion but serves as inline documentation an auditor
/// reads alongside the `unsafe` body.
#[macro_export]
macro_rules! hopper_unsafe_region {
    ( $label:literal, $body:block ) => {{
        // The label is a compile-time string literal, captured so it
        // surfaces in `cargo expand` output and can be grep'd out of
        // the expanded tree the same way as the macro name.
        const _HOPPER_UNSAFE_REGION_LABEL: &str = $label;
        #[allow(unused_unsafe)]
        // 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 { $body }
    }};
}

/// Backend-neutral logging macro.
#[macro_export]
macro_rules! msg {
    ( $literal:expr ) => {{
        $crate::log::log($literal);
    }};
    ( $fmt:expr, $($arg:tt)* ) => {{
        #[cfg(target_os = "solana")]
        {
            use core::fmt::Write;
            let mut buf = [0u8; 256];
            let mut wrapper = $crate::log::StackWriter::new(&mut buf);
            let _ = write!(wrapper, $fmt, $($arg)*);
            let len = wrapper.pos();
            $crate::log::log(
                // 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 { core::str::from_utf8_unchecked(&buf[..len]) }
            );
        }
        #[cfg(not(target_os = "solana"))]
        {
            let _ = ($fmt, $($arg)*);
        }
    }};
}

/// Emit a Hopper event via self-CPI for reliable indexing, the
/// manual-wiring form.
///
/// Most programs should not call this directly: `#[hopper::context(event_cpi)]`
/// plus `ctx.emit_event_cpi(&event)` wires the same emission (accounts,
/// bump, sink) with zero hand-written plumbing. Reach for this macro
/// only when the context macro is out of the picture (raw handlers,
/// hand-rolled account handling, a custom sink).
///
/// Wraps [`cpi_event::encode_event_cpi`] and a call into the active
/// backend's `invoke_signed` so indexers see the event as an inner
/// instruction in the transaction metadata. Log output is size-capped; inner
/// instructions are retained. Anchor's `emit_cpi!` solves the same problem
/// with the same trick; Hopper's lives in pure Rust so it works under
/// `no_std` and any of the three backends, and its wire format is
/// 3 bytes of overhead (2-byte marker + 1-byte tag) against Anchor's 16
/// (8-byte instruction tag + 8-byte event discriminator).
///
/// ## Required program plumbing (manual form only)
///
/// The caller must declare a sentinel handler so the dispatcher routes
/// the self-CPI somewhere, and should authenticate it rather than
/// no-op, or forged events become possible:
///
/// ```ignore
/// #[instruction(discriminator = [0xE0, 0x1E])]
/// fn __hopper_event_sink(ctx: &mut Context<'_>) -> ProgramResult {
///     hopper_runtime::cpi_event::handle_event_sink(ctx, ctx.instruction_data())
/// }
/// ```
///
/// And a PDA account seeded with [`cpi_event::EVENT_AUTHORITY_SEED`]
/// (`b"__hopper_event_authority"`) so the CPI has a signer, plus the
/// program's own account in the instruction so the runtime can resolve
/// the self-CPI target.
///
/// ## Usage
///
/// ```ignore
/// hopper_emit_cpi!(
///     ctx.program_id(),
///     event_authority: &AccountView,
///     event_authority_bump: u8,
///     Deposited { amount, depositor }
/// );
/// ```
///
/// `$event` must be a `#[hopper::event]` type (anything implementing
/// [`cpi_event::CpiEvent`]). Expands to: build instruction bytes,
/// invoke_signed with the event_authority PDA as the signer. One CPI,
/// bounded stack allocation, zero heap.
#[macro_export]
macro_rules! hopper_emit_cpi {
    ( $program_id:expr, $event_authority:expr, $bump:expr, $event:expr ) => {{
        // Build the wire format into a stack buffer. MAX_EVENT_PAYLOAD
        // (512) bytes fits every sensibly-sized event; callers with
        // larger events should grow the buffer at the call site or use
        // `emit!` with the log-based path.
        let __ev = $event;
        let __tag: u8 = $crate::cpi_event::CpiEvent::tag(&__ev);
        let __payload: &[u8] = $crate::cpi_event::CpiEvent::payload_bytes(&__ev);
        let mut __buf = [0u8; 2 + 1 + $crate::cpi_event::MAX_EVENT_PAYLOAD];
        let __n = $crate::cpi_event::encode_event_cpi(__tag, __payload, &mut __buf[..])
            .ok_or($crate::ProgramError::InvalidInstructionData)?;
        // Signer seeds for the event-authority PDA. The caller
        // derived and cached `$bump` so this is a stored-bump CPI.
        let __bump_byte: [u8; 1] = [$bump];
        let __seed_slices: [&[u8]; 2] = [$crate::cpi_event::EVENT_AUTHORITY_SEED, &__bump_byte[..]];
        $crate::cpi_event::invoke_event_cpi(
            $program_id,
            $event_authority,
            &__buf[..__n],
            &__seed_slices[..],
        )?;
    }};
}

/// Cheap structured logging for hot handlers.
///
/// `hopper_log!` is the compute-unit-aware sibling of [`msg!`]. It
/// dispatches to the backend's native log syscall with no format
/// machinery, no stack buffer, and no UTF-8 formatting pass. The
/// tradeoff: fewer ergonomics, predictable CU.
///
/// Forms:
///
/// - `hopper_log!("static message")` - one `sol_log_` syscall.
/// - `hopper_log!(my_str_slice)` - same, but for runtime `&str` values.
/// - `hopper_log!("label:", u64_value)` - one `sol_log_` plus one
///   `sol_log_64_`. Five `u64` slots (the `sol_log_64_` ABI) are
///   populated left-to-right and the rest zero.
/// - `hopper_log!("label:", a, b)` through `hopper_log!("label:", a, b, c, d, e)` -
///   same pattern; up to five integer values per call.
///
/// Reach for `msg!` when you need `{}`-style formatting. Reach for
/// `hopper_log!` when you are paying for every CU and you already
/// know the shape of the data.
#[macro_export]
macro_rules! hopper_log {
    // One label + 1..=5 integer values. Each integer is cast to `u64`
    // at the call site so callers do not need to sprinkle `as u64`.
    ($label:expr, $a:expr) => {{
        $crate::log::log($label);
        $crate::log::log_64($a as u64, 0, 0, 0, 0);
    }};
    ($label:expr, $a:expr, $b:expr) => {{
        $crate::log::log($label);
        $crate::log::log_64($a as u64, $b as u64, 0, 0, 0);
    }};
    ($label:expr, $a:expr, $b:expr, $c:expr) => {{
        $crate::log::log($label);
        $crate::log::log_64($a as u64, $b as u64, $c as u64, 0, 0);
    }};
    ($label:expr, $a:expr, $b:expr, $c:expr, $d:expr) => {{
        $crate::log::log($label);
        $crate::log::log_64($a as u64, $b as u64, $c as u64, $d as u64, 0);
    }};
    ($label:expr, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => {{
        $crate::log::log($label);
        $crate::log::log_64($a as u64, $b as u64, $c as u64, $d as u64, $e as u64);
    }};
    // Bare message. Uses the one-argument `log::log` syscall.
    ($msg:expr) => {{
        $crate::log::log($msg);
    }};
}

/// Declare the explicit Hopper runtime entrypoint bridge.
///
/// This is Hopper's direct runtime entrypoint over Solana account memory.
#[macro_export]
macro_rules! hopper_entrypoint {
    ( $process_instruction:expr ) => {
        $crate::hopper_entrypoint!($process_instruction, { $crate::MAX_TX_ACCOUNTS });
    };
    ( $process_instruction:expr, $maximum:expr ) => {
        /// # Safety
        ///
        /// Called by the Solana runtime; `input` is a valid BPF input buffer.
        #[no_mangle]
        pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 {
            const UNINIT: core::mem::MaybeUninit<$crate::__hopper_native::AccountView<'static>> =
                core::mem::MaybeUninit::<$crate::__hopper_native::AccountView<'static>>::uninit();
            let mut accounts = [UNINIT; $maximum];

            // 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.
            let (program_id, count, instruction_data) = unsafe {
                $crate::__hopper_native::raw_input::deserialize_accounts::<$maximum>(
                    input,
                    &mut accounts,
                )
            };

            // 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.
            let hopper_program_id = unsafe {
                &*(program_id as *const $crate::__hopper_native::Address as *const $crate::Address)
            };
            // 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.
            let hopper_accounts = unsafe {
                core::slice::from_raw_parts(
                    accounts.as_ptr() as *const $crate::AccountView<'_>,
                    count,
                )
            };

            match $process_instruction(hopper_program_id, hopper_accounts, instruction_data) {
                Ok(()) => $crate::__hopper_native::SUCCESS,
                Err(error) => error.into(),
            }
        }
    };
}

/// Declare the canonical Hopper program entrypoint.
#[macro_export]
macro_rules! program_entrypoint {
    ( $process_instruction:expr ) => {
        $crate::hopper_entrypoint!($process_instruction);
    };
    ( $process_instruction:expr, $maximum:expr ) => {
        $crate::hopper_entrypoint!($process_instruction, $maximum);
    };
}

/// Declare the fast two-argument Hopper entrypoint.
///
/// Uses the SVM's second register (`r2`) to receive instruction data
/// directly under [SIMD-0321], whose gate is active on all public
/// clusters (mainnet-beta since 2026-04-01). Post the 2026-07-07 fused
/// single-pass walk this is CU-neutral (+/- 2, measured 2026-07-21) on
/// programs whose accounts fit the declared maximum, the fused scanner
/// already banks the old "~30-40 CU" saving; so the feature stays
/// opt-in; it is the foundation of the SIMD-0449 table path.
///
/// Without the `simd-0321` cargo feature this macro expands to the
/// standard scanning entrypoint, identical semantics, sound everywhere
/// today. With the feature it expands to the two-argument form, which
/// null-checks `r2` and falls back to the scanning parse as defense in
/// depth.
///
/// [SIMD-0321]: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0321-vm-r2-instruction-data-pointer.md
#[cfg(feature = "simd-0321")]
#[macro_export]
macro_rules! hopper_fast_entrypoint {
    ( $process_instruction:expr ) => {
        $crate::hopper_fast_entrypoint!($process_instruction, { $crate::MAX_TX_ACCOUNTS });
    };
    ( $process_instruction:expr, $maximum:expr ) => {
        /// # Safety
        ///
        /// Called by the Solana runtime; `input` is a valid BPF input buffer.
        /// When SIMD-0321 is active, `ix_data` points to the instruction data
        /// with its u64 length stored at offset -8; when it is not active the
        /// register is zero and the scanning fallback is taken.
        #[no_mangle]
        pub unsafe extern "C" fn entrypoint(input: *mut u8, ix_data: *const u8) -> u64 {
            const UNINIT: core::mem::MaybeUninit<$crate::__hopper_native::AccountView> =
                core::mem::MaybeUninit::<$crate::__hopper_native::AccountView>::uninit();
            let mut accounts = [UNINIT; $maximum];

            let (program_id, count, instruction_data) = if ix_data.is_null() {
                // SIMD-0321 not active on this cluster: r2 is zero. Fall back
                // to the full scanning parse so the program stays correct.
                // SAFETY: `input` is the loader-provided input buffer; the
                // scanning parser owns all bounds/duplicate-marker checks.
                unsafe {
                    $crate::__hopper_native::raw_input::deserialize_accounts::<$maximum>(
                        input,
                        &mut accounts,
                    )
                }
            } else {
                // SAFETY: SIMD-0321 guarantees `ix_data` points at the
                // instruction-data bytes, with the u64 length prefix at
                // `ix_data - 8` and the 32-byte program id after the data.
                let ix_len =
                    unsafe { core::ptr::read_unaligned(ix_data.sub(8) as *const u64) as usize };
                let instruction_data: &'static [u8] =
                    unsafe { core::slice::from_raw_parts(ix_data, ix_len) };
                // SAFETY: program id trails the instruction data per the
                // loader serialization layout; `Address` is a transparent
                // `[u8; 32]`, so a reference into the buffer is valid at any
                // offset and lives as long as the invocation.
                let program_id: &'static $crate::__hopper_native::Address =
                    unsafe { &*(ix_data.add(ix_len) as *const $crate::__hopper_native::Address) };

                if $crate::__hopper_native::raw_input::SIMD_0449_TABLE_ENABLED {
                    // SIMD-0449 build: consume the runtime's appended
                    // pre-deduplicated account-pointer table, O(1)
                    // resolution plus one pointer copy per account. The gate
                    // is a `const`, so the untaken branch folds away entirely.
                    // Macro programs reach this arm the same way the native
                    // entrypoint does, so `hopper/simd-0449` is not a no-op
                    // one tier up.
                    // SAFETY: the `simd-0449` feature asserts the SIMD is
                    // active on the target cluster (table present);
                    // `instruction_data`/`program_id` were derived from the
                    // SIMD-0321 r2 register above.
                    unsafe {
                        $crate::__hopper_native::raw_input::deserialize_accounts_0449_into::<$maximum>(
                            input,
                            &mut accounts,
                            instruction_data,
                            program_id,
                        )
                    }
                } else {
                    // SAFETY: `input` is the loader input buffer; account-slot
                    // framing is validated by `deserialize_accounts_fast`.
                    unsafe {
                        $crate::__hopper_native::raw_input::deserialize_accounts_fast::<$maximum>(
                            input,
                            &mut accounts,
                            instruction_data,
                            program_id,
                        )
                    }
                }
            };

            // SAFETY: `Address` is a transparent 32-byte wrapper shared by the
            // native and runtime layers; the reinterpret is layout-identical.
            let hopper_program_id = unsafe {
                &*(program_id as *const $crate::__hopper_native::Address as *const $crate::Address)
            };
            // SAFETY: the first `count` slots were initialized by the parser;
            // runtime `AccountView` is repr(transparent) over the native view.
            let hopper_accounts = unsafe {
                core::slice::from_raw_parts(accounts.as_ptr() as *const $crate::AccountView, count)
            };

            match $process_instruction(hopper_program_id, hopper_accounts, instruction_data) {
                Ok(()) => $crate::__hopper_native::SUCCESS,
                Err(error) => error.into(),
            }
        }
    };
}

/// Without the `simd-0321` feature the "fast" entrypoint is an alias for
/// the standard scanning entrypoint. The SIMD-0321 gate is live on every
/// public cluster (mainnet-beta 2026-04-01), so the two-argument form is
/// sound to build; it stays opt-in because the r2 path measured CU-neutral
/// against the fused scanning walk for ~368 bytes of extra `.text` (see the
/// `simd-0321` feature note in the workspace `Cargo.toml`). Build with
/// `--features simd-0321` to select the r2 entrypoint.
#[cfg(not(feature = "simd-0321"))]
#[macro_export]
macro_rules! hopper_fast_entrypoint {
    ( $process_instruction:expr ) => {
        $crate::hopper_entrypoint!($process_instruction);
    };
    ( $process_instruction:expr, $maximum:expr ) => {
        $crate::hopper_entrypoint!($process_instruction, $maximum);
    };
}

/// Declare the count-exact program entrypoint.
///
/// Reads the discriminator from the SIMD-0321 `r2` instruction-data pointer
/// first, then materializes exactly the matched instruction's declared
/// account bound before dispatching to the helper `#[program]` generated
/// for it. `arms` pairs each one-byte discriminator with that bound and
/// that helper. Accounts past the bound are neither materialized nor
/// walked, and there is no transaction-sized pointer table: the entry cost
/// is the declared accounts only. The `Context` (segment borrow registry,
/// write gate, parametric args) is built exactly as on the scanning path.
///
/// The `r2` gate (`5xXZc66h4UdB6Yq7FzdBxBiRAFMMScMLwHxk2QZDaNZL`) is active
/// on mainnet-beta, devnet, and testnet. A runtime that leaves `r2` zero
/// gets `ProgramError::InvalidArgument` back instead of a scanning
/// fallback, which keeps the dual-path code out of the binary; `hopper
/// feature-gate` reports the gate for a target cluster.
#[macro_export]
macro_rules! hopper_exact_entrypoint {
    ( $( ( $disc:literal, $bound:expr, $helper:path ) ),* $(,)? ) => {
        /// # Safety
        ///
        /// Called by the Solana runtime with the loader input in `input` and,
        /// under SIMD-0321, the instruction-data pointer in `ix_data` (length
        /// at `ix_data - 8`, program id after the data).
        #[no_mangle]
        pub unsafe extern "C" fn entrypoint(input: *mut u8, ix_data: *const u8) -> u64 {
            if ix_data.is_null() {
                return $crate::ProgramError::InvalidArgument.into();
            }
            // SAFETY: SIMD-0321 serialization contract, see above.
            let ix_len =
                unsafe { core::ptr::read_unaligned(ix_data.sub(8) as *const u64) as usize };
            // SAFETY: `ix_len` bytes of instruction data start at `ix_data`
            // and live for the whole invocation.
            let instruction_data: &'static [u8] =
                unsafe { core::slice::from_raw_parts(ix_data, ix_len) };
            // SAFETY: the 32-byte program id trails the data; `Address` is a
            // transparent `[u8; 32]` with alignment 1.
            let program_id: &'static $crate::Address =
                unsafe { &*(ix_data.add(ix_len) as *const $crate::Address) };
            // The matched arm's bound first, so one walk and one `Context`
            // serve every instruction (no per-arm copy of either).
            let bound: usize = match instruction_data.first() {
                $( ::core::option::Option::Some(&$disc) => $bound, )*
                _ => return $crate::ProgramError::InvalidInstructionData.into(),
            };
            const WIDEST: usize = $crate::max_account_bound(&[ $( $bound ),* ]);
            const UNINIT: core::mem::MaybeUninit<
                $crate::__hopper_native::AccountView<'static>,
            > = core::mem::MaybeUninit::uninit();
            let mut views = [UNINIT; WIDEST];
            // SAFETY: `input` is the loader input buffer; the prefix walk
            // validates its own framing and never exceeds `WIDEST` slots.
            let count = unsafe {
                $crate::__hopper_native::raw_input::deserialize_leading_accounts::<WIDEST>(
                    input,
                    &mut views,
                    bound,
                )
            };
            // SAFETY: the first `count` slots were initialized by the walk;
            // runtime `AccountView` is repr(transparent) over the native view.
            let accounts = unsafe {
                core::slice::from_raw_parts(views.as_ptr() as *const $crate::AccountView<'_>, count)
            };
            let mut ctx = $crate::Context::new(program_id, accounts, instruction_data);
            let result: ::core::result::Result<(), $crate::ProgramError> =
                match instruction_data.first() {
                    $( ::core::option::Option::Some(&$disc) => $helper(&mut ctx, instruction_data), )*
                    _ => ::core::result::Result::Err($crate::ProgramError::InvalidInstructionData),
                };
            match result {
                ::core::result::Result::Ok(()) => $crate::__hopper_native::SUCCESS,
                ::core::result::Result::Err(error) => error.into(),
            }
        }
    };
}

/// The widest of a program's per-instruction account bounds; sizes the
/// scratch the count-exact entrypoint materializes into.
#[doc(hidden)]
pub const fn max_account_bound(bounds: &[usize]) -> usize {
    let mut widest = 0usize;
    let mut i = 0usize;
    while i < bounds.len() {
        if bounds[i] > widest {
            widest = bounds[i];
        }
        i += 1;
    }
    widest
}

/// Backward-compatible alias for the fast Hopper entrypoint macro.
#[macro_export]
macro_rules! fast_entrypoint {
    ( $process_instruction:expr ) => {
        $crate::hopper_fast_entrypoint!($process_instruction);
    };
    ( $process_instruction:expr, $maximum:expr ) => {
        $crate::hopper_fast_entrypoint!($process_instruction, $maximum);
    };
}

/// Declare the Hopper lazy entrypoint, RUNTIME-typed, matching the
/// eager `hopper_fast_entrypoint!`'s layering.
///
/// The handler receives `&mut hopper_runtime::lazy::LazyContext` (also
/// in the facade prelude) and returns the runtime `ProgramResult`; the
/// expansion bridges to the substrate lazy parser and maps errors
/// through the layout-twin glue at the boundary. Substrate authors who
/// want the native-typed context use the substrate layer's own
/// `hopper_lazy_entrypoint!` directly, exactly as with the eager pair.
#[macro_export]
macro_rules! hopper_lazy_entrypoint {
    ( $process:expr ) => {
        $crate::__hopper_native::hopper_lazy_entrypoint!(
            |__hopper_native_ctx: &mut $crate::__hopper_native::LazyContext|
                -> ::core::result::Result<(), $crate::__hopper_native::error::ProgramError> {
                let mut __hopper_ctx =
                    $crate::lazy::LazyContext::from_native(__hopper_native_ctx);
                match $process(&mut __hopper_ctx) {
                    ::core::result::Result::Ok(()) => ::core::result::Result::Ok(()),
                    ::core::result::Result::Err(e) => {
                        ::core::result::Result::Err(::core::convert::From::from(e))
                    }
                }
            }
        );
    };
}

/// Backward-compatible alias for the lazy Hopper entrypoint macro.
#[macro_export]
macro_rules! lazy_entrypoint {
    ( $process:expr ) => {
        $crate::hopper_lazy_entrypoint!($process);
    };
}

#[macro_export]
macro_rules! no_allocator {
    () => {
        #[cfg(target_os = "solana")]
        mod __hopper_allocator {
            struct NoAlloc;

            unsafe impl core::alloc::GlobalAlloc for NoAlloc {
                unsafe fn alloc(&self, _layout: core::alloc::Layout) -> *mut u8 {
                    // A no-alloc program must never reach here. Returning null
                    // fails the allocation and builds on stable SBF without the
                    // experimental inline-asm arch feature. Reach for
                    // `hopper_native::no_allocator!` (which traps via asm) when
                    // the crate already enables `asm_experimental_arch`.
                    core::ptr::null_mut()
                }

                unsafe fn dealloc(&self, _ptr: *mut u8, _layout: core::alloc::Layout) {}
            }

            #[global_allocator]
            static ALLOCATOR: NoAlloc = NoAlloc;
        }
    };
}

/// Install the default bump allocator over the SVM heap region. Opt-in
/// counterpart to [`no_allocator!`] for programs that need `alloc` on a
/// cold path. See [`hopper_native::BumpAllocator`].
#[macro_export]
macro_rules! default_allocator {
    () => {
        #[cfg(target_os = "solana")]
        #[global_allocator]
        static ALLOCATOR: $crate::__hopper_native::BumpAllocator =
            $crate::__hopper_native::BumpAllocator {
                start: $crate::__hopper_native::HEAP_START_ADDRESS,
                len: $crate::__hopper_native::HEAP_LENGTH,
            };
    };
}

#[macro_export]
macro_rules! nostd_panic_handler {
    () => {
        #[cfg(target_os = "solana")]
        #[panic_handler]
        fn panic(_info: &core::panic::PanicInfo) -> ! {
            // Stable-SBF panic handler: no inline asm, so it builds without the
            // experimental `asm_experimental_arch` feature. The runtime caps
            // compute, so the spin terminates the transaction. Use
            // `hopper_native::nostd_panic_handler!` for the asm trap variant
            // when the crate already enables that feature.
            let _ = _info;
            loop {
                core::hint::spin_loop();
            }
        }
    };
}