Utils, Amount, Asset
Chains
- xchainpy2_utils.chain.COSMOS_CHAINS = {Chain.Cosmos, Chain.Maya, Chain.THORChain}
COSMOS_CHAINS is a set of chains that are based on the Cosmos SDK.
- xchainpy2_utils.chain.CURRENCY_SYMBOLS = {Chain.Bitcoin: '₿', Chain.BitcoinCash: '₿', Chain.Doge: 'Ð', Chain.Ethereum: 'Ξ', Chain.Litecoin: 'Ł', Chain.Maya: '𐌂', Chain.THORChain: 'ᚱ'}
CURRENCY_SYMBOLS is a dictionary that maps each chain to its currency symbol.
- class xchainpy2_utils.chain.Chain(value)
Bases:
EnumEnum 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'
- BinanceSmartChain = 'BSC'
- Bitcoin = 'BTC'
- BitcoinCash = 'BCH'
- Cosmos = 'GAIA'
- Dash = 'DASH'
- Doge = 'DOGE'
- Ethereum = 'ETH'
- Kujira = 'KUJI'
- Litecoin = 'LTC'
- Maya = 'MAYA'
- Ripple = 'XRP'
- Solana = 'SOL'
- THORChain = 'THOR'
- UNKNOWN = 'Unknown'
- property currency_symbol
Returns the currency symbol for the chain. :return: The currency symbol for the chain.
- 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
- xchainpy2_utils.chain.EVM_CHAINS = {Chain.Avalanche, Chain.Base, Chain.BinanceSmartChain, Chain.Ethereum}
EVM_CHAINS is a set of chains that are based on the Ethereum Virtual Machine (EVM).
- xchainpy2_utils.chain.UTXO_CHAINS = {Chain.Bitcoin, Chain.BitcoinCash, Chain.Dash, Chain.Doge, Chain.Litecoin}
UTXO_CHAINS is a set of chains that use the UTXO model.
Constants
- xchainpy2_utils.consts.AMOUNT_10K_SAT = (10000, 8)
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:
NamedTupleChainAttributes 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), ('THOR', 'RUNE', '', AssetKind.NATIVE)), cacao: CryptoAmount = ((0, 10), ('MAYA', 'CACAO', '', AssetKind.NATIVE)))
Bases:
NamedTupleDustAmount 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:
EnumEnum 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.NATIVE)
Bases:
NamedTupleAsset is used to identify a blockchain asset in the cross-chain environment. It has chain, symbol, and contract fields.
- property as_derived
Return a “derived”-type copy of the asset object. Note, that chain will be set as THORChain.
- Returns:
Asset
- property as_native
Get a native copy of the asset object. Native assets use ‘.’ as delimiter (THOR.RUNE).
- Returns:
A native version of the asset.
- property as_secured
Get a secured copy of the asset object. Secured assets use ‘-’ as delimiter (ETH-ETH).
- Returns:
A secured version of the asset.
- property as_synth
Get a synth copy of the asset object. Synth assets use ‘/’ as delimiter (BTC/BTC).
- Returns:
A synth version of the asset.
- property as_trade
Get a trade copy of the asset object. Trade assets use ‘~’ as delimiter (BTC~BTC).
- Returns:
A trade version of the asset.
- classmethod auto(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.
- Parameters:
x – The input string to parse
- Returns:
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
- Returns:
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 dimensionless()
Get a dimensionless asset, which is an asset with empty chain and symbol.
- Returns:
A dimensionless Asset object.
- 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”. 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.auto() for that. :param s: The input string to parse :return: An Asset object if the input string is valid, otherwise None
- classmethod from_string_no_exc(s) Asset | None
Create an Asset object by parsing the input string. Return None if input string is invalid. Does not raise an exception.
- Parameters:
s – The input string to parse
- Returns:
An Asset object if the input string is valid, otherwise None
- Return type:
Optional[Asset]
- 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.
- Parameters:
input_str – The input string to parse
- Returns:
A tuple containing the name and contract
- property is_derived
Check if the asset is a derived asset.
- property is_dimensionless
Check if the asset is dimensionless, which means it has an empty chain and symbol.
- Returns:
True if the asset is dimensionless, otherwise False.
- property is_gas
Check if the asset is a gas asset for its chain.
- property is_native
Check if the asset is a native (L1) asset.
- property is_rune_native
Check if the asset is a native RUNE asset.
- Returns:
- property is_secured
Check if the asset is a secured asset.
- 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
native, synth, trade, derived, secured.
- Type:
Asset kind. Default is native (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.
- xchainpy2_utils.asset.AssetAEth = ('ARB', 'ETH', '', AssetKind.NATIVE)
Arbitrum Ethereum asset on the Arbitrum network.
- xchainpy2_utils.asset.AssetATOM = ('GAIA', 'ATOM', '', AssetKind.NATIVE)
Cosmos Atom asset on the Cosmos network.
- xchainpy2_utils.asset.AssetAVAX = ('AVAX', 'AVAX', '', AssetKind.NATIVE)
Avalanche asset on the Avalanche C-Chain.
- xchainpy2_utils.asset.AssetBCH = ('BCH', 'BCH', '', AssetKind.NATIVE)
Bitcoin Cash asset on the Bitcoin Cash network.
- xchainpy2_utils.asset.AssetBSC = ('BSC', 'BNB', '', AssetKind.NATIVE)
Binance Coin asset on the Binance Smart Chain.
- xchainpy2_utils.asset.AssetBTC = ('BTC', 'BTC', '', AssetKind.NATIVE)
Bitcoin asset on the Bitcoin network.
- xchainpy2_utils.asset.AssetBaseETH = ('BASE', 'ETH', '', AssetKind.NATIVE)
Base Ethereum asset on the Base network.
- xchainpy2_utils.asset.AssetCACAO = ('MAYA', 'CACAO', '', AssetKind.NATIVE)
Maya Cacao asset on the Maya network.
- xchainpy2_utils.asset.AssetDASH = ('DASH', 'DASH', '', AssetKind.NATIVE)
Dash asset on the Dash network.
- xchainpy2_utils.asset.AssetDOGE = ('DOGE', 'DOGE', '', AssetKind.NATIVE)
Dogecoin asset on the Dogecoin network.
- xchainpy2_utils.asset.AssetETH = ('ETH', 'ETH', '', AssetKind.NATIVE)
Ethereum asset on the Ethereum network.
- xchainpy2_utils.asset.AssetKUJI = ('KUJI', 'KUJI', '', AssetKind.NATIVE)
Kujira asset on the Kujira network.
- class xchainpy2_utils.asset.AssetKind(value)
Bases:
EnumAn enumeration.
- DERIVED = 'derived'
THORChain derived assets. See: https://docs.thorchain.org/frequently-asked-questions/asset-types#derived-assets
- NATIVE = 'native'
Native Assets are L1 assets (eg BTC) available on its native L1 (eg Bitcoin Network).
- SECURED = 'secured'
Secure Assets allow L1 tokens to be deposited to THORChain, creating a new native asset, which can be transferred between accounts, over IBC and integrated with CosmWasm smart contracts using standard Cosmos SDK messages. They also replace Trade Assets. See: https://docs.thorchain.org/thorchain-finance/secured-assets
- SYNTH = 'synth'
1 peg upon redemption. See: https://docs.thorchain.org/frequently-asked-questions/asset-types#synthetic-assets Attention! Synthetic assets are now suspended on the network due to THORFi being on pause. Please use trade and secured assets instead.
- Type:
THORChain synthetics are fully collateralized while they exist and switch to a 1
- TRADE = 'trade'
Trade Assets, a new class of primitives on THORChain, offer double the capital efficiency of synthetic assets, enhancing arbitrage and high-frequency trading. They settle with THORChain’s block speed and cost, enabling 6-second finality swaps without high fees. Redeemable anytime with no slippage, Trade Assets emulate centralized exchange trading but maintain on-chain transparency and security. Custodied by THORChain outside of liquidity pools, they provide user credits while holding funds 1:1 as L1 assets until withdrawal, making THORChain more user-friendly for active traders. See: https://docs.thorchain.org/frequently-asked-questions/asset-types#trade-assets
- UNKNOWN = 'unknown'
Unknown asset type.
- property delimiter
Return the delimiter based on the asset kind.
- classmethod recognize(asset_str: str) AssetKind
Detects the asset type based on the first delimiter in the asset string.
- Parameters:
asset_str – The asset string (e.g., “ETH.ETH”, “BTC-BTC”, “XRP~XRP”).
- Returns:
The asset type: “trade” for “~”, “secured” for “-”, “native” for “.”, or “unknown” if no valid delimiter is found.
:rtype AssetKind
- xchainpy2_utils.asset.AssetLTC = ('LTC', 'LTC', '', AssetKind.NATIVE)
Litecoin asset on the Litecoin network.
- xchainpy2_utils.asset.AssetRUJI = ('THOR', 'RUJI', '', AssetKind.NATIVE)
Rujira asset on the THORChain network.
- xchainpy2_utils.asset.AssetRUNE = ('THOR', 'RUNE', '', AssetKind.NATIVE)
THORChain RUNE asset on the THORChain network.
- xchainpy2_utils.asset.AssetSOL = ('SOL', 'SOL', '', AssetKind.NATIVE)
Solana asset on the Solana network.
- xchainpy2_utils.asset.AssetTCY = ('THOR', 'TCY', '', AssetKind.NATIVE)
TCY asset on the THORChain network.
- xchainpy2_utils.asset.AssetXRP = ('XRP', 'XRP', '', AssetKind.NATIVE)
XRP Ripple asset on the XRP network.
- class xchainpy2_utils.asset.CommonAssets
Bases:
objectCommon assets used in the cross-chain environment and their short codes.
- AEth = ('ARB', 'ETH', '', AssetKind.NATIVE)
Arbitrum Ethereum asset
- ATOM = ('GAIA', 'ATOM', '', AssetKind.NATIVE)
Cosmos Atom asset
- AVAX = ('AVAX', 'AVAX', '', AssetKind.NATIVE)
Avalanche asset in the Avalanche C-Chain
- BASE_ETH = ('BASE', 'ETH', '', AssetKind.NATIVE)
Base Ethereum asset
- BCH = ('BCH', 'BCH', '', AssetKind.NATIVE)
Bitcoin Cash asset
- BSC = ('BSC', 'BNB', '', AssetKind.NATIVE)
Binance Coin asset in the Binance Smart Chain
- BTC = ('BTC', 'BTC', '', AssetKind.NATIVE)
Bitcoin asset
- CACAO = ('MAYA', 'CACAO', '', AssetKind.NATIVE)
Maya Cacao asset
- DASH = ('DASH', 'DASH', '', AssetKind.NATIVE)
Dash asset
- DOGE = ('DOGE', 'DOGE', '', AssetKind.NATIVE)
Dogecoin asset
- ETH = ('ETH', 'ETH', '', AssetKind.NATIVE)
Ethereum asset
- INVERTED_SHORT_CODES = {('AVAX', 'AVAX', '', AssetKind.NATIVE): 'a', ('BASE', 'ETH', '', AssetKind.NATIVE): 'f', ('BCH', 'BCH', '', AssetKind.NATIVE): 'c', ('BSC', 'BNB', '', AssetKind.NATIVE): 's', ('BTC', 'BTC', '', AssetKind.NATIVE): 'b', ('DOGE', 'DOGE', '', AssetKind.NATIVE): 'd', ('ETH', 'ETH', '', AssetKind.NATIVE): 'e', ('GAIA', 'ATOM', '', AssetKind.NATIVE): 'g', ('LTC', 'LTC', '', AssetKind.NATIVE): 'l', ('THOR', 'RUNE', '', AssetKind.NATIVE): 'r', ('XRP', 'XRP', '', AssetKind.NATIVE): 'x'}
- KUJI = ('KUJI', 'KUJI', '', AssetKind.NATIVE)
Kujira asset
- LTC = ('LTC', 'LTC', '', AssetKind.NATIVE)
Litecoin asset
- RUNE = ('THOR', 'RUNE', '', AssetKind.NATIVE)
THORChain asset
- SHORT_CODES = {'a': ('AVAX', 'AVAX', '', AssetKind.NATIVE), 'b': ('BTC', 'BTC', '', AssetKind.NATIVE), 'c': ('BCH', 'BCH', '', AssetKind.NATIVE), 'd': ('DOGE', 'DOGE', '', AssetKind.NATIVE), 'e': ('ETH', 'ETH', '', AssetKind.NATIVE), 'f': ('BASE', 'ETH', '', AssetKind.NATIVE), 'g': ('GAIA', 'ATOM', '', AssetKind.NATIVE), 'l': ('LTC', 'LTC', '', AssetKind.NATIVE), 'r': ('THOR', 'RUNE', '', AssetKind.NATIVE), 's': ('BSC', 'BNB', '', AssetKind.NATIVE), 'x': ('XRP', 'XRP', '', AssetKind.NATIVE)}
THORChain short codes for common assets. todo: move them to the THORChain package
- SOL = ('SOL', 'SOL', '', AssetKind.NATIVE)
Solana asset
- XRP = ('XRP', 'XRP', '', AssetKind.NATIVE)
XRP Ripple asset
- xchainpy2_utils.asset.NATIVE_DELIMITER = '.'
Native assets use ‘.’ as delimiter (THOR.RUNE, BTC.BTC)
- xchainpy2_utils.asset.SECURED_DELIMITER = '-'
Secured assets use ‘-’ as delimiter (ETH-ETH). See: https://docs.thorchain.org/thorchain-finance/secured-assets
- 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.
- Parameters:
chain – The chain to get the gas asset for. Can be a Chain object or a string.
- Raises:
ValueError – If the chain is not recognized.
- Returns:
The gas Asset for the specified chain.
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.auto(100, AssetRUNE)
5amount2 = CryptoAmount.auto(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.auto(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)
Bases:
NamedTupleRepresents an amount of an asset with a specific number of decimal places. Internal amount is always in base units (no decimal, integer number).
- property as_decimal
Convert the amount to Decimal with default context DC.
- Returns:
Decimal
- as_decimal_ctx(context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]))
Convert the amount to Decimal with the specified context
- Parameters:
context – Decimal context
- Returns:
Decimal
- classmethod auto(x, decimals=8, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]))
Convert any type to an Amount instance. .. warning:: This method uses “asset” amount, e.g. 1 BTC is 1, not 100000000 (satoshi). See also: auto_base.
- Parameters:
x – Input value (int, float, str, Decimal, Amount)
decimals – Number of decimals (default 8)
context – Decimal context (optional)
- Returns:
Amount
- classmethod auto_base(x, decimals=8)
Convert any type to an Amount instance in base denomination.
- Parameters:
x – Input value (int, float, str, Decimal, Amount)
decimals – Number of decimals (default 8)
- Returns:
Amount
- converted_decimals(new_decimals, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])) Amount
Change the decimals of the amount. Non-destructive. Returns a new instance.
- Parameters:
new_decimals – New number of decimals
context – Decimal context (optional)
- Returns:
Amount
- property decimal_part
Return the decimal part of the amount.
- Returns:
int
- property decimal_part_str
Return the decimal part as a string.
- Returns:
str
- decimals: int
The number of decimal places for the amount. Default is 8.
- format(trailing_zeros=False)
Format the amount as a string.
- Parameters:
trailing_zeros – If keeping zeros than it will be like 1.0000, otherwise. e.g. 1
- Returns:
str
- property integer_part
Return the integer part of the amount.
- Returns:
int
- internal_amount: int
The amount in base units (no decimal). Always an integer.
- property is_zero
Check if the amount is zero.
- Returns:
bool
- like_me(x)
Convert x to an Amount instance with the same decimals and decimals as self.
- Parameters:
x – Any value suitable for Amount.auto
- Returns:
Amount
- property ten_power
Return 10 ** decimals as an integer.
- Returns:
int
- classmethod zero(decimals=8)
Create a zero amount with the specified number of decimals
- Parameters:
decimals – Number of decimals (default 8)
- Returns:
Amount
- xchainpy2_utils.amount.AmountLike
Either an Amount instance or a number (int, float, Decimal, str) that can be converted to Amount.
alias of
Amount|Decimal|float|int|str
- class xchainpy2_utils.amount.CryptoAmount(amount: Amount, asset: Asset)
Bases:
NamedTupleRepresents an amount of a cryptocurrency asset. Basically a combination of an Amount and an Asset.
- classmethod auto(_amount: Amount | Decimal | float | int | str, asset: Asset | str, decimals=None) CryptoAmount
˚ Create a CryptoAmount instance from an amount and an asset. The amount can be a number, string, or an Amount instance. The amount is treated as an asset amount, e.g. 1 BTC is 1, not 100000000 (satoshi). The 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.
- Parameters:
_amount – Amount of asset
asset – an asset name or Asset instance
decimals – Decimals for this asset, if None, then it will be guessed automatically
- Returns:
CryptoAmount
- classmethod auto_base(_amount: Amount | Decimal | float | int | str, asset: Asset | str, decimals=None) CryptoAmount
Create a CryptoAmount instance from an amount and an asset. The amount can be a number, string, or an Amount instance. The amount is treated as a base amount, e.g. if you pass 100000000, that will be 1 BTC (in satoshi). The 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.
- Parameters:
_amount – Amount of asset
asset – an asset name or Asset instance
decimals – Decimals for this asset, if None, then it will be guessed automatically
- Returns:
CryptoAmount
- property base_amount
Return the amount in base units (no decimal, e.g. satoshi).
- Returns:
int
- changed_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.
- Parameters:
new_amount – New amount
- Returns:
CryptoAmount
- changed_amount_base(new_amount: int) CryptoAmount
Change the amount only of this CryptoAmount. Sets the base amount (integer) The asset remains the same. Non-destructive. Returns a new instance.
- Parameters:
new_amount – New amount
- Returns:
CryptoAmount
- converted_decimals(new_decimals, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])) CryptoAmount
Change the decimals of the amount. Non-destructive. Returns a new instance.
- Parameters:
new_decimals – New number of decimals
context – Decimal context (optional)
- Returns:
CryptoAmount
- property decimals
Return the number of decimals for the amount. Shortcut for self.amount.decimals.
- Returns:
int
- classmethod pick(balances: List[CryptoAmount], asset: Asset) CryptoAmount
Pick an amount from the list of balances. Search by asset. If not found, return zero CryptoAmount.
- Parameters:
balances – List of CryptoAmount instances
asset – Asset to search for
- Returns:
CryptoAmount
- classmethod zero(asset: str | Asset, decimals=None)
Create a zero CryptoAmount with the specified asset and decimals. If decimals is None, it will be guessed automatically based on the asset.
- Parameters:
asset – Asset instance or asset name
decimals – Decimals for this asset (optional)
- Returns:
CryptoAmount
- classmethod zero_from(amount: CryptoAmount) CryptoAmount
Create a zero CryptoAmount with the same asset and decimals as the given amount.
- Parameters:
amount – Reference amount
- Returns:
CryptoAmount
- xchainpy2_utils.amount.CryptoAmountLike
Either a CryptoAmount instance or an AmountLike that can be converted to CryptoAmount.
alias of
CryptoAmount|Amount|Decimal|float|int|str
- xchainpy2_utils.amount.DC = Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
Just a shortcut for the default decimal context.
- xchainpy2_utils.amount.DECIMAL_CONTEXT = Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
Default decimal context for all Amount and CryptoAmount operations.
- xchainpy2_utils.amount.DEFAULT_ASSET_DECIMAL = 8
Default number of decimals for asset amounts. Widely used in THORChain, Maya, Cosmos.
- xchainpy2_utils.amount.decimal_power_10(x, context=Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]))
Return 10 ** x as Decimal.
- Parameters:
x – number
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.deprecated(reason='This function is deprecated.')
- 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:
EnumEnum 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.