jiminy-core 0.17.0

Core systems layer for Jiminy: account layout, zero-copy IO, validation, PDA, sysvar access, math, time checks. Declarative macros for error codes, instruction dispatch, and account uniqueness. no_std, no_alloc, no proc macros, BPF-safe.
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
//! Jiminy ABI field primitives: alignment-1 wire types.
//!
//! These are the canonical field types for `zero_copy_layout!` structs.
//! Each type is `#[repr(transparent)]` over a byte array, guaranteeing
//! alignment 1 and eliminating UB from unaligned references on any target.
//!
//! ## Why
//!
//! SBF has 1-byte alignment for everything, so raw `u64` overlays work
//! on-chain. But native tests, Miri, and future VMs may enforce real
//! alignment, and taking `&u64` to an unaligned pointer is instant UB.
//!
//! These wrappers store fields as `[u8; N]` (LE) and access via
//! `from_le_bytes` / `to_le_bytes`. Zero overhead on SBF. Safe everywhere.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use jiminy_core::abi::{LeU64, LeBool};
//!
//! zero_copy_layout! {
//!     pub struct Vault, discriminator = 1, version = 1 {
//!         header:    AccountHeader = 16,
//!         balance:   LeU64         = 8,
//!         is_frozen: LeBool        = 1,
//!         authority: Address       = 32,
//!     }
//! }
//!
//! let vault = Vault::overlay(&data)?;
//! let bal: u64 = vault.balance.get();
//! ```

use crate::account::{FixedLayout, Pod};

// ── Macro to stamp out unsigned LE integer wrappers ──────────────────────────

macro_rules! impl_le_unsigned {
    ($name:ident, $inner:ty, $size:literal) => {
        #[doc = concat!("Alignment-1, little-endian `", stringify!($inner), "` for on-chain ABI fields.")]
        #[repr(transparent)]
        #[derive(Clone, Copy, PartialEq, Eq)]
        pub struct $name(pub [u8; $size]);

        const _: () = assert!(core::mem::size_of::<$name>() == $size);
        const _: () = assert!(core::mem::align_of::<$name>() == 1);

        impl $name {
            /// Zero value.
            pub const ZERO: Self = Self([0u8; $size]);

            /// Wrap a native value.
            #[inline(always)]
            pub const fn new(v: $inner) -> Self {
                Self(v.to_le_bytes())
            }

            /// Read the native value.
            #[inline(always)]
            pub const fn get(&self) -> $inner {
                <$inner>::from_le_bytes(self.0)
            }

            /// Write a native value.
            #[inline(always)]
            pub fn set(&mut self, v: $inner) {
                self.0 = v.to_le_bytes();
            }
        }

        impl Default for $name {
            #[inline(always)]
            fn default() -> Self {
                Self::ZERO
            }
        }

        impl core::fmt::Debug for $name {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}({})", stringify!($name), self.get())
            }
        }

        impl core::fmt::Display for $name {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}", self.get())
            }
        }

        impl PartialOrd for $name {
            #[inline(always)]
            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }

        impl Ord for $name {
            #[inline(always)]
            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
                self.get().cmp(&other.get())
            }
        }

        impl From<$inner> for $name {
            #[inline(always)]
            fn from(v: $inner) -> Self {
                Self::new(v)
            }
        }

        impl From<$name> for $inner {
            #[inline(always)]
            fn from(v: $name) -> Self {
                v.get()
            }
        }

        // SAFETY: repr(transparent) over [u8; N], all bit patterns valid.
        unsafe impl Pod for $name {}
        impl FixedLayout for $name {
            const SIZE: usize = $size;
        }
    };
}

// ── Macro to stamp out signed LE integer wrappers ────────────────────────────

macro_rules! impl_le_signed {
    ($name:ident, $inner:ty, $size:literal) => {
        #[doc = concat!("Alignment-1, little-endian `", stringify!($inner), "` for on-chain ABI fields.")]
        #[repr(transparent)]
        #[derive(Clone, Copy, PartialEq, Eq)]
        pub struct $name(pub [u8; $size]);

        const _: () = assert!(core::mem::size_of::<$name>() == $size);
        const _: () = assert!(core::mem::align_of::<$name>() == 1);

        impl $name {
            /// Zero value.
            pub const ZERO: Self = Self([0u8; $size]);

            /// Wrap a native value.
            #[inline(always)]
            pub const fn new(v: $inner) -> Self {
                Self(v.to_le_bytes())
            }

            /// Read the native value.
            #[inline(always)]
            pub const fn get(&self) -> $inner {
                <$inner>::from_le_bytes(self.0)
            }

            /// Write a native value.
            #[inline(always)]
            pub fn set(&mut self, v: $inner) {
                self.0 = v.to_le_bytes();
            }
        }

        impl Default for $name {
            #[inline(always)]
            fn default() -> Self {
                Self::ZERO
            }
        }

        impl core::fmt::Debug for $name {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}({})", stringify!($name), self.get())
            }
        }

        impl core::fmt::Display for $name {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}", self.get())
            }
        }

        impl PartialOrd for $name {
            #[inline(always)]
            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }

        impl Ord for $name {
            #[inline(always)]
            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
                self.get().cmp(&other.get())
            }
        }

        impl From<$inner> for $name {
            #[inline(always)]
            fn from(v: $inner) -> Self {
                Self::new(v)
            }
        }

        impl From<$name> for $inner {
            #[inline(always)]
            fn from(v: $name) -> Self {
                v.get()
            }
        }

        // SAFETY: repr(transparent) over [u8; N], all bit patterns valid.
        unsafe impl Pod for $name {}
        impl FixedLayout for $name {
            const SIZE: usize = $size;
        }
    };
}

