Skip to content

Commit

Permalink
Update python examples
Browse files Browse the repository at this point in the history
  • Loading branch information
FrankC01 committed Oct 21, 2023
1 parent c4937ab commit b160d87
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 37 deletions.
2 changes: 1 addition & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ $ cd ~/suibase/python
$ python3 -m venv env
$ . env/bin/activate
$ pip install -U pip
$ pip install --use-pep517 -r requirements.txt
$ pip install -r requirements.txt
```

## Demo's
Expand Down
2 changes: 1 addition & 1 deletion python/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pysui >= 0.21.0
pysui >= 0.37.1
18 changes: 11 additions & 7 deletions python/src/common/demo_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,18 @@
# -*- coding: utf-8 -*-

"""Common demo utilities shared across demo apps."""
import sys

from pysui import SyncClient, SuiAddress
from pysui.abstracts import SignatureScheme, KeyPair
from pysui.sui.sui_clients.sync_client import SuiClient
from pysui.sui.sui_types.address import SuiAddress


def first_address_for_keytype(client: SuiClient, keytype: SignatureScheme) -> tuple[str, KeyPair]:
def first_address_for_keytype(
client: SyncClient, keytype: SignatureScheme
) -> tuple[str, KeyPair]:
"""Get a SuiAddress and KeyPair tuple for specific keytype.
Args:
client (SuiClient): Use the configuration from a specific SuiClient provider
client (SyncClient): Use the configuration from a specific SyncClient provider
keytype (SignatureScheme): Indicate the key type to filter on
Raises:
Expand All @@ -34,8 +35,11 @@ def first_address_for_keytype(client: SuiClient, keytype: SignatureScheme) -> tu
Returns:
tuple[str, KeyPair]: A matching address string and keypair of first found tuple
"""
filtered: tuple[SuiAddress, KeyPair] = [(k, v) for (k, v) in client.config.addresses_and_keys.items()
if v.scheme == keytype]
filtered: tuple[SuiAddress, KeyPair] = [
(k, v)
for (k, v) in client.config.addresses_and_keys.items()
if v.scheme == keytype
]
if filtered:
return filtered[0]
raise ValueError(f"No keypair type of {keytype.as_str()}")
31 changes: 19 additions & 12 deletions python/src/demo1/sysinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,45 @@
"""Demonstrate fetching general system information."""

from datetime import datetime
from pysui import SyncClient, SuiConfig
from pysui.sui.sui_clients.common import handle_result
from pysui.sui.sui_config import SuiConfig
from pysui.sui.sui_clients.sync_client import SuiClient
from pysui.sui.sui_builders.get_builders import GetLatestSuiSystemState
from pysui.sui.sui_txresults.single_tx import SuiLatestSystemState


def _stats_0291(client: SuiClient):
def _stats_0291(client: SyncClient):
"""Show system info for local node.
Args:
client (SuiClient): The interface to the Sui RPC API
client (SyncClient): The interface to the Sui RPC API
"""
from pysui.sui.sui_builders.get_builders import GetLatestSuiSystemState
from pysui.sui.sui_txresults.single_tx import SuiLatestSystemState

sysinfo: SuiLatestSystemState = handle_result(client.execute(GetLatestSuiSystemState()))
sysinfo: SuiLatestSystemState = handle_result(
client.execute(GetLatestSuiSystemState())
)
dtime = datetime.utcfromtimestamp(int(sysinfo.epoch_start_timestamp_ms) / 1000)
print(f"Current Epoch: {sysinfo.epoch}, running since UTC: {dtime.strftime('%Y-%m-%d %H:%M:%S')}")
print(
f"Current Epoch: {sysinfo.epoch}, running since UTC: {dtime.strftime('%Y-%m-%d %H:%M:%S')}"
)
print(f"Reference gas price: {sysinfo.reference_gas_price} mist")
print(f"Active Validators: {len(sysinfo.active_validators)}")
for vmd in sysinfo.active_validators:
print(f"[{vmd.name}] address: {vmd.sui_address} staking balance: {vmd.staking_pool_sui_balance}")
print(
f"[{vmd.name}] address: {vmd.sui_address} staking balance: {vmd.staking_pool_sui_balance}"
)


def main(client: SuiClient):
def main(client: SyncClient):
"""Entry point for demo."""
print(f"\nSui client RPC version {client.rpc_version}")
# Information not related to some version
addy_keypair = client.config.keypair_for_address(client.config.active_address)
print(f"Active address: {client.config.active_address} public-key: {addy_keypair.public_key}")
print(
f"Active address: {client.config.active_address} public-key: {addy_keypair.public_key}"
)
_stats_0291(client)


if __name__ == "__main__":
main(SuiClient(SuiConfig.sui_base_config()))
main(SyncClient(SuiConfig.sui_base_config()))
19 changes: 11 additions & 8 deletions python/src/demo2/coinage.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@

import json

from pysui.sui.sui_config import SuiConfig
from pysui import SuiConfig, SyncClient
from pysui.sui.sui_clients.common import handle_result
from pysui.sui.sui_clients.sync_client import SuiClient
from pysui.sui.sui_builders.get_builders import GetAllCoins
from pysui.sui.sui_txresults.single_tx import SuiCoinObjects


def coin(client: SuiClient) -> None:
def coin(client: SyncClient) -> None:
"""Summarize, by address by coin type, count of coin and balance
It organizes the information in a dict structure:
Expand All @@ -37,11 +36,13 @@ def coin(client: SuiClient) -> None:
}
Args:
client (SuiClient): The interface to the Sui RPC API.
client (SyncClient): The interface to the Sui RPC API.
"""
summary = {}
for address in client.config.addresses:
coin_type_list: SuiCoinObjects = handle_result(client.execute(GetAllCoins(owner=address)))
coin_type_list: SuiCoinObjects = handle_result(
client.execute(GetAllCoins(owner=address))
)
coin_collection = {}
for coinage in coin_type_list.data:
if coinage.coin_type in coin_collection:
Expand All @@ -54,12 +55,14 @@ def coin(client: SuiClient) -> None:
print(json.dumps(summary, indent=2))


def main(client: SuiClient):
def main(client: SyncClient):
"""Entry point for demo."""
addy_keypair = client.config.keypair_for_address(client.config.active_address)
print(f"Active address: {client.config.active_address} public-key: {addy_keypair.public_key}")
print(
f"Active address: {client.config.active_address} public-key: {addy_keypair.public_key}"
)
coin(client)


if __name__ == "__main__":
main(SuiClient(SuiConfig.sui_base_config()))
main(SyncClient(SuiConfig.sui_base_config()))
19 changes: 11 additions & 8 deletions python/src/demo3/prgtxn.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,17 @@
"""Demonstrate Programmable Transactions."""

from pysui.abstracts import SignatureScheme
from pysui import SyncClient, SuiConfig
from pysui.sui.sui_txn import SyncTransaction
from pysui.sui.sui_types.address import SuiAddress
from pysui.sui.sui_config import SuiConfig
from pysui.sui.sui_clients.sync_client import SuiClient
from pysui.sui.sui_clients.transaction import SuiTransaction
from pysui.sui.sui_txresults.single_tx import SuiCoinObject
from pysui.sui.sui_clients.common import handle_result


from src.common.demo_utils import first_address_for_keytype


def main(client: SuiClient):
def main(client: SyncClient):
"""Entry point for demo.
This demonstrates using pysui Programmable Transaction (SuiTransaction).
Expand All @@ -42,7 +41,7 @@ def main(client: SuiClient):

# Setup the Transaction Builder using the client
# By default, the 'sender' is set to client.config.active-address
tx_builder = SuiTransaction(client)
tx_builder = SyncTransaction(client)
# We reset sender to the 'from_address'
from_address = SuiAddress(from_address)
tx_builder.signer_block.sender = from_address
Expand All @@ -53,10 +52,14 @@ def main(client: SuiClient):
# Get it's balance and convert to int
a_coin_balance = int(a_coin.balance)

print(f"Transferring 50% of coin: {a_coin.coin_object_id} from address: {from_address} to address: {to_address}")
print(
f"Transferring 50% of coin: {a_coin.coin_object_id} from address: {from_address} to address: {to_address}"
)
# Construct a split coin for 50% of a_coin
# We want the result as input into the subsequent transfer
split_coin = tx_builder.split_coin(coin=a_coin.coin_object_id, amounts=int(a_coin_balance / 2))
split_coin = tx_builder.split_coin(
coin=a_coin.coin_object_id, amounts=int(a_coin_balance / 2)
)
# Construct a transfer to send the result of splitting out the coin
# to the recipient
tx_builder.transfer_objects(transfers=split_coin, recipient=SuiAddress(to_address))
Expand All @@ -82,4 +85,4 @@ def main(client: SuiClient):


if __name__ == "__main__":
main(SuiClient(SuiConfig.sui_base_config()))
main(SyncClient(SuiConfig.sui_base_config()))

0 comments on commit b160d87

Please sign in to comment.