Utils, Amount, Asset

Chains

class xchainpy2_utils.chain.Chain(value)

Bases: Enum

Enum representing the different chains supported by this library. These values must correspond to the chain names in THORChain; do not change them without a good reason.

Arbitrum = 'ARB'
Avalanche = 'AVAX'
Base = 'BASE'
Binance = 'BNB'
BinanceSmartChain = 'BSC'
Bitcoin = 'BTC'
BitcoinCash = 'BCH'
Cosmos = 'GAIA'
Dash = 'DASH'
Doge = 'DOGE'
Ethereum = 'ETH'
Kujira = 'KUJI'
Litecoin = 'LTC'
Maya = 'MAYA'
THORChain = 'THOR'
UNKNOWN = 'Unknown'
property is_cosmos

Returns True if the chain is a Cosmos-based chain (Cosmos, THORChain, Maya, Binance) :return: True if the chain is a Cosmos-based chain

property is_evm

Returns True if the chain is an EVM chain (Ethereum, BinanceSmartChain, Avalanche, Arbitrum) :return: True if the chain is an EVM chain

property is_utxo

Returns True if the chain is a UTXO chain (Bitcoin, Litecoin, BitcoinCash, Doge, Dash) :return: True if the chain is a UTXO chain

Constants

xchainpy2_utils.consts.AMOUNT_10K_SAT = (10000, 8, Denomination.ASSET)

AMOUNT_10K_SAT is an Amount object that represents 10,000 satoshis.

xchainpy2_utils.consts.Address

MAX_BASIS_POINTS is the maximum number of basis points.

class xchainpy2_utils.consts.ChainAttributes(block_reward: float, avg_block_time: float, dust: DustAmount)

Bases: NamedTuple

ChainAttributes is used to represent some attributes of a blockchain.

avg_block_time: float

The average time in seconds it takes to mine a block in the blockchain.

block_reward: float

The reward for each block in the blockchain.

dust: DustAmount

Typically, the smallest amount of an asset that can be used by a protocol.

xchainpy2_utils.consts.DAY = 86400

YEAR is the number of seconds in a year.

xchainpy2_utils.consts.DOLLAR_SIGN = '$'

RUNE ticker symbol.

class xchainpy2_utils.consts.DustAmount(asset: CryptoAmount, rune: CryptoAmount = ((0, 8, Denomination.ASSET), ('THOR', 'RUNE', '', AssetKind.DERIVED)), cacao: CryptoAmount = ((0, 8, Denomination.ASSET), ('MAYA', 'CACAO', '', AssetKind.NORMAL)))

Bases: NamedTuple

DustAmount is used to represent the smallest amount of an asset that can be used by a protocol.

asset: CryptoAmount

The asset that the dust amount represents.

cacao: CryptoAmount

The Cacao amount that the dust amount represents. It is used in case of MayaProtocol.

rune: CryptoAmount

The Rune amount that the dust amount represents. It is used in case of THORChain.

xchainpy2_utils.consts.MAX_BASIS_POINTS = 100000

DAY is the number of seconds in a day.

xchainpy2_utils.consts.NINE_REALMS_CLIENT_HEADER = 'x-client-id'

Nine Reamls Client Header

class xchainpy2_utils.consts.NetworkType(value)

Bases: Enum

Enum representing the different networks types supported by THORChain.

DEVNET = 'devnet'

This one is rarely used for some development purposes.

MAINNET = 'mainnet'

Mainnet is the production network where real transactions are processed.

STAGENET = 'stagenet'

THORChain has introduced a stagenet with real-value tokens to attract more developers so they can test security features for the platform’s new blockchains.

TESTNET = 'testnet'

Testnet network type can be used for some Chain clients but not for THORChain. Try STAGENET instead.

xchainpy2_utils.consts.RAIDO_GLYPH = 'ᚱ'

DOLLAR_SIGN is the unicode character for the dollar sign.

xchainpy2_utils.consts.XCHAINJS_IDENTIFIER = 'xchainjs-client'

XCHAINPY_IDENTIFIER is the identifier for the xchainpy-client. It is used in the x-client-id header when connecting to 9R servers.

xchainpy2_utils.consts.XCHAINPY_IDENTIFIER = 'xchainpy-client'

DEFAULT_USER_AGENT is the default user agent for the xchainpy2-client.

xchainpy2_utils.consts.calculate_days_from_blocks(blocks: int, chain: Chain = Chain.THORChain) float