// ── Unsigned types ───────────────────────────────────────────────────────────

impl_le_unsigned!(LeU16, u16, 2);
impl_le_unsigned!(LeU32, u32, 4);
impl_le_unsigned!(LeU64, u64, 8);
impl_le_unsigned!(LeU128, u128, 16);

// ── Signed types ─────────────────────────────────────────────────────────────

impl_le_signed!(LeI16, i16, 2);
impl_le_signed!(LeI32, i32, 4);
impl_le_signed!(LeI64, i64, 8);
impl_le_signed!(LeI128, i128, 16);

// ── Bool ─────────────────────────────────────────────────────────────────────

/// Alignment-1 boolean for on-chain ABI fields.
///
/// Stored as a single byte: `0` = false, any non-zero = true.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct LeBool(pub [u8; 1]);

const _: () = assert!(core::mem::size_of::<LeBool>() == 1);
const _: () = assert!(core::mem::align_of::<LeBool>() == 1);

impl LeBool {
    /// False value.
    pub const FALSE: Self = Self([0]);
    /// True value.
    pub const TRUE: Self = Self([1]);

    /// Wrap a native bool.
    #[inline(always)]
    pub const fn new(v: bool) -> Self {
        Self([v as u8])
    }

    /// Read the native bool.
    #[inline(always)]
    pub const fn get(&self) -> bool {
        self.0[0] != 0
    }

    /// Write a native bool.
    #[inline(always)]
    pub fn set(&mut self, v: bool) {
        self.0[0] = v as u8;
    }
}

impl Default for LeBool {
    #[inline(always)]
    fn default() -> Self {
        Self::FALSE
    }
}

impl core::fmt::Debug for LeBool {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "LeBool({})", self.get())
    }
}

impl core::fmt::Display for LeBool {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.get())
    }
}

impl From<bool> for LeBool {
    #[inline(always)]
    fn from(v: bool) -> Self {
        Self::new(v)
    }
}

impl From<LeBool> for bool {
    #[inline(always)]
    fn from(v: LeBool) -> Self {
        v.get()
    }
}

// SAFETY: repr(transparent) over [u8; 1], all bit patterns valid.
unsafe impl Pod for LeBool {}
impl FixedLayout for LeBool {
    const SIZE: usize = 1;
}

// ── Field reference wrappers for borrow-splitting ────────────────────────────

/// Immutable typed view over a field-sized byte slice.
///
/// Produced by `split_fields` (generated by `zero_copy_layout!`).
/// Provides typed access without holding a reference to the whole struct.
pub struct FieldRef<'a> {
    data: &'a [u8],
}

impl<'a> FieldRef<'a> {
    /// Create a field reference from a byte slice.
    #[inline(always)]
    pub const fn new(data: &'a [u8]) -> Self {
        Self { data }
    }

    /// The byte length of this field.
    #[inline(always)]
    pub const fn len(&self) -> usize {
        self.data.len()
    }

    /// Whether the field is zero-length.
    #[inline(always)]
    pub const fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Read the raw bytes.
    #[inline(always)]
    pub const fn as_bytes(&self) -> &[u8] {
        self.data
    }

    /// Read as an `Address` (32-byte public key).
    ///
    /// Copies the bytes into an owned `Address`.
    #[inline(always)]
    pub fn read_address(&self) -> hopper_runtime::Address {
        let mut addr = [0u8; 32];
        addr.copy_from_slice(&self.data[..32]);
        hopper_runtime::Address::from(addr)
    }

    /// Borrow the field bytes as an `&Address` reference.
    ///
    /// # Panics
    ///
    /// Panics if the field is smaller than 32 bytes.
    #[inline(always)]
    pub fn as_address(&self) -> &hopper_runtime::Address {
        // SAFETY: Address is repr(transparent) over [u8; 32], alignment 1.
        // The slice has been bounds-checked to 32 bytes.
        let ptr = self.data[..32].as_ptr() as *const hopper_runtime::Address;
        unsafe { &*ptr }
    }

