Skip to content

Commit

Permalink
Fix _get_script in blockfrost context
Browse files Browse the repository at this point in the history
Sometimes script cbor returned from blockfrost needs to be reloaded by cbor again, sometimes not. This fix will handle both cases.
  • Loading branch information
cffls committed Apr 19, 2023
1 parent 1bcf1f1 commit 7e46dcb
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions pycardano/backend/blockfrost.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import warnings
from typing import Dict, List, Optional, Union

import cbor2
from blockfrost import ApiError, ApiUrls, BlockFrostApi
from blockfrost.utils import Namespace

Expand All @@ -18,7 +19,7 @@
from pycardano.hash import SCRIPT_HASH_SIZE, DatumHash, ScriptHash
from pycardano.nativescript import NativeScript
from pycardano.network import Network
from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script
from pycardano.plutus import ExecutionUnits, PlutusV1Script, PlutusV2Script, script_hash
from pycardano.serialization import RawCBOR
from pycardano.transaction import (
Asset,
Expand All @@ -34,6 +35,19 @@
__all__ = ["BlockFrostChainContext"]


def _try_fix_script(
scripth: str, script: Union[PlutusV1Script, PlutusV2Script]
) -> Union[PlutusV1Script, PlutusV2Script]:
if str(script_hash(script)) == scripth:
return script
else:
new_script = script.__class__(cbor2.loads(script))
if str(script_hash(new_script)) == scripth:
return new_script
else:
raise ValueError("Cannot recover script from hash.")


class BlockFrostChainContext(ChainContext):
"""A `BlockFrost <https://blockfrost.io/>`_ API wrapper for the client code to interact with.
Expand Down Expand Up @@ -151,9 +165,15 @@ def _get_script(
) -> Union[PlutusV1Script, PlutusV2Script, NativeScript]:
script_type = self.api.script(script_hash).type
if script_type == "plutusV1":
return PlutusV1Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor))
v1script = PlutusV1Script(
bytes.fromhex(self.api.script_cbor(script_hash).cbor)
)
return _try_fix_script(script_hash, v1script)
elif script_type == "plutusV2":
return PlutusV2Script(bytes.fromhex(self.api.script_cbor(script_hash).cbor))
v2script = PlutusV2Script(
bytes.fromhex(self.api.script_cbor(script_hash).cbor)
)
return _try_fix_script(script_hash, v2script)
else:
script_json: JsonDict = self.api.script_json(
script_hash, return_type="json"
Expand Down

0 comments on commit 7e46dcb

Please sign in to comment.