Skip to content

Commit

Permalink
Merge pull request #33 from janezpodhostnik/janez/cleanup
Browse files Browse the repository at this point in the history
Overall cleanup and release prep
  • Loading branch information
janezpodhostnik authored Nov 6, 2021
2 parents 599a263 + 0e0f851 commit 1b8211e
Show file tree
Hide file tree
Showing 15 changed files with 123 additions and 79 deletions.
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
---
title: Flow Python SDK
description: Packages for Python developers to build applications that interact with the Flow network
contentType: INTRO
---

The Flow Python SDK provides a set of packages for Python developers to build applications that interact with the Flow network.

[![PyPI](https://img.shields.io/pypi/v/flow-py-sdk.svg)](https://pypi.org/project/flow-py-sdk/)
Expand Down
20 changes: 12 additions & 8 deletions examples/account_examples.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from flow_py_sdk.tx import Tx

from flow_py_sdk import flow_client
from flow_py_sdk.account_key import AccountKey
from flow_py_sdk import ProposalKey, create_account_template
from flow_py_sdk.templates import ContractTemplates
import flow_py_sdk.cadence as cadence
from flow_py_sdk.signer import SignAlgo, HashAlgo
from flow_py_sdk import (
flow_client,
AccountKey,
ProposalKey,
create_account_template,
Tx,
ContractTemplates,
cadence,
SignAlgo,
HashAlgo,
)
from examples.common import Example, Config
from examples.common.utils import random_account


# -------------------------------------------------------------------------
# Create an account
# -------------------------------------------------------------------------
Expand Down
19 changes: 10 additions & 9 deletions examples/block_examples.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from flow_py_sdk import flow_client
from examples.common import Example, Config


# -------------------------------------------------------------------------
# Retrieve a block by ID
# -------------------------------------------------------------------------
Expand All @@ -16,9 +17,9 @@ async def run(self, ctx: Config):
) as client:
latest_block = await client.get_latest_block()
block = await client.get_block_by_i_d(id=latest_block.id)
print("Block ID: {}".format(block.id.hex()))
print("Block height: {}".format(block.height))
print("Block timestamp: [{}]".format(block.timestamp))
self.log.info(f"Block ID: {block.id.hex()}")
self.log.info(f"Block height: {block.height}")
self.log.info(f"Block timestamp: [{block.timestamp}]")


# -------------------------------------------------------------------------
Expand All @@ -36,9 +37,9 @@ async def run(self, ctx: Config):
) as client:
latest_block = await client.get_latest_block()
block = await client.get_block_by_height(height=latest_block.height)
print("Block ID: {}".format(block.id.hex()))
print("Block height: {}".format(block.height))
print("Block timestamp: [{}]".format(block.timestamp))
self.log.info(f"Block ID: {block.id.hex()}")
self.log.info(f"Block height: {block.height}")
self.log.info(f"Block timestamp: [{block.timestamp}]")


# -------------------------------------------------------------------------
Expand All @@ -55,6 +56,6 @@ async def run(self, ctx: Config):
host=ctx.access_node_host, port=ctx.access_node_port
) as client:
block = await client.get_latest_block(is_sealed=False)
print("Block ID: {}".format(block.id.hex()))
print("Block height: {}".format(block.height))
print("Block timestamp: [{}]".format(block.timestamp))
self.log.info(f"Block ID: {block.id.hex()}")
self.log.info(f"Block height: {block.height}")
self.log.info(f"Block timestamp: [{block.timestamp}]")
8 changes: 2 additions & 6 deletions examples/client_examples.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import logging

from examples.common import Example, Config
from flow_py_sdk import flow_client

log = logging.getLogger(__name__)


class ClientExample1(Example):
class CreateClientExample(Example):
"""
Use the client to get an accounts deployed contracts
"""
Expand All @@ -22,4 +18,4 @@ async def run(self, ctx: Config):
address=ctx.service_account_address.bytes
)

log.info(f"Account contracts length {len(script.contracts)}")
self.log.info(f"Account contracts length {len(script.contracts)}")
10 changes: 4 additions & 6 deletions examples/collections_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from examples.common.utils import random_account


# -------------------------------------------------------------------------
# Retrieve a collection by ID
# -------------------------------------------------------------------------
Expand All @@ -11,7 +12,6 @@ def __init__(self) -> None:
super().__init__(tag="CL.1.", name="GetCollectionByIdExample", sort_order=201)

async def run(self, ctx: Config):

