Crate fvm_mock

source ·
Expand description

fvm-mock is a tool for developer to check contract logical is correct or not locally, which is suit for hyperchain.

Demo contract

use macros::contract;
use macros::storage;
use fvm_std::runtime;
use scale::{Decode, Encode};

#[storage]
pub struct TestHello {}

#[contract]
impl TestHello {
    fn new() -> Self {
        Self {}
    }

    pub fn set(&mut self, key: String, value: String) {
        runtime::storage_write(key.as_bytes(), "test".as_bytes(), value.as_bytes())
    }

    pub fn get(&mut self, key: String) -> Vec<u8> {
        return if let Some(res) = runtime::storage_read(key.as_bytes(), "test".as_bytes()) {
            res
        } else {
            vec![]
        };
    }
}

In order to check locally, we should do as below

  • Add dependency in cargo.toml
[dev-dependencies]
# ... other dependencies
fvm-mock = "xxx"
  • Call build_runtime() in unit test
#[cfg(test)]
mod tests {
    use scale::{Decode, Encode};
    use crate::TestHello;
    use fvm_mock::build_runtime;

    #[test]
    fn test_set() {
        let mut contract = TestHello::new();
        let handle = build_runtime();
        contract.set("hello".to_string(), "world".to_string());
        assert_eq!("world".as_bytes(), contract.get("hello".to_string()).as_slice())
    }

    #[test]
    fn test_get() {
        let mut contract = TestHello::new();
        let handle = build_runtime();
        handle.storage_write("hello", "test", "world");
        assert_eq!("world".as_bytes(), contract.get("hello".to_string()).as_slice())
    }
}

Notice that if you could pass the unit test, it indicates the logical is correct, but can not represent it can run well on the chain. For there are specifications that WASM core not support well, so developer should ensure that you do not use them, such as print to console, file read and so on

Re-exports

pub use self::mock_env::build_runtime;

Modules