Skip to content

Fix _get_script in blockfrost context #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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