Skip to content

Commit 7e46dcb

Browse files
committed
Fix _get_script in blockfrost context
Sometimes script cbor returned from blockfrost needs to be reloaded by cbor again, sometimes not. This fix will handle both cases.
1 parent 1bcf1f1 commit 7e46dcb

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

pycardano/backend/blockfrost.py

+23-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import warnings
55
from typing import Dict, List, Optional, Union
66

7+
import cbor2
78
from blockfrost import ApiError, ApiUrls, BlockFrostApi
89
from blockfrost.utils import Namespace
910

@@ -18,7 +19,7 @@
1819
from pycardano.hash import SCRIPT_HASH_SIZE, DatumHash, ScriptHash
1920
from pycardano.nativescript import NativeScript
2021
from pycardano.network import Network
21-
from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script
22+
from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script, script_hash
2223
from pycardano.serialization import RawCBOR
2324
from pycardano.transaction import (
2425
Asset,
@@ -34,6 +35,19 @@
3435
__all__ = ["BlockFrostChainContext"]
3536

3637

38+
def _try_fix_script(
39+
scripth: str, script: Union[PlutusV1Script, PlutusV2Script]
40+
) -> Union[PlutusV1Script, PlutusV2Script]:
41+
if str(script_hash(script)) == scripth:
42+
return script
43+
else:
44+
new_script = script.__class__(cbor2.loads(script))
45+
if str(script_hash(new_script)) == scripth:
46+
return new_script
47+
else:
48+
raise ValueError("Cannot recover script from hash.")
49+
50+
3751
class BlockFrostChainContext(ChainContext):
3852
"""A `BlockFrost <https://blockfrost.io/>`_ API wrapper for the client code to interact with.
3953
@@ -151,9 +165,15 @@ def _get_script(
151165
) -> Union[PlutusV1Script, PlutusV2Script, NativeScript]:
152166
script_type = self.api.script(script_hash).type
153167
if script_type == "plutusV1":
154-
return PlutusV1Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor))
168+
v1script = PlutusV1Script(
169+
bytes.fromhex(self.api.script_cbor(script_hash).cbor)
170+
)
171+
return _try_fix_script(script_hash, v1script)
155172
elif script_type == "plutusV2":
156-
return PlutusV2Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor))
173+
v2script = PlutusV2Script(
174+
bytes.fromhex(self.api.script_cbor(script_hash).cbor)
175+
)
176+
return _try_fix_script(script_hash, v2script)
157177
else:
158178
script_json: JsonDict = self.api.script_json(
159179
script_hash, return_type="json"

0 commit comments

Comments
 (0)