Skip to content

Commit

Permalink
More Python types and type hints (#712)
Browse files Browse the repository at this point in the history
* More Python types and type hints

* Review
  • Loading branch information
Thoralf-M authored Jul 4, 2023
1 parent 8594211 commit f586312
Show file tree
Hide file tree
Showing 17 changed files with 183 additions and 68 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from iota_sdk import Wallet

import json

# In this example we will list transactions

wallet = Wallet('./alice-database')
Expand All @@ -13,11 +11,11 @@
transactions = account.transactions()
print('Sent transactions:')
for transaction in transactions:
print(transaction['transactionId'])
print(transaction.transactionId)


# Incoming transactions
incoming_transactions = account.incoming_transactions()
print('Received transactions:')
for transaction in incoming_transactions:
print(transaction['transactionId'])
print(transaction.transactionId)
5 changes: 2 additions & 3 deletions bindings/python/examples/how_tos/alias_wallet/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@
'mandatoryInputs': [input],
}
transaction = account.send_amount(params, options)
account.retry_transaction_until_included(
transaction['transactionId'], None, None)
account.retry_transaction_until_included(transaction.transactionId, None, None)
print(
f'Transaction with custom input: https://explorer.shimmer.network/testnet/transaction/{transaction["transactionId"]}')
f'Transaction with custom input: https://explorer.shimmer.network/testnet/transaction/{transaction.transactionId}')

total_base_token_balance = account.sync(sync_options)['baseCoin']['total']
print(f'Balance after sending funds from alias: {total_base_token_balance}')
10 changes: 5 additions & 5 deletions bindings/python/examples/how_tos/native_tokens/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@
wallet.set_stronghold_password(os.environ["STRONGHOLD_PASSWORD"])

# Sync account with the node
response = account.sync()
balance = account.sync()

# We can first check if we already have an alias in our account, because an alias can have many foundry outputs and therefore we can reuse an existing one
if len(account.aliases) == 0:
if not balance["aliases"]:
# If we don't have an alias, we need to create one
transaction = account.prepare_create_alias_output(None, None).send()
print(f'Transaction sent: {transaction["transactionId"]}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
blockId = account.retry_transaction_until_included(transaction.transactionId)
print(f'Block included: {os.environ["EXPLORER_URL"]}/block/{blockId}')

account.sync()
Expand All @@ -41,10 +41,10 @@

prepared_transaction = account.prepare_create_native_token(params, None)
transaction = prepared_transaction.send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
blockId = account.retry_transaction_until_included(transaction.transactionId)
print(f'Block included: {os.environ["EXPLORER_URL"]}/block/{blockId}')

print(f'Created token: {prepared_transaction.token_id()}')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
print(f'Transaction sent: {transaction["transactionId"]}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
blockId = account.retry_transaction_until_included(transaction.transactionId)
print(f'Block included: {os.environ["EXPLORER_URL"]}/block/{blockId}')

balance = account.sync()
Expand Down
3 changes: 1 addition & 2 deletions bindings/python/examples/how_tos/nfts/burn_nft.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,4 @@

# Send transaction.
transaction = account.prepare_burn_nft(nftId).send()
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')

print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/nfts/mint_nft.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@
}]

transaction = account.prepare_mint_nfts(outputs).send()
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/nfts/send_nft.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@
}]

transaction = account.prepare_send_nft(outputs).send()
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@
}]

transaction = account.send_amount(outputs)
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
2 changes: 1 addition & 1 deletion bindings/python/examples/wallet/12-prepare_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@
account.sync()

transaction = account.send_outputs([output])
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
4 changes: 2 additions & 2 deletions bindings/python/examples/wallet/create_alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

load_dotenv()

# In this example we will create an alias ouput
# In this example we will create an alias output

wallet = Wallet('./alice-database')

Expand All @@ -20,4 +20,4 @@

# Send transaction.
transaction = account.prepare_create_alias_output(None, None).send()
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
2 changes: 1 addition & 1 deletion bindings/python/examples/wallet/destroy_alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@

# Send transaction.
transaction = account.prepare_destroy_alias(ALIAS_ID).send()
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
3 changes: 1 addition & 2 deletions bindings/python/examples/wallet/transaction_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,4 @@
transaction = account.send_amount(outputs, TransactionOptions(remainder_value_strategy=RemainderValueStrategy.ReuseAddress,
note="my first tx", tagged_data_payload=TaggedDataPayload(utf8_to_hex("tag"), utf8_to_hex("data"))))
print(transaction)
print(
f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction["blockId"]}')
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
1 change: 1 addition & 0 deletions bindings/python/iota_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
from .types.output_id import *
from .types.payload import *
from .types.token_scheme import *
from .types.transaction import *
from .types.transaction_options import *
from .types.unlock_condition import *
70 changes: 70 additions & 0 deletions bindings/python/iota_sdk/types/output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Copyright 2023 IOTA Stiftung
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, Optional
from iota_sdk.types.common import HexStr

# TODO: https://github.com/iotaledger/iota-sdk/issues/129
# @dataclass
# class Output():
# def __init__(self, type, sender=None, issuer=None, data=None, tag=None):
# """Initialize an output

# Parameters
# ----------
# type : OutputType
# The type of output
# """
# self.type = type


# @classmethod
# def from_dict(cls, output_dict: Dict) -> Output:
# obj = cls.__new__(cls)
# super(Output, obj).__init__()
# for k, v in output_dict.items():
# setattr(obj, k, v)
# return obj

@dataclass
class OutputMetadata:
"""Metadata about an output.
"""

blockId: HexStr
transactionId: HexStr
outputIndex: int
isSpent: bool
milestoneIndexBooked: int
milestoneTimestampBooked: int
ledgerIndex: int
milestoneIndexSpent: Optional[int] = None
milestoneTimestampSpent: Optional[int] = None
transactionIdSpent: Optional[HexStr] = None

@classmethod
def from_dict(cls, dict: Dict) -> OutputMetadata:
obj = cls.__new__(cls)
super(OutputMetadata, obj).__init__()
for k, v in dict.items():
setattr(obj, k, v)
return obj


@dataclass
class OutputWithMetadata:
"""An output with its metadata.
"""

metadata: OutputMetadata
output: Any # TODO: Output https://github.com/iotaledger/iota-sdk/issues/129

@classmethod
def from_dict(cls, dict: Dict) -> OutputWithMetadata:
obj = cls.__new__(cls)
super(OutputWithMetadata, obj).__init__()
for k, v in dict.items():
setattr(obj, k, v)
return obj
41 changes: 41 additions & 0 deletions bindings/python/iota_sdk/types/transaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright 2023 IOTA Stiftung
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Optional
from iota_sdk.types.common import HexStr
from iota_sdk.types.output import OutputWithMetadata
from iota_sdk.types.payload import TransactionPayload
from enum import Enum


class InclusionState(str, Enum):
Pending = 'pending'
Confirmed = 'confirmed'
Conflicting = 'conflicting'
UnknownPruned = 'unknownPruned'


@dataclass
class Transaction:
"""The transaction payload with metadata.
"""

payload: TransactionPayload
inclusionState: InclusionState
timestamp: int
transactionId: HexStr
networkId: int
incoming: bool
inputs = List[OutputWithMetadata]
note: Optional[str] = None
blockId: Optional[HexStr] = None

@classmethod
def from_dict(cls, dict: Dict) -> Transaction:
obj = cls.__new__(cls)
super(Transaction, obj).__init__()
for k, v in dict.items():
setattr(obj, k, v)
return obj
Loading

0 comments on commit f586312

Please sign in to comment.