Skip to content

Commit

Permalink
Improved get gas or coin efficiency. Closes #54
Browse files Browse the repository at this point in the history
  • Loading branch information
FrankC01 committed Jan 1, 2023
1 parent 14f98e9 commit d15a420
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 49 deletions.
51 changes: 51 additions & 0 deletions pysui/sui/sui_clients/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from pysui.sui.sui_config import SuiConfig
from pysui.sui.sui_builders.base_builder import SuiBaseBuilder
from pysui.sui.sui_builders.get_builders import (
GetCoinTypeBalance,
GetCoins,
GetPastObject,
GetObjectsOwnedByAddress,
GetObject,
Expand Down Expand Up @@ -159,6 +161,55 @@ async def _signed_execution(self, builder: SuiBaseBuilder) -> Union[SuiRpcResult

# Build and execute convenience methods

async def _get_coins_for_type(
self, address: SuiAddress, coin_type: SuiString = SuiString("0x2::sui::SUI")
) -> SuiRpcResult:
"""_get_coins_for_type Returns all the coins of type for an address.
:param address: The address to fetch coins of coin_type for
:type address: SuiAddress
:param coin_type: Fully qualified type names for the coin
(e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC),
defaults to SuiString("0x2::sui::SUI")
:type coin_type: SuiString, optional
:return: If successful, result contains an array of coins objects of coin_type found
:rtype: SuiRpcResult
"""
result = await self.execute(GetCoinTypeBalance(owner=address, coin_type=coin_type))
if result.is_ok():
limit = SuiInteger(result.result_data.items[0].coin_object_count)
result = await self.execute(GetCoins(owner=address, coin_type=coin_type, limit=limit))
return result

async def get_gas(self, address: SuiAddress = None) -> SuiRpcResult:
"""get_gas Retrieves SUI gas coin objects for address.
:param address: If None, active_address will be used, defaults to None
:type address: SuiAddress, optional
:return: If successful, result contains an array of SUI gas objects found
:rtype: SuiRpcResult
"""
address = address or self.config.active_address
return await self._get_coins_for_type(address)

async def get_coin(
self,
coin_type: SuiString,
address: SuiAddress = None,
) -> SuiRpcResult:
"""get_coin Retrieves objects of coin_type for address.
:param coin_type: Fully qualified type names for the coin
(e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC)
:type coin_type: SuiString
:param address: If None, active_address will be used, defaults to None
:type address: SuiAddress, optional
:return: If successful, result contains an array of coins objects of coin_type found
:rtype: SuiRpcResult
"""
address = address or self.config.active_address
return await self._get_coins_for_type(address, coin_type)

async def get_gas_from_faucet(self, for_address: SuiAddress = None) -> Any:
"""get_gas_from_faucet Gets gas from SUI faucet.
Expand Down
51 changes: 51 additions & 0 deletions pysui/sui/sui_clients/sync_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
from pysui.sui.sui_config import SuiConfig
from pysui.sui.sui_builders.base_builder import SuiBaseBuilder
from pysui.sui.sui_builders.get_builders import (
GetCoinTypeBalance,
GetCoins,
GetPastObject,
GetObjectsOwnedByAddress,
GetObject,
Expand Down Expand Up @@ -157,6 +159,55 @@ def _signed_execution(self, builder: SuiBaseBuilder) -> Union[SuiRpcResult, Exce

# Build and execute convenience methods

def _get_coins_for_type(
self, address: SuiAddress, coin_type: SuiString = SuiString("0x2::sui::SUI")
) -> SuiRpcResult:
"""_get_coins_for_type Returns all the coins of type for an address.
:param address: The address to fetch coins of coin_type for
:type address: SuiAddress
:param coin_type: Fully qualified type names for the coin
(e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC),
defaults to SuiString("0x2::sui::SUI")
:type coin_type: SuiString, optional
:return: If successful, result contains an array of coins objects of coin_type found
:rtype: SuiRpcResult
"""
result = self.execute(GetCoinTypeBalance(owner=address, coin_type=coin_type))
if result.is_ok():
limit = SuiInteger(result.result_data.items[0].coin_object_count)
result = self.execute(GetCoins(owner=address, coin_type=coin_type, limit=limit))
return result

def get_gas(self, address: SuiAddress = None) -> SuiRpcResult:
"""get_gas Retrieves SUI gas coin objects for address.
:param address: If None, active_address will be used, defaults to None
:type address: SuiAddress, optional
:return: If successful, result contains an array of SUI gas objects found
:rtype: SuiRpcResult
"""
address = address or self.config.active_address
return self._get_coins_for_type(address)

def get_coin(
self,
coin_type: SuiString,
address: SuiAddress = None,
) -> SuiRpcResult:
"""get_coin Retrieves objects of coin_type for address.
:param coin_type: Fully qualified type names for the coin
(e.g., 0x168da5bf1f48dafc111b0a488fa454aca95e0b5e::usdc::USDC)
:type coin_type: SuiString
:param address: If None, active_address will be used, defaults to None
:type address: SuiAddress, optional
:return: If successful, result contains an array of coins objects of coin_type found
:rtype: SuiRpcResult
"""
address = address or self.config.active_address
return self._get_coins_for_type(address, coin_type)

def get_gas_from_faucet(self, for_address: SuiAddress = None) -> Any:
"""get_gas_from_faucet Gets gas from SUI faucet.
Expand Down
16 changes: 1 addition & 15 deletions samples/async_gas.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,9 @@


from pysui.sui.sui_constants import SUI_COIN_DENOMINATOR
from pysui.sui.sui_types import SuiString, SuiInteger
from pysui.sui.sui_types.address import SuiAddress
from pysui.sui.sui_builders.get_builders import GetCoinTypeBalance, GetCoins
from pysui.sui.sui_txresults.single_tx import ObjectInfo, SuiCoinObjects, SuiGas
from pysui.sui.sui_config import SuiConfig
from pysui.sui.sui_clients.common import SuiRpcResult
from pysui.sui.sui_clients.async_client import SuiClient


Expand Down Expand Up @@ -83,17 +80,6 @@ def print_gas(gasses: SuiCoinObjects) -> int:
return total


async def _get_gas(client: SuiClient, address: SuiAddress) -> SuiRpcResult:
"""Efficient enumeration of SUI coins."""
# Will move to client proper for Sizzalena milestone
coin_type = SuiString("0x2::sui::SUI")
result = await client.execute(GetCoinTypeBalance(owner=address, coin_type=coin_type))
if result.is_ok():
limit = SuiInteger(result.result_data.items[0].coin_object_count)
result = await client.execute(GetCoins(owner=address, coin_type=coin_type, limit=limit))
return result


async def get_all_gas(client: SuiClient) -> dict[SuiAddress, list[SuiGas]]:
"""get_all_gas Gets all SuiGas for each address in configuration.
Expand All @@ -105,7 +91,7 @@ async def get_all_gas(client: SuiClient) -> dict[SuiAddress, list[SuiGas]]:
config: SuiConfig = client.config
# Build up gas descriptor fetch for each address
addys = [SuiAddress(x) for x in config.addresses]
addy_list = [_get_gas(client, x) for x in addys]
addy_list = [client.get_gas(x) for x in addys]
gresult = await asyncio.gather(*addy_list, return_exceptions=True)
return_map = {}
for index, gres in enumerate(gresult):
Expand Down
59 changes: 25 additions & 34 deletions samples/cmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""Commands and dispath dict."""
import argparse
import json
from numbers import Number
import sys
from typing import Union
from pysui import __version__
Expand Down Expand Up @@ -46,7 +45,7 @@
from pysui.sui.sui_excepts import SuiMiisingBuildFolder, SuiPackageBuildFail, SuiMiisingModuleByteCode
from pysui.sui.sui_clients.common import SuiRpcResult
from pysui.sui.sui_clients.sync_client import SuiClient
from pysui.sui.sui_txresults.single_tx import MoveDataDescriptor, SuiCoin, SuiGasDescriptor
from pysui.sui.sui_txresults.single_tx import MoveDataDescriptor, SuiCoinObjects


def sdk_version(_client: SuiClient, _args: argparse.Namespace) -> None:
Expand All @@ -73,40 +72,32 @@ def sui_addresses(client: SuiClient, _args: argparse.Namespace) -> None:


def sui_gas(client: SuiClient, args: argparse.Namespace) -> None:
"""Print gas information."""
"""Get gas for address."""

def _total_gas(coin_objects: list[SuiCoin]) -> Number:
"""Get the total of balances for SuiCoin type."""
results = 0
for cdesc in coin_objects:
results = results + cdesc.balance
return results

def _detail_gas(gas_objects: SuiRpcResult):
if gas_objects.is_ok():
print()
header_object_id = "Gas Object ID"
header_mist = "Mist"
header_sui = "SUI"
header_str = format(f"{header_object_id:^45s}{header_mist:^12s}{header_sui:^15s}")
print(header_str)
for _ in range(0, len(header_str)):
print("-", end="")
print()

for gasobj in gas_objects.result_data:
print(
f"{gasobj.identifier} | {str(gasobj.balance):>12s} | {(gasobj.balance / SUI_COIN_DENOMINATOR):.8f}"
)
mists = _total_gas(gas_objects.result_data)
sui = mists / SUI_COIN_DENOMINATOR
print(f"Total Gas = MISTS: {mists:12} SUI: {sui:.8f}")
else:
print(f"Sui RPC Error: {gas_objects.result_string} -> {gas_objects.result_data}")
def _detail_gas_objects(gas_objects: SuiCoinObjects) -> None:
total = 0
print()
header_object_id = "Gas Object ID"
header_mist = "Mist"
header_sui = "SUI"
header_str = format(f"{header_object_id:^50s}{header_mist:^12s}{header_sui:^15s}")
print(header_str)
for _ in range(0, len(header_str)):
print("-", end="")
print()
for gas_object in gas_objects.data:
balance = gas_object.balance
total += balance
print(f"{gas_object.coin_object_id:^45s} has {balance:12} -> {balance/SUI_COIN_DENOMINATOR:.8f}")
print(f"Total gas {total:12} -> {total/SUI_COIN_DENOMINATOR:.8f}")
print()
return total

descriptor_result = client.get_address_object_descriptors(SuiGasDescriptor, args.address)
identities = [ids.identifier for ids in descriptor_result.result_data]
_detail_gas(client.get_objects_for(identities))
gas_result = client.get_gas(args.address)
if gas_result.is_ok():
_detail_gas_objects(gas_result.result_data)
else:
print(f"Error: {gas_result.result_string}")


def sui_new_address(client: SuiClient, args: argparse.Namespace) -> None:
Expand Down

0 comments on commit d15a420

Please sign in to comment.