Calculate the time in days from the given number of blocks for the specified chain. :param blocks: The number of blocks :param chain: The chain to calculate the time for :return: The time in days float

xchainpy2_utils.consts.calculate_time_from_blocks(blocks: int, chain: Chain = Chain.THORChain) float

Calculate the time in seconds from the given number of blocks for the specified chain. :param blocks: The number of blocks :param chain: The chain to calculate the time for :return: The time in seconds

Assets

The class Asset is a data class that represents an asset identifier in the XChainPy2 ecosystem. It is widely used in the XChainPy2 packages.

class xchainpy2_utils.asset.Asset(chain: str, symbol: str, contract: str = '', kind: AssetKind = AssetKind.NORMAL)

Bases: NamedTuple

Asset is used to identify a blockchain asset in the cross-chain environment. It has chain, symbol, and contract fields.

property as_derived
property as_native

Get a native copy of the asset object. Native assets use ‘.’ as delimiter (THOR.RUNE). :return: A native version of the asset.

property as_synth

Get a synth copy of the asset object. Synth assets use ‘/’ as delimiter (BTC/BTC). :return: A synth version of the asset.

property as_trade

Get a trade copy of the asset object. Trade assets use ‘~’ as delimiter (BTC~BTC). :return: A trade version of the asset.

classmethod automatic(x) Asset | None

Create an Asset object by parsing the input string. This method recognizes short codes like ‘rune’ or ‘btc’ and converts the input string to uppercase. :param x: The input string to parse :return: An Asset object if the input string is valid, otherwise None

chain: str

The blockchain identifier. E.g. ‘BNB’, ‘ETH’, ‘BTC’, etc. This field has type str. Be careful to not confuse this with the Chain object.

property chain_enum: Chain

Returns chain field in form of Chain enumeration instance :return: Chain

contract: str

The contract address of the asset. E.g. ‘0x1234…5678’. Default is empty.

property delimiter

Get the delimiter based on whether the asset is a synth or not. Synth assets use ‘/’ as delimiter (BTC/BTC) while non-synth (native) assets use ‘.’ as delimiter (THOR.RUNE). Trade assets use ‘~’ as delimiter (BTC~BTC).

classmethod dummy()

Get a dummy asset with empty chain, symbol, and contract.

classmethod from_string(s) Asset | None

Create an Asset object by parsing the input string. If the input string is already an Asset object, it will be returned as is. The format of the input string should be “CHAIN.SYMBOL-CONTRACT”. Synth assets should use ‘/’ as delimiter. If you pass a string with only the symbol (e.g. ETH), it will be used as both symbol and ticker: ETH.ETH This method does not recognize short codes like ‘rune’ or ‘btc’ and does not do any case conversion. See Asset.automatic() for that. :param s: The input string to parse :return: An Asset object if the input string is valid, otherwise None

classmethod from_string_exc(s) Asset | None

Create an Asset object by parsing the input string. The difference between this method and from_string is that this method raises a ValueError if the input string is invalid.

property full_symbol

Get the full symbol of the asset including its contract if it has one. E.g. USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7.

static get_name_and_contract(input_str)

Get the name and contract from the input string. :param input_str: The input string to parse :return: A tuple containing the name and contract

property is_derived

Check if the asset is a derived asset. :return:

property is_gas

Check if the asset is a gas asset for its chain.

is_native(p: XChainProtocol = XChainProtocol.THORCHAIN)

Check if the asset is a native asset for the specified protocol. :param p: Protocol to check :type p: XChainProtocol :return: bool

property is_normal

Check if the asset is a normal (L1) asset.

property is_rune_native

Check if the asset is a native RUNE asset. :return:

property is_synth

Check if the asset is a synth asset.

property is_trade

Check if the asset is a trade asset.

property is_valid

Check if the asset is valid. An asset is valid if it has both chain and symbol. If the asset is a derived asset, it must be a THORChain asset.

kind: AssetKind

normal, synth, trade, derived.

Type:

Asset kind. Default is normal (L1 asset). Possible values

symbol: str

The asset symbol. E.g. ‘RUNE’, ‘BTC’, ‘ETH’, etc.

property synth

Check if the asset is a synth asset. Same as is_synth. It is here for compatibility with the old version of the Asset class.

property ticker

Get the ticker of the asset. Same as symbol.

upper()

Get an upper case version of the asset. All fields will be converted to upper case.

class xchainpy2_utils.asset.AssetKind(value)

