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

Fix mypy warnings. #1

Merged
merged 2 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ Issues = "https://github.com/lightsail-network/stellar-contract-bindings/issues"
CI = "https://github.com/lightsail-network/stellar-contract-bindings/actions"

[dependency-groups]
dev = ["black>=24.10.0", "pytest>=8.3.3"]
dev = [
"black>=24.10.0",
"mypy>=1.13.0",
"pytest>=8.3.3",
]
39 changes: 6 additions & 33 deletions stellar_contract_bindings/cli.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,13 @@
import os

import click
from stellar_sdk import SorobanServer
from stellar_sdk import xdr, Address, StrKey
from stellar_sdk import StrKey

from .python import generate_binding


def get_contract_wasm_by_hash(wasm_hash: bytes, rpc_url: str) -> bytes:
with SorobanServer(rpc_url) as server:
key = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_CODE,
contract_code=xdr.LedgerKeyContractCode(hash=xdr.Hash(wasm_hash)),
)
resp = server.get_ledger_entries([key])
if not resp.entries:
raise ValueError(f"Wasm not found, wasm id: {wasm_hash.hex()}")
data = xdr.LedgerEntryData.from_xdr(resp.entries[0].xdr)
return data.contract_code.code


def get_wasm_hash_by_contract_id(contract_id: str, rpc_url: str) -> bytes:
with SorobanServer(rpc_url) as server:
key = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_id).to_xdr_sc_address(),
key=xdr.SCVal(xdr.SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
durability=xdr.ContractDataDurability.PERSISTENT,
),
)
resp = server.get_ledger_entries([key])
if not resp.entries:
raise ValueError(f"Contract not found, contract id: {contract_id}")
data = xdr.LedgerEntryData.from_xdr(resp.entries[0].xdr)
return data.contract_data.val.instance.executable.wasm_hash.hash
from stellar_contract_bindings.python import generate_binding
from stellar_contract_bindings.utils import (
get_wasm_hash_by_contract_id,
get_contract_wasm_by_hash,
)


@click.group()
Expand Down
6 changes: 3 additions & 3 deletions stellar_contract_bindings/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ def parse_contract_metadata(wasm: Union[bytes, str]) -> ContractMetaData:
for name, content in custom_sections:
if name == "contractenvmetav0":
metadata.env_meta_bytes = content
metadata.env_meta = parse_entries(content, xdr.SCEnvMetaEntry)
metadata.env_meta = parse_entries(content, xdr.SCEnvMetaEntry) # type: ignore[assignment]
if name == "contractspecv0":
metadata.spec_bytes = content
metadata.spec = parse_entries(content, xdr.SCSpecEntry)
metadata.spec = parse_entries(content, xdr.SCSpecEntry) # type: ignore[assignment]
if name == "contractmetav0":
metadata.meta_bytes = content
metadata.meta = parse_entries(content, xdr.SCMetaEntry)
metadata.meta = parse_entries(content, xdr.SCMetaEntry) # type: ignore[assignment]
return metadata


Expand Down
36 changes: 17 additions & 19 deletions stellar_contract_bindings/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def to_py_type(td: xdr.SCSpecTypeDef):
if t == xdr.SCSpecType.SC_SPEC_TYPE_OPTION:
return f"Optional[{to_py_type(td.option.value_type)}]"
if t == xdr.SCSpecType.SC_SPEC_TYPE_RESULT:
t = td.result.ok_type
return to_py_type(t)
ok_t = td.result.ok_type
return to_py_type(ok_t)
if t == xdr.SCSpecType.SC_SPEC_TYPE_VEC:
return f"List[{to_py_type(td.vec.element_type)}]"
if t == xdr.SCSpecType.SC_SPEC_TYPE_MAP:
Expand Down Expand Up @@ -244,8 +244,7 @@ def from_scval(cls, val: xdr.SCVal):
return cls(scval.from_uint32(val))
"""

template = Template(template)
rendered_code = template.render(entry=entry)
rendered_code = Template(template).render(entry=entry)
return rendered_code


Expand All @@ -266,8 +265,7 @@ def from_scval(cls, val: xdr.SCVal):
return cls(scval.from_uint32(val))
"""

template = Template(template)
rendered_code = template.render(entry=entry)
rendered_code = Template(template).render(entry=entry)
return rendered_code