    /// Read a `u64` from the field (LE).
    #[inline(always)]
    pub fn read_u64(&self) -> u64 {
        u64::from_le_bytes([
            self.data[0],
            self.data[1],
            self.data[2],
            self.data[3],
            self.data[4],
            self.data[5],
            self.data[6],
            self.data[7],
        ])
    }

    /// Read a `u32` from the field (LE).
    #[inline(always)]
    pub fn read_u32(&self) -> u32 {
        u32::from_le_bytes([self.data[0], self.data[1], self.data[2], self.data[3]])
    }

    /// Read a `u16` from the field (LE).
    #[inline(always)]
    pub fn read_u16(&self) -> u16 {
        u16::from_le_bytes([self.data[0], self.data[1]])
    }

    /// Read a `u8` from the field.
    #[inline(always)]
    pub fn read_u8(&self) -> u8 {
        self.data[0]
    }

    /// Read a `bool` from the field.
    #[inline(always)]
    pub fn read_bool(&self) -> bool {
        self.data[0] != 0
    }

    /// Read an `i64` from the field (LE).
    #[inline(always)]
    pub fn read_i64(&self) -> i64 {
        i64::from_le_bytes([
            self.data[0],
            self.data[1],
            self.data[2],
            self.data[3],
            self.data[4],
            self.data[5],
            self.data[6],
            self.data[7],
        ])
    }

    /// Read an `i32` from the field (LE).
    #[inline(always)]
    pub fn read_i32(&self) -> i32 {
        i32::from_le_bytes([self.data[0], self.data[1], self.data[2], self.data[3]])
    }

    /// Read an `i16` from the field (LE).
    #[inline(always)]
    pub fn read_i16(&self) -> i16 {
        i16::from_le_bytes([self.data[0], self.data[1]])
    }

    /// Read a `u128` from the field (LE).
    #[inline(always)]
    pub fn read_u128(&self) -> u128 {
        u128::from_le_bytes([
            self.data[0],  self.data[1],  self.data[2],  self.data[3],
            self.data[4],  self.data[5],  self.data[6],  self.data[7],
            self.data[8],  self.data[9],  self.data[10], self.data[11],
            self.data[12], self.data[13], self.data[14], self.data[15],
        ])
    }

    /// Read an `i128` from the field (LE).
    #[inline(always)]
    pub fn read_i128(&self) -> i128 {
        i128::from_le_bytes([
            self.data[0],  self.data[1],  self.data[2],  self.data[3],
            self.data[4],  self.data[5],  self.data[6],  self.data[7],
            self.data[8],  self.data[9],  self.data[10], self.data[11],
            self.data[12], self.data[13], self.data[14], self.data[15],
        ])
    }

    /// Read an `i8` from the field.
    #[inline(always)]
    pub fn read_i8(&self) -> i8 {
        self.data[0] as i8
    }
}

/// Mutable typed view over a field-sized byte slice.
///
/// Produced by `split_fields_mut` (generated by `zero_copy_layout!`).
/// Provides typed mutation without holding `&mut` to the whole struct.
pub struct FieldMut<'a> {
    data: &'a mut [u8],
}

impl<'a> FieldMut<'a> {
    /// Create a mutable field reference from a byte slice.
    #[inline(always)]
    pub fn new(data: &'a mut [u8]) -> Self {
        Self { data }
    }

    /// The byte length of this field.
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Whether the field is zero-length.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

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

