neo-runtime 0.14.0

Neo N3 Runtime Stubs
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
// Copyright (c) 2025-2026 R3E Network
// Licensed under the MIT License

//! Storage convenience helpers built on top of the syscall layer.
//!
//! This module exposes two facades:
//!
//! - [`NeoStorage`] is the byte-string-typed API used by the host-side test
//!   harness and by contracts that already manage `NeoByteString`/`Vec<u8>`
//!   storage values themselves. It allocates through the standard Rust
//!   allocator and is best suited to host (`cfg(not(target_arch = "wasm32"))`)
//!   builds.
//!
//! - [`RawStorage`] is a heap-free facade that takes plain `&[u8]` slices and
//!   writes results into caller-supplied buffers. On `wasm32` it lowers
//!   directly to the translator-emitted Neo storage syscall helpers without
//!   ever touching the wasm allocator. Production smart contracts that run on
//!   Neo Express should prefer this path: it sidesteps the dlmalloc bookkeeping
//!   that the wasm-to-NeoVM translator does not currently materialise on the
//!   contract's NeoVM stack, so storage-heavy state transitions (multisig,
//!   escrow, crowdfund, etc.) stay deploy-and-invoke-able rather than
//!   "deploy-only".

use neo_syscalls::NeoVMSyscall;
use neo_types::*;

#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "neo")]
extern "C" {
    #[link_name = "neo_storage_put_bytes"]
    fn neo_storage_put_bytes(key_ptr: i32, key_len: i32, value_ptr: i32, value_len: i32);

    #[link_name = "neo_storage_delete_bytes"]
    fn neo_storage_delete_bytes(key_ptr: i32, key_len: i32);

    #[link_name = "neo_storage_get_into"]
    fn neo_storage_get_into(key_ptr: i32, key_len: i32, out_ptr: i32, out_cap: i32) -> i32;

    #[link_name = "raw_storage_put_i64"]
    fn neo_raw_storage_put_i64(key: i64, value: i64);

    #[link_name = "raw_storage_get_i64"]
    fn neo_raw_storage_get_i64(key: i64) -> i64;

    #[link_name = "raw_storage_has_i64"]
    fn neo_raw_storage_has_i64(key: i64) -> i32;

    #[link_name = "raw_storage_delete_i64"]
    fn neo_raw_storage_delete_i64(key: i64);
}

/// Storage convenience helpers built on top of the syscall layer.
pub struct NeoStorage;

impl NeoStorage {
    pub fn get_context() -> NeoResult<NeoStorageContext> {
        NeoVMSyscall::storage_get_context()
    }

    pub fn get_read_only_context() -> NeoResult<NeoStorageContext> {
        NeoVMSyscall::storage_get_read_only_context()
    }

    pub fn as_read_only(context: &NeoStorageContext) -> NeoResult<NeoStorageContext> {
        NeoVMSyscall::storage_as_read_only(context)
    }

    /// Read a stored value.
    ///
    /// **Ambiguity warning (D8):** this returns an empty `NeoByteString` both
    /// when the key is absent AND when the stored value is genuinely empty, so
    /// the two cases are indistinguishable. For existence-sensitive reads,
    /// prefer `NeoVMSyscall::storage_try_get` (returns `Option`) or
    /// `RawStorage::get_into` (returns `RawStorageGet::Missing`).
    pub fn get(context: &NeoStorageContext, key: &NeoByteString) -> NeoResult<NeoByteString> {
        NeoVMSyscall::storage_get(context, key)
    }

    pub fn put(
        context: &NeoStorageContext,
        key: &NeoByteString,
        value: &NeoByteString,
    ) -> NeoResult<()> {
        NeoVMSyscall::storage_put(context, key, value)
    }

    pub fn delete(context: &NeoStorageContext, key: &NeoByteString) -> NeoResult<()> {
        NeoVMSyscall::storage_delete(context, key)
    }

    pub fn find(
        context: &NeoStorageContext,
        prefix: &NeoByteString,
    ) -> NeoResult<NeoIterator<NeoValue>> {
        NeoVMSyscall::storage_find(context, prefix)
    }
}

