partner_chains_plutus_data/
governed_map.rs

1//! Plutus data types for governed map.
2use crate::{DataDecodingError, DecodingResult, decoding_error_and_log};
3use cardano_serialization_lib::{PlutusData, PlutusList};
4use sidechain_domain::byte_string::ByteString;
5
6#[derive(Clone, Debug, PartialEq)]
7/// Datum for governed map entries
8pub struct GovernedMapDatum {
9	/// Governed map entry key.
10	pub key: String,
11	/// Governed map entry value.
12	pub value: ByteString,
13}
14
15impl GovernedMapDatum {
16	/// Constructor for [GovernedMapDatum]
17	pub fn new(key: String, value: ByteString) -> Self {
18		Self { key, value }
19	}
20}
21
22impl TryFrom<PlutusData> for GovernedMapDatum {
23	type Error = DataDecodingError;
24	fn try_from(datum: PlutusData) -> DecodingResult<Self> {
25		let error = || {
26			decoding_error_and_log(&datum, "GovernedMapDatum", "Expected List([UTF8String, Bytes])")
27		};
28
29		datum
30			.as_list()
31			.and_then(|list| {
32				list.get(0)
33					.as_bytes()
34					.and_then(|key| String::from_utf8(key).ok().map(|key| (list, key)))
35			})
36			.and_then(|(list, key)| list.get(1).as_bytes().map(|value| (key, value)))
37			.ok_or_else(error)
38			.map(|(key, value)| Self { key, value: value.into() })
39	}
40}
41
42/// Converts [GovernedMapDatum] to [PlutusData].
43pub fn governed_map_datum_to_plutus_data(governed_map_datum: &GovernedMapDatum) -> PlutusData {
44	let mut list = PlutusList::new();
45	list.add(&PlutusData::new_bytes(governed_map_datum.key.as_bytes().to_vec()));
46	list.add(&PlutusData::new_bytes(governed_map_datum.value.0.clone()));
47	PlutusData::new_list(&list)
48}
49
50impl From<GovernedMapDatum> for PlutusData {
51	fn from(governed_map_datum: GovernedMapDatum) -> Self {
52		governed_map_datum_to_plutus_data(&governed_map_datum)
53	}
54}
55
56#[cfg(test)]
57mod tests {
58	use super::*;
59	use crate::test_helpers::*;
60	use hex_literal::hex;
61	use pretty_assertions::assert_eq;
62
63	#[test]
64	fn governed_map_from_plutus_data() {
65		let plutus_data = test_plutus_data!({"list": [{"bytes": "6b6579"}, {"bytes": "ddeeff"}]});
66
67		let expected_datum =
68			GovernedMapDatum { key: "key".to_string(), value: hex!("ddeeff").to_vec().into() };
69
70		assert_eq!(GovernedMapDatum::try_from(plutus_data).unwrap(), expected_datum)
71	}
72
73	#[test]
74	fn governed_map_to_plutus_data() {
75		let governed_map_datum =
76			GovernedMapDatum { key: "key".to_string(), value: hex!("ddeeff").to_vec().into() };
77
78		let expected_plutus_data = json_to_plutus_data(datum_json());
79
80		assert_eq!(governed_map_datum_to_plutus_data(&governed_map_datum), expected_plutus_data)
81	}
82
83	fn datum_json() -> serde_json::Value {
84		serde_json::json!({
85			"list": [
86				{ "bytes": "6b6579" },
87				{ "bytes": "ddeeff" },
88			]
89		})
90	}
91}