Skip to content
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

Improve base + blockfrost module maintainability #120

Merged
merged 16 commits into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
8894624
UPDATE. including base.py and blockfrost.py in mypy check
daehan-koreapool Nov 3, 2022
142369d
UPDATE. converting dataclass DTOs to have concrete values at all times
daehan-koreapool Nov 3, 2022
ac95e68
REFACTOR. provide all required values for ProtocolParameters in the i…
daehan-koreapool Nov 3, 2022
9386072
ADD. adding ogmios specific integration tests
daehan-koreapool Nov 3, 2022
c9a8ba6
ADD. adding a stub extra_entropy value for FixedChainContext
daehan-koreapool Nov 3, 2022
1f52577
REFACTOR. pulling out JSON type to a dedicated types module
daehan-koreapool Nov 3, 2022
d7112ec
ADD. adding type hints for BlockFrostChainContext attributes
daehan-koreapool Nov 3, 2022
dc27e75
UPDATE. explicitly specifying type information of Blockfrost API's ep…
daehan-koreapool Nov 3, 2022
0f35dd1
ADD. adding min_pool_cost to blockfrost ProtocolParameters instantiation
daehan-koreapool Nov 3, 2022
a6f5485
UPDATE. lovelace_amount variable should be an integer value
daehan-koreapool Nov 3, 2022
713cad9
ADD. adding a nested Nativescript test case before attempting to impr…
daehan-koreapool Nov 4, 2022
8e4ab25
ADD. adding ogmios parsing integration test
daehan-koreapool Nov 4, 2022
782aa40
UPDATE. renaming script_json serializing method name
daehan-koreapool Nov 4, 2022
7373fd1
UPDATE. enforcing immutability for GenesisParameters and ProtocolPara…
daehan-koreapool Nov 4, 2022
345f62d
REFACTOR. renaming JSON type to JsonDict to infer JSON object is repr…
daehan-koreapool Nov 6, 2022
4989531
Merge branch 'main' into refactor-base
daehan-koreapool Nov 6, 2022
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
16 changes: 16 additions & 0 deletions integration-test/test/test_ogmios.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from retry import retry
import pytest

from .base import TEST_RETRIES, TestBase


@pytest.mark.single
class TestProtocolParam(TestBase):
@retry(tries=TEST_RETRIES, backoff=1.5, delay=6, jitter=(0, 4))
def test_protocol_param_cost_models(self):
protocol_param = self.chain_context.protocol_param

cost_models = protocol_param.cost_models
for _, cost_model in cost_models.items():
assert "addInteger-cpu-arguments-intercept" in cost_model
assert "addInteger-cpu-arguments-slope" in cost_model
76 changes: 38 additions & 38 deletions pycardano/backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,86 +23,86 @@
class GenesisParameters:
"""Cardano genesis parameters"""

active_slots_coefficient: float = None
active_slots_coefficient: float

update_quorum: int = None
update_quorum: int

max_lovelace_supply: int = None
max_lovelace_supply: int

network_magic: int = None
network_magic: int

epoch_length: int = None
epoch_length: int

system_start: int = None
system_start: int

slots_per_kes_period: int = None
slots_per_kes_period: int

slot_length: int = None
slot_length: int

max_kes_evolutions: int = None
max_kes_evolutions: int

security_param: int = None
security_param: int


@dataclass
class ProtocolParameters:
"""Cardano protocol parameters"""

min_fee_constant: int = None
min_fee_constant: int

min_fee_coefficient: int = None
min_fee_coefficient: int

max_block_size: int = None
max_block_size: int

max_tx_size: int = None
max_tx_size: int

max_block_header_size: int = None
max_block_header_size: int

key_deposit: int = None
key_deposit: int

pool_deposit: int = None
pool_deposit: int

pool_influence: float = None
pool_influence: float

monetary_expansion: float = None
monetary_expansion: float

treasury_expansion: float = None
treasury_expansion: float

decentralization_param: float = None
decentralization_param: float

extra_entropy: str = None
extra_entropy: str

protocol_major_version: int = None
protocol_major_version: int

protocol_minor_version: int = None
protocol_minor_version: int

min_utxo: int = None
min_utxo: int

min_pool_cost: int = None
min_pool_cost: int

price_mem: float = None
price_mem: float

price_step: float = None
price_step: float

max_tx_ex_mem: int = None
max_tx_ex_mem: int

max_tx_ex_steps: int = None
max_tx_ex_steps: int

max_block_ex_mem: int = None
max_block_ex_mem: int

max_block_ex_steps: int = None
max_block_ex_steps: int

max_val_size: int = None
max_val_size: int

collateral_percent: int = None
collateral_percent: int

max_collateral_inputs: int = None
max_collateral_inputs: int

coins_per_utxo_word: int = None
coins_per_utxo_word: int

coins_per_utxo_byte: int = None
coins_per_utxo_byte: int

cost_models: Dict[str, Dict[str, int]] = None
cost_models: Dict[str, Dict[str, int]]
"""A dict contains cost models for Plutus. The key will be "PlutusV1", "PlutusV2", etc.
The value will be a dict of cost model parameters."""