Bases: Enum

An enumeration.

DERIVED = 'derived'
NORMAL = 'normal'
SYNTH = 'synth'
TRADE = 'trade'
property delimiter

Return the delimiter based on the asset kind.

classmethod recognize(asset_str: str)
class xchainpy2_utils.asset.CommonAssets

Bases: object

Common assets used in the cross-chain environment and their short codes.

AEth = ('ARB', 'ETH', '', AssetKind.NORMAL)

Arbitrum Ethereum asset

ATOM = ('GAIA', 'ATOM', '', AssetKind.NORMAL)

Cosmos Atom asset

AVAX = ('AVAX', 'AVAX', '', AssetKind.NORMAL)

Avalanche asset in the Avalanche C-Chain

BASE_ETH = ('BASE', 'ETH', '', AssetKind.NORMAL)

Base Ethereum asset

BCH = ('BCH', 'BCH', '', AssetKind.NORMAL)

Bitcoin Cash asset

BNB = ('BNB', 'BNB', '', AssetKind.NORMAL)

Binance Coin asset in the Beacon chain

BSC = ('BSC', 'BNB', '', AssetKind.NORMAL)

Binance Coin asset in the Binance Smart Chain

BTC = ('BTC', 'BTC', '', AssetKind.NORMAL)

Bitcoin asset

CACAO = ('MAYA', 'CACAO', '', AssetKind.NORMAL)

Maya Cacao asset

DASH = ('DASH', 'DASH', '', AssetKind.NORMAL)

Dash asset

DOGE = ('DOGE', 'DOGE', '', AssetKind.NORMAL)

Dogecoin asset

ETH = ('ETH', 'ETH', '', AssetKind.NORMAL)

Ethereum asset

INVERTED_SHORT_CODES = {('AVAX', 'AVAX', '', AssetKind.NORMAL): 'a', ('BASE', 'ETH', '', AssetKind.NORMAL): 'f', ('BCH', 'BCH', '', AssetKind.NORMAL): 'c', ('BNB', 'BNB', '', AssetKind.NORMAL): 'n', ('BSC', 'BNB', '', AssetKind.NORMAL): 's', ('BTC', 'BTC', '', AssetKind.NORMAL): 'b', ('DOGE', 'DOGE', '', AssetKind.NORMAL): 'd', ('ETH', 'ETH', '', AssetKind.NORMAL): 'e', ('GAIA', 'ATOM', '', AssetKind.NORMAL): 'g', ('LTC', 'LTC', '', AssetKind.NORMAL): 'l', ('THOR', 'RUNE', '', AssetKind.DERIVED): 'r'}
KUJI = ('KUJI', 'KUJI', '', AssetKind.NORMAL)

Kujira asset

LTC = ('LTC', 'LTC', '', AssetKind.NORMAL)

Litecoin asset

RUNE = ('THOR', 'RUNE', '', AssetKind.DERIVED)

THORChain asset

SHORT_CODES = {'a': ('AVAX', 'AVAX', '', AssetKind.NORMAL), 'b': ('BTC', 'BTC', '', AssetKind.NORMAL), 'c': ('BCH', 'BCH', '', AssetKind.NORMAL), 'd': ('DOGE', 'DOGE', '', AssetKind.NORMAL), 'e': ('ETH', 'ETH', '', AssetKind.NORMAL), 'f': ('BASE', 'ETH', '', AssetKind.NORMAL), 'g': ('GAIA', 'ATOM', '', AssetKind.NORMAL), 'l': ('LTC', 'LTC', '', AssetKind.NORMAL), 'n': ('BNB', 'BNB', '', AssetKind.NORMAL), 'r': ('THOR', 'RUNE', '', AssetKind.DERIVED), 's': ('BSC', 'BNB', '', AssetKind.NORMAL)}
xchainpy2_utils.asset.NON_SYNTH_DELIMITER = '.'

Native assets use ‘.’ as delimiter (THOR.RUNE, BTC.BTC)

xchainpy2_utils.asset.SYNTH_DELIMITER = '/'

Synth assets use ‘/’ as delimiter (BTC/BTC)

xchainpy2_utils.asset.TRADE_DELIMITER = '~'

Trade assets use ‘~’ as delimiter (BTC~BTC)

xchainpy2_utils.asset.get_chain_gas_asset(chain: Chain | str) Asset

