### Install Testbed Dependencies and Start Docker Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Install dependencies for the Algorand testbed and start the necessary Docker services. ```bash poetry install docker compose up -d ``` -------------------------------- ### Install Development Dependencies Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Install project dependencies using Poetry. This is the first step for local development. ```bash poetry install ``` -------------------------------- ### Build or Get Pool Source: https://pactfi.github.io/pact-py-sdk/latest/examples/build_pool.html Deploys a new pool if a pool with the given parameters does not already exist. Requires Algorand client setup and pool parameters. ```python import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk private_key = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(private_key) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") factory = pact.get_constant_product_pool_factory() pool_params = pactsdk.PoolBuildParams( primary_asset_id=0, secondary_asset_id=14111329, fee_bps=100, ) pool, created = factory.build_or_get( sender=address, pool_build_params=pool_params, signer=lambda tx_group: tx_group.sign(private_key), ) print("New pool created." if created else "Pool with specified params already exists.") print(pool) ``` -------------------------------- ### Install Local Package Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Install the locally built Pact SDK package using pip. Replace `` with the actual version number. ```bash pip install dist/pactsdk-.whl ``` -------------------------------- ### Composing Transactions Example Source: https://pactfi.github.io/pact-py-sdk/latest/_sources/examples/composing_transactions.rst.txt This example shows how to create a composite transaction by adding multiple individual transactions. It requires the Pact SDK and relevant account information. ```python from pact import Pact from pact.utils import create_keypair, sign_transaction # Initialize Pact client pact = Pact("http://localhost:8000") # Create keypair for signing private_key, public_key = create_keypair() # Define sender and recipient accounts sender_account = "account-sender" recipient_account = "account-recipient" # Create a simple transfer transaction transaction1 = { "sender": sender_account, "chain_id": "testnet01", "gas_limit": 1200, "gas_price": 0.00000001, "amount": 1.0, "recipient": recipient_account, "metadata": { "data": "transfer" } } # Create another transaction (e.g., a contract call) transaction2 = { "sender": sender_account, "chain_id": "testnet01", "gas_limit": 1200, "gas_price": 0.00000001, "amount": 0.0, "recipient": "coin-contract", "metadata": { "module": "Coin", "function": "transfer", "arguments": [ sender_account, recipient_account, 1000000.0, 1 ] } } # Compose transactions into a single transaction composite_transaction = [ transaction1, transaction2 ] # Sign the composite transaction signed_tx = sign_transaction(composite_transaction, private_key) # Submit the signed transaction # result = pact.send_transaction(signed_tx) # print(result) print("Composite transaction signed successfully.") print(signed_tx) ``` -------------------------------- ### Interact with Folks Lending Pools Source: https://pactfi.github.io/pact-py-sdk/latest/examples/folks_lending_pool.html This example demonstrates fetching Folks lending pools, creating a corresponding Pact pool, and using an adapter to perform liquidity management and swaps. It requires setting up an AlgodClient and PactClient, and assumes you have a mnemonic for private key access. The adapter simplifies interactions by abstracting the underlying pool types. ```python """This example performs a basic actions on a lending pool.""" import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk FOLKS_POOL_A = 147169673 # ALGO FOLKS_POOL_B = 147170678 # USDC folks_lending_pool_ids = sorted([FOLKS_POOL_A, FOLKS_POOL_B]) pk = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(pk) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") # Folks pools. print("Fetching folks lending pools...") primary_folks_pool = pact.fetch_folks_lending_pool(folks_lending_pool_ids[0]) secondary_folks_pool = pact.fetch_folks_lending_pool(folks_lending_pool_ids[1]) # Pact pool. print("Fetching or creating pact pool...") factory = pact.get_constant_product_pool_factory() pool_build_params = pactsdk.PoolBuildParams( primary_asset_id=primary_folks_pool.f_asset.index, secondary_asset_id=secondary_folks_pool.f_asset.index, fee_bps=2, ) pact_pool, created = factory.build_or_get( sender=address, pool_build_params=pool_build_params, signer=lambda tx_group: tx_group.sign(pk), ) # Make an adapter. lending_pool_adapter = pact.get_folks_lending_pool_adapter( primary_lending_pool=primary_folks_pool, secondary_lending_pool=secondary_folks_pool, pact_pool=pact_pool, ) if created: # Adapter opt-in to all the assets. print("Opting in adapter to assets...") asset_ids = [ primary_folks_pool.original_asset.index, secondary_folks_pool.original_asset.index, primary_folks_pool.f_asset.index, secondary_folks_pool.f_asset.index, pact_pool.liquidity_asset.index, ] tx_group = lending_pool_adapter.prepare_opt_in_to_asset_tx_group(address, asset_ids) algod.send_transactions(tx_group.sign(pk)) print(tx_group.group_id) print() # Add liquidity. print("Adding liquidity...") liquidity_addition = lending_pool_adapter.prepare_add_liquidity(100_000, 100_000, 0.5) tx_group = lending_pool_adapter.prepare_add_liquidity_tx_group( address, liquidity_addition ) algod.send_transactions(tx_group.sign(pk)) print(tx_group.group_id) print() # Swap. print("Swapping...") swap = lending_pool_adapter.prepare_swap( primary_folks_pool.original_asset, amount=100_000, slippage_pct=100 ) tx_group = lending_pool_adapter.prepare_swap_tx_group(swap, address) algod.send_transactions(tx_group.sign(pk)) print(tx_group.group_id) print() # Remove liquidity. print("Removing liquidity...") tx_group = lending_pool_adapter.prepare_remove_liquidity_tx_group(address, 20_000) algod.send_transactions(tx_group.sign(pk)) print(tx_group.group_id) ``` -------------------------------- ### Perform Swap on a Pool Source: https://pactfi.github.io/pact-py-sdk/latest/examples/swap.html This snippet shows how to opt-in to an asset and then perform a swap operation on a pre-existing liquidity pool. Ensure you have the necessary Algorand client setup and have fetched the relevant assets and pool. ```python """This example performs a swap on a pool.""" import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk private_key = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(private_key) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") algo = pact.fetch_asset(0) usdc = pact.fetch_asset(31566704) pool = pact.fetch_pools_by_assets(algo, usdc)[0] # Opt-in for usdc. opt_in_txn = usdc.prepare_opt_in_tx(address) sent_optin_txid = algod.send_transaction(opt_in_txn.sign(private_key)) print(f"Opt-in transaction {sent_optin_txid}") # Do a swap. swap = pool.prepare_swap( asset=algo, amount=100_000, slippage_pct=2, ) swap_tx_group = swap.prepare_tx_group(address) signed_group = swap_tx_group.sign(private_key) algod.send_transactions(signed_group) print(f"Swap transaction group {swap_tx_group.group_id}") ``` -------------------------------- ### Fetch Pool State Source: https://pactfi.github.io/pact-py-sdk/latest/examples/get_pool_state.html Use this snippet to get the current state of a liquidity pool. Ensure you have initialized the AlgodClient and PactClient with valid credentials and network settings. This example fetches the state for a pool composed of Algo and USDC assets on the testnet. ```python """This example fetches a pool and reads its state.""" from algosdk.v2client.algod import AlgodClient import pactsdk algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") algo = pact.fetch_asset(0) usdc = pact.fetch_asset(31566704) pool = pact.fetch_pools_by_assets(algo, usdc)[0] print(f"State {pool.state}") ``` -------------------------------- ### Validate Pact SDK Installation Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Validate the installation by checking the installed Pact SDK version. This confirms the package is correctly installed. ```python import pactsdk; print(pactsdk.__version__) ``` -------------------------------- ### List Constant Product Pools Source: https://pactfi.github.io/pact-py-sdk/latest/examples/list_pools.html Lists constant product pools created by the factory. This example requires the algosdk and pactsdk libraries. Ensure you have a valid mnemonic, algod client configuration, and are connected to the testnet. ```python """This examples lists constant product pools created by the factory. It will not list old pools created before introducing pool factory to the Pact architecture. Each pool type require using a dedicated factory.""" import pprint import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk private_key = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(private_key) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") factory = pact.get_constant_product_pool_factory() pool_params = factory.list_pools() print("pools:") pprint.pprint(pool_params) # To fully fetch the pool of choice... pool = factory.fetch_pool(pool_params[0]) print("Selected pool:") pprint.pprint(pool) ``` -------------------------------- ### Get Constant Product Zap Params Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Calculates the necessary parameters for a constant product zap transaction. Requires liquidity amounts, zap amount, and fee details. ```python def get_constant_product_zap_params(_liq_a_: int, _liq_b_: int, _zap_amount_: int, _fee_bps_: int, _pact_fee_bps_: int) -> ZapParams: ``` -------------------------------- ### Get Pool State Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Prints the current state of a liquidity pool, including total liquidity, asset balances, and prices. ```python print(pool.state) # PoolState( # total_liquidity=900000, # total_primary=956659, # total_secondary=849972, # primary_asset_price=0.8884795940873393, # secondary_asset_price=1.1255182523659604, # ) ``` -------------------------------- ### get_nft_constant_product_pool_factory Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/client.html Gets the NFT constant product pool factory according to the client’s configuration. ```APIDOC ## get_nft_constant_product_pool_factory ### Description Gets the NFT constant product pool factory according to the client’s configuration. ### Returns - `ConstantProductFactory` ``` -------------------------------- ### get_constant_product_pool_factory Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/client.html Gets the constant product pool factory according to the client’s configuration. ```APIDOC ## get_constant_product_pool_factory ### Description Gets the constant product pool factory according to the client’s configuration. ### Returns - `ConstantProductFactory` ``` -------------------------------- ### Initialize PactClient and Fetch Assets/Pools Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/client.html Demonstrates the typical usage of initializing the PactClient with an AlgodClient and then fetching assets and pools based on asset IDs. ```python import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk algod = AlgodClient("", "") pact = pactsdk.PactClient(algod) algo = pact.fetch_asset(0) other_coin = pact.fetch_asset(12345678) pools = pact.fetch_pools_by_assets(algo, other_coin) ``` -------------------------------- ### Create Pact Client (Mainnet) Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Initializes a Pact client for interacting with the mainnet. Requires an Algod client instance. ```python from algosdk.v2client.algod import AlgodClient import pactsdk algod = AlgodClient(token, url) pact = pactsdk.PactClient(algod) ``` -------------------------------- ### Get Zap Parameters Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Retrieves the calculated ZapParams object for the current zap configuration. ```python def get_zap_params(self) -> ZapParams: ``` -------------------------------- ### PactClient Initialization Source: https://pactfi.github.io/pact-py-sdk/latest/docs/source/pactsdk.html Initializes the PactClient with an Algorand client and specifies the network. Optional keyword arguments can be used to overwrite configuration parameters. ```APIDOC ## PactClient Constructor ### Description Initializes the PactClient class, serving as the entry point for interacting with the SDK. ### Parameters * **algod** (`AlgodClient`) – Required - Algorand client to work with. * **network** (`Literal`[‘mainnet’, ‘testnet’, ‘dev’]) – Optional - The Algorand network to use the client with. Defaults to 'mainnet'. * **kwargs** – Optional - Use it to overwrite configuration parameters. ``` -------------------------------- ### Build Pact SDK Package Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Build the Pact SDK package using Poetry. This creates a distributable file. ```bash poetry build ``` -------------------------------- ### pactsdk.config.get_config Source: https://pactfi.github.io/pact-py-sdk/latest/docs/source/pactsdk.html Retrieves the current Pact SDK configuration. This function can be used to get the active Config object, potentially with network-specific settings. ```APIDOC ## pactsdk.config.get_config ### Description Retrieves the current Pact SDK configuration. This function can be used to get the active Config object, potentially with network-specific settings. ### Parameters - **network** (str) - Required - The network identifier for which to get the configuration. - **kwargs** - Optional - Additional keyword arguments to configure the returned Config object. ``` -------------------------------- ### Get Secondary Added Liquidity From Zapping Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Calculates the amount of the secondary asset to be added as liquidity during a zap. This is derived from the swapped amount and total pool liquidity. ```python def get_secondary_added_liquidity_from_zapping(_swap_deposited_: int, _total_primary_: int, _total_secondary_: int, _fee_bps_: int) -> int: ``` -------------------------------- ### prepare_swap Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Creates a new swap instance for receiving a specified amount of an asset within a slippage percentage from the pool. ```APIDOC ## prepare_swap ### Description 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** (bool) - 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 `Swap` ### Returns A new swap object. ``` -------------------------------- ### Create Pact Client (Testnet) Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Initializes a Pact client configured for the testnet by specifying the network. This changes default configuration values like API URLs and contract IDs. ```python pact = pactsdk.PactClient(algod, network="testnet") ``` -------------------------------- ### Get Swap Amount Deposited From Zapping Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Calculates the amount of a deposited asset that will be swapped during a zap. Depends on the zap amount, total asset amount, and fee percentages. ```python def get_swap_amount_deposited_from_zapping(_zap_amount_: int, _total_amount_: int, _fee_bps_: int, _pact_fee_bps_: int) -> int: ``` -------------------------------- ### prepare_add_liquidity Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Creates a new LiquidityAddition instance for adding liquidity to the pool. ```APIDOC ## prepare_add_liquidity ### Description Creates a new LiquidityAddition instance for adding liquidity to the pool. ### Parameters * **options** (Options) - Options for adding the liquidity. ### Return type `LiquidityAddition` ### Returns A new LiquidityAddition object. ``` -------------------------------- ### Prepare Add Liquidity for Zap Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Prepares the liquidity addition component of a zap transaction. ```python def prepare_add_liq(self): ``` -------------------------------- ### Get Last Timestamp from Folks Lending Pool Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/folks_lending_pool.html Retrieves the last recorded timestamp from the Folks Lending Pool. This is crucial for accurate conversion calculations, especially when dealing with time-sensitive operations. ```python folks_lending_pool.get_last_timestamp() ``` -------------------------------- ### pactsdk.asset.Asset.build_opt_in_tx Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/asset.html Creates the actual transaction for an account to opt in to holding an asset, using suggested Algorand transaction parameters. ```APIDOC ## build_opt_in_tx ### Description Creates the actual transaction for the account to opt-in to holding the asset. ### Parameters #### Path 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. ``` -------------------------------- ### build_raw_add_liquidity_txs Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Builds raw transactions for adding liquidity. ```APIDOC ## build_raw_add_liquidity_txs ### 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. * **minimum_minted_liquidity_tokens** – The minimum amount of LP tokens to mint. * **suggested_params** (`SuggestedParams`) – Algorand suggested parameters for transactions. * **fee** – The transaction fee. * **note** (`bytes`) – An optional note that can be added to the application ADDLIQ transaction. Defaults to b''. ``` -------------------------------- ### prepare_zap Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Prepares a new zap instance, gathering all necessary data for performing a zap operation. ```APIDOC ## prepare_zap ### Description Creates a new zap instance for getting all required data for performing a zap. ### Parameters #### Path Parameters - **asset** (Asset) - Required - The asset to zap. - **amount** (int) - Required - Amount used for the zap. - **slippage_pct** (float) - Required - The maximum allowed slippage in percents e.g. 10 is 10%. The swap will fail if the slippage will be higher. ### Return type `Zap` ### Returns A new zap object. ``` -------------------------------- ### PoolFactory.build Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/factories.html Deploys a new pool to the network with the specified parameters. Requires sender address, pool build parameters, and a signer callback for transaction authorization. ```APIDOC ## PoolFactory.build ### Description Deploys a new liquidity pool to the network. This method requires the sender's address, the parameters for building the pool, and a function to sign the necessary transactions. ### Method ``` PoolFactory.build(sender: str, pool_build_params: PoolBuildParams, signer: Callable[[TransactionGroup], list[SignedTransaction]]) ``` ### Parameters #### Path Parameters - **sender** (str) - Required - The address initiating the pool creation. - **pool_build_params** (PoolBuildParams) - Required - The parameters defining the pool to be created. - **signer** (Callable[[TransactionGroup], list[SignedTransaction]]) - Required - A callback function that signs the transaction group. ### Returns - `Pool` - An instance of the newly created pool. ``` -------------------------------- ### Fetch Folks Lending Pool Info Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/folks_lending_pool.html Fetches lending pool application information from the algod, parses global state, and constructs a FolksLendingPool object. Use this to initialize the SDK with existing pool data. ```python folks_lending_pool.fetch_folks_lending_pool(algod, app_id) ``` -------------------------------- ### Prepare Swap Transaction Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Prepares a swap transaction, specifying the asset to swap, the amount, and the maximum acceptable slippage percentage. Allows inspection of the swap's effects before submission. ```python swap = pool.prepare_swap( asset=algo, amount=200_000, slippage_pct=2, ) # You can inspect swap effect before submitting the transaction. print(swap.effect) # SwapEffect( # amount_deposited=200000, # amount_received=146529, # minimum_amount_received=143598, # fee=441, # price=0.73485, # primary_asset_price_after_swap=0.6081680080300244, # secondary_asset_price_after_swap=1.6442824791774173, # primary_asset_price_change_pct=-31.549580645715963, # secondary_asset_price_change_pct=46.091142966447585, # ) ``` -------------------------------- ### ConstantProductCalculator Class Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/constant_product_calculator.html Implements the mathematical logic for constant product liquidity pools. ```APIDOC ## Class: ConstantProductCalculator ### Description An implementation of the math behind constant product pools. ### Methods - **get_price(liq_a, liq_b)**: Calculates the current price of the pool. - **get_swap_gross_amount_received(liq_a, liq_b, amount_deposited)**: Calculates the gross amount received from a swap. - **get_swap_amount_deposited(liq_a, liq_b, gross_amount_received)**: Calculates the amount deposited for a swap given the amount received. - **get_minted_liquidity_tokens(added_liq_a, added_liq_b)**: Calculates the number of liquidity tokens minted when adding liquidity. ``` -------------------------------- ### pactsdk.asset.Asset.prepare_opt_in_tx Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/asset.html Creates a transaction to allow an account to opt in to an asset. This is necessary before receiving an asset or managing liquidity tokens. ```APIDOC ## prepare_opt_in_tx ### Description 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 #### Path 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_zap_txs Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Builds the transactions required to perform a zap on the pool, which involves swapping one asset to match the required ratio and then adding liquidity. This is primarily for constant product pools. ```APIDOC ## build_zap_txs ### Description 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()` and `pactsdk.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 #### Path Parameters - **zap** (Zap) - Required - The zap for which to generate transactions. - **address** (str) - Required - The address that is performing the Zap. - **suggested_params** (SuggestedParams) - Required - Algorand suggested parameters for transactions. ### Return type `list[Transaction]` ### Returns List of transactions to perform the Zap. ``` -------------------------------- ### PactClient Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/client.html Constructor for the PactClient class. ```APIDOC ## PactClient ### Description 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. ``` -------------------------------- ### Swap Class Source: https://pactfi.github.io/pact-py-sdk/latest/docs/source/pactsdk.html Represents a swap trade on a particular pool. Users typically use `pactsdk.pool.Pool.prepare_swap()` instead of manually instantiating this class. It holds details about the pool, assets involved, amounts, slippage, and the computed effect of the swap. ```APIDOC ## class pactsdk.swap.Swap ### Description 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. ### Attributes * `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). * `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): If true then amount is what you want to receive from the swap. Otherwise, it’s an amount that you want to swap (deposit). * `effect` (pactsdk.swap.SwapEffect): The effect of the swap computed at the time of construction. ### Methods #### prepare_tx_group(address: str) -> TransactionGroup 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. Returns: A transaction group that when executed will perform the swap. ``` -------------------------------- ### build_swap_txs Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Builds two transactions for performing a swap. ```APIDOC ## build_swap_txs ### Description 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 ``` -------------------------------- ### Swap Class Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/swap.html Represents a swap trade on a particular pool. Users typically use `pactsdk.pool.Pool.prepare_swap()` instead of manually instantiating this class. ```APIDOC ## Class: Swap ### Description Represents a swap trade on a particular pool. This class is typically instantiated via `pactsdk.pool.Pool.prepare_swap()`. ### Attributes - **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 `swap_for_exact`. - **slippage_pct** (`float`): The maximum percentage of slippage allowed. - **swap_for_exact** (`bool`): If true, `amount` is what you want to receive. Otherwise, it’s the amount you want to deposit. Note that contracts do not support exact-for swaps directly; this is handled by client-side calculation. - **effect** (`SwapEffect`): The computed effect of the swap at the time of construction. ### Methods #### prepare_tx_group(address: str) -> TransactionGroup 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. Returns: A `TransactionGroup` that when executed will perform the swap. ``` -------------------------------- ### Submit Swap Transaction Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Submits a prepared swap transaction group to the Algorand network after signing. This executes the swap operation. ```python # Let's submit the swap. swap_tx_group = swap.prepare_tx_group(address) signed_tx_group = swap_tx_group.sign(private_key) algod.send_transactions(signed_tx_group) ``` -------------------------------- ### fetch_folks_lending_pool Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/folks_lending_pool.html Fetches Folks lending pool application information from the algod, parses the global state, and builds a FolksLendingPool object. ```APIDOC ## fetch_folks_lending_pool ### Description Fetches Folks lending pool application information from the algod, parses the global state and builds FolksLendingPool object. ### Parameters #### Path Parameters - **algod** (algosdk.v2client.algod.AlgodClient) - Description not available - **app_id** (int) - Description not available ### Return Type FolksLendingPool ``` -------------------------------- ### PoolFactory.build_or_get Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/factories.html Deploys a new pool if it doesn't exist, otherwise returns the existing pool. Returns a tuple indicating the pool and whether it was newly created. ```APIDOC ## PoolFactory.build_or_get ### Description Attempts to deploy a new pool with the given parameters. If a pool with these parameters already exists, it returns the existing pool instead of creating a new one. Returns a boolean indicating if a new pool was created. ### Method ``` PoolFactory.build_or_get(sender: str, pool_build_params: PoolBuildParams, signer: Callable[[TransactionGroup], list[SignedTransaction]]) ``` ### Parameters #### Path Parameters - **sender** (str) - Required - The address initiating the pool creation or retrieval. - **pool_build_params** (PoolBuildParams) - Required - The parameters of the pool. - **signer** (Callable[[TransactionGroup], list[SignedTransaction]]) - Required - A callback function that signs the transaction group. ### Returns - `tuple[Pool, bool]` - A tuple containing the pool instance and a boolean. `True` if a new pool was created, `False` if an existing pool was returned. ``` -------------------------------- ### get_folks_lending_pool_adapter Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/client.html 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. ```APIDOC ## get_folks_lending_pool_adapter ### Description 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. ### Returns - `FolksLendingPoolAdapter` - The adapter object. ``` -------------------------------- ### Clone Pact Contracts Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Clone the Algorand testbed repository which contains the Pact V1 contracts. This is a prerequisite for development. ```bash git clone git@github.com:pactfi/algorand-testbed.git cd algorand-testbed ``` -------------------------------- ### Asset Opt-in and Add Liquidity in One Transaction Group Source: https://pactfi.github.io/pact-py-sdk/latest/examples/composing_transactions.html Use this snippet to perform asset opt-in and add liquidity to a pool in a single atomic transaction group. This requires setting up the Algod client, Pact client, fetching a pool, and preparing the individual transactions before grouping and signing them. ```python """This example performs asset opt-in and add liquidity in a single atomic group.""" import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk private_key = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(private_key) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") pool = pact.fetch_pool_by_id(620995314) # ALGO/USDC suggested_params = algod.suggested_params() opt_in_tx = pool.liquidity_asset.prepare_opt_in_tx(address) liquidity_addition = pool.prepare_add_liquidity( primary_asset_amount=100_000, secondary_asset_amount=200_000, slippage_pct=0.5, ) add_liquidity_txs = pool.build_add_liquidity_txs( address="
", liquidity_addition=liquidity_addition, suggested_params=suggested_params, ) txs = [opt_in_tx, *add_liquidity_txs] group = pactsdk.TransactionGroup(txs) signed_group = group.sign(private_key) algod.send_transactions(signed_group) print(f"Transaction group {group.group_id}") ``` -------------------------------- ### Zap Class Initialization Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/zap.html Represents a zap trade, enabling single asset exchange for PLP tokens by swapping and adding liquidity. Primarily for Constant Product pools. Typically instantiated via `pool.prepare_zap()`. ```python class Zap: def __init__(self, pool: Pool, asset: Asset, amount: int, slippage_pct: float): self.pool = pool self.asset = asset self.amount = amount self.slippage_pct = slippage_pct self.swap: Swap self.liquidity_addition: LiquidityAddition self.params: ZapParams ``` -------------------------------- ### build_add_liquidity_txs Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Builds the transactions to add liquidity for the primary and secondary assets of the pool. ```APIDOC ## build_add_liquidity_txs ### Description 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. ``` -------------------------------- ### Run Tests with Pytest Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Run all project tests using Pytest. This command executes the test suite defined in the project. ```bash poetry run pytest ``` -------------------------------- ### Opt-in for Assets Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Prepares and signs a transaction to opt-in for specific assets. Opt-in is required before interacting with assets other than Algo. The function checks if already opted-in. ```python import algosdk private_key = algosdk.mnemonic.to_private_key('') address = algosdk.account.address_from_private_key(private_key) def opt_in(asset): is_opted_in = asset.is_opted_in(address) if not is_opted_in: opt_in_tx = asset.prepare_opt_in_tx(address) signed_tx = opt_in_tx.sign(private_key) algod.send_transaction(signed_tx) opt_in(pool.primary_asset) opt_in(pool.secondary_asset) opt_in(pool.liquidity_asset) # Needed if you want to manage the liquidity. ``` -------------------------------- ### FolksLendingPoolAdapter Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/folks_lending_pool.html The FolksLendingPoolAdapter class provides an interface to add/remove liquidity and make swaps using a combination of Pact and Folks Finance lending pools. It mimics the interface of a pactsdk.pool.Pool. ```APIDOC ## class FolksLendingPoolAdapter ### Description Represents an adapter contract for interacting with Pact and Folks Finance lending pools. It allows users to add/remove liquidity and perform swaps, mimicking the interface of a `pactsdk.pool.Pool`. ### Methods - **`original_asset_to_f_asset(original_asset)`**: Converts an original asset to its Folks Finance equivalent. - **`f_asset_to_original_asset(f_asset)`**: Converts a Folks Finance asset back to its original asset representation. - **`prepare_add_liquidity(primary_asset_amount, secondary_asset_amount, slippage_pct)`**: Prepares the data structure for adding liquidity. - **`prepare_add_liquidity_tx_group(address, liquidity_addition)`**: Creates a transaction group for adding liquidity. - **`build_add_liquidity_txs(address, liquidity_addition, suggested_params)`**: Builds the transactions required for adding liquidity. - **`prepare_remove_liquidity_tx_group(address, amount)`**: Creates a transaction group for removing liquidity. - **`build_remove_liquidity_txs(address, amount, suggested_params)`**: Builds the transactions required for removing liquidity. - **`prepare_swap(asset, amount, slippage_pct, swap_for_exact=False)`**: Prepares the data structure for a swap operation. - **`prepare_swap_tx_group(swap, address)`**: Creates a transaction group for executing a swap. - **`build_swap_txs(swap, address, suggested_params)`**: Builds the transactions required for executing a swap. - **`prepare_opt_in_to_asset_tx_group(address, asset_ids)`**: Creates a transaction group for opting into specified assets. - **`build_opt_in_to_asset_tx_group(address, asset_ids, suggested_params)`**: Builds the transactions required for opting into specified assets. ``` -------------------------------- ### pactsdk.factories.base_factory.get_contract_deploy_cost Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/factories.html Calculates the cost of deploying a contract, considering factors like extra pages, byte slices, uints, and whether it's an Algorand contract. ```APIDOC ## pactsdk.factories.base_factory.get_contract_deploy_cost ### Description Calculates the estimated cost for deploying a smart contract. This function takes into account various parameters that influence deployment cost on the blockchain. ### Method ``` pactsdk.factories.base_factory.get_contract_deploy_cost(_extra_pages_, _num_byte_slices_, _num_uint_, _is_algo_) ``` ### Parameters #### Path Parameters - **_extra_pages_** (int) - Number of extra pages required for the contract. - **_num_byte_slices_** (int) - Number of byte slices used by the contract. - **_num_uint_** (int) - Number of unsigned integers used by the contract. - **_is_algo_** (bool) - Flag indicating if the contract is for Algorand. ### Returns - `int` - The estimated deployment cost. ``` -------------------------------- ### prepare_add_liquidity_tx_group Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Prepares a TransactionGroup for adding liquidity to the pool. ```APIDOC ## prepare_add_liquidity_tx_group ### Description Prepares a `pactsdk.transaction_group.TransactionGroup` for adding liquidity to the pool. See `pactsdk.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 `TransactionGroup` ### Returns A transaction group that when executed will add liquidity to the pool. ``` -------------------------------- ### pactsdk.stableswap_calculator.get_new_liq Source: https://pactfi.github.io/pact-py-sdk/latest/docs/source/pactsdk.html Calculates the new liquidity amount based on existing liquidity and pool parameters. ```APIDOC ## pactsdk.stableswap_calculator.get_new_liq ### Description Calculates the new liquidity amount based on the other liquidity, amplifier, invariant, and precision. ### Parameters - **liq_other** (int) - **amplifier** (int) - **inv** (int) - **precision** (int) ### Returns - **int** - The new liquidity amount. ``` -------------------------------- ### pactsdk.asset.Asset.prepare_opt_out_tx Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/asset.html Creates a transaction to allow an account to opt out of an asset. ```APIDOC ## prepare_opt_out_tx ### Description This creates a transaction that will allow the account to “opt out” of the asset. ### Parameters #### Path 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. ``` -------------------------------- ### Add Liquidity to a Pool Source: https://pactfi.github.io/pact-py-sdk/latest/examples/add_liquidity.html This snippet shows how to add liquidity to an existing asset pool. It requires setting up an AlgodClient and PactClient, fetching the relevant assets and pool, opting into the liquidity token, and then preparing and sending the add liquidity transaction group. Ensure you have the necessary private key and network configuration. ```python """This example adds liquidity to the pool.""" import algosdk from algosdk.v2client.algod import AlgodClient import pactsdk private_key = algosdk.mnemonic.to_private_key("") address = algosdk.account.address_from_private_key(private_key) algod = AlgodClient("", "") pact = pactsdk.PactClient(algod, network="testnet") algo = pact.fetch_asset(0) usdc = pact.fetch_asset(31566704) pool = pact.fetch_pools_by_assets(algo, usdc)[0] # Opt-in for liquidity token. opt_in_txn = pool.liquidity_asset.prepare_opt_in_tx(address) sent_optin_txid = algod.send_transaction(opt_in_txn.sign(private_key)) print(f"OptIn transaction {sent_optin_txid}") # Add liquidity liquidity_addition = pool.prepare_add_liquidity( primary_asset_amount=1_000_000, secondary_asset_amount=500_000, slippage_pct=0.5, ) add_liq_tx_group = liquidity_addition.prepare_tx_group(address=address) signed_tx_group = add_liq_tx_group.sign(private_key) algod.send_transactions(signed_tx_group) print(f"Add liquidity transaction group {add_liq_tx_group.group_id}") ``` -------------------------------- ### prepare_swap_tx_group Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Prepares a transaction group that will perform a swap on the pool. ```APIDOC ## prepare_swap_tx_group ### Description 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 `TransactionGroup` ### Returns Transaction group that when executed will perform a swap on the pool. ``` -------------------------------- ### SwapEffect Class Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/swap.html Details the basic effects of a swap on a liquidity pool. ```APIDOC ## Class: SwapEffect ### Description Swap Effect details the basic effects of performing a swap on a liquidity pool. ### Attributes - **amount_received** (`int`): The amount of the received asset. - **amount_deposited** (`int`): The amount of the deposited asset. - **minimum_amount_received** (`int`): The minimum acceptable amount of the received asset. - **fee** (`int`): The transaction fee. - **primary_asset_price_after_swap** (`float`): The price of the primary asset after the swap. - **secondary_asset_price_after_swap** (`float`): The price of the secondary asset after the swap. - **primary_asset_price_change_pct** (`float`): The percentage change in the primary asset's price. - **secondary_asset_price_change_pct** (`float`): The percentage change in the secondary asset's price. - **price** (`float`): The price of the swap. - **tx_fee** (`int`): The transaction fee amount. - **amplifier** (`float`): Relevant for Stableswap only; otherwise zero. ``` -------------------------------- ### Add Liquidity Source: https://pactfi.github.io/pact-py-sdk/latest/index.html Prepares and signs a transaction group to add liquidity to a pool. Requires specifying the amounts of primary and secondary assets to deposit. ```python # Add liquidity. liquidity_addition = pool.prepare_add_liquidity( primary_asset_amount=100_000, secondary_asset_amount=50_000, ); add_liq_tx_group = liquidity_addition.prepare_tx_group(address) signed_add_liq_tx_group = add_liq_tx_group.sign(private_key) algod.send_transactions(signed_add_liq_tx_group) ``` -------------------------------- ### pactsdk.asset.Asset.build_opt_out_tx Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/asset.html Creates the actual transaction for an account to opt out of an asset, using suggested Algorand transaction parameters. ```APIDOC ## build_opt_out_tx ### Description Creates the actual transaction for the account to opt-out from asset. ### Parameters #### Path 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. ``` -------------------------------- ### get_add_liquidity_bonus_pct Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/stableswap_calculator.html Calculates the percentage bonus for adding liquidity to a Stableswap pool. ```APIDOC ## get_add_liquidity_bonus_pct ### Description Calculates the percentage bonus for adding liquidity to a Stableswap pool. ### Parameters #### Query Parameters - **added_primary** (int) – Required - **added_secondary** (int) – Required - **total_primary** (int) – Required - **total_secondary** (int) – Required - **fee_bps** (int) – Required - **amplifier** (int) – Required - **precision** (int) – Required ### Returns - **float** – The percentage bonus. ``` -------------------------------- ### pactsdk.pool.fetch_app_global_state Source: https://pactfi.github.io/pact-py-sdk/latest/pactsdk/pool.html Fetches the global state of a PACT application. ```APIDOC ## pactsdk.pool.fetch_app_global_state ### Description Fetches the global state 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 `AppInternalState` ### Returns The global state of the application. ```