/// Heap-free storage facade that operates on `&[u8]` slices.
///
/// `wasm32` lowers each call to the translator's `System.Storage.*` SYSCALL
/// helpers directly, so contracts that use this path do not depend on the
/// Rust allocator being functional inside NeoVM. Host (non-wasm32) builds
/// route through the existing `NeoVMSyscall` simulation so unit tests behave
/// the same as on wasm32.
pub struct RawStorage;

/// Outcome of [`RawStorage::get_into`].
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum RawStorageGet {
    /// Value was found and fully written into the caller buffer; the contained
    /// `usize` is the number of bytes written.
    Found(usize),
    /// The runtime explicitly reported a null/missing value. Neo N3 storage
    /// commonly surfaces absent keys as an empty byte string instead, so
    /// callers must not rely on this variant for existence checks.
    Missing,
    /// Value exists but is larger than the caller buffer; the contained
    /// `usize` is the byte length the caller must allocate before retrying.
    BufferTooSmall(usize),
}

/// Fixed-capacity stack key builder for `RawStorage` keys.
///
/// This keeps contract samples on a heap-free path while centralizing the
/// small `copy_nonoverlapping` block that fixed key construction needs.
/// Push methods return `false` when the requested write would exceed capacity;
/// existing bytes are left unchanged in that case.
pub struct RawKeyBuilder<const N: usize> {
    buf: core::mem::MaybeUninit<[u8; N]>,
    len: usize,
}

impl<const N: usize> RawKeyBuilder<N> {
    #[inline(always)]
    pub const fn new() -> Self {
        Self {
            buf: core::mem::MaybeUninit::uninit(),
            len: 0,
        }
    }

    #[inline(always)]
    pub fn push_bytes(&mut self, bytes: &[u8]) -> bool {
        if bytes.len() > N - self.len {
            return false;
        }
        unsafe {
            core::ptr::copy_nonoverlapping(
                bytes.as_ptr(),
                self.buf.as_mut_ptr().cast::<u8>().add(self.len),
                bytes.len(),
            );
        }
        self.len += bytes.len();
        true
    }

    #[inline(always)]
    pub fn push_i64_le(&mut self, value: i64) -> bool {
        self.push_bytes(&value.to_le_bytes())
    }

    #[inline(always)]
    pub fn push_byte(&mut self, value: u8) -> bool {
        if self.len == N {
            return false;
        }
        unsafe {
            *self.buf.as_mut_ptr().cast::<u8>().add(self.len) = value;
        }
        self.len += 1;
        true
    }

    #[inline(always)]
    pub fn as_slice(&self) -> &[u8] {
        debug_assert!(self.len <= N);
        unsafe { core::slice::from_raw_parts(self.buf.as_ptr().cast::<u8>(), self.len) }
    }

    #[inline(always)]
    pub fn clear(&mut self) {
        self.len = 0;
    }

    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }
}