Get the gas asset for the specified chain. :param chain: The chain to get the gas asset for. Can be a Chain object or a string. :raise ValueError: If the chain is not recognized. :return: The gas Asset for the specified chain.

xchainpy2_utils.asset.get_short_code(asset: Asset | str) str

Get the short code for the specified asset. :param asset: The asset to get the short code for :return: The short code for the asset

xchainpy2_utils.asset.is_gas_asset(asset: Asset) bool

Check if the asset is a gas asset for its chain. :param asset: The asset to check :return: True if the asset is a gas asset, otherwise False

Amounts

The class Amount is a data class that represents an amount in the XChainPy2 ecosystem. CryptoAmount represents an amount of a cryptocurrency. Basically, it is a combination of an asset and a value.

Note

For classes Amount and CryptoAmount, there are available math operations like addition, subtraction, multiplication, and division.

 1from xchainpy2_utils.amount import CryptoAmount
 2from xchainpy2_utils.asset import AssetRUNE, AssetETH
 3
 4amount1 = CryptoAmount.automatic(100, AssetRUNE)
 5amount2 = CryptoAmount.automatic(200, AssetRUNE)
 6
 7# Addition
 8result = amount1 + amount2
 9print(result.amount)  # 300
10
11# Subtraction
12result = amount2 - amount1
13print(result.amount)  # 100
14
15# Multiplication
16result = amount1 * 2
17print(result.amount)  # 200
18
19# Division
20result = amount2 / 2
21print(result.amount)  # 100
22
23# Comparison
24print(amount1 == amount2)  # False
25print(amount1 < amount2)  # True
26print(amount1 > amount2)  # False
27
28amount_bnb = CryptoAmount.automatic(100, AssetETH)
29try:
30    result = amount1 + amount_bnb
31except ValueError as e:
32    print(e)

Warning

You can not add CryptoAmount with different assets.

class xchainpy2_utils.amount.Amount(internal_amount: int, decimals: int = 8, denom: Denomination = Denomination.ASSET)

Bases: NamedTuple

Represents an amount of an asset with a specific denomination and number of decimal places.

property amount: int | float

Return the amount as an integer (in base mode) or float (in asset mode) :return:

property as_asset

Convert this amount to asset denomination. Non-destructive. Returns a new instance. :return: Amount

property as_base

Convert this amount to base denomination. Non-destructive. Returns a new instance. :return: Amount

property as_decimal

Convert the amount to Decimal with default context DC :return: Decimal

as_decimal_ctx(context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow]))

Convert the amount to Decimal with the specified context :param context: Decimal context :return: Decimal

classmethod automatic(x, decimals=8, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow]))

Convert any type to an Amount instance .. warning:: Integers are considered base amounts, floats are considered asset amounts. :param x: Input value (int, float, str, Decimal, Amount) :param decimals: Number of decimals (default 8) :param context: Decimal context (optional) :return: Amount

changed_decimals(new_decimals, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow])) Amount

Change the decimals of the amount. Non-destructive. Returns a new instance. :param new_decimals: New number of decimals :param context: Decimal context (optional) :return: Amount

property decimal_part

Return the decimal part of the amount. :return: int

property decimal_part_str

Return the decimal part as a string :return: str

decimals: int

The number of decimal places for the amount. Default is 8.

denom: Denomination

The denomination of the amount. Default is Denomination.ASSET.

format(trailing_zeros=False)

Format the amount as a string :param trailing_zeros: If keeping zeros than it will be like 1.0000, otherwise. e.g. 1 :return: str

classmethod from_asset(asset_amount: float | str | int | Decimal, decimals=8, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow]))

Create an amount from an asset amount. Like 1.2345 BTC :param asset_amount: A number in asset units (with decimal) :param decimals: Number of decimals (default 8) :param context: Decimal context (optional) :return: Amount

classmethod from_base(base_amount: str | int | Decimal, decimals=8)

Create an amount from a base amount :param base_amount: A number in base units (no decimal) :param decimals: Number of decimals (default 8) :return: Amount

property integer_part

Return the integer part of the amount. :return: int

internal_amount: int

The amount in base units (no decimal). Always an integer regardless of the denomination.

property is_zero

Check if the amount is zero :return: bool

like_me(x)

Convert x to an Amount instance with the same decimals and denomination as self :param x: Any value suitable for Amount.automatic :return: Amount

same_denom(other: Amount) Amount

Return a new Amount instance (of self) with the same denomination as the other one. The “other” argument only provides the denomination, not the value! The value is unchanged compared to self :param other: Amount to take denomination from :return: Amount

property ten_power

Return 10 ** decimals :return:

classmethod zero(decimals=8, denom=Denomination.ASSET)

Create a zero amount with the specified number of decimals and denomination :param decimals: Number of decimals (default 8) :param denom: Denomination :return: Amount

class xchainpy2_utils.amount.CryptoAmount(amount: Amount, asset: Asset)

Bases: NamedTuple

Represents an amount of a cryptocurrency asset. Basically a combination of an Amount and an Asset.

amount: Amount

The amount of the asset with decimals. Amount Object

property as_asset

Convert this CryptoAmount to asset denomination. Non-destructive. Returns a new instance. :return: CryptoAmount

property as_base

Convert this CryptoAmount to base denomination. Non-destructive. Returns a new instance. :return:

asset: Asset

The asset itself. Asset Object

classmethod automatic(_amount: Amount | str | int | float, asset: Asset | str, decimals=None)

Create a CryptoAmount instance from an amount and an asset. The amount can be a number, string, or an Amount instance. Asset can be an Asset instance or a string. The decimals can be specified, otherwise, it will be guessed automatically. But it is recommended to specify it. :param _amount: Amount of asset :param asset: an asset name or Asset instance :param decimals: Decimals for this asset, if None, then it will be guessed automatically :return:

change_amount(new_amount: int | float | Decimal) CryptoAmount

Change the amount only of this CryptoAmount. The asset remains the same. Non-destructive. Returns a new instance. :param new_amount: New amount :return: CryptoAmount

changed_decimals(new_decimals, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow])) CryptoAmount

Change the decimals of the amount. Non-destructive. Returns a new instance. :param new_decimals: New number of decimals :param context: Decimal context (optional) :return: CryptoAmount

check(a: CryptoAmount)

Check if the asset of the other CryptoAmount is the same as this one. :param a: other CryptoAmount :raises ValueError: if the assets are different :return: None

property decimals

Return the number of decimals for the amount. Instead of calling self.amount.decimals :return:

classmethod from_base(amount, asset: Asset | None = None, decimals=8) CryptoAmount

Create a CryptoAmount from a base amount :param amount: Amount in base units (no decimal) :param asset: Asset instance or asset name :param decimals: Decimals for this asset :return: CryptoAmount

classmethod pick(balances: List[CryptoAmount], asset: Asset)

Pick an amount from the list of balances. Search by asset. If not found, return zero.

classmethod zero(asset: str | Asset, decimals=8)

Create a zero CryptoAmount with the specified asset and decimals :param asset: Asset instance or asset name :param decimals: Decimals for this asset :return: CryptoAmount

classmethod zero_from(amount: CryptoAmount) CryptoAmount

Create a zero CryptoAmount with the same asset and decimals as the given amount :param amount: Reference amount :return: CryptoAmount

class xchainpy2_utils.amount.Denomination(value)

Bases: Enum

Enum representing the different denominations for amounts.

Parameters:
  • BASE – values for asset amounts in base units (no decimal)

  • ASSET – values of asset amounts (w/ decimal)

ASSET = 'asset'
BASE = 'base'
xchainpy2_utils.amount.decimal_power_10(x, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow]))

Return 10 ** x as Decimal :param x: number :param context: Decimal context

Format utils

xchainpy2_utils.format.detect_decimal_digits(x)

Detect the number of decimal digits in a number. :param x: A number. :return: The number of decimal digits.

xchainpy2_utils.format.number_commas(x)

Display an integer with commas as thousands separators. For example, 1234567 -> ‘1,234,567’. :param x: An integer. :return: A string with commas.

xchainpy2_utils.format.parse_short_number(n: str)

Parse a short number with a multiplier notation. For example, ‘1.23k’ -> 1230.0. :param n: A string with a short number. :return: A float number.

xchainpy2_utils.format.pretty_dollar(x, signed=False, postfix='')

Pretty-print a number as a dollar amount. For example, 1234.567 -> ‘$1,234.57’. :param x: The number to print. :param signed: Whether to include a ‘+’ sign for positive numbers. :param postfix: A string to append to the number. :return: A pretty-printed string.

xchainpy2_utils.format.pretty_money(x, prefix='', signed=False, postfix='')

Pretty-print a number as a money amount. For example, 1234.567 -> ‘$1,234.57’. :param x: The number to print. :param prefix: A string to prepend to the number. :param signed: Whether to include a ‘+’ sign for positive numbers. :param postfix: A string to append to the number. :return: A pretty-printed string.

