THORChain query
XChainPy2 THORChain query is a Python library for querying swap quotes, pools, and other data from THORChain.
Main Query Module
- class xchainpy2_thorchain_query.query.THORChainQuery(cache: THORChainCache | None = None, chain_attributes=None, interface_id='XChainPy2', native_decimal=8)
Bases:
objectTHORChain Query Class is designed to query THORChain data and provide estimates for transactions. It also supports caching of data through THORChainCache to reduce the number of API calls.
- static abbreviate_asset_string(asset: Asset, max_length=5) str
Helper method to abbreviate an asset string if it is too long.
- Parameters:
asset – Asset to abbreviate
max_length – Maximum length of the asset string, default is 5
- Returns:
Abbreviated asset string
- Return type:
str
- async check_liquidity_position(asset: Asset, asset_or_rune_address: str) LiquidityPosition
Checks the liquidity position of a given asset and address.
- Parameters:
asset – Asset to check
asset_or_rune_address – address to check
- Returns:
LiquidityPosition
- async close()
Close the THORChain Query instance and the cache.
- async estimate_add_lp(param: LPAmount) EstimateAddLP
Estimates a liquidity position for given crypto amount value, both asymmetrical and symmetrical :param param: LPAmount - parameters needed for a estimated liquidity position :return: EstimateAddLP
- async estimate_add_saver(add_amount: CryptoAmount) EstimateAddSaver
Estimate the add liquidity with saver. Derived from https://dev.thorchain.org/thorchain-dev/connection-guide/savers-guide
- Parameters:
add_amount – CryptoAmount
- Returns:
EstimateAddSaver
- async estimate_swap(input_amount: CryptoAmount, destination_address: str, destination_asset: Asset | str, tolerance_bps: int = 0, affiliate_bps=0, affiliate_address='', streaming_interval=0, streaming_quantity=0, height=0) SwapEstimate
Quote a swap transaction. This is a read-only method and does not send any transactions.
- Parameters:
input_amount – CryptoAmount - amount to swap
destination_address – Destination address to receive the swapped asset
destination_asset – Destination asset to swap to
tolerance_bps – Basis points of slippage tolerance (0..10000)
affiliate_bps – Affiliate basis points (0..10000)
affiliate_address – Affiliate address
streaming_interval – Streaming swap interval in blocks
streaming_quantity – Streaming swap quantity
height – Height to query (optional), 0 for latest
- Returns:
Swap estimate
- Return type:
- async estimate_thor_name(is_update: bool, thorname: str, expiry: datetime | None = None) THORNameEstimate
Estimate the cost of registering or updating a THORName. Calculations are worked out locally based on the current network values and the current state of the THORName.
- Parameters:
is_update – bool - True if updating an existing THORName
thorname – str - the THORName to register or update
expiry – datetime - the desired expiry date of the THORName
- Returns:
THORNameEstimate
- async estimate_withdraw_lp(asset: Asset, mode: WithdrawMode, withdraw_bps: int = 10000, asset_address: str | None = None, rune_address: str | None = None) EstimateWithdrawLP
Estimate the withdrawal of liquidity :param asset: Pool to withdraw from :param mode: withdrawal mode (asset, rune, symmetric) :param withdraw_bps: basis points to withdraw 0..10k (0..100%) :param asset_address: asset address (optional) :param rune_address: rune address (optional) :return:
- async estimate_withdraw_saver(asset: Asset, address: str, withdraw_bps: int, height: int = 0) EstimateWithdrawSaver
Estimate the withdrawal liquidity with saver (query THORChain node) :param asset: asset to withdraw :param address: address to withdraw to :param withdraw_bps: basis points to withdraw 0..10k (0..100%) :param height: block height to query (optional) :return: EstimateWithdrawSaver
- async get_add_savers_estimate_errors(add_amount: CryptoAmount) List[str]
- async get_inbound_details(chain: str | Chain) InboundDetail
Get the inbound details for a given chain. It contains the recommended fee, fee units, router and vault addresses and the status of the chain.
- Parameters:
chain – str or Chain enum value
- Returns:
InboundDetail
- async get_loan_quote_close(amount: CryptoAmount, from_address: str, loan_asset: Asset, loan_owner: str, min_out: Amount, height: int = 0) LoanCloseQuote
Get a quote for closing a loan.
- Parameters:
amount – CryptoAmount object representing the asset amount in 1e8 decimals and the asset used to repay the loan.
from_address – The address that is paying off the loan.
loan_asset – Asset object representing the collateral asset of the loan.
loan_owner – The owner of the loan collateral.
min_out – Amount object representing the minimal threshold for output amount.
height (int, optional) – Optional block height, defaults to the current tip if not provided.
- Returns:
LoanCloseQuote object representing the quote for closing the loan.
- Return type:
- async get_loan_quote_open(amount: CryptoAmount, target_asset: Asset, destination: str, min_out: Amount, affiliate_bps: int = 0, affiliate: str = '', height: int = 0) LoanOpenQuote
Get a quote for opening a loan :param int amount: the asset amount in 1e8 decimals and the asset used to repay the loan :param Asset target_asset: the target asset to receive (loan denominated in TOR regardless) :param str destination: the destination address, required to generate memo :param Amount min_out: the minimum amount of the target asset to accept :param str affiliate_bps: the affiliate fee in basis points :param int affiliate: the affiliate (address or thorname) :param height: optional height (default is the last block) :return: LoanOpenQuote
- async get_pool_ratio(asset: Asset) PoolRatios
Gets the pool ratio for a given asset Do not send assetNativeRune, There is no pool for it. :param asset: asset required to find the pool :return: object type ratios
- async get_saver_position(asset: str | Asset, address: str) SaversPosition | None
Get the position of a saver :param asset: asset (pool) to check :type asset: Union[str, Asset] :param address: saver’s address :type address: str :return: SaversPosition or None if not found :rtype: Optional[SaversPosition]
- async get_tx_details(tx_id: str) TxSignersResponse
Get transaction details and status from the protocol API. See TxSignersResponse for more details.
- Parameters:
tx_id – Transaction hash (inbound)
- Returns:
TxSignersResponse
- async get_tx_status(tx_id: str) TxStatusResponse
Get transaction status and stages from the protocol API. See TxStatusResponse for more details.
- Parameters:
tx_id – Transaction hash (inbound)
- Returns:
TxStatusResponse
- property native_asset
Returns the native asset (e.g. AssetRUNE or AssetCACAO).
- Returns:
Asset
- property native_block_time: float
Returns the average block time for the native chain.
- Returns:
block time in seconds
- Return type:
float
- property native_chain_attributes
Returns the chain attributes for the native chain (e.g. THORChain)
- Returns:
ChainAttributes
- async outbound_delay(outbound_amount: CryptoAmount) float
Works out how long an outbound Tx will be held by THORChain before sending. See https://gitlab.com/thorchain/thornode/-/blob/develop/x/thorchain/manager_txout_current.go#L548 This function does not guarantee the exact delay. Please use quote_swap for a more accurate estimate.
- Parameters:
outbound_amount – CryptoAmount being sent.
- Returns:
required delay in seconds
- async quote_swap(input_amount: CryptoAmount, destination_address: str, destination_asset: Asset | str, tolerance_bps: int = 0, affiliate_bps=0, affiliate_address='', streaming_interval=0, streaming_quantity=0, height=0) SwapEstimate
Quote a swap transaction. This is a read-only method and does not send any transactions.
- Parameters:
input_amount – CryptoAmount - amount to swap
destination_address – Destination address to receive the swapped asset
destination_asset – Destination asset to swap to
tolerance_bps – Basis points of slippage tolerance (0..10000)
affiliate_bps – Affiliate basis points (0..10000)
affiliate_address – Affiliate address
streaming_interval – Streaming swap interval in blocks
streaming_quantity – Streaming swap quantity
height – Height to query (optional), 0 for latest
- Returns:
Swap estimate
- Return type:
- tracker(wallet=None, inbound_chain: Chain | None = None, outbound_chain: Chain | None = None, inbound_client: XChainClient | None = None, outbound_client: XChainClient | None = None) TransactionTracker
Create a transaction tracker for a given wallet or chain/client combination. Provide either a wallet with inbound/outbound chain idents or clients combination, not both.
- Parameters:
wallet – Optional[Wallet] - the wallet to get the client from
inbound_chain – Optional[Chain] - the inbound Chain enum item
outbound_chain – Optional[Chain] - the outbound Chain enum item
inbound_client – Optional[XChainClient] - directly provide the inbound client
outbound_client – Optional[XChainClient] - directly provide the outbound client
- Returns:
TransactionTracker object
Cache for frequently used data
- class xchainpy2_thorchain_query.cache.THORChainCache(midgard_client: MidgardAPIClient | None = None, thornode_client: THORNodeAPIClient | None = None, expire_pool: float = 600, expire_inbound: float = 600, expire_network: float = 600, native_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED), network: NetworkType = NetworkType.MAINNET, stable_coins: List[Asset] | None = None)
Bases:
objectTHORChainCache is a class that provides a cache for THORChain data. This class provides caching for data related to liquidity pools, network constants (Mimir), and incoming addresses and their attributes.
- async close()
Closes the Midgard and THORNode clients. It is recommended to call this method before the application exits.
- Returns:
None
- async convert(input_amount: CryptoAmount, out_asset: Asset) CryptoAmount
Returns the exchange of a CryptoAmount to a different Asset Ex. convert(input:100 BUSD, outAsset: BTC) -> 0.0001234 BTC :param input_amount: amount/asset to convert to outAsset :param out_asset: the Asset you want to convert to :return: CryptoAmount of input
- async get_deepest_usd_pool() LiquidityPool
- async get_details_for_chain(chain: str | Chain) InboundDetail
Returns the inbound details for a given chain. Results are cached.
- Parameters:
chain – Chain (enum or str)
- Returns:
- async get_exchange_rate(a_from: Asset, a_to: Asset) Decimal
Returns the exchange rate between two assets when using selected AMM protocol. Attention: slippage is not taken into account! Use THORChainQuery.quote_swap for more accurate simulation.
:param a_from: Source Asset :param a_to: Destination Asset :return: Decimal
- async get_expected_swap_output(input_amount: CryptoAmount, dest_asset: Asset) SwapOutput
This method does an approximate calculation of the swap output using known pool ratios and math. It takes into account only slippage but not the network fees. For a more accurate simulation, use THORChainQuery.quote_swap.
- Parameters:
input_amount – amount/asset to swap
dest_asset – destination asset
- Returns:
SwapOutput structure
- async get_fee_rate(chain: str | Chain) int
Returns the fee rate for a given chain from the inbound details. Results are cached.
- Parameters:
chain – Chain
- Returns:
Typical fee rate for the chain. sat/byte for Bitcoin, gas for Ethereum, etc.
- async get_inbound_details(forced=False) Dict[str, InboundDetail]
Returns the inbound details such as inbound vault address, fee rate and so on. Results are cached.
- Parameters:
forced – force refresh
- Returns:
inbound details (dict)
- async get_last_block() List[LastBlock]
Loads the last block information from the THORNode/MayaNode API. From LastBlock you can get the block height of the protocol and last observed height of the connected chains.
- Returns:
List[LastBlock]
- async get_liquidity_provider(asset: str | Asset, address: str, height: int = 0) LiquidityProviderSummary
Get the liquidity provider details for a given asset and address. Results are not cached. If height is not provided, the latest block height will be used.
- Parameters:
asset – Asset or str name of the pool
address – Address of the liquidity provider
height – Height of the block to query, if 0 then the latest block height will be used
- Returns:
LiquidityProviderSummary
- async get_name_details(name: str) THORNameDetails | None
Look up THORName details by a THORName. Details are cached.
- Parameters:
name – THORName to look up
- Returns:
Optional[THORNameDetails]
- async get_names_by_address(address: str) Set[str]
Look up THORNames that are associated with a wallet address. Names are cached.
- Raises:
ValueError – if address is not provided
- Parameters:
address – Address to look up
- Returns:
Set[str] - just the set of names without details (see: load_names_by_address)
- async get_names_with_details(address: str) List[THORNameDetails]
Look up THORNames with their details by a wallet address. Names are cached. But details are not cached yet.
- Parameters:
address – Address to look up
- Returns:
List[THORNameDetails]
- async get_native_block_height() int
Loads the native block height from the THORNode/MayaNode API.
- Returns:
int block height
- async get_network_values(forced=False) Dict[str, int]
Loads, caches and returns the Network values (Mimir and Constants combined).
- Parameters:
forced – force refresh
- Returns:
- async get_pool_for_asset(asset: Asset) LiquidityPool
Returns the liquidity pool for the given asset. Rune does not have a pool, because it is the collateral for any other asset.
:raises ValueError: if the asset is native :raises LookupError: if the pool is not found :param asset: Asset to find pool with
- return:
LiquidityPool
- async get_pools(forced=False) Dict[str, LiquidityPool]
Returns cached liquidity pools state as a Dict.
:param forced: Force reload data from the API bypassing the cache :return: Dict[str, LiquidityPool]
- get_rune_address(lp: LiquidityProviderSummary) str
Plucks the RUNE address from the LiquidityProviderSummary object depending on the protocol. It is either ‘rune_address’ for THORChain or ‘cacao_address’ for MayaChain.
- Parameters:
lp – LiquidityProviderSummary
- Returns:
str
- property is_maya
Returns True if this class is configured for Maya protocol.
- Returns:
- is_native_asset(a: Asset)
Checks if the asset is the native asset of the chain.
:param a: Any Asset :return: True if the asset is the native asset, False otherwise :rtype: bool
- property is_thorchain
Returns True if this class is configured for THORChain protocol.
- Returns:
- property midgard_client: MidgardAPIClient
Returns the Midgard API client.
- pluck_native_block_height(data: LastBlock) int
Extracts the native block height from the LastBlock object.
- Parameters:
data – LastBlock object
- Returns:
int block height
- async refresh_inbound_cache() Dict[str, InboundDetail]
Refreshes the Inbound Details Cache which includes inbound address for each chain, current fee rate, halt state and more. It might be a better idea to call get_inbound_details() method that provides caching.
:return InboundDetails
- async refresh_network_values() Dict[str, int]
Refreshes the NetworkValues Cache (Mimir and Constants combined).
- Returns:
Dict[str, int]
- async refresh_pool_cache() Dict[str, LiquidityPool]
This will reload the pool details from both THORNode and Midgard and store them into the cache.
- Returns:
Dict[str, LiquidityPool]
- property thornode_client: THORNodeAPIClient
Returns the THORNode API client.
Transaction Status Checker
- xchainpy2_thorchain_query.track.tracker.DEFAULT_POLL_INTERVAL = 5
Default poll interval in seconds for polling transaction status
- class xchainpy2_thorchain_query.track.tracker.TransactionTracker(cache: THORChainCache, chain_attributes=None, inbound_chain_client: XChainClient | None = None, outbound_chain_client: XChainClient | None = None)
Bases:
object- async check_tx_outside_thorchain(tx_hash: str, is_inbound: bool)
Check transaction status outside THORChain, namely in the inbound or outbound chain. :param tx_hash: Transaction hash (tx_id) :param is_inbound: If True, check transaction status before it’s observed by THORChain, otherwise after it’s signed by THORChain :return:
- async check_tx_progress(inbound_tx_hash: str) TxDetails
Check transaction progress.
- Parameters:
inbound_tx_hash – Transaction hash (tx_id)
- Returns:
Transaction details
- poll(txid: str, interval=5, stage=True, status=True)
Poll TX status. Usages:
- async for details in tracker.poll(txid):
- if not details.pending:
print(f’Finished: {details}’) break
- else:
print(‘Still pending…’)
- Parameters:
status – Flag to check status of TX
stage – Flag to check stage of TX
txid – inbound TX hash
interval – Interval between requests in seconds
- Returns:
async generator
- async tc_get_tx_details(inbound_tx_hash: str, height=0) TxSignersResponse | None
- async tc_get_tx_status(inbound_tx_hash: str, height=0) TxStatusResponse | None
Get transaction status from THORChain. https://thornode.ninerealms.com/thorchain/tx/status/inbound_tx_hash According to the current implementation, if the transaction is not found, it doesn’t return “None”
but something like that
- {
- “stages”: {
- “inbound_observed”: {
“started”: false, “final_count”: 0, “completed”: false
}
}
}
- Parameters:
inbound_tx_hash – Tx hash without 0x prefix
height – Block height, if not provided, the latest block height is used
- Returns:
Optional[TxStatusResponse]
- class xchainpy2_thorchain_query.track.tracker.TransactionTrackerAsyncGenerator(tracker: TransactionTracker, interval, tx_hash, stage=True, status=True)
Bases:
object
Uses the following data types.
- class xchainpy2_thorchain_query.track.dtypes.TxDetails(txid: str, action_type: ActionType, status: TxStatus, stage: TxStage, signers: TxSignersResponse, status_details: TxStatusResponse)
Bases:
NamedTupleTransaction details, stage and status
- action_type: ActionType
Alias for field number 1
- classmethod create_from_thorchain(signers: TxSignersResponse | None, status_details: TxStatusResponse | None, tx_hash='')
- classmethod dry_run_success(tx_hash: str)
Create TxDetails that represents successful dry-run transaction
- Parameters:
tx_hash – TX hash string
- Returns:
TxDetails
- property failed
- classmethod find_refunds(status_details: TxStatusResponse)
- classmethod get_stage(status_details, stage, key='completed', default=None)
- property has_out_txs
- property has_refunds
- property pending
- signers: TxSignersResponse
Alias for field number 4
- status_details: TxStatusResponse
Alias for field number 5
- property successful
- txid: str
Alias for field number 0
- class xchainpy2_thorchain_query.track.dtypes.TxStage(value)
Bases:
EnumTransaction stage enum.
- InboundConfirmationCounted = 'InboundConfirmationCounted'
Transaction is observed and has enough confirmations
- InboundFinalised = 'InboundFinalised'
Transaction is finalised on the inbound chain
- InboundObserved = 'InboundObserved'
Transaction is observed by THORChain
- InboundSubmitted = 'InboundSubmitted'
Transaction is submitted on the inbound chain, but not observed yet by THORChain
- OutboundConfirmed = 'OutboundConfirmed'
Outbound transaction is confirmed in the outbound chain
- OutboundDelayWait = 'OutboundDelayWait'
Outbound transaction is waiting for delay
- OutboundSigned = 'OutboundSigned'
Outbound transaction is signed by THORChain
- SwapFinalised = 'SwapFinalised'
Swap transaction is finalised
- Unknown = 'Unknown'
Unknown stage. Transaction is not observed yet even by the source blockchain client.
- class xchainpy2_thorchain_query.track.dtypes.TxStatus(value)
Bases:
EnumTransaction status enum. If it is pending, it means that transaction is not finished yet. But you can check its stage. See TxStage enum. If transaction is done, it means that it is finished successfully. Incomplete means that you need to submit another transaction to complete this one (usually add liquidity for other side).
- BELOW_DUST = 'dust'
- BelowDust = 'dust'
- DONE = 'done'
- Done = 'done'
- INCOMPLETE = 'incomplete'
- Incomplete = 'incomplete'
- PENDING = 'pending'
- Pending = 'pending'
- REFUNDED = 'refunded'
- Refunded = 'refunded'
- UNKNOWN = 'unknown'
- Unknown = 'unknown'
- classmethod finished()
Return list of statuses that are considered finished (successful or failed) :return:
- property is_finished
- property is_pending
- property is_successful
Constants
- xchainpy2_thorchain_query.const.DEFAULT_EXTRA_ADD_MINUTES = 15
Default extra minutes to add to the current time for the deadline of a transaction.
- xchainpy2_thorchain_query.const.DEFAULT_INTERFACE_ID = 'XChainPy2'
Default Interface ID. This is used to identify the client when making requests to the public data provider. If you don’t attach an interface ID, the server may reject your request.
- class xchainpy2_thorchain_query.const.Mimir
Bases:
objectThis class holds some necessary Mimir constants names for THORChain.
- FULL_IL_PROTECTION_BLOCKS = 'FULLIMPLOSSPROTECTIONBLOCKS'
- HALT_CHAIN_GLOBAL = 'HALTCHAINGLOBAL'
- HALT_TRADING = 'HALTTRADING'
- MAX_TX_OUT_OFFSET = 'MAXTXOUTOFFSET'
- MIN_TX_OUT_VOLUME_THRESHOLD = 'MINTXOUTVOLUMETHRESHOLD'
- PAUSE_LP = 'PAUSELP'
- RUNEPoolDepositMaturityBlocks = 'RUNEPoolDepositMaturityBlocks'
- TNS_FEE_PER_BLOCK = 'TNSFEEPERBLOCK'
- TNS_REGISTER_FEE = 'TNSREGISTERFEE'
- TX_OUT_DELAY_RATE = 'TXOUTDELAYRATE'
- static halt_trading(chain)
Returns the Mimir constant name for halting trading on a chain.
- Parameters:
chain (str) – Name of the chain
- Returns:
Mimir constant name
- Return type:
str
- static pause_lp(chain: str)
Returns the Mimir constant name for pausing liquidity provision on a chain.
- Parameters:
chain (str) – Name of the chain
- Returns:
Mimir constant name
- Return type:
str
- xchainpy2_thorchain_query.const.TC_BOND_ADDR = 'thor17gw75axcnr8747pkanye45pnrwk7p9c3cqncsv'
Bond module’s address for THORChain.
- xchainpy2_thorchain_query.const.TC_POOL_ADDR = 'thor1g98cy3n9mmjrpn0sxmn63lztelera37n8n67c0'
Pool module’s address for THORChain.
- xchainpy2_thorchain_query.const.TC_RESERVE_ADDR = 'thor1dheycdevq39qlkxs2a6wuuzyn4aqxhve4qxtxt'
Reserve module’s address for THORChain.
- xchainpy2_thorchain_query.const.TC_STANDBY_RESERVE_ADDR = 'thor1lj62pg6ryxv2htekqx04nv7wd3g98qf9gfvamy'
Standby reserve module’s address for THORChain. Burnt.
- xchainpy2_thorchain_query.const.TEN_MINUTES = 600
Ten minutes in seconds.
- xchainpy2_thorchain_query.const.THORNAME_BLOCKS_ONE_YEAR = 5259600
Number of blocks in one year for THORChain.
- xchainpy2_thorchain_query.const.THOR_BLOCK_TIME_SEC = 6.0
Typical time in seconds for a block to be produced in THORChain.
- xchainpy2_thorchain_query.const.USD_ASSETS = {NetworkType.MAINNET: [('BNB', 'BUSD', 'BD1', AssetKind.NORMAL), ('ETH', 'USDC', '0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48', AssetKind.NORMAL), ('ETH', 'USDT', '0XDAC17F958D2EE523A2206206994597C13D831EC7', AssetKind.NORMAL), ('ETH', 'DAI', '0X6B175474E89094C44DA98B954EEDEAC495271D0F', AssetKind.NORMAL), ('ETH', 'GUSD', '0X056FD409E1D7A124BD7017459DFEA2F387B6D5CD', AssetKind.NORMAL), ('ETH', 'LUSD', '0X5F98805A4E8BE255A32880FDEC7F6728C6568BA0', AssetKind.NORMAL), ('ETH', 'USDP', '0X8E870D67F660D95D5BE530380D0EC0BD388289E1', AssetKind.NORMAL), ('AVAX', 'USDC', '0XB97EF9EF8734C71904D8002F8B6BC66DD9C48A6E', AssetKind.NORMAL), ('BSC', 'USDC', '0X8AC76A51CC950D9822D68B83FE1AD97B32CD580D', AssetKind.NORMAL)], NetworkType.STAGENET: [('ETH', 'USDT', '0XDAC17F958D2EE523A2206206994597C13D831EC7', AssetKind.NORMAL)], NetworkType.TESTNET: [('BNB', 'BUSD', '74E', AssetKind.NORMAL), ('ETH', 'USDT', '0XA3910454BF2CB59B8B3A401589A3BACC5CA42306', AssetKind.NORMAL)]}
Stable USD assets for different networks types. The list is based on the pool list from THORChain. Subject to change.
Models
- class xchainpy2_thorchain_query.models.BlockInformation(inbound_confirmation_blocks: int = 0, inbound_confirmation_seconds: float = 0.0, outbound_delay_blocks: int = 0, outbound_delay_seconds: float = 0.0)
Bases:
NamedTupleA named tuple representing inbound/outbound TX delay in blocks and seconds.
- inbound_confirmation_blocks: int
Inbound confirmation blocks
- inbound_confirmation_seconds: float
Inbound confirmation seconds
- outbound_delay_blocks: int
Outbound delay blocks
- outbound_delay_seconds: float
Outbound delay seconds
- class xchainpy2_thorchain_query.models.EstimateAddLP(asset_pool: str, slip_percent: float, pool_share: LPAmount, lp_units: int, inbound_fees: LPAmountTotal, rune_to_asset_ratio: int, estimated_wait_seconds: int, errors: List[str], can_add: bool, recommended_min_amount_in: int)
Bases:
NamedTupleA named tuple representing an estimate for adding liquidity to a pool.
- asset_pool: str
Pool name
- can_add: bool
Whether the liquidity can be added
- errors: List[str]
List of errors, if any
- estimated_wait_seconds: int
Estimated wait time in seconds
- inbound_fees: LPAmountTotal
Inbound fees
- lp_units: int
Liquidity units
Pool share
- recommended_min_amount_in: int
Recommended minimum amount to send in the transaction
- rune_to_asset_ratio: int
Rune to asset ratio
- slip_percent: float
Slippage percentage
- class xchainpy2_thorchain_query.models.EstimateAddSaver(can_add_saver, asset_amount, estimated_deposit_value, slip_basis_points, fee, expiry, to_address, memo, saver_cap_filled_percent, estimated_wait_time, errors, recommended_min_amount_in)
Bases:
NamedTuple- asset_amount: CryptoAmount
Alias for field number 1
- can_add_saver: bool
Alias for field number 0
- errors: List[str]
Alias for field number 10
- estimated_deposit_value: CryptoAmount
Alias for field number 2
- estimated_wait_time: int
Alias for field number 9
- expiry: datetime
Alias for field number 5
- memo: str
Alias for field number 7
- recommended_min_amount_in: int
Alias for field number 11
- saver_cap_filled_percent: float
Alias for field number 8
- slip_basis_points: int
Alias for field number 3
- to_address: str
Alias for field number 6
- class xchainpy2_thorchain_query.models.EstimateWithdrawLP(can_withdraw: bool, deposit_amount: CryptoAmount, asset_address: str | None, rune_address: str | None, slip_percent: float, inbound_fee: LPAmountTotal, inbound_min_to_send: LPAmountTotal, outbound_fee: LPAmountTotal, asset_amount: CryptoAmount, rune_amount: CryptoAmount, lp_growth: str, estimated_wait_seconds: int, asset_pool: str, errors: List[str], memo: str, inbound_address: str, mode: WithdrawMode)
Bases:
NamedTupleA named tuple representing an estimate for withdrawing liquidity from a pool.
- asset_address: str | None
Asset address
- asset_amount: CryptoAmount
Asset amount
- asset_pool: str
Pool name
- can_withdraw: bool
Whether the liquidity can be withdrawn
- deposit_amount: CryptoAmount
Deposit amount
- errors: List[str]
List of errors, if any
- estimated_wait_seconds: int
Estimated wait time in seconds
- inbound_address: str
Inbound address
- inbound_fee: LPAmountTotal
Inbound fee
- inbound_min_to_send: LPAmountTotal
Minimum amount to send
- lp_growth: str
LP growth
- classmethod make_error(error, mode)
- memo: str
Memo
- mode: WithdrawMode
Alias for field number 16
- outbound_fee: LPAmountTotal
Outbound fee
- rune_address: str | None
Rune address
- rune_amount: CryptoAmount
Rune amount
- slip_percent: float
Slippage percentage
- class xchainpy2_thorchain_query.models.EstimateWithdrawSaver(expected_asset_amount: CryptoAmount, fee: SaverFees, expiry: datetime, to_address: str, memo: str, estimated_wait_time: float, slip_basis_points: float, dust_amount: CryptoAmount, errors: List[str], details: QuoteSaverWithdrawResponse | None = None)
Bases:
NamedTupleA named tuple representing an estimate for withdrawing liquidity from the savers vault.
- property can_withdraw
If there are no errors, the withdrawal can be made. :return: bool
- details: QuoteSaverWithdrawResponse | None
QuoteSaverWithdrawResponse received from THORChain API, may contain additional details
- dust_amount: CryptoAmount
Dust amount, any amount below this value will be considered dust and ignored
- errors: List[str]
List of errors, if any
- estimated_wait_time: float
Estimated wait time in seconds
- expected_asset_amount: CryptoAmount
Expected asset amount that will be withdrawn to the user after applying fees and slippage
- expiry: datetime
Expiry date of the withdrawal request
- classmethod make_error(errors, asset: Asset, details=None)
Create an EstimateWithdrawSaver instance with errors list.
- Parameters:
errors – List of errors
asset – Asset to withdraw
- Returns:
EstimateWithdrawSaver
- memo: str
Memo string that is supposed to be sent along with the transaction to perform the withdrawal
- slip_basis_points: float
Slippage in basis points 0..10000 paid for internal swaps
- to_address: str
Address to send the withdraw request to
- class xchainpy2_thorchain_query.models.InboundDetail(chain: Chain, address: str, router: str | None, gas_rate: int, gas_rate_units: str, outbound_tx_size: int, outbound_fee: int, halted_chain: bool, halted_trading: bool, halted_lp: bool, dust_threshold: int)
Bases:
NamedTupleA named tuple representing the inbound details for a chain. It includes the chain, Asgard address, router, gas rate and other helpful information. See: https://thornode.ninerealms.com/thorchain/inbound_addresses
- address: str
Address of the vault
- dust_threshold: int
Dust threshold, do not send amounts below this value
- gas_rate: int
Gas rate
- gas_rate_units: str
gwei, satsperbyte, etc.
- Type:
Gas rate units
- halted_chain: bool
Whether the chain is halted
- halted_lp: bool
Whether liquidity operations is halted
- halted_trading: bool
Whether trading is halted
- outbound_fee: int
Outbound fee
- outbound_tx_size: int
Outbound transaction size
- router: str | None
Router address for EVM chains
- class xchainpy2_thorchain_query.models.InboundDetailCache(last_refreshed: float, inbound_details: Dict[str, InboundDetail])
Bases:
objectA dataclass representing a cache of inbound details for chains.
- inbound_details: Dict[str, InboundDetail]
Mapping of chain names to inbound details
- last_refreshed: float
Timestamp of the last refresh
- xchainpy2_thorchain_query.models.InboundDetails
Mapping of chain names to inbound details
alias of
Dict[str,InboundDetail]
- class xchainpy2_thorchain_query.models.LPAmount(rune: CryptoAmount, asset: CryptoAmount)
Bases:
NamedTupleA named tuple representing the amount of liquidity in a pool.
- asset: CryptoAmount
Asset amount
- rune: CryptoAmount
Rune amount
- class xchainpy2_thorchain_query.models.LPAmountTotal(rune: CryptoAmount, asset: CryptoAmount, total: CryptoAmount)
Bases:
NamedTupleA named tuple representing the total amount of liquidity in a pool.
- asset: CryptoAmount
Asset amount
- rune: CryptoAmount
Rune amount
- total: CryptoAmount
Total amount in Rune
- classmethod zero(asset: Asset | None = None) LPAmountTotal
Create a zero LPAmountTotal instance.
- Parameters:
asset – Asset
- Returns:
- Return type:
- class xchainpy2_thorchain_query.models.LastBlockCache(last_blocks: List[LastBlock], last_refreshed: float)
Bases:
objectA dataclass representing a cache of last blocks of THORChain and connected chains.
- last_blocks: List[LastBlock]
List of last blocks
- last_refreshed: float
Timestamp of the last refresh
- class xchainpy2_thorchain_query.models.LiquidityPool(pool: PoolDetail | None, thornode_details: Pool | None, asset_balance: Amount, rune_balance: Amount, asset: Asset, asset_string: str, rune_to_asset_ratio: Decimal, asset_to_rune_ratio: Decimal)
Bases:
NamedTupleCompound Names Tuple class representing a liquidity pool in THORChain. It includes the pool details taken from the Midgard API and THORNode API
- AVAILABLE = 'available'
available
- Type:
Pool status
- asset_string: str
Collateral asset as a string
- asset_to_rune_ratio: Decimal
Asset to rune ratio; Rune price in asset units
- classmethod from_node_pool(thornode_pool: Pool)
Create a LiquidityPool instance from THORNode pool details only.
- Parameters:
thornode_pool (Pool) – THORNode pool details
- Returns:
a new LiquidityPool instance
- Return type:
- classmethod from_pool_details(pool: PoolDetail, thornode_details: Pool)
Create a LiquidityPool instance from pool details from Midgard API and THORNode API.
- Parameters:
pool – Midgard pool details
thornode_details – THORNode pool details
- Returns:
a new LiquidityPool instance
- Return type:
- is_available() bool
Check if the pool is in available status.
- Returns:
True if the pool is available, False otherwise
- Return type:
bool
- pool: PoolDetail | None
Pool details from Midgard API
- rune_to_asset_ratio: Decimal
Rune to asset ratio; asset price in Runes
- thornode_details: Pool | None
Pool details from THORNode API
- class xchainpy2_thorchain_query.models.LiquidityPosition(pool_share, position, lp_growth)
Bases:
NamedTuple- lp_growth: str
Alias for field number 2
Alias for field number 0
- position: LiquidityProviderSummary
Alias for field number 1
- class xchainpy2_thorchain_query.models.LoanCloseQuote(inbound_address: str, expected_wait_time: BlockInformation, fees: QuoteFees, slippage_bps: int, router: str, expiry: int, warning: str, notes: str, dust_threshold: int, memo: str, expected_amount_out: int, expected_collateral_down: int, expected_debt_down: int, errors: List[str], recommended_min_amount_in: int)
Bases:
NamedTupleA named tuple representing a quote for closing a loan.
- dust_threshold: int
Dust threshold
- classmethod empty_with_errors(errors)
Create an empty LoanCloseQuote instance with errors list.
- Parameters:
errors – List of errors
- Returns:
LoanCloseQuote
- errors: List[str]
List of errors, if any
- expected_amount_out: int
Expected amount out
- expected_collateral_down: int
Expected collateral down
- expected_debt_down: int
Expected debt down
- expected_wait_time: BlockInformation
Expected wait time for the transaction to be confirmed
- expiry: int
Expiry block number
- fees: QuoteFees
Fees for the transaction
- inbound_address: str
Inbound address to repay the loan
- memo: str
Prepared memo for the transaction
- notes: str
Notes and instructions
- recommended_min_amount_in: int
Recommended minimum amount to send in the transaction
- router: str
Router address (for EVM chains)
- slippage_bps: int
Slippage in basis points
- warning: str
Warning message
- class xchainpy2_thorchain_query.models.LoanOpenQuote(inbound_address: str, expected_wait_time: BlockInformation, fees: QuoteFees, slippage_bps: int, router: str, expiry: int, warning: str, notes: str, dust_threshold: int, memo: str, expected_amount_out: int, expected_collateralization_ratio: float, expected_collateral_up: int, expected_debt_up: int, errors: List[str], recommended_min_amount_in: int)
Bases:
NamedTupleA named tuple representing a quote for opening a loan.
- dust_threshold: int
Dust threshold
- classmethod empty_with_errors(errors)
Create an empty LoanOpenQuote instance with errors list.
- Parameters:
errors – List of errors
- Returns:
LoanOpenQuote
- errors: List[str]
List of errors, if any
- expected_amount_out: int
Expected amount out
- expected_collateral_up: int
Expected collateral up
- expected_collateralization_ratio: float
Expected collateralization ratio
- expected_debt_up: int
Expected debt up
- expected_wait_time: BlockInformation
Expected wait time for the transaction to be confirmed
- expiry: int
Expiry block number
- fees: QuoteFees
Fees for the transaction
- inbound_address: str
Vault’s address to send your collateral to
- memo: str
Prepared memo for the transaction
- notes: str
Notes and instructions
- recommended_min_amount_in: int
Recommended minimum amount to send in the transaction
- router: str
Router address (for EVM chains)
- slippage_bps: int
Slippage in basis points
- warning: str
Warning message
- class xchainpy2_thorchain_query.models.NameCache(address_to_name: Dict[str, Set[str]], name_details: Dict[str, THORNameDetails], name_last_refreshed: Dict[str, float])
Bases:
objectA dataclass representing a cache of THORNames.
- address_to_name: Dict[str, Set[str]]
Mapping of addresses to names
- invalidate(block_height: int)
Invalidate expired THORNameDetails at the given block height.
- Parameters:
block_height – Block height to compare the expiry with
- Returns:
None
- static is_expired(n: THORNameDetails, last_block_height: int)
Check if a THORNameDetails object is expired.
- Parameters:
n (THORNameDetails) – THORName details
last_block_height (int) – Last block height to compare the expiry with
- Returns:
True if the THORNameDetails object is expired, False otherwise
- Return type:
bool
- name_details: Dict[str, THORNameDetails]
Mapping of names to name details
- name_last_refreshed: Dict[str, float]
Timestamp of the last refresh for each name
- put(name: str, n: THORNameDetails | None)
Put a THORNameDetails object into the cache.
- Parameters:
name (str) – Name of the THORName
n (Optional[THORNameDetails]) – THORNameDetails object, None if the name is to be removed from the cache
- Returns:
None
- class xchainpy2_thorchain_query.models.NetworkValuesCache(last_refreshed: float, network_values: Dict[str, int])
Bases:
objectA dataclass representing a cache of network values (constants, Mimir) for THORChain.
- last_refreshed: float
Timestamp of the last refresh
- network_values: Dict[str, int]
Mapping of network values
- class xchainpy2_thorchain_query.models.PoolCache(last_refreshed: float, pools: Dict[str, LiquidityPool])
Bases:
objectA dataclass representing a cache of liquidity pools.
- last_refreshed: float
Timestamp of the last refresh
- pools: Dict[str, LiquidityPool]
Mapping of liquidity pools by pool asset string
- class xchainpy2_thorchain_query.models.PoolRatios(asset_to_rune, rune_to_asset)
Bases:
NamedTuple- asset_to_rune: Decimal
Alias for field number 0
- rune_to_asset: Decimal
Alias for field number 1
- exception xchainpy2_thorchain_query.models.QueryError
Bases:
LookupErrorQuery error is raised when the module fails to query the data from THORChain.
- class xchainpy2_thorchain_query.models.SaverFees(affiliate, asset, outbound)
Bases:
NamedTuple- affiliate: CryptoAmount
Alias for field number 0
- outbound: CryptoAmount
Alias for field number 2
- class xchainpy2_thorchain_query.models.SaversPosition(deposit_value: CryptoAmount, redeemable_value: CryptoAmount, last_add_height: int, saver_growth: float, errors: List[str])
Bases:
NamedTupleA named tuple representing the position of a saver in the savers vault.
- deposit_value: CryptoAmount
Deposit value
- errors: List[str]
List of errors, if any
- last_add_height: int
Last add height (THORChain blocks)
- redeemable_value: CryptoAmount
Current redeemable value
- saver_growth: float
Saver growth (percentage)
- class xchainpy2_thorchain_query.models.SwapEstimate(total_fees: TotalFees, slip_bps: int, net_output: CryptoAmount, inbound_confirmation_seconds: float, outbound_delay_seconds: float, can_swap: bool, errors: List[str], recommended_min_amount_in: int, streaming_swap_interval: int, details: QuoteSwapResponse)
Bases:
NamedTupleA named tuple representing an estimate for a swap transaction.
- can_swap: bool
Whether the swap can be executed
- details: QuoteSwapResponse
Original details of the swap estimate that was returned by THORChain API
- errors: List[str]
List of errors, if any (in case the swap cannot be executed)
- inbound_confirmation_seconds: float
Estimated time in seconds for the inbound transaction to be confirmed
- property is_less_than_price_limit
Check if the swap is less than the price limit. Does search for the error message in the errors list. :return: True if the swap is less than the price limit, False otherwise :rtype: bool
- property memo
E501
generated memo for the swap # noqa: E501
- Returns:
The memo of this QuoteSwapResponse. # noqa: E501
- Return type:
str
- Type:
Gets the memo of this QuoteSwapResponse. # noqa
- net_output: CryptoAmount
Net output amount after fees and slippage
- property notes
E501
chain specific quote notes # noqa: E501
- Returns:
The notes of this QuoteSwapResponse. # noqa: E501
- Return type:
str
- Type:
Gets the notes of this QuoteSwapResponse. # noqa
- outbound_delay_seconds: float
Estimated time in seconds for the outbound transaction to be delayed
- recommended_min_amount_in: int
Recommended minimum amount to send in the swap
- slip_bps: int
Slippage in basis points (0-10000)
- streaming_swap_interval: int
Recommended interval for streaming swaps in blocks
- property streaming_swap_max_quantity: int
Get the maximum amount of trades a streaming swap can do for a trade
- class xchainpy2_thorchain_query.models.SwapOutput(output: CryptoAmount, swap_fee: CryptoAmount, slip: Decimal)
Bases:
NamedTupleA named tuple representing the output of a swap transaction.
- output: CryptoAmount
Output amount and asset
- slip: Decimal
Slippage 0..1
- swap_fee: CryptoAmount
Swap fee amount
- class xchainpy2_thorchain_query.models.THORNameEstimate(can_register: bool, reason: str, cost: CryptoAmount, details: THORNameDetails | None = None, last_block_number: int = 0)
Bases:
NamedTupleA named tuple representing a result of simulating a THORName registration. If successful, the can_register field will be True and the cost field will contain the estimated cost of the registration. If the registration is not possible, the can_register field will be False and the reason field will contain the reason why the registration is not possible.
- can_register: bool
Whether the registration is possible
- cost: CryptoAmount
The estimated cost of the registration
- details: THORNameDetails | None
The details of the registration, if successful
- classmethod error(reason: str, last_block_number: int) THORNameEstimate
Create a THORNameEstimate instance representing an error.
- Parameters:
reason – Reason for the error
last_block_number – Block number when the estimate was made
- Returns:
THORNameEstimate
- expiry_block_from_date(expiry: datetime) int
Calculate the block number at which the registration will expire.
- Parameters:
expiry (datetime) – The expiry date of the registration
- Returns:
block number at which the registration will expire
- Return type:
int
- last_block_number: int
The last block number when the estimate was made
- reason: str
The reason why the registration is not possible
- class xchainpy2_thorchain_query.models.TotalFees(asset: Asset, total_bps: int, total_fee: int, slippage_bps: int, affiliate_fee: int, liquidity_fee: int, outbound_fee: int)
Bases:
NamedTupleA named tuple representing the total fees for a swap transaction including outbound and affiliate fees.
- affiliate_fee: int
Affiliate fee in the destination asset
- property affiliate_fee_amount: CryptoAmount
- liquidity_fee: int
Liquidity fee in the destination asset
- property liquidity_fee_amount: CryptoAmount
- outbound_fee: int
Outbound fee in the destination asset
- property outbound_fee_amount: CryptoAmount
- slippage_bps: int
Slippage in basis points (0-10000)
- total_bps: int
Total basis points for the fees
- total_fee: int
Total fee in the destination asset
- property total_fee_amount: CryptoAmount
- class xchainpy2_thorchain_query.models.UnitData(liquidity_units: int, total_units: int)
Bases:
NamedTupleA named tuple representing the data of a unit of liquidity.
- liquidity_units: int
Liquidity units
- total_units: int
Total units of pool
- class xchainpy2_thorchain_query.models.WithdrawLiquidityPosition(asset, percentage, asset_address, rune_address)
Bases:
NamedTuple- asset_address: str | None
Alias for field number 2
- percentage: Decimal
Alias for field number 1
- rune_address: str | None
Alias for field number 3
Midgard interface
- class xchainpy2_thorchain_query.midgard.MidgardAPIClient(configuration: ConfigurationEx | None = None, header_name='x-client-id', header_value='xchainpy-client', cookie=None, pool_processes=None, user_agent='XChainPy2/0.0.25/python')
Bases:
HeadersPatch,ApiClientThis class is a wrapper around the Midgard API client
xchainpy2_midgard.ApiClient.- async close()
Close the REST client.
- Returns:
None
- request(method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None)
Override the request method to use the RESTClientRetry class and set the request timeout.
- Parameters:
method – Method type
url – URL
query_params – Parameters
headers – Headers
post_params – POST parameters
body – The body of the request
_preload_content – Flag to preload content
_request_timeout – Timeout for the request
- Returns:
Response
- Return type:
THORNode interface
- class xchainpy2_thorchain_query.thornode.THORNodeAPIClient(configuration: ConfigurationEx | None = None, header_name='x-client-id', header_value='xchainpy-client', cookie=None)
Bases:
HeadersPatch,ApiClientTHORNode API client.
- Parameters:
configuration – ConfigurationEx object
- async close()
Close the REST client.
- Returns:
None
- request(method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None)
Override the request method to use the RESTClientRetry class and set the request timeout.
- Parameters:
method – Method type
url – URL
query_params – Parameters
headers – Headers
post_params – POST parameters
body – The body of the request
_preload_content – Flag to preload content
_request_timeout – Timeout for the request
- Returns:
Response
- Return type:
Public API URLS
- class xchainpy2_thorchain_query.env.URLs
Bases:
objectA collection of URLs for public THORChain APIs (THORNode, RPC, Midgard). See https://ops.ninerealms.com/links for more links.
- class Midgard
Bases:
objectMidgard API URLs.
- MAINNET = 'https://midgard.ninerealms.com'
- NINE_REALMS = 'https://midgard.ninerealms.com'
- PUBLIC = 'https://midgard.thorchain.info'
- STAGENET = 'https://stagenet-midgard.ninerealms.com'
- TESTNET = 'https://testnet.midgard.thorchain.info'
- THORSWAP = 'https://midgard.thorswap.net'
- class RPC
Bases:
objectTHORChain RPC URLs.
- ARCHIVE_V0 = 'https://rpc-v0.ninerealms.com'
- MAINNET = 'https://rpc.ninerealms.com'
- NINE_REALMS = 'https://rpc.ninerealms.com'
- PUBLIC = 'https://rpc.thorchain.info'
- STAGENET = 'https://stagenet-rpc.ninerealms.com'
- TESTNET = 'https://testnet.rpc.thorchain.info/'
- THORSWAP = 'https://rpc.thorswap.net'
- class THORNode
Bases:
objectTHORNode API URLs.
- ARCHIVE_V0 = 'https://thornode-v0.ninerealms.com'
- ARCHIVE_V1 = 'https://thornode-v1.ninerealms.com'
- MAINNET = 'https://thornode.ninerealms.com'
- NINE_REALMS = 'https://thornode.ninerealms.com'
- PUBLIC = 'https://thornode.thorchain.info'
- STAGENET = 'https://stagenet-thornode.ninerealms.com'
- TESTNET = 'https://testnet.thornode.thorchain.info'
- THORSWAP = 'https://thornode.thorswap.net'
Swap arithmetic
- xchainpy2_thorchain_query.swap.calc_network_fee(asset: Asset, inbound: InboundDetail, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) CryptoAmount
Works out the required inbound fee based on the chain. https://dev.thorchain.org/thorchain-dev/thorchain-and-fees#fee-calcuation-by-chain
- Parameters:
base_asset
asset – source asset
inbound – inbound detail to get gas rates
- Returns:
amount of network fee
- xchainpy2_thorchain_query.swap.calc_outbound_fee(asset: Asset, inbound: InboundDetail, base_asset=('THOR', 'RUNE', '', AssetKind.DERIVED)) CryptoAmount
Works out the required outbound fee based on the chain.
- Parameters:
asset – Asset to send
inbound – Inbound detail for specific chain
base_asset – Rune or Cacao depending on the protocol
- Returns:
CryptoAmount of outbound fee
- xchainpy2_thorchain_query.swap.get_base_amount_with_diff_decimals(amount: CryptoAmount | Amount, out_decimals: int) Decimal
Helper function to get convert an amount to a Decimal with different decimal places.
- Parameters:
amount – Input amount
out_decimals – Number of decimal places to convert to
- Returns:
Decimal value
- xchainpy2_thorchain_query.swap.get_base_asset_decimals(base_asset: Asset) int
Helper function to get the base asset decimals.
- Parameters:
base_asset – RUNE or CACAO depending on the protocol used
- Returns:
int decimal places
- xchainpy2_thorchain_query.swap.get_double_swap_output(input_amount: CryptoAmount, pool1: LiquidityPool, pool2: LiquidityPool) CryptoAmount
This function locally estimates the output amount of a double swap.
- Parameters:
input_amount – Input amount to swap from pool1 to pool2
pool1 (LiquidityPool) – First pool
pool2 (LiquidityPool) – Second pool
- Returns:
CryptoAmount of output
- xchainpy2_thorchain_query.swap.get_double_swap_slip(input_amount: CryptoAmount, pool1: LiquidityPool, pool2: LiquidityPool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) Decimal
Works out the slippage fee for a double swap (Asset1 of pool1 -> Asset2 of pool2). Assets can not be RUNE. For Rune swaps please use get_swap_slip.
- Parameters:
input_amount – CryptoAmount to swap from pool1 to pool2
pool1 – source LiquidityPool
pool2 – target LiquidityPool
base_asset – AssetRUNE for TC, AssetCacao for Maya
- Returns:
- xchainpy2_thorchain_query.swap.get_single_swap(input_amount: CryptoAmount, pool: LiquidityPool, to_rune: bool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) SwapOutput
Calculates the output for a single swap (from Rune to Asset or Asset to Rune).
- Parameters:
input_amount – amount to swap
pool – Pool Data, RUNE and ASSET Depths
to_rune – To Rune or not to Rune
base_asset – AssetRUNE for TC, AssetCacao for Maya
- Returns:
swap output object - output - fee - slip
- xchainpy2_thorchain_query.swap.get_swap_fee(input_amount: CryptoAmount, pool: LiquidityPool, to_rune: bool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) CryptoAmount
Get the swap slip-based fee (slip * output) for a given swap.
- Parameters:
input_amount – amount to swap
pool – Pool Data, RUNE and ASSET Depths
to_rune – Direction of Swap. True if swapping to RUNE/CACAO.
base_asset – AssetRUNE for TC, AssetCacao for Maya
- Returns:
- xchainpy2_thorchain_query.swap.get_swap_output(input_amount: CryptoAmount, pool: LiquidityPool, to_rune: bool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) CryptoAmount
Works out locally the output amount for a given single swap (a single pool engaged).
- Parameters:
input_amount – amount to swap
pool – Pool Data, RUNE and ASSET Depths
to_rune – Direction of Swap. True if swapping to RUNE.
base_asset – AssetRUNE for TC, AssetCacao for Maya
- Returns:
The output amount
- xchainpy2_thorchain_query.swap.get_swap_slip(input_amount: CryptoAmount, pool: LiquidityPool, to_rune: bool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.DERIVED)) Decimal
Works out the swap slip for a given swap.
- Parameters:
input_amount – amount to swap
pool – Pool Data, RUNE and ASSET Depths
to_rune – Direction of Swap. True if swapping to RUNE.
base_asset – AssetRUNE for TC, AssetCacao for Maya
- Returns:
The amount of slip. Needs to * 100 to get percentage.
Liquidity math
- xchainpy2_thorchain_query.liquidity.get_liquidity_units(liquidity: LPAmount, pool: LiquidityPool) int
See: https://dev.thorchain.org/thorchain-dev/interface-guide/math#lp-units-add :param liquidity: asset amount added :param pool: pool depths :return: liquidity units - ownership of pool
- xchainpy2_thorchain_query.liquidity.get_pool_ownership(liquidity: LPAmount, pool: LiquidityPool) Decimal
Calculate liquidity units - % ownership of pool.
See: https://docs.thorchain.org/thorchain-finance/continuous-liquidity-pools#calculating-pool-ownership :param liquidity: asset amount added :param pool: pool depths :return: liquidity units - % ownership of pool
Get pool share of both asset and rune formula: (rune * part) / total; (asset * part) / total :param base_asset: AssetRUNE or AssetCACAO :param unit_data: units for both asset and rune :param pool: pool that the asset is bound to :return: pool share of both asset and rune in percentage
- xchainpy2_thorchain_query.liquidity.get_slip_on_liquidity(stake: LPAmount, pool: LiquidityPool) Decimal
Get slip percentage when adding liquidity. Formula: (t * R - T * r)/ (T*r + R*T).
- Parameters:
stake – the share of asset and rune added to the pool
pool – Pool that the asset is attached to
- Returns:
returns bignumber representing a slip percentage
Patch clients
This module is used to patch the API clients with the following features:
x-client-id header
Retry mechanism
Backup hosts
- class xchainpy2_thorchain_query.patch_clients.ConfigurationEx
Bases:
ConfigurationConfigurationEx object extends Configuration with additional parameters. timeout: request timeout in seconds retry_config: retry configuration (see: https://github.com/inyutin/aiohttp_retry) raise_for_status: if True, raise exceptions for HTTP errors backup_hosts: list of backup hosts to try if the main host fails
- classmethod new(host=None, api_key=None, api_key_prefix=None, username=None, password=None, ssl_ca_cert=None, cert_file=None, key_file=None, timeout=300, retry_config=<aiohttp_retry.retry_options.ExponentialRetry object>, raise_for_status=False, backup_hosts=None, verify_ssl=True)
Create a new ConfigurationEx object.
- Parameters:
host – The main host URL
api_key – Optional API key, not used by default in our case
api_key_prefix – Optional API key prefix, not used by default in our case
username – Optional username, not used by default in our case
password – Optional password, not used by default in our case
ssl_ca_cert – SSL CA certificate if needed
cert_file – Certificate file if needed
key_file – Key file if needed
timeout – Timeout in seconds for requests
retry_config – Retry configuration (see: https://github.com/inyutin/aiohttp_retry)
raise_for_status – if True, raise exceptions for HTTP errors
backup_hosts – An optional list of backup hosts to try if the main host fails
verify_ssl – Flag to verify SSL certificates, default is True
- Returns:
- xchainpy2_thorchain_query.patch_clients.DEFAULT_RETRY_ATTEMPTS = 3
Default number of retry attempts for requests.
- xchainpy2_thorchain_query.patch_clients.DEFAULT_TIMEOUT = 300
Default request timeout in seconds.
- class xchainpy2_thorchain_query.patch_clients.HeadersPatch
Bases:
objectThis is a trait class to patch REST clients with additional headers. Such as User-Agent and X-Chain-Client header. You probably don’t need to use it directly.
- patch_client(user_agent='Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36', identifier9r='xchainpy-client')
- class xchainpy2_thorchain_query.patch_clients.RESTClientRetry(configuration: ConfigurationEx | None, pools_size=4, maxsize=4)
Bases:
RESTClientObject- async close()
- async xchainpy2_thorchain_query.patch_clients.request_api_with_backup_hosts(api, method, *args, **kwargs)
Request API with backup hosts. It calls the specified method starting from the main host and then tries backup hosts if the main host fails. This is a helper function. You probably don’t need to call it directly.
- Parameters:
api – API object to use
method – Method to call
args – Arguments
kwargs – Keyword arguments
- Returns: