THORChain query

XChainPy2 THORChain query is a Python library for querying swap quotes, pools, and other data from THORChain.

Main Query Module

Cache for frequently used data

Transaction Status Checker

Uses the following data types.

Constants

xchainpy2_thorchain_query.const.DEFAULT_CACAO_NETWORK_FEE = ((5000000000, 10), ('MAYA', 'CACAO', '', AssetKind.NATIVE))

Default Cacao fee for transactions. Subject to change. Please check the network constants for the actual network fee.

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.

xchainpy2_thorchain_query.const.DEFAULT_REST_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'

Default User-Agent for REST requests.

xchainpy2_thorchain_query.const.DEFAULT_RUNE_NETWORK_FEE = ((2000000, 8), ('THOR', 'RUNE', '', AssetKind.NATIVE))

Default network fee for RUNE transactions. This may be overridden by the network constants. Please check the network constants for the actual network fee.

class xchainpy2_thorchain_query.const.Mimir

Bases: object

This 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 = 5256000.0

Number of THORChain blocks in one year.

xchainpy2_thorchain_query.const.THOR_AFFILIATE_BASIS_POINT_MAX = 1000

Affiliate cannot receive more than 10% of the trade value.

xchainpy2_thorchain_query.const.THOR_BASIS_POINT_MAX = 10000

Maximum basis point value for THORChain. 10,000 basis points = 100% of the value. 0 basis points = 0% of the value.

xchainpy2_thorchain_query.const.THOR_BLOCK_TIME_SEC = 6.0

Typical time in seconds for a block to be produced in THORChain. Note! It is planned to be lowered to 2 seconds in the future, so it may change.

xchainpy2_thorchain_query.const.USD_ASSETS = {NetworkType.MAINNET: [('BNB', 'BUSD', 'BD1', AssetKind.NATIVE), ('ETH', 'USDC', '0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48', AssetKind.NATIVE), ('ETH', 'USDT', '0XDAC17F958D2EE523A2206206994597C13D831EC7', AssetKind.NATIVE), ('ETH', 'DAI', '0X6B175474E89094C44DA98B954EEDEAC495271D0F', AssetKind.NATIVE), ('ETH', 'GUSD', '0X056FD409E1D7A124BD7017459DFEA2F387B6D5CD', AssetKind.NATIVE), ('ETH', 'LUSD', '0X5F98805A4E8BE255A32880FDEC7F6728C6568BA0', AssetKind.NATIVE), ('ETH', 'USDP', '0X8E870D67F660D95D5BE530380D0EC0BD388289E1', AssetKind.NATIVE), ('AVAX', 'USDC', '0XB97EF9EF8734C71904D8002F8B6BC66DD9C48A6E', AssetKind.NATIVE), ('BSC', 'USDC', '0X8AC76A51CC950D9822D68B83FE1AD97B32CD580D', AssetKind.NATIVE)], NetworkType.STAGENET: [('ETH', 'USDT', '0XDAC17F958D2EE523A2206206994597C13D831EC7', AssetKind.NATIVE), ('BSC', 'USDT', '0X55D398326F99059FF775485246999027B3197955', AssetKind.NATIVE)], NetworkType.TESTNET: [('BNB', 'BUSD', '74E', AssetKind.NATIVE), ('ETH', 'USDT', '0XA3910454BF2CB59B8B3A401589A3BACC5CA42306', AssetKind.NATIVE)]}

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: NamedTuple

A 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: NamedTuple

A 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: LPAmount

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.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: NamedTuple

A 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.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: NamedTuple

A 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

chain: Chain

Chain

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: object

A 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: NamedTuple

A named tuple representing the amount of liquidity in a pool.

asset: CryptoAmount

Asset amount

rune: CryptoAmount

Rune amount

classmethod zero(asset: Asset | None = None) LPAmount

Create a zero LPAmount instance.

Parameters:

asset – Asset

Returns:

LPAmount instance

Return type:

LPAmount

class xchainpy2_thorchain_query.models.LPAmountTotal(rune: CryptoAmount, asset: CryptoAmount, total: CryptoAmount)

Bases: NamedTuple

A 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:

LPAmountTotal

class xchainpy2_thorchain_query.models.LastBlockCache(last_blocks: List[LastBlock], last_refreshed: float)

Bases: object

A 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: NamedTuple

Compound 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: Asset

Collateral asset of the pool

asset_balance: Amount

Amount of asset in the pool

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:

LiquidityPool

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:

LiquidityPool

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_balance: Amount

Amount of Rune/Cacao in the pool

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

pool_share: LPAmount

Alias for field number 0

position: LiquidityProviderSummary

Alias for field number 1

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: object

A 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: object

A 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: object

A 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: LookupError

Query error is raised when the module fails to query the data from THORChain.

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: NamedTuple

A 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

total_fees: TotalFees

Total fees that will be charged for the swap

class xchainpy2_thorchain_query.models.SwapOutput(output: CryptoAmount, swap_fee: CryptoAmount, slip: Decimal)

Bases: NamedTuple

A 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: NamedTuple

A 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: NamedTuple

A 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
asset: Asset

Destination asset

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
classmethod zero(asset: Asset) TotalFees

Create a zero TotalFees instance.

Parameters:

asset – Destination asset

Returns:

TotalFees instance

class xchainpy2_thorchain_query.models.UnitData(liquidity_units: int, total_units: int)

Bases: NamedTuple

A 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: Asset

Alias for field number 0

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

class xchainpy2_thorchain_query.models.WithdrawMode(value)

Bases: Enum

An enumeration representing the mode of withdrawal.

AssetOnly = 'AssetOnly'

Withdraw only Asset

RuneOnly = 'RuneOnly'

Withdraw only Rune

Symmetric = 'Symmetric'

Both Rune and Asset

xchainpy2_thorchain_query.models.get_rune_balance_of_node_pool(pool: Pool) Amount

Helper function to get the rune/cacao balance of a pool. Just unification of the rune/cacao balance attribute.

Parameters:

pool – Pool object

Returns:

Amount of rune/cacao in the pool

Midgard interface

class xchainpy2_thorchain_query.midgard.MidgardAPIClient(configuration: ConfigurationEx | None = None, header_name='x-client-id', header_value='xchainpy-client', cookie=None, user_agent='XChainPy2/0.1.1/python')

Bases: HeadersPatch, ApiClient

This 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:

RESTResponse

THORNode interface

Public API URLS

class xchainpy2_thorchain_query.env.URLs

Bases: object

A collection of URLs for public THORChain APIs (THORNode, RPC, Midgard). See https://ops.ninerealms.com/links for more links.

class Midgard

Bases: object

Midgard 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: object

THORChain 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: object

THORNode 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.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.NATIVE)) 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.NATIVE)) 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.NATIVE)) 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.NATIVE)) 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.NATIVE)) 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

xchainpy2_thorchain_query.liquidity.get_pool_share(unit_data: UnitData, pool: LiquidityPool, base_asset: Asset = ('THOR', 'RUNE', '', AssetKind.NATIVE)) LPAmount

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:

  1. x-client-id header

  2. Retry mechanism

  3. Backup hosts

class xchainpy2_thorchain_query.patch_clients.ConfigurationEx

Bases: Configuration

ConfigurationEx 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: object

This 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: