Skip to content

Commit

Permalink
More python types (#825)
Browse files Browse the repository at this point in the history
* More python types

* Add BlockBuilderOptions and use dataclass more

* Split Output

* More changelog

* Use correct types

* Update bindings/python/CHANGELOG.md

* Only AliasAddress, changelog

* Only allowed features

* Update doc comments

* Add type hint
  • Loading branch information
Thoralf-M authored Jul 21, 2023
1 parent dab41b4 commit 8b3eaf7
Show file tree
Hide file tree
Showing 22 changed files with 420 additions and 280 deletions.
7 changes: 7 additions & 0 deletions bindings/python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `RegularTransactionEssence`;
- `Unlock` types;
- `PreparedTransactionData, SignedTransactionData, InputSigningData, RemainderData`;
- `UtxoChanges`;
- `TreasuryOutput, BasicOutput, AliasOutput, FoundryOutput, NftOutput`;
- `TokenScheme`;
- `Signature`;
- `BlockBuilderOptions`;

### Changed

Expand All @@ -61,6 +66,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Switched order of `AddressAndAmount` init params;
- Renamed `PreparedTransactionData` to `PreparedTransaction`;
- `{Client, SecretManager}::sign_transaction` return type from `SignedTransactionData` to `TransactionPayload`;
- Split `Output` into multiple classes;
- Renamed `TokenScheme` to `SimpleTokenScheme`;

### Removed

Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/client/build_foundry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# Configure foundry output
# Replace with your own values
serial_number = 1
token_scheme = TokenScheme(32, 0, 64)
token_scheme = SimpleTokenScheme(32, 0, 64)
unlock_conditions = [
ImmutableAliasAddressUnlockCondition(
AliasAddress(
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/examples/client/submit_and_read_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@
# Get the whole block
block = client.get_block_data(block_id)
payload_out = block.payload
tag_hex_out = block.payload['tag']
message_hex_out = block.payload['data']
tag_hex_out = block.payload.tag
message_hex_out = block.payload.data

# Unpackage the payload (from hex to text)
message_out = hex_to_utf8(message_hex_out)
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/examples/how_tos/outputs/unlock_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
Ed25519Address(hex_address)
)

token_scheme = TokenScheme(50, 0, 100)
token_scheme = SimpleTokenScheme(50, 0, 100)

# Most simple output
basic_output = client.build_basic_output(
Expand Down Expand Up @@ -83,4 +83,4 @@
)
outputs.append(foundry_output)

print(json.dumps(outputs, indent=2))
print(json.dumps(list(map(lambda o: o.as_dict(), outputs)), indent=2))
2 changes: 2 additions & 0 deletions bindings/python/iota_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .types.address import *
from .types.balance import *
from .types.block import *
from .types.block_builder_options import *
from .types.burn import *
from .types.client_options import *
from .types.common import *
Expand All @@ -35,3 +36,4 @@
from .types.transaction_options import *
from .types.unlock import *
from .types.unlock_condition import *
from .types.utxo_changes import *
26 changes: 16 additions & 10 deletions bindings/python/iota_sdk/client/_node_core_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from iota_sdk.types.output import OutputWithMetadata, OutputMetadata
from iota_sdk.types.output_id import OutputId
from iota_sdk.types.payload import MilestonePayload
from iota_sdk.types.utxo_changes import UtxoChanges
from typing import List
from dacite import from_dict

Expand Down Expand Up @@ -96,24 +97,29 @@ def post_block_raw(self, block_bytes: List[int]) -> HexStr:
'blockBytes': block_bytes
})

def get_output(self, output_id: OutputId) -> OutputWithMetadata:
def get_output(self, output_id: OutputId | HexStr) -> OutputWithMetadata:
"""Get the output corresponding to the given output id.
Returns:
The output itself with its metadata.
"""
output_id_str = output_id.output_id if isinstance(
output_id, OutputId) else output_id
return from_dict(OutputWithMetadata, self._call_method('getOutput', {
'outputId': output_id
'outputId': output_id_str
}))

def get_output_metadata(self, output_id: OutputId) -> OutputMetadata:
def get_output_metadata(self, output_id: OutputId |
HexStr) -> OutputMetadata:
"""Get the output metadata corresponding to the given output id.
Returns:
The output metadata.
"""
output_id_str = output_id.output_id if isinstance(
output_id, OutputId) else output_id
return from_dict(OutputMetadata, self._call_method('getOutputMetadata', {
'outputId': output_id
'outputId': output_id_str
}))

def get_milestone_by_id(self, milestone_id: HexStr) -> MilestonePayload:
Expand Down Expand Up @@ -158,19 +164,19 @@ def get_milestone_by_index_raw(self, index: int) -> List[int]:
'index': index
})

def get_utxo_changes_by_id(self, milestone_id: HexStr):
def get_utxo_changes_by_id(self, milestone_id: HexStr) -> UtxoChanges:
"""Get the UTXO changes applied in the given milestone.
"""
return self._call_method('getUtxoChangesById', {
return from_dict(UtxoChanges, self._call_method('getUtxoChangesById', {
'milestoneId': milestone_id
})
}))

def get_utxo_changes_by_index(self, index: int):
def get_utxo_changes_by_index(self, index: int) -> UtxoChanges:
"""Get the UTXO changes applied at the given milestone index.
"""
return self._call_method('getUtxoChangesByIndex', {
return from_dict(UtxoChanges, self._call_method('getUtxoChangesByIndex', {
'index': index
})
}))

def get_receipts(self):
"""Get all receipts.
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/iota_sdk/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from iota_sdk.types.network_info import NetworkInfo
from iota_sdk.types.output import Output
from iota_sdk.types.payload import Payload, TransactionPayload
from iota_sdk.types.token_scheme import TokenScheme
from iota_sdk.types.token_scheme import SimpleTokenScheme
from iota_sdk.types.unlock_condition import UnlockCondition
from iota_sdk.types.transaction_data import PreparedTransactionData
from json import dumps, loads
Expand Down Expand Up @@ -265,7 +265,7 @@ def build_basic_output(self,

def build_foundry_output(self,
serial_number: int,
token_scheme: TokenScheme,
token_scheme: SimpleTokenScheme,
unlock_conditions: List[UnlockCondition],
amount: Optional[int] = None,
native_tokens: Optional[List[NativeToken]] = None,
Expand Down
57 changes: 22 additions & 35 deletions bindings/python/iota_sdk/types/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
# SPDX-License-Identifier: Apache-2.0

from iota_sdk.types.common import HexStr
from dataclasses import dataclass
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class AddressType(IntEnum):
Expand All @@ -23,59 +22,47 @@ class AddressType(IntEnum):
@dataclass
class Address():
"""Base class for addresses.
Attributes:
type: The address type.
pubKeyHash: The hex encoded public key hash.
aliasId: The hex encoded alias id.
nftId: The hex encoded nft id.
"""
type: int
pubKeyHash: Optional[HexStr] = None
aliasId: Optional[HexStr] = None
nftId: Optional[HexStr] = None

def as_dict(self):
return {k: v for k, v in self.__dict__.items() if v is not None}


@dataclass
class Ed25519Address(Address):
"""Represents an Ed25519 address.
Attributes:
pubKeyHash: The hex encoded Ed25519 public key hash.
"""

def __init__(self, address: HexStr):
"""Initialize an Ed25519Address
Args:
address: The hex encoded address to use.
"""
super().__init__(AddressType.ED25519, pubKeyHash=address)
pubKeyHash: HexStr
type: int = field(
default_factory=lambda: int(
AddressType.ED25519),
init=False)


@dataclass
class AliasAddress(Address):
"""Represents an Alias address.
Attributes:
aliasId: The hex encoded alias id.
"""

def __init__(self, address_or_id: HexStr):
"""Initialize an AliasAddress
Args:
address_or_id: The hex encoded address to use.
"""
super().__init__(AddressType.ALIAS, aliasId=address_or_id)
aliasId: HexStr
type: int = field(
default_factory=lambda: int(
AddressType.ALIAS),
init=False)


@dataclass
class NFTAddress(Address):
"""Represents an NFT address.
Attributes:
nftId: The hex encoded NFT id.
"""

def __init__(self, address_or_id: HexStr):
"""Initialize an NFTAddress
Args:
address_or_id: The hex encoded address to use.
"""
super().__init__(AddressType.NFT, nftId=address_or_id)
nftId: HexStr
type: int = field(default_factory=lambda: int(AddressType.NFT), init=False)


@dataclass
Expand Down
32 changes: 32 additions & 0 deletions bindings/python/iota_sdk/types/block_builder_options.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2023 IOTA Stiftung
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from iota_sdk.types.common import HexStr, AddressAndAmount
from iota_sdk.client._high_level_api import Range
from iota_sdk.types.burn import Burn
from iota_sdk.types.output import Output
from iota_sdk.types.input import UtxoInput


@dataclass
class BlockBuilderOptions:
"""Options to build a block.
"""
total: str
available: str
coinType: Optional[int] = None
accountInde: Optional[int] = None
initialAddressIndex: Optional[int] = None
inputs: Optional[List[UtxoInput]] = None
inputRange: Optional[Range] = None
output: Optional[AddressAndAmount] = None
outputHex: Optional[List[Dict[str, Any]]] = None
outputs: Optional[List[Output]] = None
customRemainderAddress: Optional[str] = None
tag: Optional[HexStr] = None
data: Optional[HexStr] = None
parents: Optional[List[HexStr]] = None
burn: Optional[Burn] = None
Loading

0 comments on commit 8b3eaf7

Please sign in to comment.