neo_devpack/utils.rs
1//! General utility functions for Neo N3 smart contracts.
2
3use neo_types::{NeoByteString, NeoStruct, NeoValue};
4use serde::{Deserialize, Serialize};
5use serde_json::{self, Value as JsonValue};
6
7/// Deserializes a NeoByteString as JSON.
8///
9/// # Type Parameters
10/// * `T` - The target type for deserialization
11///
12/// # Returns
13/// * `Some(T)` if deserialization succeeds
14/// * `None` if the bytes are not valid JSON for the target type
15pub fn bytes_to_json<T: for<'de> Deserialize<'de>>(bytes: &NeoByteString) -> Option<T> {
16 serde_json::from_slice(bytes.as_slice()).ok()
17}
18
19/// Serializes a value to JSON and returns it as a NeoByteString.
20///
21/// # Type Parameters
22/// * `T` - The type to serialize
23///
24/// # Returns
25/// A NeoByteString containing the JSON, or an empty byte string on error.
26pub fn json_to_bytes<T: Serialize>(value: &T) -> NeoByteString {
27 match serde_json::to_vec(value) {
28 Ok(data) => NeoByteString::from_slice(&data),
29 Err(_) => NeoByteString::new(Vec::new()),
30 }
31}
32
33/// Creates a storage entry struct with key and value fields.
34///
35/// This is a convenience function for creating the standard storage
36/// entry format used by Neo N3 storage find operations.
37pub fn storage_struct(key: &NeoByteString, value: &NeoByteString) -> NeoValue {
38 let mut entry = NeoStruct::new();
39 entry.set_field("key", NeoValue::from(key.clone()));
40 entry.set_field("value", NeoValue::from(value.clone()));
41 NeoValue::from(entry)
42}
43
44/// Extracts JSON from a NeoValue containing a ByteString.
45///
46/// # Returns
47/// * `Some(JsonValue)` if the value is a ByteString containing valid JSON
48/// * `None` otherwise
49pub fn json_from_value(value: &NeoValue) -> Option<JsonValue> {
50 value
51 .as_byte_string()
52 .and_then(|bytes| serde_json::from_slice(bytes.as_slice()).ok())
53}