Skip to content

Commit 0cf3cc5

Browse files
committed
Add from_json for RawPlutusData
1 parent 26e0dac commit 0cf3cc5

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

pycardano/plutus.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,59 @@ def _dfs(obj):
813813
def from_primitive(cls: Type[RawPlutusData], value: CBORTag) -> RawPlutusData:
814814
return cls(value)
815815

816+
@classmethod
817+
def from_dict(cls: Type[RawPlutusData], data: dict) -> RawPlutusData:
818+
"""Convert a dictionary to RawPlutusData
819+
820+
Args:
821+
data (dict): A dictionary.
822+
823+
Returns:
824+
RawPlutusData: Restored RawPlutusData.
825+
"""
826+
827+
def _dfs(obj):
828+
if isinstance(obj, dict):
829+
if "constructor" in obj:
830+
converted_fields = []
831+
for f in obj["fields"]:
832+
converted_fields.append(_dfs(f))
833+
tag = get_tag(obj["constructor"])
834+
if tag is None:
835+
return CBORTag(102, [obj["constructor"], IndefiniteList(converted_fields)])
836+
else:
837+
return CBORTag(tag, converted_fields)
838+
elif "map" in obj:
839+
return {_dfs(pair["k"]): _dfs(pair["v"]) for pair in obj["map"]}
840+
elif "int" in obj:
841+
return obj["int"]
842+
elif "bytes" in obj:
843+
if len(obj["bytes"]) > 64:
844+
return ByteString(bytes.fromhex(obj["bytes"]))
845+
else:
846+
return bytes.fromhex(obj["bytes"])
847+
elif "list" in obj:
848+
return IndefiniteList([_dfs(item) for item in obj["list"]])
849+
else:
850+
raise DeserializeException(f"Unexpected data structure: {obj}")
851+
else:
852+
raise TypeError(f"Unexpected data type: {type(obj)}")
853+
854+
return cls(_dfs(data))
855+
856+
@classmethod
857+
def from_json(cls: Type[RawPlutusData], data: str) -> RawPlutusData:
858+
"""Restore a json encoded string to a RawPlutusData.
859+
860+
Args:
861+
data (str): An encoded json string.
862+
863+
Returns:
864+
RawPlutusData: The restored RawPlutusData.
865+
"""
866+
obj = json.loads(data)
867+
return cls.from_dict(obj)
868+
816869
def __deepcopy__(self, memo):
817870
return self.__class__.from_cbor(self.to_cbor_hex())
818871

test/pycardano/test_plutus.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,8 @@ def test_raw_plutus_data_json():
217217
beneficiary=key_hash, deadline=deadline, testa=testa, testb=testb
218218
)
219219

220-
encoded_json = RawPlutusData(my_vesting.to_primitive()).to_json(
220+
my_vesting_primitive = my_vesting.to_primitive()
221+
encoded_json = RawPlutusData(my_vesting_primitive).to_json(
221222
separators=(",", ":")
222223
)
223224

@@ -229,7 +230,9 @@ def test_raw_plutus_data_json():
229230
== encoded_json
230231
)
231232

232-
assert my_vesting == VestingParam.from_json(encoded_json)
233+
# note that json encoding is lossy, so we can't compare the original object with the one decoded from json
234+
# but we can compare the jsons
235+
assert encoded_json == RawPlutusData.from_json(encoded_json).to_json(separators=(",", ":"))
233236

234237

235238
def test_plutus_data_hash():

0 commit comments

Comments
 (0)