xchainpy2_utils.format.pretty_rune(x, signed=False, prefix='')

Pretty-print a number as a RUNE amount. For example, 1234.567 -> ‘ᚱ1,234.57’. :param x: The number to print. :param signed: Whether to include a ‘+’ sign for positive numbers. :param prefix: A string to prepend to the number. :return: A pretty-printed string.

xchainpy2_utils.format.round_half_up(n, decimals=0)

Round a number to a certain number of decimal places. :param n: A number to round. :param decimals: The number of decimal places. :return: The rounded number.

xchainpy2_utils.format.round_to_dig(x, e=2)

Round a number to a certain number of significant digits. :param x: A number to round. :param e: The number of significant digits. :return: The rounded number.

xchainpy2_utils.format.short_dollar(x, localization=None, signed=False)

Shorten a dollar amount. For example, 1234.567 -> ‘$1.23K’ and -123444344.0 -> ‘-$123.44M’. :param x: The number to shorten. :param localization: A dictionary mapping short names to long names. Keys are K, M, B, T :param signed: Whether to include a ‘+’ sign for positive numbers. :return: A shortened string.

xchainpy2_utils.format.short_money(x, prefix='', postfix='', localization=None, signed=False, integer=False)

Shorten a money amount. For example, 1234.567 -> ‘$1.23K’ and -123444344.0 -> ‘-$123.44M’. :param x: The number to shorten. :param prefix: A string to prepend to the number. :param postfix: A string to append to the number. :param localization: A dictionary mapping short names to long names. Keys are K, M, B, T :param signed: Whether to include a ‘+’ sign for positive numbers. :param integer: Whether to round the number to an integer. :return: A shortened string.

xchainpy2_utils.format.too_big(x, limit_abs=1e+24)

Check if a number is too big to be displayed. :param x: A number. :param limit_abs: The absolute value limit. :return: True if the number is too big, False otherwise.

Date utils

xchainpy2_utils.dates.parse_iso_date(date_str: str) datetime

Parse an ISO date string to a datetime object. :param date_str: The ISO date string to parse. :return: A datetime object.

Decimal constants

xchainpy2_utils.decimals.guess_decimals(a: Asset | str)

Guess the number of decimals for an asset. Don’t blindly trust this function, it may return wrong values for exotic assets. You are encouraged to specify the number of decimals explicitly. :param a: Asset or asset string :return: Number of decimals

Math utils

xchainpy2_utils.math.clamp(x, min_x, max_x)

Clamp a number to a range. :param x: The number to clamp. :param min_x: The minimum value. :param max_x: The maximum value. :return: The clamped number.

Sequence utils

xchainpy2_utils.seqs.batched(iterable, n)

Batch an iterable into chunks of size n :param iterable: iterable :param n: chunk size :return: generator of chunks

xchainpy2_utils.seqs.flatten(items)

Flatten nested lists :param items: a list of lists :return: list

xchainpy2_utils.seqs.key_attr_getter(msg, key: str)

Get attribute from object or value from dict by key :param msg: object or dict :param key: str :return:

xchainpy2_utils.seqs.unique_by_key(items, key)

Filter out duplicate items by key function Guaranteed that there will be no duplicates y = key(item) :param items: iterable of items :param key: function to get key from item :return: list of unique items

Version utils

xchainpy2_utils.versions.get_version(package_name: str) str

Get the version of the specified package. :param package_name: The name of the package. :return: The version of the package.

Testing utils

xchainpy2_utils.testing_utils.load_example_json(base_file, *args)

Load a JSON file from the same directory as the base file, with the given path components. :param base_file: The base file to start from. :param args: The path components to append to the base file. :return: The loaded JSON data.

Other utils

class xchainpy2_utils.util.XChainProtocol(value)

Bases: Enum

Enum representing the different DeFi protocols supported by XChainPy2.

MAYA = 'MAYA'
THORCHAIN = 'THORCHAIN'
xchainpy2_utils.util.class_logger(self, prefix='')

Get a logger with the class name as the prefix. :param self: The class instance. :param prefix: The prefix to use in the logger. :return: A logger with the class name as the prefix.

xchainpy2_utils.util.remove_0x_prefix(s: str)

Remove the ‘0x’ prefix from a string if it exists. :param s: The input string. :return: The string without the ‘0x’ prefix.