Struct cardano_serialization_lib::plutus::PlutusData
source · pub struct PlutusData { /* private fields */ }
Implementations§
source§impl PlutusData
impl PlutusData
sourcepub fn to_bytes(&self) -> Vec<u8>
pub fn to_bytes(&self) -> Vec<u8>
Examples found in repository?
More examples
src/serialization.rs (line 1003)
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
fn serialize<'a, W: Write + Sized>(
&self,
serializer: &'a mut Serializer<W>,
) -> cbor_event::Result<&'a mut Serializer<W>> {
serializer.write_array(cbor_event::Len::Len(2))?;
match &self {
DataOption::DataHash(data_hash) => {
serializer.write_unsigned_integer(0)?;
data_hash.serialize(serializer)?;
}
DataOption::Data(data) => {
serializer.write_unsigned_integer(1)?;
let bytes = data.to_bytes();
serializer.write_tag(24)?.write_bytes(&bytes)?;
}
}
Ok(serializer)
}
source§impl PlutusData
impl PlutusData
pub fn from_bytes(bytes: Vec<u8>) -> Result<PlutusData, DeserializeError>
source§impl PlutusData
impl PlutusData
pub fn from_hex(hex_str: &str) -> Result<PlutusData, DeserializeError>
source§impl PlutusData
impl PlutusData
sourcepub fn new_constr_plutus_data(constr_plutus_data: &ConstrPlutusData) -> Self
pub fn new_constr_plutus_data(constr_plutus_data: &ConstrPlutusData) -> Self
Examples found in repository?
src/plutus.rs (line 639)
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
pub fn new_empty_constr_plutus_data(alternative: &BigNum) -> Self {
Self::new_constr_plutus_data(&ConstrPlutusData::new(alternative, &PlutusList::new()))
}
pub fn new_map(map: &PlutusMap) -> Self {
Self {
datum: PlutusDataEnum::Map(map.clone()),
original_bytes: None,
}
}
pub fn new_list(list: &PlutusList) -> Self {
Self {
datum: PlutusDataEnum::List(list.clone()),
original_bytes: None,
}
}
pub fn new_integer(integer: &BigInt) -> Self {
Self {
datum: PlutusDataEnum::Integer(integer.clone()),
original_bytes: None,
}
}
pub fn new_bytes(bytes: Vec<u8>) -> Self {
Self {
datum: PlutusDataEnum::Bytes(bytes),
original_bytes: None,
}
}
pub fn kind(&self) -> PlutusDataKind {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(_) => PlutusDataKind::ConstrPlutusData,
PlutusDataEnum::Map(_) => PlutusDataKind::Map,
PlutusDataEnum::List(_) => PlutusDataKind::List,
PlutusDataEnum::Integer(_) => PlutusDataKind::Integer,
PlutusDataEnum::Bytes(_) => PlutusDataKind::Bytes,
}
}
pub fn as_constr_plutus_data(&self) -> Option<ConstrPlutusData> {
match &self.datum {
PlutusDataEnum::ConstrPlutusData(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_map(&self) -> Option<PlutusMap> {
match &self.datum {
PlutusDataEnum::Map(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_list(&self) -> Option<PlutusList> {
match &self.datum {
PlutusDataEnum::List(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_integer(&self) -> Option<BigInt> {
match &self.datum {
PlutusDataEnum::Integer(x) => Some(x.clone()),
_ => None,
}
}
pub fn as_bytes(&self) -> Option<Vec<u8>> {
match &self.datum {
PlutusDataEnum::Bytes(x) => Some(x.clone()),
_ => None,
}
}
pub fn to_json(&self, schema: PlutusDatumSchema) -> Result<String, JsError> {
decode_plutus_datum_to_json_str(self, schema)
}
pub fn from_json(json: &str, schema: PlutusDatumSchema) -> Result<PlutusData, JsError> {
encode_json_str_to_plutus_datum(json, schema)
}
}
//TODO: replace this by cardano-node schemas
impl JsonSchema for PlutusData {
fn is_referenceable() -> bool {
String::is_referenceable()
}
fn schema_name() -> String {
String::from("PlutusData")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
}
//TODO: need to figure out what schema to use here
impl serde::Serialize for PlutusData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer {
let json = decode_plutus_datum_to_json_str(
self,
PlutusDatumSchema::DetailedSchema)
.map_err(|ser_err| serde::ser::Error::custom(&format!("Serialization error: {:?}", ser_err)))?;
serializer.serialize_str(&json)
}
}
impl <'de> serde::de::Deserialize<'de> for PlutusData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: serde::de::Deserializer<'de> {
let datum_json = <String as serde::Deserialize>::deserialize(deserializer)?;
encode_json_str_to_plutus_datum(&datum_json, PlutusDatumSchema::DetailedSchema)
.map_err(|ser_err| serde::de::Error::custom(&format!("Deserialization error: {:?}", ser_err)))
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Ord, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct PlutusList {
elems: Vec<PlutusData>,
// We should always preserve the original datums when deserialized as this is NOT canonicized
// before computing datum hashes. This field will default to cardano-cli behavior if None
// and will re-use the provided one if deserialized, unless the list is modified.
pub(crate) definite_encoding: Option<bool>,
}
impl std::cmp::PartialEq<Self> for PlutusList {
fn eq(&self, other: &Self) -> bool {
self.elems.eq(&other.elems)
}
}
impl std::cmp::Eq for PlutusList {}
to_from_bytes!(PlutusList);
#[wasm_bindgen]
impl PlutusList {
pub fn new() -> Self {
Self {
elems: Vec::new(),
definite_encoding: None,
}
}
pub fn len(&self) -> usize {
self.elems.len()
}
pub fn get(&self, index: usize) -> PlutusData {
self.elems[index].clone()
}
pub fn add(&mut self, elem: &PlutusData) {
self.elems.push(elem.clone());
self.definite_encoding = None;
}
}
impl From<Vec<PlutusData>> for PlutusList {
fn from(elems: Vec<PlutusData>) -> Self {
Self {
elems,
definite_encoding: None,
}
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct Redeemer {
tag: RedeemerTag,
index: BigNum,
data: PlutusData,
ex_units: ExUnits,
}
impl_to_from!(Redeemer);
#[wasm_bindgen]
impl Redeemer {
pub fn tag(&self) -> RedeemerTag {
self.tag.clone()
}
pub fn index(&self) -> BigNum {
self.index.clone()
}
pub fn data(&self) -> PlutusData {
self.data.clone()
}
pub fn ex_units(&self) -> ExUnits {
self.ex_units.clone()
}
pub fn new(tag: &RedeemerTag, index: &BigNum, data: &PlutusData, ex_units: &ExUnits) -> Self {
Self {
tag: tag.clone(),
index: index.clone(),
data: data.clone(),
ex_units: ex_units.clone(),
}
}
pub(crate) fn clone_with_index(&self, index: &BigNum) -> Self {
Self {
tag: self.tag.clone(),
index: index.clone(),
data: self.data.clone(),
ex_units: self.ex_units.clone(),
}
}
}
#[wasm_bindgen]
#[derive(
Copy,
Clone,
Debug,
Eq,
Ord,
PartialEq,
PartialOrd,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub enum RedeemerTagKind {
Spend,
Mint,
Cert,
Reward,
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct RedeemerTag(RedeemerTagKind);
impl_to_from!(RedeemerTag);
#[wasm_bindgen]
impl RedeemerTag {
pub fn new_spend() -> Self {
Self(RedeemerTagKind::Spend)
}
pub fn new_mint() -> Self {
Self(RedeemerTagKind::Mint)
}
pub fn new_cert() -> Self {
Self(RedeemerTagKind::Cert)
}
pub fn new_reward() -> Self {
Self(RedeemerTagKind::Reward)
}
pub fn kind(&self) -> RedeemerTagKind {
self.0
}
}
#[wasm_bindgen]
#[derive(
Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize, JsonSchema,
)]
pub struct Redeemers(pub(crate) Vec<Redeemer>);
impl_to_from!(Redeemers);
#[wasm_bindgen]
impl Redeemers {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Redeemer {
self.0[index].clone()
}
pub fn add(&mut self, elem: &Redeemer) {
self.0.push(elem.clone());
}
pub fn total_ex_units(&self) -> Result<ExUnits, JsError> {
let mut tot_mem = BigNum::zero();
let mut tot_steps = BigNum::zero();
for i in 0..self.0.len() {
let r: &Redeemer = &self.0[i];
tot_mem = tot_mem.checked_add(&r.ex_units().mem())?;
tot_steps = tot_steps.checked_add(&r.ex_units().steps())?;
}
Ok(ExUnits::new(&tot_mem, &tot_steps))
}
}
impl From<Vec<Redeemer>> for Redeemers {
fn from(values: Vec<Redeemer>) -> Self {
Self(values)
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Strings(Vec<String>);
#[wasm_bindgen]
impl Strings {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> String {
self.0[index].clone()
}
pub fn add(&mut self, elem: String) {
self.0.push(elem);
}
}
// json
/// JSON <-> PlutusData conversion schemas.
/// Follows ScriptDataJsonSchema in cardano-cli defined at:
/// https://github.com/input-output-hk/cardano-node/blob/master/cardano-api/src/Cardano/Api/ScriptData.hs#L254
///
/// All methods here have the following restrictions due to limitations on dependencies:
/// * JSON numbers above u64::MAX (positive) or below i64::MIN (negative) will throw errors
/// * Hex strings for bytes don't accept odd-length (half-byte) strings.
/// cardano-cli seems to support these however but it seems to be different than just 0-padding
/// on either side when tested so proceed with caution
#[wasm_bindgen]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PlutusDatumSchema {
/// ScriptDataJsonNoSchema in cardano-node.
///
/// This is the format used by --script-data-value in cardano-cli
/// This tries to accept most JSON but does not support the full spectrum of Plutus datums.
/// From JSON:
/// * null/true/false/floats NOT supported
/// * strings starting with 0x are treated as hex bytes. All other strings are encoded as their utf8 bytes.
/// To JSON:
/// * ConstrPlutusData not supported in ANY FORM (neither keys nor values)
/// * Lists not supported in keys
/// * Maps not supported in keys
////
BasicConversions,
/// ScriptDataJsonDetailedSchema in cardano-node.
///
/// This is the format used by --script-data-file in cardano-cli
/// This covers almost all (only minor exceptions) Plutus datums, but the JSON must conform to a strict schema.
/// The schema specifies that ALL keys and ALL values must be contained in a JSON map with 2 cases:
/// 1. For ConstrPlutusData there must be two fields "constructor" contianing a number and "fields" containing its fields
/// e.g. { "constructor": 2, "fields": [{"int": 2}, {"list": [{"bytes": "CAFEF00D"}]}]}
/// 2. For all other cases there must be only one field named "int", "bytes", "list" or "map"
/// Integer's value is a JSON number e.g. {"int": 100}
/// Bytes' value is a hex string representing the bytes WITHOUT any prefix e.g. {"bytes": "CAFEF00D"}
/// Lists' value is a JSON list of its elements encoded via the same schema e.g. {"list": [{"bytes": "CAFEF00D"}]}
/// Maps' value is a JSON list of objects, one for each key-value pair in the map, with keys "k" and "v"
/// respectively with their values being the plutus datum encoded via this same schema
/// e.g. {"map": [
/// {"k": {"int": 2}, "v": {"int": 5}},
/// {"k": {"map": [{"k": {"list": [{"int": 1}]}, "v": {"bytes": "FF03"}}]}, "v": {"list": []}}
/// ]}
/// From JSON:
/// * null/true/false/floats NOT supported
/// * the JSON must conform to a very specific schema
/// To JSON:
/// * all Plutus datums should be fully supported outside of the integer range limitations outlined above.
////
DetailedSchema,
}
#[wasm_bindgen]
pub fn encode_json_str_to_plutus_datum(
json: &str,
schema: PlutusDatumSchema,
) -> Result<PlutusData, JsError> {
let value = serde_json::from_str(json).map_err(|e| JsError::from_str(&e.to_string()))?;
encode_json_value_to_plutus_datum(value, schema)
}
pub fn encode_json_value_to_plutus_datum(
value: serde_json::Value,
schema: PlutusDatumSchema,
) -> Result<PlutusData, JsError> {
use serde_json::Value;
fn encode_number(x: serde_json::Number) -> Result<PlutusData, JsError> {
if let Some(x) = x.as_u64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else if let Some(x) = x.as_i64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else {
Err(JsError::from_str("floats not allowed in plutus datums"))
}
}
fn encode_string(
s: &str,
schema: PlutusDatumSchema,
is_key: bool,
) -> Result<PlutusData, JsError> {
if schema == PlutusDatumSchema::BasicConversions {
if s.starts_with("0x") {
// this must be a valid hex bytestring after
hex::decode(&s[2..])
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|err| JsError::from_str(&format!("Error decoding {}: {}", s, err)))
} else if is_key {
// try as an integer
BigInt::from_str(s)
.map(|x| PlutusData::new_integer(&x))
// if not, we use the utf8 bytes of the string instead directly
.or_else(|_err| Ok(PlutusData::new_bytes(s.as_bytes().to_vec())))
} else {
// can only be UTF bytes if not in a key and not prefixed by 0x
Ok(PlutusData::new_bytes(s.as_bytes().to_vec()))
}
} else {
if s.starts_with("0x") {
Err(JsError::from_str("Hex byte strings in detailed schema should NOT start with 0x and should just contain the hex characters"))
} else {
hex::decode(s)
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|e| JsError::from_str(&e.to_string()))
}
}
}
fn encode_array(
json_arr: Vec<Value>,
schema: PlutusDatumSchema,
) -> Result<PlutusData, JsError> {
let mut arr = PlutusList::new();
for value in json_arr {
arr.add(&encode_json_value_to_plutus_datum(value, schema)?);
}
Ok(PlutusData::new_list(&arr))
}
match schema {
PlutusDatumSchema::BasicConversions => match value {
Value::Null => Err(JsError::from_str("null not allowed in plutus datums")),
Value::Bool(_) => Err(JsError::from_str("bools not allowed in plutus datums")),
Value::Number(x) => encode_number(x),
// no strings in plutus so it's all bytes (as hex or utf8 printable)
Value::String(s) => encode_string(&s, schema, false),
Value::Array(json_arr) => encode_array(json_arr, schema),
Value::Object(json_obj) => {
let mut map = PlutusMap::new();
for (raw_key, raw_value) in json_obj {
let key = encode_string(&raw_key, schema, true)?;
let value = encode_json_value_to_plutus_datum(raw_value, schema)?;
map.insert(&key, &value);
}
Ok(PlutusData::new_map(&map))
}
},
PlutusDatumSchema::DetailedSchema => match value {
Value::Object(obj) => {
if obj.len() == 1 {
// all variants except tagged constructors
let (k, v) = obj.into_iter().next().unwrap();
fn tag_mismatch() -> JsError {
JsError::from_str("key does not match type")
}
match k.as_str() {
"int" => match v {
Value::Number(x) => encode_number(x),
_ => Err(tag_mismatch()),
},
"bytes" => {
encode_string(v.as_str().ok_or_else(tag_mismatch)?, schema, false)
}
"list" => {
encode_array(v.as_array().ok_or_else(tag_mismatch)?.clone(), schema)
}
"map" => {
let mut map = PlutusMap::new();
fn map_entry_err() -> JsError {
JsError::from_str("entry format in detailed schema map object not correct. Needs to be of form {\"k\": {\"key_type\": key}, \"v\": {\"value_type\", value}}")
}
for entry in v.as_array().ok_or_else(tag_mismatch)? {
let entry_obj = entry.as_object().ok_or_else(map_entry_err)?;
let raw_key = entry_obj.get("k").ok_or_else(map_entry_err)?;
let value = entry_obj.get("v").ok_or_else(map_entry_err)?;
let key =
encode_json_value_to_plutus_datum(raw_key.clone(), schema)?;
map.insert(
&key,
&encode_json_value_to_plutus_datum(value.clone(), schema)?,
);
}
Ok(PlutusData::new_map(&map))
}
invalid_key => Err(JsError::from_str(&format!(
"key '{}' in tagged object not valid",
invalid_key
))),
}
} else {
// constructor with tagged variant
if obj.len() != 2 {
return Err(JsError::from_str("detailed schemas must either have only one of the following keys: \"int\", \"bytes\", \"list\" or \"map\", or both of these 2 keys: \"constructor\" + \"fields\""));
}
let variant: BigNum = obj
.get("constructor")
.and_then(|v| Some(to_bignum(v.as_u64()?)))
.ok_or_else(|| JsError::from_str("tagged constructors must contain an unsigned integer called \"constructor\""))?;
let fields_json =
obj.get("fields")
.and_then(|f| f.as_array())
.ok_or_else(|| {
JsError::from_str(
"tagged constructors must contian a list called \"fields\"",
)
})?;
let mut fields = PlutusList::new();
for field_json in fields_json {
let field = encode_json_value_to_plutus_datum(field_json.clone(), schema)?;
fields.add(&field);
}
Ok(PlutusData::new_constr_plutus_data(&ConstrPlutusData::new(
&variant, &fields,
)))
}
}
_ => Err(JsError::from_str(&format!(
"DetailedSchema requires ALL JSON to be tagged objects, found: {}",
value
))),
},
}
}
sourcepub fn new_empty_constr_plutus_data(alternative: &BigNum) -> Self
pub fn new_empty_constr_plutus_data(alternative: &BigNum) -> Self
Same as .new_constr_plutus_data
but creates constr with empty data list
sourcepub fn new_map(map: &PlutusMap) -> Self
pub fn new_map(map: &PlutusMap) -> Self
Examples found in repository?
src/plutus.rs (line 1112)
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
pub fn encode_json_value_to_plutus_datum(
value: serde_json::Value,
schema: PlutusDatumSchema,
) -> Result<PlutusData, JsError> {
use serde_json::Value;
fn encode_number(x: serde_json::Number) -> Result<PlutusData, JsError> {
if let Some(x) = x.as_u64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else if let Some(x) = x.as_i64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else {
Err(JsError::from_str("floats not allowed in plutus datums"))
}
}
fn encode_string(
s: &str,
schema: PlutusDatumSchema,
is_key: bool,
) -> Result<PlutusData, JsError> {
if schema == PlutusDatumSchema::BasicConversions {
if s.starts_with("0x") {
// this must be a valid hex bytestring after
hex::decode(&s[2..])
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|err| JsError::from_str(&format!("Error decoding {}: {}", s, err)))
} else if is_key {
// try as an integer
BigInt::from_str(s)
.map(|x| PlutusData::new_integer(&x))
// if not, we use the utf8 bytes of the string instead directly
.or_else(|_err| Ok(PlutusData::new_bytes(s.as_bytes().to_vec())))
} else {
// can only be UTF bytes if not in a key and not prefixed by 0x
Ok(PlutusData::new_bytes(s.as_bytes().to_vec()))
}
} else {
if s.starts_with("0x") {
Err(JsError::from_str("Hex byte strings in detailed schema should NOT start with 0x and should just contain the hex characters"))
} else {
hex::decode(s)
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|e| JsError::from_str(&e.to_string()))
}
}
}
fn encode_array(
json_arr: Vec<Value>,
schema: PlutusDatumSchema,
) -> Result<PlutusData, JsError> {
let mut arr = PlutusList::new();
for value in json_arr {
arr.add(&encode_json_value_to_plutus_datum(value, schema)?);
}
Ok(PlutusData::new_list(&arr))
}
match schema {
PlutusDatumSchema::BasicConversions => match value {
Value::Null => Err(JsError::from_str("null not allowed in plutus datums")),
Value::Bool(_) => Err(JsError::from_str("bools not allowed in plutus datums")),
Value::Number(x) => encode_number(x),
// no strings in plutus so it's all bytes (as hex or utf8 printable)
Value::String(s) => encode_string(&s, schema, false),
Value::Array(json_arr) => encode_array(json_arr, schema),
Value::Object(json_obj) => {
let mut map = PlutusMap::new();
for (raw_key, raw_value) in json_obj {
let key = encode_string(&raw_key, schema, true)?;
let value = encode_json_value_to_plutus_datum(raw_value, schema)?;
map.insert(&key, &value);
}
Ok(PlutusData::new_map(&map))
}
},
PlutusDatumSchema::DetailedSchema => match value {
Value::Object(obj) => {
if obj.len() == 1 {
// all variants except tagged constructors
let (k, v) = obj.into_iter().next().unwrap();
fn tag_mismatch() -> JsError {
JsError::from_str("key does not match type")
}
match k.as_str() {
"int" => match v {
Value::Number(x) => encode_number(x),
_ => Err(tag_mismatch()),
},
"bytes" => {
encode_string(v.as_str().ok_or_else(tag_mismatch)?, schema, false)
}
"list" => {
encode_array(v.as_array().ok_or_else(tag_mismatch)?.clone(), schema)
}
"map" => {
let mut map = PlutusMap::new();
fn map_entry_err() -> JsError {
JsError::from_str("entry format in detailed schema map object not correct. Needs to be of form {\"k\": {\"key_type\": key}, \"v\": {\"value_type\", value}}")
}
for entry in v.as_array().ok_or_else(tag_mismatch)? {
let entry_obj = entry.as_object().ok_or_else(map_entry_err)?;
let raw_key = entry_obj.get("k").ok_or_else(map_entry_err)?;
let value = entry_obj.get("v").ok_or_else(map_entry_err)?;
let key =
encode_json_value_to_plutus_datum(raw_key.clone(), schema)?;
map.insert(
&key,
&encode_json_value_to_plutus_datum(value.clone(), schema)?,
);
}
Ok(PlutusData::new_map(&map))
}
invalid_key => Err(JsError::from_str(&format!(
"key '{}' in tagged object not valid",
invalid_key
))),
}
} else {
// constructor with tagged variant
if obj.len() != 2 {
return Err(JsError::from_str("detailed schemas must either have only one of the following keys: \"int\", \"bytes\", \"list\" or \"map\", or both of these 2 keys: \"constructor\" + \"fields\""));
}
let variant: BigNum = obj
.get("constructor")
.and_then(|v| Some(to_bignum(v.as_u64()?)))
.ok_or_else(|| JsError::from_str("tagged constructors must contain an unsigned integer called \"constructor\""))?;
let fields_json =
obj.get("fields")
.and_then(|f| f.as_array())
.ok_or_else(|| {
JsError::from_str(
"tagged constructors must contian a list called \"fields\"",
)
})?;
let mut fields = PlutusList::new();
for field_json in fields_json {
let field = encode_json_value_to_plutus_datum(field_json.clone(), schema)?;
fields.add(&field);
}
Ok(PlutusData::new_constr_plutus_data(&ConstrPlutusData::new(
&variant, &fields,
)))
}
}
_ => Err(JsError::from_str(&format!(
"DetailedSchema requires ALL JSON to be tagged objects, found: {}",
value
))),
},
}
}
sourcepub fn new_list(list: &PlutusList) -> Self
pub fn new_list(list: &PlutusList) -> Self
sourcepub fn new_integer(integer: &BigInt) -> Self
pub fn new_integer(integer: &BigInt) -> Self
Examples found in repository?
src/plutus.rs (line 1049)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
fn encode_number(x: serde_json::Number) -> Result<PlutusData, JsError> {
if let Some(x) = x.as_u64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else if let Some(x) = x.as_i64() {
Ok(PlutusData::new_integer(&BigInt::from(x)))
} else {
Err(JsError::from_str("floats not allowed in plutus datums"))
}
}
fn encode_string(
s: &str,
schema: PlutusDatumSchema,
is_key: bool,
) -> Result<PlutusData, JsError> {
if schema == PlutusDatumSchema::BasicConversions {
if s.starts_with("0x") {
// this must be a valid hex bytestring after
hex::decode(&s[2..])
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|err| JsError::from_str(&format!("Error decoding {}: {}", s, err)))
} else if is_key {
// try as an integer
BigInt::from_str(s)
.map(|x| PlutusData::new_integer(&x))
// if not, we use the utf8 bytes of the string instead directly
.or_else(|_err| Ok(PlutusData::new_bytes(s.as_bytes().to_vec())))
} else {
// can only be UTF bytes if not in a key and not prefixed by 0x
Ok(PlutusData::new_bytes(s.as_bytes().to_vec()))
}
} else {
if s.starts_with("0x") {
Err(JsError::from_str("Hex byte strings in detailed schema should NOT start with 0x and should just contain the hex characters"))
} else {
hex::decode(s)
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|e| JsError::from_str(&e.to_string()))
}
}
}
sourcepub fn new_bytes(bytes: Vec<u8>) -> Self
pub fn new_bytes(bytes: Vec<u8>) -> Self
Examples found in repository?
src/plutus.rs (line 1065)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
fn encode_string(
s: &str,
schema: PlutusDatumSchema,
is_key: bool,
) -> Result<PlutusData, JsError> {
if schema == PlutusDatumSchema::BasicConversions {
if s.starts_with("0x") {
// this must be a valid hex bytestring after
hex::decode(&s[2..])
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|err| JsError::from_str(&format!("Error decoding {}: {}", s, err)))
} else if is_key {
// try as an integer
BigInt::from_str(s)
.map(|x| PlutusData::new_integer(&x))
// if not, we use the utf8 bytes of the string instead directly
.or_else(|_err| Ok(PlutusData::new_bytes(s.as_bytes().to_vec())))
} else {
// can only be UTF bytes if not in a key and not prefixed by 0x
Ok(PlutusData::new_bytes(s.as_bytes().to_vec()))
}
} else {
if s.starts_with("0x") {
Err(JsError::from_str("Hex byte strings in detailed schema should NOT start with 0x and should just contain the hex characters"))
} else {
hex::decode(s)
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|e| JsError::from_str(&e.to_string()))
}
}
}
pub fn kind(&self) -> PlutusDataKind
pub fn as_constr_plutus_data(&self) -> Option<ConstrPlutusData>
pub fn as_map(&self) -> Option<PlutusMap>
pub fn as_list(&self) -> Option<PlutusList>
pub fn as_integer(&self) -> Option<BigInt>
pub fn as_bytes(&self) -> Option<Vec<u8>>
pub fn to_json(&self, schema: PlutusDatumSchema) -> Result<String, JsError>
pub fn from_json(
json: &str,
schema: PlutusDatumSchema
) -> Result<PlutusData, JsError>
Trait Implementations§
source§impl Clone for PlutusData
impl Clone for PlutusData
source§fn clone(&self) -> PlutusData
fn clone(&self) -> PlutusData
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for PlutusData
impl Debug for PlutusData
source§impl<'de> Deserialize<'de> for PlutusData
impl<'de> Deserialize<'de> for PlutusData
source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Deserialize for PlutusData
impl Deserialize for PlutusData
fn deserialize<R: BufRead + Seek>(
raw: &mut Deserializer<R>
) -> Result<Self, DeserializeError>
source§impl JsonSchema for PlutusData
impl JsonSchema for PlutusData
source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
Whether JSON Schemas generated for this type should be re-used where possible using the
$ref
keyword. Read moresource§fn schema_name() -> String
fn schema_name() -> String
The name of the generated JSON Schema. Read more
source§fn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
Generates a JSON Schema for this type. Read more
source§impl Ord for PlutusData
impl Ord for PlutusData
source§fn cmp(&self, other: &PlutusData) -> Ordering
fn cmp(&self, other: &PlutusData) -> Ordering
1.21.0 · source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read more
source§impl PartialEq<PlutusData> for PlutusData
impl PartialEq<PlutusData> for PlutusData
source§impl PartialOrd<PlutusData> for PlutusData
impl PartialOrd<PlutusData> for PlutusData
source§fn partial_cmp(&self, other: &PlutusData) -> Option<Ordering>
fn partial_cmp(&self, other: &PlutusData) -> Option<Ordering>
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read more