pactsdk package
Submodules
pactsdk.api module
Module for interacting with Pact API.
- class pactsdk.api.ListPoolsParams
Bases:
TypedDict
Parameters for calling the
pactsdk.pool.list_pools()
function.All keys are optional and can be omitted.
- offset: int
- limit: int
- is_verified: str
- creator: str
- primary_asset__on_chain_id: int
- secondary_asset__on_chain_id: int
- primary_asset__unit_name: str
- secondary_asset__unit_name: str
- primary_asset__name: str
- secondary_asset__name: str
- class pactsdk.api.ApiAsset
Bases:
TypedDict
Details about the liquidity pool assets returned from the asset pool.
- on_chain_id: str
- decimals: int
- id: int
- is_liquidity_token: bool
- is_verified: bool
- name: str
- total_amount: str
- tvl_usd: str
- unit_name: str
- volume_7d: str
- volume_24h: str
- class pactsdk.api.ApiPool
Bases:
TypedDict
The individual pool information returned from
pactsdk.pool.list_pools()
, this contains the basic pool information.- address: str
- on_chain_id: str
- confirmed_round: int
- creator: str
- fee_amount_7d: str
- fee_amount_24h: str
- fee_usd_7d: str
- fee_usd_24h: str
- tvl_usd: str
- volume_7d: str
- volume_24h: str
- apr_7d: str
- id: int
- is_verified: bool
- pool_asset: pactsdk.api.ApiAsset
- primary_asset: pactsdk.api.ApiAsset
- secondary_asset: pactsdk.api.ApiAsset
- class pactsdk.api.ApiListPoolsResponse
Bases:
TypedDict
Response from
pactsdk.pool.list_pools()
function containing pagination information and results.- count: int
- offset: int
- limit: int
- results: list[pactsdk.api.ApiPool]
- pactsdk.api.list_pools(pact_api_url, params)
Finds all the pools that match the pool options passed in.
- Parameters
pact_api_url (
str
) – The API URL to query the list of pools.params (
ListPoolsParams
) – Dict of params for querying the pools.
- Return type
- Returns
Pool data for all pools in the Pact that meets the pool options.
pactsdk.asset module
Utility functions and class for dealing with Algorand Standard Assets.
- pactsdk.asset.ASSETS_CACHE: dict[tuple[algosdk.v2client.algod.AlgodClient, int], 'Asset'] = {}
Dictionary mapping the asset index number to the
pactsdk.asset.Asset
class to speed up look up of the asset information.
- pactsdk.asset.fetch_asset_by_index(algod, index)
Fetches an
pactsdk.asset.Asset
class with the details about the asset for a given id number.The function uses an internal cache so as to minimize the number of times the actual Algorand client is used to look up the asset. This function is used through out the pact sdk to query asset information.
- Parameters
algod (
AlgodClient
) – An Algorand client to query about the asset.index (
int
) – An Algorand Asset number to look up.
- Return type
- Returns
An asset instance for the index passed in.
- class pactsdk.asset.Asset(algod, index, decimals, name=None, unit_name=None)
Bases:
object
Describes the basic data and the utility functions for an Algorand Standard Asset.
Typically you don’t create instances of this class manually. Use
pactsdk.client.PactClient.fetch_asset()
instead. Also, when instantiating the pool e.g. by usingpactsdk.client.PactClient.fetch_pool_by_id()
the missing pool assets are fetched automatically.- algod: algosdk.v2client.algod.AlgodClient
The Algorand sdk client to use for extracting asset details.
- index: int
The ID of the asset.
- decimals: int
The number of decimal places that the Asset supports.
- name: Optional[str] = None
The name of the Asset if there is one. This may be None.
- unit_name: Optional[str] = None
The name of a unit of the asset if there is one. This may be None.
- property ratio: int
The ratio between a base unit and the unit of the asset.
This is used to convert between an integer and floating point representation of the asset without loss of precision.
- Return type
int
- prepare_opt_in_tx(address)
This creates a transaction that will allow the account to “opt in” to the asset.
In Algorand, every account has to explicitly opt-in for an asset before receiving it. Needed if you want to receive an asset from a swap or to manage liquidity tokens.
- Parameters
address (
str
) – Account to opt in to this asset.- Return type
AssetTransferTxn
- Returns
A ready to send transaction to opt-in into the ASA.
- build_opt_in_tx(address, suggested_params)
Creates the actual transaction for the account to opt-in to holding the asset.
- Parameters
address (
str
) – Address of the account to opt in to the asset.suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.
- Return type
AssetTransferTxn
- Returns
A transaction to opt-in into asset.
- prepare_opt_out_tx(address, close_to)
This creates a transaction that will allow the account to “opt out” of the asset.
- Parameters
address (
str
) – Account to opt out of this asset.- Return type
AssetTransferTxn
- Returns
A ready to send transaction to opt-out of the ASA.
- build_opt_out_tx(address, close_to, suggested_params)
Creates the actual transaction for the account to opt-out from asset.
- Parameters
address (
str
) – Address of the account to opt out of the asset.suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.
- Return type
AssetTransferTxn
- Returns
A transaction to opt-out of the asset.
- is_opted_in(address)
Checks if the account is already able to hold this asset, that is it has already opted in.
This functions should be called to check if the opt-in transaction needs to be created. See
pactsdk.asset.Asset.prepare_opt_in_tx()
.- Parameters
address (
str
) – The account to check if the asset is opted in on.- Return type
bool
- Returns
True if the account is already opted in, false otherwise.
- get_holding(address)
Returns the amount of holding of this asset the account has.
Note that this function may return None if the account has not opted in for this asset.
- Parameters
address (
str
) – The account to check the current holding.- Return type
Optional
[int
]- Returns
The amount of this asset the account is holding, or None if the account is not opted into the asset.
- get_holding_from_account_info(account_info)
- Return type
Optional
[int
]
- build_transfer_tx(sender, receiver, amount, suggested_params, note=None)
- Return type
Transaction
- __eq__(other_asset)
Return equal by comparing the assets index value.
- Return type
bool
pactsdk.client module
This module exposes PactClient class which is an entry points for interacting with the SDK.
Typical usage example:
import algosdk
from algosdk.v2client.algod import AlgodClient
import pactsdk
algod = AlgodClient("<token>", "<url>")
pact = pactsdk.PactClient(algod)
algo = pact.fetch_asset(0)
other_coin = pact.fetch_asset(12345678)
pools = pact.fetch_pools_by_assets(algo, other_coin)
- class pactsdk.client.PactClient(algod, network='mainnet', **kwargs)
Bases:
object
An entry point for interacting with the SDK.
Exposes convenience methods for fetching assets and pools.
- __init__(algod, network='mainnet', **kwargs)
Constructor for the PactClient class.
- Parameters
algod (
AlgodClient
) – Algorand client to work with.network (
Literal
[‘mainnet’, ‘testnet’, ‘dev’]) – The Algorand network to use the client with. The configuration values depend on the chosen network.kwargs – Use it to overwrite configuration parameters.
- algod: algosdk.v2client.algod.AlgodClient
Algorand client to work with.
- config: pactsdk.config.Config
Client configuration with global contracts ids etc.
- farming: pactsdk.farming.farming_client.PactFarmingClient
- fetch_asset(asset_index)
A convenient method for fetching ASAs (Algorand Standard Asset).
This will return an Asset class with the relevant data about the asset if the asset index is valid. Note that an index of zero (0) will return the Algo asset.
- Parameters
asset_index (
int
) – The id of the asset.- Raises
algosdk.error.AlgodHTTPError – If the asset does not exist.
- Return type
- Returns
Asset instance for the given index.
- list_pools(params=None)
Returns a list of pools according to the pool options passed in. Uses Pact API for fetching the data.
This method is deprecated but is kept for backward compatibility. Pact is in the process of changing the way the pools are created. In the future, all pools will be created using a pool factory contract which allows for an on-chain discoverability of pools.
- Parameters
params (
Optional
[ListPoolsParams
]) – API call parameters.- Return type
- Returns
Paginated list of pools.
- fetch_pools_by_assets(primary_asset, secondary_asset)
Returns a list of liquidity pools on Pact that are across the primary and secondary assets.
First, it uses Pact API retrieve app ids matching the provided assets and then uses algod client to fetch contracts data from the blockchain.
- fetch_pool_by_id(app_id)
Fetches the pool by the application id. It uses algod client to fetch the data directly from the blockchain.
- Parameters
app_id (
int
) – The application id of pool to return.- Raises
algosdk.error.AlgodHTTPError – If the pool does not exist.
- Return type
- Returns
The pool for the application id.
- fetch_folks_lending_pool(app_id)
Fetches Folks Finance lending pool that can be used in FolksLendingPoolAdapter which allows higher APR than a normal pool. See
pactsdk.folks_lending_pool
for details.- Parameters
app_id (
int
) – The application id of the Folks Finance pool. You can find the ids here - https://docs.folks.finance/developer/contracts- Return type
- Returns
The Folks Finance lending pool for the given application id.
- get_folks_lending_pool_adapter(pact_pool, primary_lending_pool, secondary_lending_pool)
Creates the adapter object that allows composing Folks Finance lending pools with Pact pool, resulting in a higher APR. See
pactsdk.folks_lending_pool
for details.- Parameters
pact_pool (
Pool
) – The Pact pool between two fAssets tokens.primary_lending_pool (
FolksLendingPool
) – The Folks Finance pool for the primary fAsset.secondary_lending_pool (
FolksLendingPool
) – The Folks Finance pool for the secondary fAsset.
- Return type
- Returns
The adapter object.
- get_constant_product_pool_factory()
Gets the constant product pool factory according to the client’s configuration.
- Return type
- get_nft_constant_product_pool_factory()
Gets the NFT constant product pool factory according to the client’s configuration.
- Return type
pactsdk.constant_product_calculator module
- class pactsdk.constant_product_calculator.ConstantProductParams(fee_bps, pact_fee_bps)
Bases:
object
- fee_bps: int
- pact_fee_bps: int
- pactsdk.constant_product_calculator.get_swap_gross_amount_received(liq_a, liq_b, amount_deposited)
- Return type
int
- pactsdk.constant_product_calculator.get_swap_amount_deposited(liq_a, liq_b, gross_amount_received)
- Return type
int
- pactsdk.constant_product_calculator.get_constant_product_minted_liquidity_tokens(added_primary, added_secondary, total_primary, total_secondary, total_liquidity)
- Return type
int
- class pactsdk.constant_product_calculator.ConstantProductCalculator(pool)
Bases:
object
An implementation of a math behind constant product pools.
- get_price(liq_a, liq_b)
- Return type
float
- get_swap_gross_amount_received(liq_a, liq_b, amount_deposited)
- Return type
int
- get_swap_amount_deposited(liq_a, liq_b, gross_amount_received)
- Return type
int
- get_minted_liquidity_tokens(added_liq_a, added_liq_b)
- Return type
int
pactsdk.exceptions module
Exception thrown within the PactSDK.
- exception pactsdk.exceptions.PactSdkError
Bases:
Exception
The general exception used throughout pactsdk.
pactsdk.pool module
- pactsdk.pool.OperationType
The basic three operation types in a PACT liquidity pool, namely Add Liquidity (ADDLIQ), Remove Liquidity (REMLIQ) and making a swap (SWAP).
alias of
Literal
[‘SWAP’, ‘ADDLIQ’, ‘REMLIQ’]
- pactsdk.pool.fetch_app_global_state(algod, app_id)
Fetches the global state of the of an application.
- Parameters
algod (
AlgodClient
) – The algo client to query the app in.app_id (
int
) – The application id to fetch the state of.
- Return type
- Returns
The global state of the application.
- pactsdk.pool.fetch_pool_by_id(algod, app_id)
Fetches the pool from the blockchain using the provided algod client.
- Parameters
algod (
AlgodClient
) – The algo client to use.app_id (
int
) – The application id to fetch.
- Returns
The pool object for the application id passed in.
- Return type
- pactsdk.pool.fetch_pools_by_assets(algod, asset_a, asset_b, pact_api_url)
Returns the list of pools for the assets passed in.
There can be zero pools if there are no pools matching the assets, or multiple if there are multiple at different fees. The order of assets that you provide is irrelevant.
- Parameters
- Return type
list
[Pool]- Returns
A list of pools matching the provided assets.
- pactsdk.pool.get_app_ids_from_assets(pact_api_url, primary_asset_index, secondary_asset_index)
Returns the application ids for any pools that match the primary and secondary asset.
This function finds any pools using the pact_api_url passed in that match the asset ids passed in.
- Parameters
pact_api_url (
str
) – The API url to use.primary_asset_index (
int
) – The asset id for the primary asset of the pool.secondary_asset_index (
int
) – The asset id for the secondary asset of the pool.
- Return type
list
[int
]- Returns
List of asset ids.
- class pactsdk.pool.Pool(algod, app_id, primary_asset, secondary_asset, liquidity_asset, internal_state, fee_bps=30)
Bases:
object
Pool represents a liquidity pool in the PACT AMM.
Typically, users don’t have to instantiate this class manually. Use
pactsdk.client.PactClient.fetch_pool_by_id()
orpactsdk.client.PactClient.fetch_pools_by_assets()
instead.The primary methods of the pool are to create the transaction groups to enable you to:
Add Liquidity,
Removing Liquidity,
Create a Swap on the Pool.
- algod: algosdk.v2client.algod.AlgodClient
The Algorand client to use.
- app_id: int
The application id for the pool.
- primary_asset: pactsdk.asset.Asset
The asset of the liquidity pool with the lower index.
- secondary_asset: pactsdk.asset.Asset
The asset of the liquidity pool with the higher index.
- liquidity_asset: pactsdk.asset.Asset
The asset for the liquidity pool token (LP token) that is given when liquidity is added, and burned when liquidity is withdrawn.
- internal_state: pactsdk.pool_state.AppInternalState
The global state on the blockchain for this pool.
- fee_bps: int = 30
The fee in basis points for swaps trading on the pool.
- pool_type: Literal['CONSTANT_PRODUCT', 'NFT_CONSTANT_PRODUCT', 'STABLESWAP']
Different pool types use different formulas for making swaps.
- version: int
The version of the contract. May be 0 for some old pools which don’t expose the version in the global state.
- __eq__(other_pool)
Return equal by comparing the pools app_id value.
- Return type
bool
- get_escrow_address()
Get the escrow address of the pool.
- Return type
str
- Returns
The address corresponding to that pools’s escrow account.
- get_other_asset(asset)
Returns the “other” asset, i.e. primary if secondary is passed in and vice versa.
- Parameters
asset (
Asset
) – The primary or secondary asset of the pool.- Raises
PactSdkError – If the asset passed in is not the primary or secondary asset.
- Return type
- Returns
The other asset, if the primary asset was passed in it will be the secondary asset and vice versa.
- update_state()
Updates the internal and pool state properties by re-reading the global state in the blockchain.
Updating the pool state is recommended if there is a pause between the construction of the pool and the creation of the transactions on the pool. Calling this method ensures that the the pool state is not stale.
- Return type
- Returns
The new pool state.
- prepare_add_liquidity(primary_asset_amount, secondary_asset_amount, slippage_pct)
Creates a new LiquidityAddition instance.
- Parameters
options – Options for adding the liquidity.
- Return type
LiquidityAddition
- Returns
A new LiquidityAddition object.
- prepare_add_liquidity_tx_group(address, liquidity_addition)
Prepares a
pactsdk.transaction_group.TransactionGroup
for adding liquidity to the pool. Seepactsdk.pool.Pool.buildAddLiquidityTxs()
for details.- Parameters
address (
str
) – Account address that will deposit the primary and secondary assets and receive the LP token.primary_asset_amount – The amount of primary asset to deposit.
secondary_asset_amount – The amount of secondary asset to deposit.
- Return type
- Returns
A transaction group that when executed will add liquidity to the pool.
- build_add_liquidity_txs(address, liquidity_addition, suggested_params)
Builds the transactions to add liquidity for the primary asset and secondary asset of the pool.
In typical circumstances 3 transactions are generated:
deposit of asset A
deposit of asset B
“ADDLIQ” application call to add liquidity with the above deposits
The initial liquidity must satisfy the expression sqrt(a * b) - 1000 > 0.
- Parameters
address (
str
) – Account address that will deposit the primary and secondary assets and receive the LP token.primary_asset_amount – The amount of primary asset to deposit.
secondary_asset_amount – The amount of secondary asset to deposit.
suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.note – An optional note that can be added to the application ADDLIQ transaction.
- Raises
AssertionError – If initial liquidity is too low.
- Return type
list
[Transaction
]- Returns
List of transactions to add the liquidity.
- build_raw_add_liquidity_txs(address, primary_asset_amount, secondary_asset_amount, minimum_minted_liquidity_tokens, suggested_params, fee, note=b'')
- prepare_remove_liquidity_tx_group(address, amount)
Prepares the transaction group for removing liquidity from the pool.
- Parameters
address (
str
) – Account address that will deposit the LP token and receive the primary and secondary assets.amount (
int
) – The amount of the LP token to return to the pool.
- Return type
- Returns
Transaction group that when executed will remove liquidity from the pool.
- build_remove_liquidity_txs(address, amount, suggested_params)
This creates two transactions in a group for the remove operation.
deposit of the liquidity asset
“REMLIQ” application call to remove the LP token from the account and receive the deposited assets in return.
- Parameters
address (
str
) – Account address that will deposit the LP token and receive the primary and secondary assets.amount (
int
) – The amount of the LP token to return to the pool.suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.
- Return type
list
[Transaction
]- Returns
List of transactions to remove the liquidity.
- prepare_swap(asset, amount, slippage_pct, swap_for_exact=False)
Creates a new swap instance for receiving the amount of asset within the slippage percent from the pool.
- Parameters
asset (
Asset
) – The asset to swap.amount (
int
) – Amount to swap or to receive. Look at swap_for_exact flag for details.slippage_pct (
float
) – The maximum allowed slippage in percents e.g. 10 is 10%. The swap will fail if the slippage will be higher.swap_for_exact – If false or not provided, the amount is the amount to swap (deposit in the contract). If true, the amount is the amount to receive from the swap.
- Return type
- Returns
A new swap object.
- prepare_swap_tx_group(swap, address)
Prepares a transaction group that when executed will perform a swap on the pool.
- Parameters
swap (
Swap
) – The swap for which to generate transactions.address (
str
) – The address that is performing the swap.
- Return type
- Returns
Transaction group that when executed will perform a swap on the pool.
- build_swap_txs(swap, address, suggested_params)
Builds two transactions:
deposit of the asset to swap
“SWAP’ application call that performs the swap to receive the other asset
- Parameters
swap (
Swap
) – The swap for which to generate transactions.address (
str
) – The address that is performing the swap.suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.
- Return type
list
[Transaction
]- Returns
List of transactions to perform the swap.
- is_asset_in_the_pool(asset)
Check if the asset is the primary or secondary asset of this pool.
- Parameters
asset (
Asset
) – The asset to check is in the pool.- Return type
bool
- Returns
True if the asset is in the pool or False otherwise.
- parse_internal_state(state)
Read the new pool state from the global state of the application.
- Parameters
state (
AppInternalState
) – Global state for the application.- Return type
- Returns
Parsed state.
- prepare_zap(asset, amount, slippage_pct)
Creates a new zap instance for getting all required data for performing a zap.
- prepare_zap_tx_group(zap, address)
Prepares a transaction group that when executed will perform a Zap on the pool.
- Parameters
zap (
Zap
) – The zap for which to generate transactions.address (
str
) – The address that is performing the Zap.
- Return type
- Returns
Transaction group that when executed will perform a Zap on the pool.
- build_zap_txs(zap, address, suggested_params)
Builds the transactions to perform a Zap on the pool as per the options passed in. Zap allows to add liquidity to the pool by providing only one asset.
This function will generate swap Txs to get a proper amount of the second asset and then generate add liquidity Txs with both of those assets. See
pactsdk.pool.Pool.buildSwapTxs()
andpactsdk.pool.Pool.buildAddLiquidityTxs()
for more details.This feature is supposed to work with constant product pools only. Stableswaps can accept one asset to add liquidity by default.
- Parameters
zap (
Zap
) – The zap for which to generate transactions.address (
str
) – The address that is performing the Zap.suggested_params (
SuggestedParams
) – Algorand suggested parameters for transactions.
- Return type
list
[Transaction
]- Returns
List of transactions to perform the Zap.
pactsdk.pool_calculator module
- class pactsdk.pool_calculator.SwapCalculator(*args, **kwargs)
Bases:
Protocol
- get_price(liq_a, liq_b)
Calculates the price of assets. Accepts and returns decimal values.
- Parameters
liq_a (
float
) – Primary liquidity if calculating price for primary asset, secondary otherwise.liq_b (
float
) – Secondary liquidity if calculating price for primary asset, primary otherwise.
- Return type
float
- Returns
The price of one asset in relation to the other.
- get_swap_gross_amount_received(liq_a, liq_b, amount_deposited)
Converts amountDeposited to amountReceived. Ignores fee calculations.
- Parameters
liq_a (
int
) – Primary liquidity if swapping primary asset, secondary otherwise.liq_b (
int
) – Secondary liquidity if swapping primary asset, primary otherwise.amount_deposited (
int
) – Amount of the asset deposited in the contract.
- Return type
int
- Returns
Amount of asset received from the contract after swap.
- get_swap_amount_deposited(liq_a, liq_b, amount_received)
Converts amountReceived to amountDeposited. Ignores fee calculations.
- Parameters
liq_a (
int
) – Primary liquidity if swapping primary asset, secondary otherwise.liq_b (
int
) – Secondary liquidity if swapping primary asset, primary otherwise.amount_received (
int
) – Amount of asset the user want to receive from the swap.
- Return type
int
- Returns
Amount of the asset the user has to deposit in the contract.
- get_minted_liquidity_tokens(added_liq_a, added_liq_b)
Returns amount of liquidity tokens that are going to be minted when adding liquidity.
- Parameters
added_liq_a (
int
) – Amount of primary asset to add to the pool.added_liq_b (
int
) – Amount of secondary asset to add to the pool.
- Return type
int
- Returns
Amount of liquidity tokens that will be minted and given to user.
- class pactsdk.pool_calculator.PoolCalculator(pool)
Bases:
object
Contains functions for calculation statistics and other numerical data about the pool.
The pool calculator uses internal data from the pool to calculate values like the Prices, Net Amounts and values for the swap. Uses different formulas based on pool type.
- property primary_asset_amount: int
- Return type
int
- property secondary_asset_amount: int
- Return type
int
- property primary_asset_amount_decimal: float
- Return type
float
- property secondary_asset_amount_decimal: float
- Return type
float
- property is_empty: bool
Checks if the pool is currently empty.
A pool is empty if either the primary or secondary asset is zero.
- Return type
bool
- Returns
True if the pool is empty, False otherwise.
- property primary_asset_price: float
Returns: Amount of secondary assets for a single primary asset.
- Return type
float
- property secondary_asset_price: float
Returns: Amount of primary assets for a single secondary asset.
- Return type
float
- amount_deposited_to_net_amount_received(asset, amount_deposited)
Converts amount deposited in the contract to amount received from the contract. Includes fee calculations.
- Parameters
asset (
Asset
) – Asset to deposit in the contract.amount_deposited (
int
) – Amount to deposit in the contract.
- Return type
int
- Returns
The amount to receive from the contract.
- net_amount_received_to_amount_deposited(asset, net_amount_received)
Converts amount received from the contract to amount deposited in the contract.
- Parameters
asset (
Asset
) – Asset to deposit in the contract.amount_deposited – Amount to receive from the contract.
- Return type
int
- Returns
The amount to deposit in the contract.
- get_fee_from_gross_amount(gross_amount)
Calculates the fee from the gross amount based on pool’s fee_bps.
- Parameters
gross_amount (
int
) – The amount to receive from the contract not yet lessened by the fee.- Return type
int
- Returns
The calculated fee.
- get_fee_from_net_amount(net_amount)
Calculates the fee from the net amount based on pool’s fee_bps. This is used in the swap for exact calculations.
- Parameters
net_amount (
int
) – The amount to receive from the contract already lessened by the fee.- Return type
int
- Returns
The calculated fee.
- get_liquidities(asset)
Returns the array of liquidities from the pool, sorting them by setting provided asset as primary.
- Parameters
asset (
Asset
) – The asset that is supposed to be the primary one.- Return type
tuple
[int
,int
]- Returns
Total liquidities of assets.
- get_minimum_amount_received(asset, amount, slippage_pct)
Based on the deposited amount and a slippage, calculate the minimum amount the user will receive from the contract.
- Parameters
asset (
Asset
) – The asset to deposit in the contract.amount_deposited – The amount to deposit in the contract.
slippage_pct (
float
) – Slippage in percents.
- Return type
int
- Returns
The minimum amount to receive from the contract.
- get_fee(asset, amount_deposited)
Calculates the exchange fee based on deposited amount.
- Parameters
asset (
Asset
) – The asset to deposit in the contract.amount_deposited (
int
) – The amount to deposit in the contract.
- Return type
int
- Returns
The calculated fee.
- get_asset_price_after_liq_change(asset, primary_liq_change, secondary_liq_change)
Simulates new asset price after changing the pool’s liquidity.
- Parameters
asset (
Asset
) – The asset for which to calculate the price for.primary_liq_change (
int
) – The change of primary liquidity on the pool.secondary_liq_change (
int
) – The change of secondary liquidity on the pool.
- Return type
float
- Returns
New asset price.
- get_price_impact_pct(asset, primary_liq_change, secondary_liq_change)
Calculates the price impact of changing the liquidity in a certain way.
- Parameters
asset (
Asset
) – The asset for which to calculate the price impact for.primary_liq_change (
int
) – The change of primary liquidity on the pool.secondary_liq_change (
int
) – The change of secondary liquidity on the pool.
- Return type
float
- Returns
The asset price impact.
- get_swap_price(asset_deposited, amount_deposited)
Calculates the price for which the asset in going to be swapped.
- Parameters
asset_deposited (
Asset
) – The asset deposited in the contract.amount_deposited (
int
) – The amount deposited in the contract.
- Return type
float
- Returns
The price of deposited asset in relation to received asset.
pactsdk.pool_state module
- class pactsdk.pool_state.AppInternalState(A, B, ASSET_A, ASSET_B, LTID, L, FEE_BPS, CONTRACT_NAME=None, VERSION=None, PACT_FEE_BPS=None, ADMIN=None, FUTURE_ADMIN=None, TREASURY=None, PRIMARY_FEES=None, SECONDARY_FEES=None, INITIAL_A=None, INITIAL_A_TIME=None, FUTURE_A=None, FUTURE_A_TIME=None, PRECISION=None)
Bases:
object
The one to one representation of pool’s global state.
- A: int
- B: int
- ASSET_A: int
- ASSET_B: int
- LTID: int
- L: int
- FEE_BPS: int
- CONTRACT_NAME: Optional[Literal['PACT AMM', '[SI] PACT AMM']] = None
- VERSION: Optional[int] = None
- PACT_FEE_BPS: Optional[int] = None
- ADMIN: Optional[str] = None
- FUTURE_ADMIN: Optional[str] = None
- TREASURY: Optional[str] = None
- PRIMARY_FEES: Optional[int] = None
- SECONDARY_FEES: Optional[int] = None
- INITIAL_A: Optional[int] = None
- INITIAL_A_TIME: Optional[int] = None
- FUTURE_A: Optional[int] = None
- FUTURE_A_TIME: Optional[int] = None
- PRECISION: Optional[int] = None
- class pactsdk.pool_state.PoolState(total_liquidity, total_primary, total_secondary, primary_asset_price, secondary_asset_price)
Bases:
object
A user friendly representation of pool’s global state.
- total_liquidity: int
- total_primary: int
- total_secondary: int
- primary_asset_price: float
- secondary_asset_price: float
- pactsdk.pool_state.parse_global_pool_state(raw_state)
- Parameters
raw_state (
list
) – The contract’s global state retrieved from algosdk.- Return type
- pactsdk.pool_state.get_pool_type_from_internal_state(state)
- Return type
Literal
[‘CONSTANT_PRODUCT’, ‘NFT_CONSTANT_PRODUCT’, ‘STABLESWAP’]
pactsdk.stableswap_calculator module
- exception pactsdk.stableswap_calculator.ConvergenceError
- class pactsdk.stableswap_calculator.StableswapParams(fee_bps, pact_fee_bps, initial_a, initial_a_time, future_a, future_a_time, precision)
Bases:
object
- fee_bps: int
- pact_fee_bps: int
- initial_a: int
- initial_a_time: int
- future_a: int
- future_a_time: int
- precision: int
- pactsdk.stableswap_calculator.get_tx_fee(invariant_iterations, extra_margin)
To calculate the pool invariant, a Newton-Raphson method is used in both - the SDK and the smart contract.
Algorand has a limit of the number of operations available in a single app call. To increase the limit, an additional empty inner transaction have to be created. Each extra tx increases tx fee. This functions calculates the fee needed for a swap transaction.
- Parameters
invariant_iterations (
int
) – Number of iterations of Newton-Raphson interpolation.extra_margin (
int
) – Number of extra inner transactions needed in case of slippage.
- Return type
int
- Returns
The required fee.
- pactsdk.stableswap_calculator.get_stableswap_minted_liquidity_tokens(added_primary, added_secondary, total_primary, total_secondary, total_liquidity, amplifier, precision, fee_bps)
Returns a tuple of minted tokens and total Newton-Raphson iterations (needed for tx fee calculations).
- Return type
tuple
[int
,int
]
- pactsdk.stableswap_calculator.get_add_liquidity_bonus_pct(added_primary, added_secondary, total_primary, total_secondary, fee_bps, amplifier, precision)
- Return type
float
- pactsdk.stableswap_calculator.get_add_liquidity_fees(initial_totals, updated_totals, fee_bps, amplifier, precision)
- Return type
tuple
[tuple
[int
,int
],int
,int
]
- pactsdk.stableswap_calculator.get_swap_gross_amount_received(liq_a, liq_b, amount_deposited, amplifier, precision)
- Return type
tuple
[int
,int
]
- pactsdk.stableswap_calculator.get_swap_amount_deposited(liq_a, liq_b, gross_amount_received, amplifier, precision)
- Return type
tuple
[int
,int
]
- pactsdk.stableswap_calculator.get_invariant(liq_a, liq_b, amp, precision)
Uses a Newton-Raphson method to calculate the pool invariant.
- Return type
tuple
[int
,int
]- Returns
A tuple of invariant and number of iterations required to calculate the invariant.
- pactsdk.stableswap_calculator.get_new_liq(liq_other, amplifier, inv, precision)
- Return type
int
- pactsdk.stableswap_calculator.get_amplifier(timestamp, initial_a, initial_a_time, future_a, future_a_time)
Calculates the amplifier at specified timestamp using linear interpolation.
- Return type
int
- class pactsdk.stableswap_calculator.StableswapCalculator(pool)
Bases:
object
An implementation of a math behind stableswap pools.
- swap_invariant_iterations = 0
Keeps the amount of iteration used to calculate invariant in the last call to getSwapGrossAmountReceived or getSwapAmountDeposited. Needed to calculate transaction fee.
- mint_tokens_invariant_iterations = 0
The same as swap_invariant_iterations but for adding liquidity.
- property stableswap_params: pactsdk.stableswap_calculator.StableswapParams
- Return type
- get_amplifier()
- get_price(liq_a, liq_b)
May return zero for highly unbalanced pools.
- Return type
float
- _get_price(liq_a, liq_b, retries)
Price is calculated by simulating a swap for 10**6 of micro values. This price is highly inaccurate for low liquidity pools. In case of ConvergenceError we try to simulate a swap using a different swap amount. Returns zero if all retries will fail.
- Return type
float
- get_swap_gross_amount_received(liq_a, liq_b, amount_deposited, save_iterations=True)
- Return type
int
- get_swap_amount_deposited(liq_a, liq_b, gross_amount_received, save_iterations=True)
- Return type
int
- get_minted_liquidity_tokens(added_liq_a, added_liq_b)
- Return type
int
pactsdk.swap module
Set of utility classes for managing and performing swaps.
- class pactsdk.swap.SwapEffect(amount_received, amount_deposited, minimum_amount_received, fee, primary_asset_price_after_swap, secondary_asset_price_after_swap, primary_asset_price_change_pct, secondary_asset_price_change_pct, price, tx_fee, amplifier)
Bases:
object
Swap Effect are the basic details of the effect on the pool of performing the swap.
- amount_received: int
- amount_deposited: int
- minimum_amount_received: int
- fee: int
- primary_asset_price_after_swap: float
- secondary_asset_price_after_swap: float
- primary_asset_price_change_pct: float
- secondary_asset_price_change_pct: float
- price: float
- tx_fee: int
- amplifier: float
Stableswap only. Zero otherwise.
- class pactsdk.swap.Swap(pool, asset_deposited, amount, slippage_pct, swap_for_exact=False)
Bases:
object
Swap class represents a swap trade on a particular pool.
Typically, users don’t have to manually instantiate this class. Use
pactsdk.pool.Pool.prepare_swap()
instead.- pool: pactsdk.pool.Pool
The pool the swap is going to be performed in.
- asset_deposited: pactsdk.asset.Asset
The asset that will be swapped (deposited in the contract).
- asset_received: pactsdk.asset.Asset
The asset that will be received.
- amount: int
Either the amount to swap (deposit) or the amount to receive depending on the swap_for_exact parameter.
- slippage_pct: float
The maximum percentage of slippage allowed in performing the swap.
- swap_for_exact: bool = False
If true then amount is what you want to receive from the swap. Otherwise, it’s an amount that you want to swap (deposit). Note that the contracts do not support the “swap exact for” swap. It works by calculating the amount to deposit on the client side and doing a normal swap on the exchange.
- effect: pactsdk.swap.SwapEffect
The effect of the swap computed at the time of construction.
- prepare_tx_group(address)
Creates the transactions needed to perform the swap trade and returns them as a transaction group ready to be signed and committed.
- Parameters
address (
str
) – The account that will be performing the swap.- Return type
- Returns
A transaction group that when executed will perform the swap.
pactsdk.zap module
Set of utility classes for managing and performing zaps.
- class pactsdk.zap.ZapParams(swap_deposited, primary_add_liq, secondary_add_liq)
Bases:
object
All amounts that should be used in swap and add liquidity transactions.
- swap_deposited: int
- primary_add_liq: int
- secondary_add_liq: int
- pactsdk.zap.get_constant_product_zap_params(liq_a, liq_b, zap_amount, fee_bps, pact_fee_bps)
- Return type
- pactsdk.zap.get_swap_amount_deposited_from_zapping(zap_amount, total_amount, fee_bps, pact_fee_bps)
- Return type
int
- pactsdk.zap.get_secondary_added_liquidity_from_zapping(swap_deposited, total_primary, total_secondary, fee_bps)
- Return type
int
- class pactsdk.zap.Zap(pool, asset, amount, slippage_pct)
Bases:
object
Zap class represents a zap trade on a particular pool, which allows to exchange single asset for PLP token.
Zap performs a swap to get second asset from the pool and then adds liquidity using both of those assets. Users may be left with some leftovers due to rounding and slippage settings.
Zaps are meant only for Constant Product pools; For Stableswaps, adding only one asset works out of the box.
Typically, users don’t have to manually instantiate this class. Use
pactsdk.pool.Pool.prepare_zap()
instead.- pool: pactsdk.pool.Pool
The pool the zap is going to be performed in.
- asset: pactsdk.asset.Asset
The asset that will be used in zap.
- amount: int
Amount to be used in zap.
- slippage_pct: float
The maximum amount of slippage allowed in performing the swap.
- swap: pactsdk.swap.Swap
The swap object that will be executed during the zap.
- liquidity_addition: pactsdk.add_liquidity.LiquidityAddition
Liquidity Addition object that will be executed during the zap.
- params: pactsdk.zap.ZapParams
All amounts used in swap and add liquidity transactions.
- prepare_tx_group(address)
Creates the transactions needed to perform zap and returns them as a transaction group ready to be signed and committed.
- Parameters
address (
str
) – The account that will be performing the zap.- Return type
- Returns
A transaction group that when executed will perform the zap.
- prepare_add_liq()
pactsdk.transaction_group module
- class pactsdk.transaction_group.TransactionGroup(transactions)
Bases:
object
A convenience class to make managing Algorand transactions groups easier.
- __init__(transactions)
Creates the TransactionGroup from an array of transactions by assigning a group id to each transaction.
- Parameters
transactions (
list
[Transaction
]) – A list of transactions to put in a group.- Raises
PactSdkError – If the list is empty (length 0) or if the group id was not assigned to the transactions due to e.g. a failure in the Algorand SDK.
- transactions: list[algosdk.transaction.Transaction]
A list of transactions in a group.
- sign(private_key)
Signs all the transactions in the group with the private key.
Using the private_key passed in assigns all the transactions stored internally for the transaction group.
- Parameters
private_key (
str
) – Sign the transactions with this private key.- Return type
list
[SignedTransaction
]- Returns
A list of encoded signed transactions as per the Transaction.sign from the Algorand sdk.
- property group_id
Returns The group id as a base64 encoded string.
pactsdk.factory module
pactsdk.folks_lending_pool module
This module allows for composing Pact swaps and adding/removing liquidity with Folks Finance lending pools, resulting in a higher APR for liquidity providers that accommodates both, the trading APR and the lending APR.
The user is not interacting with Folks Finance pools or Pact pools directly. Instead, the user is calling a global adapter contract that makes inner transactions to the other applications.
The Pact pool is between two fAssets e.g. fALGO and fUSDC but the user doesn’t have to be opted into those fAssets. The user interacts only with ALGO and USDC. Converting between the original assets and fAssets is hidden in the adapter contract.
- To add liquidity:
The user deposits ALGO and USDC in the adapter contract.
The user calls “pre_add_liquidity” method on the adapter.
The adapter converts ALGO to fALGO and USDC to fUSDC in corresponding Folks Finance pools.
The user calls “add_liquidity” method on the adapter.
The adapter deposits fALGO and fUSDC in Pact pool and receives liquidity tokens in return.
The adapter transfers the liquidity tokens to the user.
- To remove liquidity:
The user deposits liquidity tokens in the adapter contract.
The user calls “remove_liquidity” method on the adapter.
The adapter removes liquidity from the Pact pool and receives fALGO and fUSDC in return.
The user calls “post_remove_liquidity” method on the adapter.
The adapter converts fALGO to ALGO and fUSDC to USDC in corresponding Folks Finance pools.
The adapter transfers ALGO and USDC tokens to the user.
- For swap:
The user deposits one of the assets in the adapter e.g. USDC.
The user calls “swap” method on the adapter.
The adapter converts USDC to fUSDC in a corresponding Folks Finance pool.
The adapter swaps fUSDC to fALGO in a Pact pool.
The adapter converts fALGO to ALGO in a corresponding Folks Finance pool.
The adapter transfers ALGO to the user.
- class pactsdk.folks_lending_pool.FolksLendingPool(algod, app_id, manager_app_id, deposit_interest_rate, deposit_interest_index, updated_at, original_asset, f_asset, last_timestamp_override=None)
Bases:
object
- algod: algosdk.v2client.algod.AlgodClient
- app_id: int
- manager_app_id: int
- deposit_interest_rate: int
- deposit_interest_index: int
- updated_at: datetime.datetime
- original_asset: pactsdk.asset.Asset
- f_asset: pactsdk.asset.Asset
- escrow_address: str
- last_timestamp_override: Optional[int] = None
The conversion calculations are dependant of precise timestamps. The Folks contract uses the last block timestamp for this value. The SDK, by default, uses current system time. This field allows to override the default behavior. This is needed in unit tests and normal users should leave this field as None.
- convert_deposit(amount)
Calculates the amount fAsset received when depositing original asset.
- Return type
int
- convert_withdraw(amount, ceil=False)
Calculates the amount original asset received when depositing fAsset.
- Return type
int
- get_last_timestamp()
- Return type
int
- pactsdk.folks_lending_pool.fetch_folks_lending_pool(algod, app_id)
Fetches Folks lending pool application info from the algod, parses the global state and builds FolksLendingPool object.
- Return type
- class pactsdk.folks_lending_pool.LendingLiquidityAddition(lending_pool_adapter, primary_asset_amount, secondary_asset_amount, slippage_pct)
Bases:
object
A wrapper around LiquidityAddition object that converts assets to fAssets before creating LiquidityAddition object.
- lending_pool_adapter: pactsdk.folks_lending_pool.FolksLendingPoolAdapter
- primary_asset_amount: int
Amount of original primary asset deposited.
- secondary_asset_amount: int
Amount of original secondary asset deposited.
- slippage_pct: float
The maximum amount of slippage allowed in performing the add liquidity.
- liquidity_addition: pactsdk.add_liquidity.LiquidityAddition
Information about actual add liquidity operation on the Pact pool.
- class pactsdk.folks_lending_pool.LendingSwap(f_swap, asset_deposited, asset_received, amount_deposited, amount_received, minimum_amount_received, tx_fee)
Bases:
object
A wrapper around Swap object that adds some lending specific information.
- f_swap: pactsdk.swap.Swap
Information about the actual swap on the Pact pool.
- asset_deposited: pactsdk.asset.Asset
- asset_received: pactsdk.asset.Asset
- amount_deposited: int
Amount of original asset deposited by the user.
- amount_received: int
Amount of original asset received by the user.
- minimum_amount_received: int
Minimal amount of original asset received by the user after the slippage.
- tx_fee: int
- class pactsdk.folks_lending_pool.FolksLendingPoolAdapter(algod, app_id, pact_pool, primary_lending_pool, secondary_lending_pool)
Bases:
object
The representation of the adapter contract.
It allows adding/removing liquidity and making swaps using a combination Pact pool and Folks Finance lending pools.
This class tries to mimic the interface of a
pactsdk.pool.Pool
for making the above operations.- algod: algosdk.v2client.algod.AlgodClient
- app_id: int
- pact_pool: pactsdk.pool.Pool
- primary_lending_pool: pactsdk.folks_lending_pool.FolksLendingPool
- secondary_lending_pool: pactsdk.folks_lending_pool.FolksLendingPool
- escrow_address: str
- prepare_add_liquidity(primary_asset_amount, secondary_asset_amount, slippage_pct)
- Return type
- prepare_add_liquidity_tx_group(address, liquidity_addition)
- Return type
- build_add_liquidity_txs(address, liquidity_addition, suggested_params)
- Return type
list
[Transaction
]
- prepare_remove_liquidity_tx_group(address, amount)
- Return type
- build_remove_liquidity_txs(address, amount, suggested_params)
- Return type
list
[Transaction
]
- prepare_swap(asset, amount, slippage_pct, swap_for_exact=False)
- Return type
- prepare_swap_tx_group(swap, address)
- Return type
- build_swap_txs(swap, address, suggested_params)
- Return type
list
[Transaction
]
- prepare_opt_in_to_asset_tx_group(address, asset_ids)
- Return type
- build_opt_in_to_asset_tx_group(address, asset_ids, suggested_params)
pactsdk.config module
- class pactsdk.config.Config(api_url='', gas_station_id=0, folks_lending_pool_adapter_id=0, factory_constant_product_id=0, factory_nft_constant_product_id=0)
Bases:
object
- api_url: str = ''
- gas_station_id: int = 0
- folks_lending_pool_adapter_id: int = 0
- factory_constant_product_id: int = 0
- factory_nft_constant_product_id: int = 0