    /// Get the raw mutable bytes.
    #[inline(always)]
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.data
    }

    /// Read as an `Address` (32-byte public key).
    #[inline(always)]
    pub fn read_address(&self) -> hopper_runtime::Address {
        let mut addr = [0u8; 32];
        addr.copy_from_slice(&self.data[..32]);
        hopper_runtime::Address::from(addr)
    }

    /// Borrow the field bytes as an `&Address` reference.
    #[inline(always)]
    pub fn as_address(&self) -> &hopper_runtime::Address {
        // SAFETY: Address is repr(transparent) over [u8; 32], alignment 1.
        let ptr = self.data[..32].as_ptr() as *const hopper_runtime::Address;
        unsafe { &*ptr }
    }

    /// Write an `Address` (32-byte public key).
    #[inline(always)]
    pub fn write_address(&mut self, addr: &hopper_runtime::Address) {
        self.data[..32].copy_from_slice(addr.as_ref());
    }

    /// Write a `u64` (LE).
    #[inline(always)]
    pub fn write_u64(&mut self, v: u64) {
        self.data[..8].copy_from_slice(&v.to_le_bytes());
    }

    /// Write a `u32` (LE).
    #[inline(always)]
    pub fn write_u32(&mut self, v: u32) {
        self.data[..4].copy_from_slice(&v.to_le_bytes());
    }

    /// Write a `u16` (LE).
    #[inline(always)]
    pub fn write_u16(&mut self, v: u16) {
        self.data[..2].copy_from_slice(&v.to_le_bytes());
    }

    /// Write a `u8`.
    #[inline(always)]
    pub fn write_u8(&mut self, v: u8) {
        self.data[0] = v;
    }

    /// Write a `bool`.
    #[inline(always)]
    pub fn write_bool(&mut self, v: bool) {
        self.data[0] = v as u8;
    }

    /// Write an `i64` (LE).
    #[inline(always)]
    pub fn write_i64(&mut self, v: i64) {
        self.data[..8].copy_from_slice(&v.to_le_bytes());
    }

    /// Write an `i32` (LE).
    #[inline(always)]
    pub fn write_i32(&mut self, v: i32) {
        self.data[..4].copy_from_slice(&v.to_le_bytes());
    }

    /// Write an `i16` (LE).
    #[inline(always)]
    pub fn write_i16(&mut self, v: i16) {
        self.data[..2].copy_from_slice(&v.to_le_bytes());
    }

    /// Write an `i8`.
    #[inline(always)]
    pub fn write_i8(&mut self, v: i8) {
        self.data[0] = v as u8;
    }

    /// Write a `u128` (LE).
    #[inline(always)]
    pub fn write_u128(&mut self, v: u128) {
        self.data[..16].copy_from_slice(&v.to_le_bytes());
    }

    /// Write an `i128` (LE).
    #[inline(always)]
    pub fn write_i128(&mut self, v: i128) {
        self.data[..16].copy_from_slice(&v.to_le_bytes());
    }

    /// Read a `u64` (LE).
    #[inline(always)]
    pub fn read_u64(&self) -> u64 {
        u64::from_le_bytes([
            self.data[0],
            self.data[1],
            self.data[2],
            self.data[3],
            self.data[4],
            self.data[5],
            self.data[6],
            self.data[7],
        ])
    }

    /// Read a `u32` (LE).
    #[inline(always)]
    pub fn read_u32(&self) -> u32 {
        u32::from_le_bytes([self.data[0], self.data[1], self.data[2], self.data[3]])
    }

    /// Read a `u16` (LE).
    #[inline(always)]
    pub fn read_u16(&self) -> u16 {
        u16::from_le_bytes([self.data[0], self.data[1]])
    }

    /// Read a `u8`.
    #[inline(always)]
    pub fn read_u8(&self) -> u8 {
        self.data[0]
    }

    /// Read a `bool`.
    #[inline(always)]
    pub fn read_bool(&self) -> bool {
        self.data[0] != 0
    }

    /// Read an `i64` (LE).
    #[inline(always)]
    pub fn read_i64(&self) -> i64 {
        i64::from_le_bytes([
            self.data[0],
            self.data[1],
            self.data[2],
            self.data[3],
            self.data[4],
            self.data[5],
            self.data[6],
            self.data[7],
        ])
    }

    /// Read an `i32` (LE).
    #[inline(always)]
    pub fn read_i32(&self) -> i32 {
        i32::from_le_bytes([self.data[0], self.data[1], self.data[2], self.data[3]])
    }

    /// Read an `i16` (LE).
    #[inline(always)]
    pub fn read_i16(&self) -> i16 {
        i16::from_le_bytes([self.data[0], self.data[1]])
    }

    /// Read an `i8`.
    #[inline(always)]
    pub fn read_i8(&self) -> i8 {
        self.data[0] as i8
    }

    /// Read a `u128` (LE).
    #[inline(always)]
    pub fn read_u128(&self) -> u128 {
        u128::from_le_bytes([
            self.data[0],  self.data[1],  self.data[2],  self.data[3],
            self.data[4],  self.data[5],  self.data[6],  self.data[7],
            self.data[8],  self.data[9],  self.data[10], self.data[11],
            self.data[12], self.data[13], self.data[14], self.data[15],
        ])
    }

    /// Read an `i128` (LE).
    #[inline(always)]
    pub fn read_i128(&self) -> i128 {
        i128::from_le_bytes([
            self.data[0],  self.data[1],  self.data[2],  self.data[3],
            self.data[4],  self.data[5],  self.data[6],  self.data[7],
            self.data[8],  self.data[9],  self.data[10], self.data[11],
            self.data[12], self.data[13], self.data[14], self.data[15],
        ])
    }

    /// Copy from a byte slice (e.g., an Address).
    #[inline(always)]
    pub fn copy_from(&mut self, src: &[u8]) {
        self.data[..src.len()].copy_from_slice(src);
    }
}