Expand Down Expand Up @@ -311,8 +309,7 @@ def __hash__(self) -> int:
return hash(({% for field in entry.fields %}self.{{ field.name.decode() }}{% if not loop.last %}, {% endif %}{% endfor %}))
"""

template = Template(template)
rendered_code = template.render(
rendered_code = Template(template).render(
entry=entry,
to_py_type=to_py_type,
to_scval=to_scval,
Expand Down Expand Up @@ -350,8 +347,7 @@ def __hash__(self) -> int:
return hash(self.value)
"""

template = Template(template)
rendered_code = template.render(
rendered_code = Template(template).render(
entry=entry, to_py_type=to_py_type, to_scval=to_scval, from_scval=from_scval
)
return rendered_code
Expand All @@ -369,8 +365,7 @@ class {{ entry.name.decode() }}Kind(Enum):
{%- endfor %}
"""

kind_enum_template = Template(kind_enum_template)
kind_enum_rendered_code = kind_enum_template.render(entry=entry, xdr=xdr)
kind_enum_rendered_code = Template(kind_enum_template).render(entry=entry, xdr=xdr)

template = """
class {{ entry.name.decode() }}:
Expand Down Expand Up @@ -404,8 +399,10 @@ def to_scval(self) -> xdr.SCVal:
{%- else %}
if self.kind == {{ entry.name.decode() }}Kind.{{ case.tuple_case.name.decode() }}:
{%- if len(case.tuple_case.type) == 1 %}
assert self.{{ camel_to_snake(case.tuple_case.name.decode()) }} is not None
return scval.to_enum(self.kind.name, {{ to_scval(case.tuple_case.type[0], 'self.' ~ camel_to_snake(case.tuple_case.name.decode())) }})
{%- else %}
assert isinstance(self.{{ camel_to_snake(case.tuple_case.name.decode()) }}, tuple)
return scval.to_enum(self.kind.name, [
{%- for t in case.tuple_case.type %}
{{ to_scval(t, 'self.' + camel_to_snake(case.tuple_case.name.decode()) + '[' + loop.index0|string + ']') }}{% if not loop.last %},{% endif %}
Expand All @@ -427,8 +424,10 @@ def from_scval(cls, val: xdr.SCVal):
{%- else %}
if kind == {{ entry.name.decode() }}Kind.{{ case.tuple_case.name.decode() }}:
{%- if len(case.tuple_case.type) == 1 %}
assert elements[1] is not None and isinstance(elements[1], xdr.SCVal)
return cls(kind, {{ camel_to_snake(case.tuple_case.name.decode()) }}={{ from_scval(case.tuple_case.type[0], 'elements[1]') }})
{%- else %}
assert elements[1] is not None and isinstance(elements[1], list)
return cls(kind, {{ camel_to_snake(case.tuple_case.name.decode()) }}=(
{%- for i, t in enumerate(case.tuple_case.type) %}
{{ from_scval(t, 'elements[1][' + loop.index0|string + ']') }}{% if not loop.last %},{% endif %}
Expand Down Expand Up @@ -460,8 +459,7 @@ def __hash__(self) -> int:
{%- endfor %}
return hash(self.kind)
"""
template = Template(template)
union_rendered_code = template.render(
union_rendered_code = Template(template).render(
entry=entry,
to_py_type=to_py_type,
to_scval=to_scval,
Expand All @@ -478,7 +476,7 @@ def render_client(entries: List[xdr.SCSpecFunctionV0]):
template = '''
class Client(ContractClient):
{%- for entry in entries %}
def {{ entry.name.sc_symbol.decode() }}(self, {% for param in entry.inputs %}{{ param.name.decode() }}: {{ to_py_type(param.type) }}, {% endfor %} source: Union[str, MuxedAccount] = NULL_ACCOUNT, signer: Keypair = None, base_fee: int = 100, transaction_timeout: int = 300, submit_timeout: int = 30, simulate: bool = True, restore: bool = True) -> AssembledTransaction[{{ parse_result_type(entry.outputs) }}]:
def {{ entry.name.sc_symbol.decode() }}(self, {% for param in entry.inputs %}{{ param.name.decode() }}: {{ to_py_type(param.type) }}, {% endfor %} source: Union[str, MuxedAccount] = NULL_ACCOUNT, signer: Optional[Keypair] = None, base_fee: int = 100, transaction_timeout: int = 300, submit_timeout: int = 30, simulate: bool = True, restore: bool = True) -> AssembledTransaction[{{ parse_result_type(entry.outputs) }}]:
{%- if entry.doc %}
"""{{ entry.doc.decode() }}"""
{%- endif %}
Expand All @@ -487,7 +485,7 @@ def {{ entry.name.sc_symbol.decode() }}(self, {% for param in entry.inputs %}{{

class ClientAsync(ContractClientAsync):
{%- for entry in entries %}
async def {{ entry.name.sc_symbol.decode() }}(self, {% for param in entry.inputs %}{{ param.name.decode() }}: {{ to_py_type(param.type) }}, {% endfor %} source: Union[str, MuxedAccount] = NULL_ACCOUNT, signer: Keypair = None, base_fee: int = 100, transaction_timeout: int = 300, submit_timeout: int = 30, simulate: bool = True, restore: bool = True) -> AssembledTransactionAsync[{{ parse_result_type(entry.outputs) }}]:
async def {{ entry.name.sc_symbol.decode() }}(self, {% for param in entry.inputs %}{{ param.name.decode() }}: {{ to_py_type(param.type) }}, {% endfor %} source: Union[str, MuxedAccount] = NULL_ACCOUNT, signer: Optional[Keypair] = None, base_fee: int = 100, transaction_timeout: int = 300, submit_timeout: int = 30, simulate: bool = True, restore: bool = True) -> AssembledTransactionAsync[{{ parse_result_type(entry.outputs) }}]:
{%- if entry.doc %}
"""{{ entry.doc.decode() }}"""
{%- endif %}
Expand All @@ -513,8 +511,7 @@ def parse_result_xdr_fn(output: List[xdr.SCSpecTypeDef]):
"Tuple return type is not supported, please report this issue"
)

template = Template(template)
client_rendered_code = template.render(
client_rendered_code = Template(template).render(
entries=entries,
to_py_type=to_py_type,
to_scval=to_scval,
Expand Down Expand Up @@ -549,7 +546,8 @@ def generate_binding(wasm: bytes) -> str:
function_specs: List[xdr.SCSpecFunctionV0] = [
spec.function_v0
for spec in specs
if spec.kind == xdr.SCSpecEntryKind.SC_SPEC_ENTRY_FUNCTION_V0 and not spec.function_v0.name.sc_symbol.decode().startswith("__")
if spec.kind == xdr.SCSpecEntryKind.SC_SPEC_ENTRY_FUNCTION_V0
and not spec.function_v0.name.sc_symbol.decode().startswith("__")
]
generated.append(render_client(function_specs))
return "\n".join(generated)
Expand Down
46 changes: 46 additions & 0 deletions stellar_contract_bindings/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from stellar_sdk import SorobanServer
from stellar_sdk import xdr, Address


def get_contract_wasm_by_hash(wasm_hash: bytes, rpc_url: str) -> bytes:
"""Get the contract wasm by wasm hash.

:param wasm_hash: The wasm hash.
:param rpc_url: The Soroban RPC URL.
:return: The contract wasm.
:raises ValueError: If wasm not found.
"""
with SorobanServer(rpc_url) as server:
key = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_CODE,
contract_code=xdr.LedgerKeyContractCode(hash=xdr.Hash(wasm_hash)),
)
resp = server.get_ledger_entries([key])
if not resp.entries:
raise ValueError(f"Wasm not found, wasm id: {wasm_hash.hex()}")
data = xdr.LedgerEntryData.from_xdr(resp.entries[0].xdr)
return data.contract_code.code


def get_wasm_hash_by_contract_id(contract_id: str, rpc_url: str) -> bytes:
"""Get the wasm hash by contract id.

:param contract_id: The contract id.
:param rpc_url: The Soroban RPC URL.
:return: The wasm hash.
:raises ValueError: If contract not found.
"""
with SorobanServer(rpc_url) as server:
key = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_id).to_xdr_sc_address(),
key=xdr.SCVal(xdr.SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
durability=xdr.ContractDataDurability.PERSISTENT,
),
)
resp = server.get_ledger_entries([key])
if not resp.entries:
raise ValueError(f"Contract not found, contract id: {contract_id}")
data = xdr.LedgerEntryData.from_xdr(resp.entries[0].xdr)
return data.contract_data.val.instance.executable.wasm_hash.hash
Loading