Expand Down
15 changes: 12 additions & 3 deletions pycardano/backend/blockfrost.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import os
import tempfile
import time
from typing import Dict, List, Union
from typing import Dict, List, Optional, Union

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

from pycardano.address import Address
from pycardano.backend.base import (
Expand Down Expand Up @@ -40,6 +41,12 @@ class BlockFrostChainContext(ChainContext):
network (Network): Network to use.
"""

api: BlockFrostApi
_epoch_info: Namespace
_epoch: Optional[int] = None
_genesis_param: Optional[GenesisParameters] = None
_protocol_param: Optional[ProtocolParameters] = None

def __init__(
self, project_id: str, network: Network = Network.TESTNET, base_url: str = None
):
Expand Down Expand Up @@ -72,7 +79,8 @@ def network(self) -> Network:
@property
def epoch(self) -> int:
if not self._epoch or self._check_epoch_and_update():
self._epoch = self.api.epoch_latest().epoch
new_epoch: int = self.api.epoch_latest().epoch
self._epoch = new_epoch
return self._epoch

@property
Expand Down Expand Up @@ -107,6 +115,7 @@ def protocol_param(self) -> ProtocolParameters:
protocol_major_version=int(params.protocol_major_ver),
protocol_minor_version=int(params.protocol_minor_ver),
min_utxo=int(params.min_utxo),
min_pool_cost=int(params.min_pool_cost),
price_mem=float(params.price_mem),
price_step=float(params.price_step),
max_tx_ex_mem=int(params.max_tx_ex_mem),
Expand Down Expand Up @@ -152,7 +161,7 @@ def utxos(self, address: str) -> List[UTxO]:
[result.tx_hash, result.output_index]
)
amount = result.amount
lovelace_amount = None
daehan-koreapool marked this conversation as resolved.
Show resolved Hide resolved
lovelace_amount = 0
multi_assets = MultiAsset()
for item in amount:
if item.unit == "lovelace":
Expand Down
26 changes: 16 additions & 10 deletions pycardano/backend/ogmios.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,11 @@
UTxO,
Value,
)
from pycardano.types import JSON

__all__ = ["OgmiosChainContext"]


JSON = Dict[str, Any]


class OgmiosQueryType(str, Enum):
Query = "Query"
SubmitTx = "SubmitTx"
Expand Down Expand Up @@ -151,6 +149,7 @@ def _fetch_protocol_param(self) -> ProtocolParameters:
extra_entropy=result.get("extraEntropy", ""),
protocol_major_version=result["protocolVersion"]["major"],
protocol_minor_version=result["protocolVersion"]["minor"],
min_utxo=self._get_min_utxo(),
min_pool_cost=result["minPoolCost"],
price_mem=self._fraction_parser(result["prices"]["memory"]),
price_step=self._fraction_parser(result["prices"]["steps"]),
Expand All @@ -165,17 +164,24 @@ def _fetch_protocol_param(self) -> ProtocolParameters:
"coinsPerUtxoWord", ALONZO_COINS_PER_UTXO_WORD
),
coins_per_utxo_byte=result.get("coinsPerUtxoByte", 0),
cost_models=result.get("costModels", {}),
cost_models=self._parse_cost_models(result),
)

if "plutus:v1" in param.cost_models:
param.cost_models["PlutusV1"] = param.cost_models.pop("plutus:v1")
if "plutus:v2" in param.cost_models:
param.cost_models["PlutusV2"] = param.cost_models.pop("plutus:v2")
return param

def _get_min_utxo(self) -> int:
result = self._query_genesis_config()
param.min_utxo = result["protocolParameters"]["minUtxoValue"]
return param
return result["protocolParameters"]["minUtxoValue"]

def _parse_cost_models(self, ogmios_result: JSON) -> Dict[str, Dict[str, int]]:
ogmios_cost_models = ogmios_result.get("costModels", {})

cost_models = {}
if "plutus:v1" in ogmios_cost_models:
cost_models["PlutusV1"] = ogmios_cost_models["plutus:v1"].copy()
if "plutus:v2" in ogmios_cost_models:
cost_models["PlutusV2"] = ogmios_cost_models["plutus:v2"].copy()
return cost_models

@property
def genesis_param(self) -> GenesisParameters:
Expand Down
3 changes: 3 additions & 0 deletions pycardano/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from typing import Any, Dict

JSON = Dict[str, Any]
daehan-koreapool marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ profile = "black"
ignore_missing_imports = true
python_version = 3.7
exclude = [
'^pycardano/backend/base.py$',
'^pycardano/backend/blockfrost.py$',
'^pycardano/cip/cip8.py$',
'^pycardano/crypto/bech32.py$',
'^pycardano/address.py$',
Expand Down
1 change: 1 addition & 0 deletions test/pycardano/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class FixedChainContext(ChainContext):
treasury_expansion=0.2,
monetary_expansion=0.003,
decentralization_param=0,
extra_entropy="",
protocol_major_version=6,
protocol_minor_version=0,
min_utxo=1000000,
Expand Down