cotyledon 0.1.0

Framework for writing sprouts — sandboxed, event-driven on-chain trading bots.
Documentation
//! Per-sprout key/value storage, persisted by the engine.

use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::{Result, host};

/// A small key/value store scoped to the sprout. Values are JSON-serialized.
pub struct State;

impl State {
    /// Read a value, deserializing it into `T`. `None` if the key is unset.
    pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
        match host::state_get(key).await? {
            Some(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
            None => Ok(None),
        }
    }

    /// Write a value.
    pub async fn set<T: Serialize>(&self, key: &str, value: &T) -> Result<()> {
        host::state_set(key, &serde_json::to_vec(value)?).await
    }
}