Skip to main content

dpp_plugin_sdk/
codec.rs

1//! Pure glue (host-testable, no linear-memory side effects): JSON
2//! encode/decode between a [`DppSectorPlugin`] and the ABI byte buffers.
3
4use dpp_plugin_traits::{AbiResult, DppSectorPlugin, PluginError, PluginInput};
5use serde::Serialize;
6
7pub(crate) fn to_bytes<T: Serialize>(value: &T) -> Vec<u8> {
8    serde_json::to_vec(value).unwrap_or_default()
9}
10
11fn parse_input(bytes: &[u8]) -> Result<PluginInput, PluginError> {
12    serde_json::from_slice(bytes).map_err(|e| PluginError::InvalidInput(e.to_string()))
13}
14
15/// Serialise the plugin's [`PluginMeta`](dpp_plugin_traits::PluginMeta) to JSON bytes.
16pub fn metadata_bytes<P: DppSectorPlugin>(plugin: &P) -> Vec<u8> {
17    to_bytes(&plugin.meta())
18}
19
20/// Serialise the plugin's [`PluginCapabilities`](dpp_plugin_traits::PluginCapabilities) to JSON bytes.
21pub fn describe_bytes<P: DppSectorPlugin>(plugin: &P) -> Vec<u8> {
22    to_bytes(&plugin.capabilities())
23}
24
25/// Run `validate_input` and serialise the [`AbiResult`] envelope.
26pub fn validate_bytes<P: DppSectorPlugin>(plugin: &P, input: &[u8]) -> Vec<u8> {
27    let outcome = match parse_input(input) {
28        Ok(value) => match plugin.validate_input(&value) {
29            Ok(()) => AbiResult::Ok(serde_json::Value::Null),
30            Err(e) => AbiResult::Error(e),
31        },
32        Err(e) => AbiResult::Error(e),
33    };
34    to_bytes(&outcome)
35}
36
37/// Run `calculate_metrics` and serialise the [`AbiResult`] envelope.
38pub fn calculate_metrics_bytes<P: DppSectorPlugin>(plugin: &P, input: &[u8]) -> Vec<u8> {
39    let outcome = match parse_input(input) {
40        Ok(value) => match plugin.calculate_metrics(&value) {
41            Ok(result) => AbiResult::ok(&result),
42            Err(e) => AbiResult::Error(e),
43        },
44        Err(e) => AbiResult::Error(e),
45    };
46    to_bytes(&outcome)
47}
48
49/// Run `generate_passport` and serialise the [`AbiResult`] envelope.
50pub fn generate_passport_bytes<P: DppSectorPlugin>(plugin: &P, input: &[u8]) -> Vec<u8> {
51    let outcome = match parse_input(input) {
52        Ok(value) => match plugin.generate_passport(&value) {
53            Ok(payload) => AbiResult::Ok(payload),
54            Err(e) => AbiResult::Error(e),
55        },
56        Err(e) => AbiResult::Error(e),
57    };
58    to_bytes(&outcome)
59}