# First Step : Create a client to connect to the flow blockchain
# flow_client function creates a client using the host and port
async with flow_client(
Expand All @@ -22,9 +22,7 @@ async def run(self, ctx: Config):
collection_id = block.collection_guarantees[0].collection_id

collection = await client.get_collection_by_i_d(id=collection_id)
print("ID: {}".format(collection.id.hex()))
print(
"Transactions: [{}]".format(
", ".join(x.hex() for x in collection.transaction_ids)
)
self.log.info(f"ID: {collection.id.hex()}")
self.log.info(
f"Transactions: [{', '.join(x.hex() for x in collection.transaction_ids)}]"
)
1 change: 1 addition & 0 deletions examples/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def __init__(self, config_location: Path) -> None:
self.access_node_port: int = 3569

self.service_account_key_id: int = 0
# noinspection PyBroadException
try:
with open(config_location) as json_file:
data = json.load(json_file)
Expand Down
13 changes: 12 additions & 1 deletion examples/common/example_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ def register(self, ex: "Example"):
ex : Example
The example to register
Returns
-------
bool
True if the example passed, False otherwise
"""
if ex.tag in self._examples:
log.error(f"Trying to register an example with a duplicate tag: {ex.tag}")
Expand All @@ -35,6 +39,11 @@ async def run_all(self, cfg: Config) -> Annotated[bool, "Success"]:
----------
cfg : Config
Environment configuration for the examples
Returns
-------
bool
True if all examples passed, False otherwise
"""
examples = sorted(self._examples.values(), key=lambda e: e.sort_order)
success = True
Expand All @@ -46,7 +55,8 @@ async def run(self, cfg: Config, tag: str) -> Annotated[bool, "Success"]:
ex = self._examples[tag]
return await self._run(cfg, ex)

async def _run(self, cfg: Config, ex: "Example") -> Annotated[bool, "Success"]:
@staticmethod
async def _run(cfg: Config, ex: "Example") -> Annotated[bool, "Success"]:
log.info(f"=== RUNNING: [{ex.tag}] {ex.name} ===")
# noinspection PyBroadException
try:
Expand Down Expand Up @@ -111,6 +121,7 @@ def __init__(self, *, tag: str, name: str, sort_order: int) -> None:
self.sort_order = sort_order
self.tag = tag
self.name = name
self.log = logging.getLogger(name)

@abstractmethod
async def run(self, ctx: Config):
Expand Down
13 changes: 7 additions & 6 deletions examples/events_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from examples.common import Example, Config
from examples.common.utils import random_account


# -------------------------------------------------------------------------
# Retrieve events by name in the block height range Class
# In this example, an account is created and then we try to get "AccountCreated"
Expand Down Expand Up @@ -50,9 +51,9 @@ async def run(self, ctx: Config):
events = await client.get_events_for_block_i_ds(
type="flow.AccountCreated", block_ids=[latest_block.id]
)
print("event type: {}".format(events[0].events[0].type))
print("event value: {}".format(events[0].events[0].value))
print("event value: {}".format(events[0].events[0].transaction_id.hex()))
self.log.info(f"event type: {events[0].events[0].type}")
self.log.info(f"event value: {events[0].events[0].value}")
self.log.info(f"event value: {events[0].events[0].transaction_id.hex()}")


# -------------------------------------------------------------------------
Expand Down Expand Up @@ -127,6 +128,6 @@ async def run(self, ctx: Config):

assert add_event.fields[2].as_type(cadence.Int).value == 7

print("event type: {}".format(result.events[0].type))
print("event value: {}".format(result.events[0].value))
print("event value: {}".format(result.events[0].transaction_id.hex()))
self.log.info(f"event type: {result.events[0].type}")
self.log.info(f"event value: {result.events[0].value}")
self.log.info(f"event value: {result.events[0].transaction_id.hex()}")
20 changes: 7 additions & 13 deletions examples/generate_key.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from flow_py_sdk.account_key import AccountKey
from flow_py_sdk.signer.hash_algo import HashAlgo
from flow_py_sdk.signer import SignAlgo, HashAlgo
import ecdsa
from flow_py_sdk import flow_client
from ecdsa import SigningKey
from flow_py_sdk import flow_client, AccountKey, signer
from ecdsa.keys import SigningKey
from examples.common import Example, Config


# -------------------------------------------------------------------------
# Create AccountKey Instant.
#
Expand All @@ -15,18 +13,15 @@
# # -------------------------------------------------------------------------
# # First: an account key can be created using a public key.
# # -------------------------------------------------------------------------


class CreateAccountKeyByPublicExample(Example):
def __init__(self) -> None:
super().__init__(
tag="A.1.", name="CreateAccountKeyByPublicExample", sort_order=801
)

async def run(self, ctx: Config):

sign_algo = ecdsa.NIST256p
hash_algo = HashAlgo.SHA2_256
hash_algo = signer.HashAlgo.SHA2_256

secret_key = SigningKey.generate()
_ = secret_key.to_string() # private_key
Expand All @@ -37,7 +32,7 @@ async def run(self, ctx: Config):
public_key=public_key, sign_algo=sign_algo, hash_algo=hash_algo
)

print(acc_key.__dict__)
self.log.info(acc_key.__dict__)


# -------------------------------------------------------------------------
Expand All @@ -50,7 +45,6 @@ def __init__(self) -> None:
super().__init__(tag="A.2.", name="GetAccountKeyByProtoExample", sort_order=802)

async def run(self, ctx: Config):

# First Step : Create a client to connect to the flow blockchain
# flow_client function creates a client using the host and port
async with flow_client(
Expand All @@ -76,7 +70,7 @@ def __init__(self) -> None:
async def run(self, ctx: Config):
# This function return AccountKey and Signer
_, _ = AccountKey.from_seed(
sign_algo=SignAlgo.ECDSA_P256,
hash_algo=HashAlgo.SHA3_256,
sign_algo=signer.SignAlgo.ECDSA_P256,
hash_algo=signer.HashAlgo.SHA3_256,
seed="JNFWM-NDDSE-GENPV-BUBYK-XAVEJ-MVECB-UHIHT-FKKHR-FFDQX-HNSIQ-QVATO-ZEHEQ",
)
17 changes: 9 additions & 8 deletions examples/get_account_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from examples.common import Example, Config
from examples.common.utils import random_account


# -------------------------------------------------------------------------
# Get an account using its address.
# -------------------------------------------------------------------------
Expand All @@ -18,10 +19,10 @@ async def run(self, ctx: Config):
account = await client.get_account(
address=ctx.service_account_address.bytes
)
print("Account Address: {}".format(account.address.hex()))
print("Account Balance: {}".format(account.balance))
print("Account Contracts: {}".format(len(account.contracts)))
print("Account Keys: {}".format(len(account.keys)))
self.log.info(f"Account Address: {account.address.hex()}")
self.log.info(f"Account Balance: {account.balance}")
self.log.info(f"Account Contracts: {len(account.contracts)}")
self.log.info(f"Account Keys: {len(account.keys)}")


# -------------------------------------------------------------------------
Expand All @@ -43,10 +44,10 @@ async def run(self, ctx: Config):
account = await client.get_account_at_latest_block(
address=ctx.service_account_address.bytes
)
print("Account Address: {}".format(account.address.hex()))
print("Account Balance: {}".format(account.balance))
print("Account Contracts: {}".format(len(account.contracts)))
print("Account Keys: {}".format(len(account.keys)))
self.log.info(f"Account Address: {account.address.hex()}")
self.log.info(f"Account Balance: {account.balance}")
self.log.info(f"Account Contracts: {len(account.contracts)}")
self.log.info(f"Account Keys: {len(account.keys)}")


# -------------------------------------------------------------------------
Expand Down
22 changes: 17 additions & 5 deletions examples/scripts_examples.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from flow_py_sdk.script import Script
from flow_py_sdk import flow_client, cadence
from flow_py_sdk import flow_client, cadence, Script
from examples.common import Example, Config


# -------------------------------------------------------------------------
# Submit a script and parse the response Function
# -------------------------------------------------------------------------
Expand Down Expand Up @@ -114,6 +114,18 @@ async def run(self, ctx: Config):
# , block_id
# , block_height
)
print("Name: {}".format(complex_script.fields[2].value))
print("Address: {}".format(complex_script.fields[1].bytes.hex()))
print("Balance: {}".format(complex_script.fields[0].value))

if not complex_script:
raise Exception("Script execution failed")

script_result: cadence.Value = complex_script

self.log.info(
f"Name: {script_result.as_type(cadence.Struct).fields[2].as_type(cadence.String).value}"
)
self.log.info(
f"Address: {script_result.as_type(cadence.Struct).fields[1].as_type(cadence.Address).bytes.hex()}"
)
self.log.info(
f"Balance: {script_result.as_type(cadence.Struct).fields[0].as_type(cadence.UFix64).value}"
)
16 changes: 6 additions & 10 deletions examples/transactions_examples.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from flow_py_sdk.tx import Tx
from flow_py_sdk import ProposalKey, flow_client, cadence
from flow_py_sdk import ProposalKey, flow_client, cadence, Tx
from examples.common.utils import random_account
from examples.common import Example, Config

Expand Down Expand Up @@ -205,7 +204,6 @@ async def run(self, ctx: Config):
async with flow_client(
host=ctx.access_node_host, port=ctx.access_node_port
) as client:

account_address, _, new_signer = await random_account(
client=client, ctx=ctx
)
Expand Down Expand Up @@ -236,11 +234,9 @@ async def run(self, ctx: Config):
transaction_id = response.id

transaction = await client.get_transaction(id=transaction_id)
print("transaction ID: {}".format(transaction_id.hex()))
print("transaction payer: {}".format(transaction.payer.hex()))
print(
"transaction proposer: {}".format(
transaction.proposal_key.address.hex()
)
self.log.info(f"transaction ID: {transaction_id.hex()}")
self.log.info(f"transaction payer: {transaction.payer.hex()}")
self.log.info(
f"transaction proposer: {transaction.proposal_key.address.hex()}"
)
print("transaction script: {}".format(transaction.script.decode("utf-8")))
self.log.info(f"transaction script: {transaction.script.decode('utf-8')}")
2 changes: 1 addition & 1 deletion flow_py_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from .exceptions import PySDKError, NotCadenceValueError
from .signer import SignAlgo, HashAlgo, InMemorySigner, Signer
from .account_key import AccountKey
from .templates import create_account_template
from .templates import create_account_template, ContractTemplates
from .tx import Tx, ProposalKey, TxSignature, TransactionStatus

logging.getLogger(__name__).addHandler(logging.NullHandler())
Loading

0 comments on commit 1b8211e

Please sign in to comment.