impl<const N: usize> Default for RawKeyBuilder<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl RawStorage {
    /// Write `value` to `key` in the executing contract's persistent storage.
    pub fn put(key: &[u8], value: &[u8]) {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_storage_put_bytes(
                key.as_ptr() as i32,
                key.len() as i32,
                value.as_ptr() as i32,
                value.len() as i32,
            );
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let ctx = match NeoVMSyscall::storage_get_context() {
                Ok(c) => c,
                Err(_) => return,
            };
            let _ = NeoVMSyscall::storage_put(
                &ctx,
                &NeoByteString::from_slice(key),
                &NeoByteString::from_slice(value),
            );
        }
    }

    /// Delete `key` from the executing contract's persistent storage.
    pub fn delete(key: &[u8]) {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_storage_delete_bytes(key.as_ptr() as i32, key.len() as i32);
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let ctx = match NeoVMSyscall::storage_get_context() {
                Ok(c) => c,
                Err(_) => return,
            };
            let _ = NeoVMSyscall::storage_delete(&ctx, &NeoByteString::from_slice(key));
        }
    }

    /// Read the value at `key` into `buf`.
    ///
    /// Returns one of:
    /// - [`RawStorageGet::Found`] with the byte count actually written into
    ///   `buf` when the key is present and the value fits.
    /// - [`RawStorageGet::Missing`] only when the runtime explicitly reports
    ///   null/missing; Neo N3 commonly returns zero bytes for absent keys.
    /// - [`RawStorageGet::BufferTooSmall`] with the value's true length when
    ///   `buf` cannot hold it; the value bytes are NOT copied in this case.
    pub fn get_into(key: &[u8], buf: &mut [u8]) -> RawStorageGet {
        #[cfg(target_arch = "wasm32")]
        let actual = unsafe {
            neo_storage_get_into(
                key.as_ptr() as i32,
                key.len() as i32,
                buf.as_mut_ptr() as i32,
                buf.len() as i32,
            )
        };
        #[cfg(not(target_arch = "wasm32"))]
        let actual = host_get_into(key, buf);

        if actual == -1 {
            RawStorageGet::Missing
        } else if actual >= 0 {
            RawStorageGet::Found(actual as usize)
        } else {
            RawStorageGet::BufferTooSmall((-actual) as usize)
        }
    }

    /// Read an exact 8-byte little-endian `i64` at `key`. Returns `None` for
    /// missing keys or for stored values whose length is not exactly 8.
    pub fn get_i64(key: &[u8]) -> Option<i64> {
        let mut buf = [0u8; 8];
        match Self::get_into(key, &mut buf) {
            RawStorageGet::Found(8) => Some(i64::from_le_bytes(buf)),
            _ => None,
        }
    }

    /// Read an exact 2-byte little-endian `u16` at `key`. Returns `None` for
    /// missing keys or for stored values whose length is not exactly 2.
    pub fn get_u16(key: &[u8]) -> Option<u16> {
        let mut buf = [0u8; 2];
        match Self::get_into(key, &mut buf) {
            RawStorageGet::Found(2) => Some(u16::from_le_bytes(buf)),
            _ => None,
        }
    }

    /// Read an exact 1-byte boolean at `key`. Returns `None` for missing keys
    /// or for stored values whose length is not exactly 1.
    pub fn get_bool(key: &[u8]) -> Option<bool> {
        let mut buf = [0u8; 1];
        match Self::get_into(key, &mut buf) {
            RawStorageGet::Found(1) => Some(buf[0] != 0),
            _ => None,
        }
    }

    /// Convenience: store an `i64` little-endian at `key`.
    pub fn put_i64(key: &[u8], value: i64) {
        Self::put(key, &value.to_le_bytes());
    }

    /// Convenience: store a `u16` little-endian at `key`.
    pub fn put_u16(key: &[u8], value: u16) {
        Self::put(key, &value.to_le_bytes());
    }

    /// Convenience: store a `bool` (encoded as a single 0/1 byte) at `key`.
    pub fn put_bool(key: &[u8], value: bool) {
        Self::put(key, &[value as u8]);
    }

    /// Store an `i64` value under an `i64` key without touching wasm linear
    /// memory. On wasm32 this lowers directly to `System.Storage.Put`.
    pub fn put_i64_key(key: i64, value: i64) {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_raw_storage_put_i64(key, value);
        }
        #[cfg(not(target_arch = "wasm32"))]
        host_put_i64_key(key, value);
    }

    /// Read an `i64` value from an `i64` key. Missing keys return `0`.
    pub fn get_i64_key_or_zero(key: i64) -> i64 {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_raw_storage_get_i64(key)
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            host_get_i64_key(key).unwrap_or(0)
        }
    }

    /// Check whether an `i64` key has a stored integer value.
    ///
    /// Neo Express surfaces absent direct keys as empty bytes. The translator
    /// therefore treats any non-empty `Storage.Get` result as present.
    pub fn has_i64_key(key: i64) -> bool {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_raw_storage_has_i64(key) != 0
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            host_has_i64_key(key)
        }
    }

    /// Delete an `i64` key without touching wasm linear memory.
    pub fn delete_i64_key(key: i64) {
        #[cfg(target_arch = "wasm32")]
        unsafe {
            neo_raw_storage_delete_i64(key);
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let ctx = match NeoVMSyscall::storage_get_context() {
                Ok(c) => c,
                Err(_) => return,
            };
            let key_bytes = neovm_i64_bytes(key);
            let _ = NeoVMSyscall::storage_delete(&ctx, &NeoByteString::from_slice(&key_bytes));
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn host_get_into(key: &[u8], buf: &mut [u8]) -> i32 {
    let ctx = match NeoVMSyscall::storage_get_context() {
        Ok(c) => c,
        Err(_) => return -1,
    };
    let stored = match NeoVMSyscall::storage_try_get(&ctx, &NeoByteString::from_slice(key)) {
        Ok(Some(b)) => b,
        // D14: return -1 for a missing key so the host path matches the wasm
        // path's `RawStorageGet::Missing` (was returning 0, i.e. Found(0), so
        // host and wasm disagreed on absence).
        Ok(None) => return -1,
        Err(_) => return -1,
    };
    let bytes = stored.as_slice();
    if bytes.len() > buf.len() {
        return -(bytes.len() as i32);
    }
    let len = bytes.len();
    buf[..len].copy_from_slice(bytes);
    len as i32
}

#[cfg(not(target_arch = "wasm32"))]
fn host_put_i64_key(key: i64, value: i64) {
    let ctx = match NeoVMSyscall::storage_get_context() {
        Ok(c) => c,
        Err(_) => return,
    };
    let key_bytes = neovm_i64_bytes(key);
    let value_bytes = neovm_i64_bytes(value);
    let _ = NeoVMSyscall::storage_put(
        &ctx,
        &NeoByteString::from_slice(&key_bytes),
        &NeoByteString::from_slice(&value_bytes),
    );
}

#[cfg(not(target_arch = "wasm32"))]
fn host_get_i64_key(key: i64) -> Option<i64> {
    let ctx = NeoVMSyscall::storage_get_context().ok()?;
    let key_bytes = neovm_i64_bytes(key);
    let stored = NeoVMSyscall::storage_try_get(&ctx, &NeoByteString::from_slice(&key_bytes))
        .ok()
        .flatten()?;
    storage_bytes_to_i64(stored.as_slice())
}

#[cfg(not(target_arch = "wasm32"))]
fn host_has_i64_key(key: i64) -> bool {
    let ctx = match NeoVMSyscall::storage_get_context() {
        Ok(c) => c,
        Err(_) => return false,
    };
    let key_bytes = neovm_i64_bytes(key);
    NeoVMSyscall::storage_try_get(&ctx, &NeoByteString::from_slice(&key_bytes))
        .ok()
        .flatten()
        .map(|stored| !stored.as_slice().is_empty())
        .unwrap_or(false)
}

#[cfg(not(target_arch = "wasm32"))]
fn neovm_i64_bytes(value: i64) -> Vec<u8> {
    if value == 0 {
        return vec![0];
    }

    let mut bytes = value.to_le_bytes().to_vec();
    while bytes.len() > 1 {
        let last = *bytes.last().unwrap_or(&0);
        let prev = bytes[bytes.len() - 2];
        let redundant_positive = last == 0x00 && (prev & 0x80) == 0;
        let redundant_negative = last == 0xff && (prev & 0x80) != 0;
        if redundant_positive || redundant_negative {
            bytes.pop();
        } else {
            break;
        }
    }
    bytes
}

#[cfg(not(target_arch = "wasm32"))]
fn storage_bytes_to_i64(bytes: &[u8]) -> Option<i64> {
    match bytes.len() {
        0 => None,
        1..=8 => {
            let sign_extend = bytes.last().copied().unwrap_or(0) & 0x80 != 0;
            let mut buf = if sign_extend { [0xff; 8] } else { [0u8; 8] };
            buf[..bytes.len()].copy_from_slice(bytes);
            Some(i64::from_le_bytes(buf))
        }
        _ => None,
    }
}