use cardano_serialization_lib as csl;
use whisky_common::data::PlutusDataJson;
use whisky_common::WError;
pub trait PlutusDataCbor: PlutusDataJson {
fn from_cbor(cbor_hex: &str) -> Result<Self, WError>;
fn to_cbor(&self) -> Result<String, WError>;
}
impl<T: PlutusDataJson> PlutusDataCbor for T {
fn from_cbor(cbor_hex: &str) -> Result<Self, WError> {
let csl_data = csl::PlutusData::from_hex(cbor_hex)
.map_err(WError::from_err("PlutusDataCbor::from_cbor - invalid CBOR hex"))?;
let json_str = csl_data
.to_json(csl::PlutusDatumSchema::DetailedSchema)
.map_err(WError::from_err(
"PlutusDataCbor::from_cbor - failed to convert to JSON",
))?;
let json_value: serde_json::Value = serde_json::from_str(&json_str)
.map_err(WError::from_err("PlutusDataCbor::from_cbor - invalid JSON"))?;
Self::from_json(&json_value)
}
fn to_cbor(&self) -> Result<String, WError> {
let json_str = self.to_json_string();
let csl_data = csl::PlutusData::from_json(&json_str, csl::PlutusDatumSchema::DetailedSchema)
.map_err(WError::from_err("PlutusDataCbor::to_cbor - failed to parse JSON"))?;
Ok(csl_data.to_hex())
}
}