namada_core/
internal.rs

1//! Shared internal types between the host env and guest (wasm).
2
3use borsh::{BorshDeserialize, BorshSerialize};
4use namada_macros::BorshDeserializer;
5#[cfg(feature = "migrations")]
6use namada_migrations::*;
7
8/// A result of a wasm call to host functions that may fail.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum HostEnvResult {
11    /// A success
12    Success = 1,
13    /// A non-fatal failure does **not** interrupt WASM execution
14    Fail = -1,
15}
16
17/// Key-value pair represents data from account's subspace.
18/// It is used for prefix iterator's WASM host_env functions.
19#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshDeserializer)]
20pub struct KeyVal {
21    /// The storage key
22    pub key: String,
23    /// The value as arbitrary bytes
24    pub val: Vec<u8>,
25}
26
27impl HostEnvResult {
28    /// Convert result to `i64`, which can be passed to wasm
29    pub fn to_i64(self) -> i64 {
30        self as _
31    }
32
33    /// Check if the given result as `i64` is a success
34    pub fn is_success(int: i64) -> bool {
35        int == Self::Success.to_i64()
36    }
37
38    /// Check if the given result as `i64` is a non-fatal failure
39    pub fn is_fail(int: i64) -> bool {
40        int == Self::Fail.to_i64()
41    }
42
43    /// Expect [`HostEnvResult::Success`].
44    pub fn success_or_else<F, E>(int: i64, or_else: F) -> Result<(), E>
45    where
46        F: FnOnce() -> E,
47    {
48        if Self::is_success(int) {
49            Ok(())
50        } else {
51            Err(or_else())
52        }
53    }
54
55    /// Expect [`HostEnvResult::Success`].
56    pub fn success_or<E>(int: i64, or_else: E) -> Result<(), E> {
57        Self::success_or_else(int, || or_else)
58    }
59}
60
61impl From<bool> for HostEnvResult {
62    fn from(success: bool) -> Self {
63        if success { Self::Success } else { Self::Fail }
64    }
65}