Skip to content

Commit 943c39e

Browse files
authored
Load plutus script from json file (#453)
* Load plutus script from json file * fix qa
1 parent 016c2a1 commit 943c39e

File tree

4 files changed

+54
-17
lines changed

4 files changed

+54
-17
lines changed

pycardano/plutus.py

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,25 +1064,52 @@ def plutus_script_hash(script: Union[NativeScript, PlutusScript]) -> ScriptHash:
10641064
return script_hash(script)
10651065

10661066

1067-
class PlutusScript(bytes):
1067+
class PlutusScript(CBORSerializable, bytes):
1068+
"""
1069+
Plutus script class.
1070+
1071+
This class is a base class for all Plutus script versions.
1072+
1073+
Example - Load a Plutus script from `test/resources/scriptV2.plutus <https://github.com/Python-Cardano/pycardano/blob/main/test/resources/scriptV2.plutus>`_ and get its address: # noqa: E501
1074+
1075+
1076+
>>> from pycardano import Address, Network
1077+
>>> script = PlutusV2Script.load("test/resources/scriptV2.plutus")
1078+
>>> Address(plutus_script_hash(script), network=Network.TESTNET).encode()
1079+
'addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym'
1080+
"""
1081+
10681082
@property
10691083
def version(self) -> int:
10701084
raise NotImplementedError("")
10711085

1086+
def to_shallow_primitive(self) -> bytes:
1087+
return bytes(self)
1088+
1089+
@classmethod
1090+
def from_primitive(
1091+
cls: Type[PlutusScript], value: Any, type_args: Optional[tuple] = None
1092+
) -> PlutusScript:
1093+
if not isinstance(value, (bytes, bytearray)):
1094+
raise DeserializeException(f"Expect bytes, got {type(value)} instead.")
1095+
return cls(value)
1096+
10721097
@classmethod
10731098
def from_version(cls, version: int, script_data: bytes) -> "PlutusScript":
1074-
if version == 1:
1075-
return PlutusV1Script(script_data)
1076-
elif version == 2:
1077-
return PlutusV2Script(script_data)
1078-
elif version == 3:
1079-
return PlutusV3Script(script_data)
1080-
else:
1099+
class_name = f"PlutusV{version}Script"
1100+
script_class = globals().get(class_name)
1101+
1102+
if script_class is None:
10811103
raise ValueError(f"No Plutus script class found for version {version}")
10821104

1105+
return script_class(script_data)
1106+
10831107
def get_script_hash_prefix(self) -> bytes:
10841108
raise NotImplementedError("")
10851109

1110+
def __repr__(self):
1111+
return f"{self.__class__.__name__}({self.hex()})"
1112+
10861113

10871114
class PlutusV1Script(PlutusScript):
10881115
def get_script_hash_prefix(self) -> bytes:

pycardano/serialization.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -720,14 +720,6 @@ def _restore_typed_primitive(
720720
if not isinstance(v, bytes):
721721
raise DeserializeException(f"Expected type bytes but got {type(v)}")
722722
return ByteString(v)
723-
elif isclass(t) and t.__name__ in [
724-
"PlutusV1Script",
725-
"PlutusV2Script",
726-
"PlutusV3Script",
727-
]:
728-
if not isinstance(v, bytes):
729-
raise DeserializeException(f"Expected type bytes but got {type(v)}")
730-
return t(v)
731723
elif hasattr(t, "__origin__") and (t.__origin__ is dict):
732724
t_args = t.__args__
733725
if len(t_args) != 2:

test/pycardano/test_plutus.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@
99
import pytest
1010
from cbor2 import CBORTag
1111

12-
from pycardano import TransactionWitnessSet
12+
from pycardano import Address, Network, TransactionWitnessSet
1313
from pycardano.exception import DeserializeException
1414
from pycardano.plutus import (
1515
COST_MODELS,
1616
Datum,
1717
ExecutionUnits,
1818
PlutusData,
19+
PlutusV2Script,
1920
RawPlutusData,
2021
Redeemer,
2122
RedeemerKey,
@@ -593,3 +594,15 @@ def test_empty_map_deser():
593594
serialized = witness.to_primitive()
594595
deserialized = TransactionWitnessSet.from_primitive(serialized)
595596
assert deserialized.redeemer == empty_map
597+
598+
599+
def test_load_plutus_script():
600+
script = PlutusV2Script.load("test/resources/scriptV2.plutus")
601+
assert (
602+
script.to_cbor_hex()
603+
== "581a581801000022232632498cd5ce2481064255524e542100120011"
604+
)
605+
assert (
606+
Address(plutus_script_hash(script), network=Network.TESTNET).encode()
607+
== "addr_test1wrmz3pjz4dmfxj0fc0a0eyw69tp6h7mpndzf9g3kttq9cqqqw47ym"
608+
)

test/resources/scriptV2.plutus

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"type": "PlutusScriptV2",
3+
"description": "",
4+
"cborHex": "581a581801000022232632498cd5ce2481064255524e542100120011"
5+
}

0 commit comments

Comments
 (0)