code
stringlengths
0
94.8k
repo_name
stringclasses
1 value
path
stringlengths
14
57
language
stringclasses
1 value
license
stringclasses
1 value
size
int64
0
94.8k
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.domains.python import PyObject project = 'algokit-utils-py' copyright = '2025, Algorand Foundation' author = 'Algorand Foundation' release = '3.0' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = ['myst_parser', 'autoapi.extension', "sphinx.ext.autosectionlabel", "sphinx.ext.githubpages"] templates_path = ['_templates'] exclude_patterns = [] autoapi_dirs = ['../../src/algokit_utils'] autoapi_options = ['members', 'undoc-members', 'show-inheritance', 'show-module-summary'] autoapi_ignore = ['*algokit_utils/beta/__init__.py', '*algokit_utils/asset.py', '*algokit_utils/deploy.py', "*algokit_utils/network_clients.py", "*algokit_utils/common.py", "*algokit_utils/account.py", "*algokit_utils/application_client.py", "*algokit_utils/application_specification.py", "*algokit_utils/logic_error.py", "*algokit_utils/dispenser_api.py"] myst_heading_anchors = 5 myst_all_links_external = False autosectionlabel_prefix_document = True # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'furo' html_static_path = ['_static'] pygments_style = "sphinx" pygments_dark_style = "monokai" exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
algorandfoundation/algokit-utils-py
docs/source/conf.py
Python
MIT
2,144
algorandfoundation/algokit-utils-py
legacy_v2_tests/__init__.py
Python
MIT
0
from typing import Literal import beaker import pyteal from beaker.lib.storage import BoxMapping class State: greeting = beaker.GlobalStateValue(pyteal.TealType.bytes) last = beaker.LocalStateValue(pyteal.TealType.bytes, default=pyteal.Bytes("unset")) box = BoxMapping(pyteal.abi.StaticBytes[Literal[4]], pyteal.abi.String) app = beaker.Application("HelloWorldApp", state=State()) @app.external def version(*, output: pyteal.abi.Uint64) -> pyteal.Expr: return output.set(pyteal.Tmpl.Int("TMPL_VERSION")) @app.external(read_only=True) def readonly(error: pyteal.abi.Uint64) -> pyteal.Expr: return pyteal.If(error.get(), pyteal.Assert(pyteal.Int(0), comment="An error"), pyteal.Approve()) @app.external() def set_box(name: pyteal.abi.StaticBytes[Literal[4]], value: pyteal.abi.String) -> pyteal.Expr: return app.state.box[name.get()].set(value.get()) @app.external def get_box(name: pyteal.abi.StaticBytes[Literal[4]], *, output: pyteal.abi.String) -> pyteal.Expr: return output.set(app.state.box[name.get()].get()) @app.external(read_only=True) def get_box_readonly(name: pyteal.abi.StaticBytes[Literal[4]], *, output: pyteal.abi.String) -> pyteal.Expr: return output.set(app.state.box[name.get()].get()) @app.update(authorize=beaker.Authorize.only_creator()) def update() -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Tmpl.Int("TMPL_UPDATABLE"), comment="is updatable"), app.state.greeting.set(pyteal.Bytes("Updated ABI")), ) @app.update(bare=True, authorize=beaker.Authorize.only_creator()) def update_bare() -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Tmpl.Int("TMPL_UPDATABLE"), comment="is updatable"), app.state.greeting.set(pyteal.Bytes("Updated Bare")), ) @app.update(authorize=beaker.Authorize.only_creator()) def update_args(check: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Eq(check.get(), pyteal.Bytes("Yes")), comment="passes update check"), pyteal.Assert(pyteal.Tmpl.Int("TMPL_UPDATABLE"), comment="is updatable"), app.state.greeting.set(pyteal.Bytes("Updated Args")), ) @app.delete(authorize=beaker.Authorize.only_creator()) def delete() -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Tmpl.Int("TMPL_DELETABLE"), comment="is deletable"), ) @app.delete(bare=True, authorize=beaker.Authorize.only_creator()) def delete_bare() -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Tmpl.Int("TMPL_DELETABLE"), comment="is deletable"), ) @app.delete(authorize=beaker.Authorize.only_creator()) def delete_args(check: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Eq(check.get(), pyteal.Bytes("Yes")), comment="passes delete check"), pyteal.Assert(pyteal.Tmpl.Int("TMPL_DELETABLE"), comment="is deletable"), ) @app.external(method_config={"opt_in": pyteal.CallConfig.CREATE}) def create_opt_in() -> pyteal.Expr: return pyteal.Seq( app.state.greeting.set(pyteal.Bytes("Opt In")), pyteal.Approve(), ) @app.external def update_greeting(greeting: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( app.state.greeting.set(greeting.get()), ) @app.create(bare=True) def create_bare() -> pyteal.Expr: return pyteal.Seq( app.state.greeting.set(pyteal.Bytes("Hello Bare")), pyteal.Approve(), ) @app.create def create() -> pyteal.Expr: return pyteal.Seq( app.state.greeting.set(pyteal.Bytes("Hello ABI")), pyteal.Approve(), ) @app.create def create_args(greeting: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( app.state.greeting.set(greeting.get()), pyteal.Approve(), ) @app.external(read_only=True) def hello(name: pyteal.abi.String, *, output: pyteal.abi.String) -> pyteal.Expr: return output.set(pyteal.Concat(app.state.greeting, pyteal.Bytes(", "), name.get())) @app.external def hello_remember(name: pyteal.abi.String, *, output: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( app.state.last.set(name.get()), output.set(pyteal.Concat(app.state.greeting, pyteal.Bytes(", "), name.get())) ) @app.external(read_only=True) def get_last(*, output: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq(output.set(app.state.last.get())) @app.clear_state def clear_state() -> pyteal.Expr: return pyteal.Approve() @app.opt_in def opt_in() -> pyteal.Expr: return pyteal.Seq( app.state.last.set(pyteal.Bytes("Opt In ABI")), pyteal.Approve(), ) @app.opt_in(bare=True) def opt_in_bare() -> pyteal.Expr: return pyteal.Seq( app.state.last.set(pyteal.Bytes("Opt In Bare")), pyteal.Approve(), ) @app.opt_in def opt_in_args(check: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Eq(check.get(), pyteal.Bytes("Yes")), comment="passes opt_in check"), app.state.last.set(pyteal.Bytes("Opt In Args")), pyteal.Approve(), ) @app.close_out def close_out() -> pyteal.Expr: return pyteal.Seq( pyteal.Approve(), ) @app.close_out(bare=True) def close_out_bare() -> pyteal.Expr: return pyteal.Seq( pyteal.Approve(), ) @app.close_out def close_out_args(check: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq( pyteal.Assert(pyteal.Eq(check.get(), pyteal.Bytes("Yes")), comment="passes close_out check"), pyteal.Approve(), ) @app.external def call_with_payment(payment: pyteal.abi.PaymentTransaction, *, output: pyteal.abi.String) -> pyteal.Expr: return pyteal.Seq(pyteal.Assert(payment.get().amount() > pyteal.Int(0)), output.set("Payment Successful"))
algorandfoundation/algokit-utils-py
legacy_v2_tests/app_client_test.py
Python
MIT
5,773
import beaker import pyteal app = beaker.Application("MultiUnderscoreApp") @app.external def some_value(*, output: pyteal.abi.Uint64) -> pyteal.Expr: return output.set(pyteal.Tmpl.Int("TMPL_SOME_VALUE")) @app.update(bare=True, authorize=beaker.Authorize.only_creator()) def update() -> pyteal.Expr: return pyteal.Assert(pyteal.Tmpl.Int("TMPL_UPDATABLE"), comment="is updatable") @app.delete(bare=True, authorize=beaker.Authorize.only_creator()) def delete() -> pyteal.Expr: return pyteal.Assert(pyteal.Tmpl.Int("TMPL_DELETABLE"), comment="is deletable") @app.create(bare=True) def create() -> pyteal.Expr: return pyteal.Approve()
algorandfoundation/algokit-utils-py
legacy_v2_tests/app_multi_underscore_template_var.py
Python
MIT
655
import inspect import math import random import subprocess from pathlib import Path from typing import TYPE_CHECKING from uuid import uuid4 import algosdk.transaction import pytest from dotenv import load_dotenv from algokit_utils import ( DELETABLE_TEMPLATE_NAME, UPDATABLE_TEMPLATE_NAME, Account, ApplicationClient, ApplicationSpecification, EnsureBalanceParameters, ensure_funded, get_account, get_algod_client, get_indexer_client, get_kmd_client_from_algod_client, replace_template_variables, ) from legacy_v2_tests import app_client_test if TYPE_CHECKING: from algosdk.kmd import KMDClient from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture(autouse=True, scope="session") def _environment_fixture() -> None: env_path = Path(__file__).parent / ".." / "example.env" load_dotenv(env_path) def check_output_stability(logs: str, *, test_name: str | None = None) -> None: """Test that the contract output hasn't changed for an Application, using git diff""" caller_frame = inspect.stack()[1] caller_path = Path(caller_frame.filename).resolve() caller_dir = caller_path.parent test_name = test_name or caller_frame.function caller_stem = Path(caller_frame.filename).stem output_dir = caller_dir / f"{caller_stem}.approvals" output_dir.mkdir(exist_ok=True) output_file = output_dir / f"{test_name}.approved.txt" output_file_str = str(output_file) output_file_did_exist = output_file.exists() output_file.write_text(logs, encoding="utf-8") git_diff = subprocess.run( [ "git", "diff", "--exit-code", "--no-ext-diff", "--no-color", output_file_str, ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) # first fail if there are any changes to already committed files, you must manually add them in that case assert git_diff.returncode == 0, git_diff.stdout # if first time running, fail in case of accidental change to output directory if not output_file_did_exist: pytest.fail( f"New output folder created at {output_file_str} from test {test_name} - " "if this was intentional, please commit the files to the git repo" ) def read_spec( file_name: str, *, updatable: bool | None = None, deletable: bool | None = None, template_values: dict | None = None, ) -> ApplicationSpecification: path = Path(__file__).parent / file_name spec = ApplicationSpecification.from_json(Path(path).read_text(encoding="utf-8")) template_variables = template_values or {} if updatable is not None: template_variables["UPDATABLE"] = int(updatable) if deletable is not None: template_variables["DELETABLE"] = int(deletable) spec.approval_program = ( replace_template_variables(spec.approval_program, template_variables) .replace(f"// {UPDATABLE_TEMPLATE_NAME}", "// updatable") .replace(f"// {DELETABLE_TEMPLATE_NAME}", "// deletable") ) return spec def get_specs( updatable: bool | None = None, deletable: bool | None = None, ) -> tuple[ApplicationSpecification, ApplicationSpecification, ApplicationSpecification]: return ( read_spec("app_v1.json", updatable=updatable, deletable=deletable), read_spec("app_v2.json", updatable=updatable, deletable=deletable), read_spec("app_v3.json", updatable=updatable, deletable=deletable), ) def get_unique_name() -> str: name = str(uuid4()).replace("-", "") assert name.isalnum() return name def is_opted_in(client_fixture: ApplicationClient) -> bool: _, sender = client_fixture.resolve_signer_sender() account_info = client_fixture.algod_client.account_info(sender) assert isinstance(account_info, dict) apps_local_state = account_info["apps-local-state"] return any(x for x in apps_local_state if x["id"] == client_fixture.app_id) @pytest.fixture(scope="session") def algod_client() -> "AlgodClient": return get_algod_client() @pytest.fixture(scope="session") def kmd_client(algod_client: "AlgodClient") -> "KMDClient": return get_kmd_client_from_algod_client(algod_client) @pytest.fixture(scope="session") def indexer_client() -> "IndexerClient": return get_indexer_client() @pytest.fixture def creator(algod_client: "AlgodClient") -> Account: creator_name = get_unique_name() return get_account(algod_client, creator_name) @pytest.fixture(scope="session") def funded_account(algod_client: "AlgodClient") -> Account: creator_name = get_unique_name() return get_account(algod_client, creator_name) @pytest.fixture(scope="session") def app_spec() -> ApplicationSpecification: app_spec = app_client_test.app.build() path = Path(__file__).parent / "app_client_test.json" path.write_text(app_spec.to_json()) return read_spec("app_client_test.json", deletable=True, updatable=True, template_values={"VERSION": 1}) def generate_test_asset(algod_client: "AlgodClient", sender: Account, total: int | None) -> int: if total is None: total = math.floor(random.random() * 100) + 20 decimals = 0 asset_name = f"ASA ${math.floor(random.random() * 100) + 1}_${math.floor(random.random() * 100) + 1}_${total}" params = algod_client.suggested_params() txn = algosdk.transaction.AssetConfigTxn( sender=sender.address, sp=params, total=total * 10**decimals, decimals=decimals, default_frozen=False, unit_name="", asset_name=asset_name, manager=sender.address, reserve=sender.address, freeze=sender.address, clawback=sender.address, url="https://path/to/my/asset/details", metadata_hash=None, note=None, lease=None, rekey_to=None, ) signed_transaction = txn.sign(sender.private_key) algod_client.send_transaction(signed_transaction) ptx = algod_client.pending_transaction_info(txn.get_txid()) if isinstance(ptx, dict) and "asset-index" in ptx and isinstance(ptx["asset-index"], int): return ptx["asset-index"] else: raise ValueError("Unexpected response from pending_transaction_info") def assure_funds(algod_client: "AlgodClient", account: Account) -> None: ensure_funded( algod_client, EnsureBalanceParameters( account_to_fund=account, min_spending_balance_micro_algos=300000, min_funding_increment_micro_algos=1, ), )
algorandfoundation/algokit-utils-py
legacy_v2_tests/conftest.py
Python
MIT
6,720
from typing import TYPE_CHECKING from algokit_utils import get_account from legacy_v2_tests.conftest import get_unique_name if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient def test_account_can_be_called_twice(algod_client: "AlgodClient") -> None: account_name = get_unique_name() account1 = get_account(algod_client, account_name) account2 = get_account(algod_client, account_name) assert account1 == account2
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_account.py
Python
MIT
452
import pytest from algokit_utils import AppDeployMetaData @pytest.mark.parametrize( "app_note_json", [ b'ALGOKIT_DEPLOYER:j{"name":"VotingRoundApp","version":"1.0","deletable":true,"updatable":true}', b'ALGOKIT_DEPLOYER:j{"name":"VotingRoundApp","version":"1.0","deletable":true}', ], ) def test_metadata_serialization(app_note_json: bytes) -> None: metadata = AppDeployMetaData.decode(app_note_json) assert metadata
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app.py
Python
MIT
456
import pytest from algokit_utils import ( DeploymentFailedError, get_next_version, ) @pytest.mark.parametrize( ("current", "expected_next"), [ ("1", "2"), ("v1", "v2"), ("v1-alpha", "v2-alpha"), ("1.0", "1.1"), ("v1.0", "v1.1"), ("v1.0-alpha", "v1.1-alpha"), ("1.0.0", "1.0.1"), ("v1.0.0", "v1.0.1"), ("v1.0.0-alpha", "v1.0.1-alpha"), ], ) def test_auto_version_increment(current: str, expected_next: str) -> None: value = get_next_version(current) assert value == expected_next def test_auto_version_increment_failure() -> None: with pytest.raises(DeploymentFailedError): get_next_version("teapot")
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client.py
Python
MIT
717
from collections.abc import Generator from hashlib import sha256 from pathlib import Path from typing import TYPE_CHECKING from unittest.mock import Mock, patch import pytest from algosdk.atomic_transaction_composer import ( AccountTransactionSigner, AtomicTransactionComposer, TransactionWithSigner, ) from algosdk.transaction import ApplicationCallTxn, PaymentTxn import algokit_utils import algokit_utils._legacy_v2 import algokit_utils._legacy_v2.logic_error from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, CreateCallParameters, get_account, ) from legacy_v2_tests.conftest import check_output_stability, get_unique_name if TYPE_CHECKING: from algosdk.abi import Method from algosdk.v2client.algod import AlgodClient @pytest.fixture(scope="module") def client_fixture(algod_client: "AlgodClient", app_spec: ApplicationSpecification) -> ApplicationClient: creator_name = get_unique_name() creator = get_account(algod_client, creator_name) client = ApplicationClient(algod_client, app_spec, signer=creator) create_response = client.create("create") assert create_response.tx_id return client # This fixture is automatically applied to all application call tests. # If you need to run a test without debug mode, you can reference this mock within the test and disable it explicitly. @pytest.fixture(autouse=True) def mock_config() -> Generator[Mock, None, None]: with patch("algokit_utils._legacy_v2.application_client.config", new_callable=Mock) as mock_config: mock_config.debug = True mock_config.project_root = None yield mock_config def test_app_client_from_app_spec_path(algod_client: "AlgodClient") -> None: client = ApplicationClient(algod_client, Path(__file__).parent / "app_client_test.json") assert client.app_spec def test_abi_call_with_atc(client_fixture: ApplicationClient) -> None: atc = AtomicTransactionComposer() client_fixture.compose_call(atc, "hello", name="test") result = atc.execute(client_fixture.algod_client, 4) assert result.abi_results[0].return_value == "Hello ABI, test" class PretendSubroutine: def __init__(self, method: "Method"): self._method = method def method_spec(self) -> "Method": return self._method def test_abi_call_with_method_spec(client_fixture: ApplicationClient) -> None: hello = client_fixture.app_spec.contract.get_method_by_name("hello") subroutine = PretendSubroutine(hello) result = client_fixture.call(subroutine, name="test") assert result.return_value == "Hello ABI, test" def test_abi_call_with_transaction_arg(client_fixture: ApplicationClient, funded_account: Account) -> None: call_with_payment = client_fixture.app_spec.contract.get_method_by_name("call_with_payment") payment = PaymentTxn( sender=funded_account.address, receiver=client_fixture.app_address, amt=1_000_000, note=sha256(b"self-payment").digest(), sp=client_fixture.algod_client.suggested_params(), ) # type: ignore[no-untyped-call] payment_with_signer = TransactionWithSigner(payment, AccountTransactionSigner(funded_account.private_key)) result = client_fixture.call(call_with_payment, payment=payment_with_signer) assert result.return_value == "Payment Successful" def test_abi_call_multiple_times_with_atc(client_fixture: ApplicationClient) -> None: atc = AtomicTransactionComposer() client_fixture.compose_call(atc, "hello", name="test") client_fixture.compose_call(atc, "hello", name="test2") client_fixture.compose_call(atc, "hello", name="test3") result = atc.execute(client_fixture.algod_client, 4) assert result.abi_results[0].return_value == "Hello ABI, test" assert result.abi_results[1].return_value == "Hello ABI, test2" assert result.abi_results[2].return_value == "Hello ABI, test3" def test_call_parameters_from_derived_type_ignored(client_fixture: ApplicationClient) -> None: client_fixture = client_fixture.prepare() # make a copy parameters = CreateCallParameters( extra_pages=1, ) client_fixture.app_id = 123 atc = AtomicTransactionComposer() client_fixture.compose_call(atc, "hello", transaction_parameters=parameters, name="test") signed_txn = atc.txn_list[0] app_txn = signed_txn.txn assert isinstance(app_txn, ApplicationCallTxn) assert app_txn.extra_pages == 0 def test_call_with_box(client_fixture: ApplicationClient) -> None: algokit_utils.ensure_funded( client_fixture.algod_client, algokit_utils.EnsureBalanceParameters( account_to_fund=client_fixture.app_address, min_spending_balance_micro_algos=200_000, min_funding_increment_micro_algos=200_000, ), ) set_response = client_fixture.call( "set_box", algokit_utils.OnCompleteCallParameters(boxes=[(0, b"ssss")]), name=b"ssss", value="test", ) assert set_response.confirmed_round get_response = client_fixture.call( "get_box", algokit_utils.OnCompleteCallParameters(boxes=[(0, b"ssss")]), name=b"ssss", ) assert get_response.return_value == "test" def test_call_with_box_readonly(client_fixture: ApplicationClient) -> None: algokit_utils.ensure_funded( client_fixture.algod_client, algokit_utils.EnsureBalanceParameters( account_to_fund=client_fixture.app_address, min_spending_balance_micro_algos=200_000, min_funding_increment_micro_algos=200_000, ), ) set_response = client_fixture.call( "set_box", algokit_utils.OnCompleteCallParameters(boxes=[(0, b"ssss")]), name=b"ssss", value="test", ) assert set_response.confirmed_round get_response = client_fixture.call( "get_box_readonly", algokit_utils.OnCompleteCallParameters(boxes=[(0, b"ssss")]), name=b"ssss", ) assert get_response.return_value == "test" def test_readonly_call(client_fixture: ApplicationClient) -> None: response = client_fixture.call( "readonly", error=0, ) assert response.confirmed_round is None def test_readonly_call_with_error(client_fixture: ApplicationClient) -> None: with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 client_fixture.call( "readonly", error=1, ) check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) def test_readonly_call_with_error_with_new_client_provided_template_values( algod_client: "AlgodClient", funded_account: Account, ) -> None: app_spec = Path(__file__).parent / "app_client_test.json" client = ApplicationClient( algod_client, app_spec, signer=funded_account, template_values={"VERSION": 1, "UPDATABLE": 1, "DELETABLE": 1} ) create_response = client.create("create") assert create_response.tx_id new_client = ApplicationClient( algod_client, app_spec, app_id=client.app_id, signer=funded_account, template_values=client.template_values ) new_client.approval_source_map = client.approval_source_map with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 new_client.call( "readonly", error=1, ) check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) def test_readonly_call_with_error_with_new_client_provided_source_map( algod_client: "AlgodClient", funded_account: Account, ) -> None: app_spec = Path(__file__).parent / "app_client_test.json" client = ApplicationClient( algod_client, app_spec, signer=funded_account, template_values={"VERSION": 1, "UPDATABLE": 1, "DELETABLE": 1} ) create_response = client.create("create") assert create_response.tx_id new_client = ApplicationClient(algod_client, app_spec, app_id=client.app_id, signer=funded_account) new_client.approval_source_map = client.approval_source_map with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 new_client.call( "readonly", error=1, ) check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) def test_readonly_call_with_error_with_imported_source_map( algod_client: "AlgodClient", funded_account: Account, ) -> None: app_spec = Path(__file__).parent / "app_client_test.json" client = ApplicationClient( algod_client, app_spec, signer=funded_account, template_values={"VERSION": 1, "UPDATABLE": 1, "DELETABLE": 1} ) create_response = client.create("create") assert create_response.tx_id source_map_export = client.export_source_map() assert source_map_export new_client = ApplicationClient(algod_client, app_spec, app_id=client.app_id, signer=funded_account) new_client.import_source_map(source_map_export) with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 new_client.call( "readonly", error=1, ) check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) def test_readonly_call_with_error_with_new_client_missing_source_map( algod_client: "AlgodClient", funded_account: Account, ) -> None: app_spec = Path(__file__).parent / "app_client_test.json" client = ApplicationClient( algod_client, app_spec, signer=funded_account, template_values={"VERSION": 1, "UPDATABLE": 1, "DELETABLE": 1} ) create_response = client.create("create") assert create_response.tx_id new_client = ApplicationClient(algod_client, app_spec, app_id=client.app_id, signer=funded_account) with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 new_client.call( "readonly", error=1, ) check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) def test_readonly_call_with_error_debug_mode_disabled(mock_config: Mock, client_fixture: ApplicationClient) -> None: mock_config.debug = False with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 client_fixture.call( "readonly", error=1, ) assert ex.value.traces is None mock_config.debug = True def test_readonly_call_with_error_debug_mode_enabled(client_fixture: ApplicationClient) -> None: with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 client_fixture.call( "readonly", error=1, ) assert ex.value.traces is not None assert ex.value.traces[0].exec_trace["approval-program-trace"] is not None def test_app_call_with_error_debug_mode_disabled(mock_config: Mock, client_fixture: ApplicationClient) -> None: mock_config.debug = False algokit_utils.ensure_funded( client_fixture.algod_client, algokit_utils.EnsureBalanceParameters( account_to_fund=client_fixture.app_address, min_spending_balance_micro_algos=200_000, min_funding_increment_micro_algos=200_000, ), ) with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 client_fixture.call( "set_box", name=b"ssss", value="test", ) assert ex.value.traces is None mock_config.debug = True def test_app_call_with_error_debug_mode_enabled(client_fixture: ApplicationClient) -> None: algokit_utils.ensure_funded( client_fixture.algod_client, algokit_utils.EnsureBalanceParameters( account_to_fund=client_fixture.app_address, min_spending_balance_micro_algos=200_000, min_funding_increment_micro_algos=200_000, ), ) with pytest.raises(algokit_utils._legacy_v2.logic_error.LogicError) as ex: # noqa: SLF001 client_fixture.call( "set_box", name=b"ssss", value="test", ) assert ex.value.traces is not None
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_call.py
Python
MIT
12,318
import base64 from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, ) from legacy_v2_tests.conftest import is_opted_in if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", app_spec: ApplicationSpecification, funded_account: Account, ) -> ApplicationClient: client = ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) create_response = client.create("create") assert create_response.tx_id opt_in_response = client.opt_in("opt_in") assert opt_in_response.tx_id return client def test_clear_state(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) close_out_response = client_fixture.clear_state() assert close_out_response.tx_id assert not is_opted_in(client_fixture) def test_clear_state_app_already_deleted(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) client_fixture.delete("delete") assert is_opted_in(client_fixture) close_out_response = client_fixture.clear_state() assert close_out_response.tx_id assert not is_opted_in(client_fixture) def test_clear_state_app_args(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) app_args = [b"test", b"data"] close_out_response = client_fixture.clear_state(app_args=app_args) assert close_out_response.tx_id tx_info = client_fixture.algod_client.pending_transaction_info(close_out_response.tx_id) assert isinstance(tx_info, dict) assert [base64.b64decode(x) for x in tx_info["txn"]["txn"]["apaa"]] == app_args
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_clear_state.py
Python
MIT
1,870
from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, LogicError, ) from legacy_v2_tests.conftest import check_output_stability, is_opted_in if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", app_spec: ApplicationSpecification, funded_account: Account, ) -> ApplicationClient: client = ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) create_response = client.create("create") assert create_response.tx_id opt_in_response = client.opt_in("opt_in") assert opt_in_response.tx_id return client def test_abi_close_out(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) close_out_response = client_fixture.close_out("close_out") assert close_out_response.tx_id assert not is_opted_in(client_fixture) def test_bare_close_out(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) close_out_response = client_fixture.close_out(call_abi_method=False) assert close_out_response.tx_id assert not is_opted_in(client_fixture) def test_abi_close_out_args(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) close_out_response = client_fixture.close_out("close_out_args", check="Yes") assert close_out_response.tx_id assert not is_opted_in(client_fixture) def test_abi_close_out_args_fails(client_fixture: ApplicationClient) -> None: assert is_opted_in(client_fixture) with pytest.raises(LogicError) as ex: client_fixture.close_out("close_out_args", check="No") check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) assert is_opted_in(client_fixture)
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_close_out.py
Python
MIT
1,986
import dataclasses from typing import TYPE_CHECKING import pytest from algosdk.atomic_transaction_composer import AccountTransactionSigner, AtomicTransactionComposer, TransactionSigner from algosdk.transaction import ApplicationCallTxn, GenericSignedTransaction, OnComplete, Transaction from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, CreateCallParameters, get_account, get_app_id_from_tx_id, ) from legacy_v2_tests.conftest import check_output_stability, get_unique_name if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture(scope="module") def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", app_spec: ApplicationSpecification, funded_account: Account, ) -> ApplicationClient: return ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) def test_bare_create(client_fixture: ApplicationClient) -> None: client_fixture.create(call_abi_method=False) assert client_fixture.call("hello", name="test").return_value == "Hello Bare, test" def test_abi_create(client_fixture: ApplicationClient) -> None: client_fixture.create("create") assert client_fixture.call("hello", name="test").return_value == "Hello ABI, test" @pytest.mark.parametrize("method", ["create_args", "create_args(string)void", True]) def test_abi_create_args(method: str | bool, client_fixture: ApplicationClient) -> None: client_fixture.create(method, greeting="ahoy") assert client_fixture.call("hello", name="test").return_value == "ahoy, test" def test_create_auto_find(client_fixture: ApplicationClient) -> None: client_fixture.create(transaction_parameters=CreateCallParameters(on_complete=OnComplete.OptInOC)) assert client_fixture.call("hello", name="test").return_value == "Opt In, test" def test_create_auto_find_ambiguous(client_fixture: ApplicationClient) -> None: with pytest.raises(Exception, match="Could not find an exact method to use") as ex: client_fixture.create() check_output_stability(str(ex.value)) def test_abi_create_with_atc(client_fixture: ApplicationClient) -> None: atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create") create_result = atc.execute(client_fixture.algod_client, 4) client_fixture.app_id = get_app_id_from_tx_id(client_fixture.algod_client, create_result.tx_ids[0]) assert client_fixture.call("hello", name="test").return_value == "Hello ABI, test" def test_bare_create_with_atc(client_fixture: ApplicationClient) -> None: atc = AtomicTransactionComposer() client_fixture.compose_create(atc, call_abi_method=False) create_result = atc.execute(client_fixture.algod_client, 4) client_fixture.app_id = get_app_id_from_tx_id(client_fixture.algod_client, create_result.tx_ids[0]) assert client_fixture.call("hello", name="test").return_value == "Hello Bare, test" def test_create_parameters_lease(client_fixture: ApplicationClient) -> None: lease = b"a" * 32 atc = AtomicTransactionComposer() client_fixture.compose_create( atc, "create", transaction_parameters=CreateCallParameters( lease=lease, ), ) signed_txn = atc.txn_list[0] assert signed_txn.txn.lease == lease def test_create_parameters_note(client_fixture: ApplicationClient) -> None: note = b"test note" atc = AtomicTransactionComposer() client_fixture.compose_create( atc, "create", transaction_parameters=CreateCallParameters( note=note, ), ) signed_txn = atc.txn_list[0] assert signed_txn.txn.note == note def test_create_parameters_on_complete(client_fixture: ApplicationClient) -> None: on_complete = OnComplete.OptInOC atc = AtomicTransactionComposer() client_fixture.compose_create( atc, "create", transaction_parameters=CreateCallParameters(on_complete=OnComplete.OptInOC) ) signed_txn = atc.txn_list[0] app_txn = signed_txn.txn assert isinstance(app_txn, ApplicationCallTxn) assert app_txn.on_complete == on_complete def test_create_parameters_extra_pages(client_fixture: ApplicationClient) -> None: extra_pages = 1 atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(extra_pages=extra_pages)) signed_txn = atc.txn_list[0] app_txn = signed_txn.txn assert isinstance(app_txn, ApplicationCallTxn) assert app_txn.extra_pages == extra_pages def test_create_parameters_signer(client_fixture: ApplicationClient) -> None: another_account_name = get_unique_name() account = get_account(client_fixture.algod_client, another_account_name) signer = AccountTransactionSigner(account.private_key) atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(signer=signer)) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.signer, AccountTransactionSigner) assert signed_txn.signer.private_key == signer.private_key @dataclasses.dataclass class DataclassTransactionSigner(TransactionSigner): def sign_transactions(self, txn_group: list[Transaction], indexes: list[int]) -> list[GenericSignedTransaction]: return self.transaction_signer.sign_transactions(txn_group, indexes) transaction_signer: TransactionSigner def test_create_parameters_dataclass_signer(client_fixture: ApplicationClient) -> None: another_account_name = get_unique_name() account = get_account(client_fixture.algod_client, another_account_name) signer = DataclassTransactionSigner(AccountTransactionSigner(account.private_key)) atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(signer=signer)) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.signer, DataclassTransactionSigner) def test_create_parameters_sender(client_fixture: ApplicationClient) -> None: another_account_name = get_unique_name() account = get_account(client_fixture.algod_client, another_account_name) atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(sender=account.address)) signed_txn = atc.txn_list[0] assert signed_txn.txn.sender == account.address def test_create_parameters_rekey_to(client_fixture: ApplicationClient) -> None: another_account_name = get_unique_name() account = get_account(client_fixture.algod_client, another_account_name) atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(rekey_to=account.address)) signed_txn = atc.txn_list[0] assert signed_txn.txn.rekey_to == account.address def test_create_parameters_suggested_params(client_fixture: ApplicationClient) -> None: sp = client_fixture.algod_client.suggested_params() sp.gen = "test-genesis" atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(suggested_params=sp)) signed_txn = atc.txn_list[0] assert signed_txn.txn.genesis_id == sp.gen def test_create_parameters_boxes(client_fixture: ApplicationClient) -> None: boxes = [(0, b"one"), (0, b"two")] atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(boxes=boxes)) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.txn, ApplicationCallTxn) assert [(b.app_index, b.name) for b in signed_txn.txn.boxes] == boxes def test_create_parameters_accounts(client_fixture: ApplicationClient) -> None: another_account_name = get_unique_name() account = get_account(client_fixture.algod_client, another_account_name) atc = AtomicTransactionComposer() client_fixture.compose_create( atc, "create", transaction_parameters=CreateCallParameters(accounts=[account.address]) ) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.txn, ApplicationCallTxn) assert signed_txn.txn.accounts == [account.address] def test_create_parameters_foreign_apps(client_fixture: ApplicationClient) -> None: foreign_apps = [1, 2, 3] atc = AtomicTransactionComposer() client_fixture.compose_create(atc, "create", transaction_parameters=CreateCallParameters(foreign_apps=foreign_apps)) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.txn, ApplicationCallTxn) assert signed_txn.txn.foreign_apps == foreign_apps def test_create_parameters_foreign_assets(client_fixture: ApplicationClient) -> None: foreign_assets = [10, 20, 30] atc = AtomicTransactionComposer() client_fixture.compose_create( atc, "create", transaction_parameters=CreateCallParameters(foreign_assets=foreign_assets) ) signed_txn = atc.txn_list[0] assert isinstance(signed_txn.txn, ApplicationCallTxn) assert signed_txn.txn.foreign_assets == foreign_assets
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_create.py
Python
MIT
9,250
from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, LogicError, ) from legacy_v2_tests.conftest import check_output_stability if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: Account, app_spec: ApplicationSpecification, ) -> ApplicationClient: client = ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) client.create("create") return client def test_abi_delete(client_fixture: ApplicationClient) -> None: delete_response = client_fixture.delete("delete") assert delete_response.tx_id def test_bare_delete(client_fixture: ApplicationClient) -> None: delete_response = client_fixture.delete(call_abi_method=False) assert delete_response.tx_id def test_abi_delete_args(client_fixture: ApplicationClient) -> None: delete_response = client_fixture.delete("delete_args", check="Yes") assert delete_response.tx_id def test_abi_delete_args_fails(client_fixture: ApplicationClient) -> None: with pytest.raises(LogicError) as ex: client_fixture.delete("delete_args", check="No") check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}"))
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_delete.py
Python
MIT
1,463
from typing import TYPE_CHECKING import pytest from algokit_utils import ( ABICreateCallArgs, Account, ApplicationClient, ApplicationSpecification, TransferParameters, transfer, ) from legacy_v2_tests.conftest import get_unique_name, read_spec if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: Account, ) -> ApplicationClient: app_spec = read_spec("app_client_test.json", deletable=True, updatable=True, template_values={"VERSION": 1}) return ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, app_name=get_unique_name() ) def test_deploy_with_create(client_fixture: ApplicationClient, creator: Account) -> None: client_fixture.deploy( "v1", create_args=ABICreateCallArgs( method="create", ), ) transfer( client_fixture.algod_client, TransferParameters(from_account=creator, to_address=client_fixture.app_address, micro_algos=100_000), ) assert client_fixture.call("hello", name="test").return_value == "Hello ABI, test" def test_deploy_with_create_args(client_fixture: ApplicationClient, app_spec: ApplicationSpecification) -> None: create_args = next(m for m in app_spec.contract.methods if m.name == "create_args") client_fixture.deploy("v1", create_args=ABICreateCallArgs(method=create_args, args={"greeting": "deployed"})) assert client_fixture.call("hello", name="test").return_value == "deployed, test" def test_deploy_with_bare_create(client_fixture: ApplicationClient) -> None: client_fixture.deploy( "v1", create_args=ABICreateCallArgs( method=False, ), ) assert client_fixture.call("hello", name="test").return_value == "Hello Bare, test"
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_deploy.py
Python
MIT
1,988
from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, LogicError, ) from legacy_v2_tests.conftest import check_output_stability, is_opted_in if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", app_spec: ApplicationSpecification, funded_account: Account, ) -> ApplicationClient: client = ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) client.create("create") return client def test_abi_opt_in(client_fixture: ApplicationClient) -> None: opt_in_response = client_fixture.opt_in("opt_in") assert opt_in_response.tx_id assert client_fixture.call("get_last").return_value == "Opt In ABI" assert is_opted_in(client_fixture) def test_bare_opt_in(client_fixture: ApplicationClient) -> None: opt_in_response = client_fixture.opt_in(call_abi_method=False) assert opt_in_response.tx_id assert client_fixture.call("get_last").return_value == "Opt In Bare" assert is_opted_in(client_fixture) def test_abi_opt_in_args(client_fixture: ApplicationClient) -> None: update_response = client_fixture.opt_in("opt_in_args", check="Yes") assert update_response.tx_id assert client_fixture.call("get_last").return_value == "Opt In Args" assert is_opted_in(client_fixture) def test_abi_update_args_fails(client_fixture: ApplicationClient) -> None: with pytest.raises(LogicError) as ex: client_fixture.opt_in("opt_in_args", check="No") check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}")) assert not is_opted_in(client_fixture)
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_opt_in.py
Python
MIT
1,854
import base64 from typing import TYPE_CHECKING from algosdk.atomic_transaction_composer import AccountTransactionSigner from algokit_utils import ( ApplicationClient, ApplicationSpecification, ) if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient def test_app_client_prepare_with_no_existing_or_new( algod_client: "AlgodClient", app_spec: ApplicationSpecification ) -> None: client = ApplicationClient(algod_client, app_spec) new_client = client.prepare() assert new_client.signer is None assert new_client.sender is None def test_app_client_prepare_with_existing_signer_sender( algod_client: "AlgodClient", app_spec: ApplicationSpecification ) -> None: signer = AccountTransactionSigner(base64.b64encode(b"a" * 64).decode("utf-8")) client = ApplicationClient(algod_client, app_spec, signer=signer, sender="a sender") new_client = client.prepare() assert isinstance(new_client.signer, AccountTransactionSigner) assert signer.private_key == new_client.signer.private_key assert client.sender == new_client.sender def test_app_client_prepare_with_new_sender(algod_client: "AlgodClient", app_spec: ApplicationSpecification) -> None: client = ApplicationClient(algod_client, app_spec) new_client = client.prepare(sender="new_sender") assert new_client.sender == "new_sender" def test_app_client_prepare_with_new_signer(algod_client: "AlgodClient", app_spec: ApplicationSpecification) -> None: signer = AccountTransactionSigner(base64.b64encode(b"a" * 64).decode("utf-8")) client = ApplicationClient(algod_client, app_spec) new_client = client.prepare(signer=signer) assert isinstance(new_client.signer, AccountTransactionSigner) assert new_client.signer.private_key == signer.private_key
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_prepare.py
Python
MIT
1,804
from typing import TYPE_CHECKING from algokit_utils import ( Account, ApplicationClient, DefaultArgumentDict, ) from legacy_v2_tests.conftest import read_spec if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient def test_resolve(algod_client: "AlgodClient", creator: Account) -> None: app_spec = read_spec("app_resolve.json") client_fixture = ApplicationClient(algod_client, app_spec, signer=creator) client_fixture.create() client_fixture.opt_in() int_default_argument: DefaultArgumentDict = {"source": "constant", "data": 1} assert client_fixture.resolve(int_default_argument) == 1 string_default_argument: DefaultArgumentDict = {"source": "constant", "data": "stringy"} assert client_fixture.resolve(string_default_argument) == "stringy" global_state_int_default_argument: DefaultArgumentDict = { "source": "global-state", "data": "global_state_val_int", } assert client_fixture.resolve(global_state_int_default_argument) == 1 global_state_byte_default_argument: DefaultArgumentDict = { "source": "global-state", "data": "global_state_val_byte", } assert client_fixture.resolve(global_state_byte_default_argument) == b"test" local_state_int_default_argument: DefaultArgumentDict = { "source": "local-state", "data": "acct_state_val_int", } acct_state_val_int_value = 2 # defined in TEAL assert client_fixture.resolve(local_state_int_default_argument) == acct_state_val_int_value local_state_byte_default_argument: DefaultArgumentDict = { "source": "local-state", "data": "acct_state_val_byte", } assert client_fixture.resolve(local_state_byte_default_argument) == b"local-test" method_default_argument: DefaultArgumentDict = { "source": "abi-method", "data": {"name": "dummy", "args": [], "returns": {"type": "string"}}, } assert client_fixture.resolve(method_default_argument) == "deadbeef"
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_resolve.py
Python
MIT
2,011
import base64 import contextlib from typing import TYPE_CHECKING, Any import pytest from algosdk.atomic_transaction_composer import AccountTransactionSigner, TransactionSigner from algokit_utils import ( ApplicationClient, ApplicationSpecification, get_sender_from_signer, ) if TYPE_CHECKING: from algosdk import transaction from algosdk.transaction import GenericSignedTransaction from algosdk.v2client.algod import AlgodClient class CustomSigner(TransactionSigner): def sign_transactions( self, txn_group: list["transaction.Transaction"], indexes: list[int] ) -> list["GenericSignedTransaction"]: raise NotImplementedError fake_key = base64.b64encode(b"a" * 64).decode("utf8") @pytest.mark.parametrize("override_sender", ["override_sender", None]) @pytest.mark.parametrize("override_signer", [CustomSigner(), AccountTransactionSigner(fake_key), None]) @pytest.mark.parametrize("default_sender", ["default_sender", None]) @pytest.mark.parametrize("default_signer", [CustomSigner(), AccountTransactionSigner(fake_key), None]) def test_resolve_signer_sender( *, algod_client: "AlgodClient", app_spec: ApplicationSpecification, default_signer: TransactionSigner | None, default_sender: str | None, override_signer: TransactionSigner | None, override_sender: str | None, ) -> None: """Regression test against unexpected changes to signer/sender resolution in ApplicationClient""" app_client = ApplicationClient(algod_client, app_spec, signer=default_signer, sender=default_sender) expected_signer = override_signer or default_signer expected_sender = ( override_sender or get_sender_from_signer(override_signer) or default_sender or get_sender_from_signer(default_signer) ) ctx: Any if expected_signer is None: ctx = pytest.raises(ValueError, match="No signer provided") elif expected_sender is None: ctx = pytest.raises(ValueError, match="No sender provided") else: ctx = contextlib.nullcontext() with ctx: signer, sender = app_client.resolve_signer_sender(override_signer, override_sender) assert signer == expected_signer assert sender == expected_sender
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_signer_sender.py
Python
MIT
2,264
from typing import TYPE_CHECKING import pytest import algokit_utils from legacy_v2_tests.conftest import get_unique_name, read_spec if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient def test_create_with_all_template_values_on_initialize( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, template_values={"VERSION": 1, "UPDATABLE": 1, "DELETABLE": 1}, app_name=get_unique_name(), ) client.create("create") assert client.call("version").return_value == 1 def test_create_with_some_template_values_on_initialize( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, template_values={ "VERSION": 1, }, app_name=get_unique_name(), ) with pytest.raises( expected_exception=algokit_utils.DeploymentFailedError, match=r"allow_update must be specified if deploy time configuration of update is being used", ): client.create("create") def test_deploy_with_some_template_values_on_initialize( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, template_values={ "VERSION": 1, }, app_name=get_unique_name(), ) client.deploy(allow_delete=True, allow_update=True, create_args=algokit_utils.ABICreateCallArgs(method="create")) assert client.call("version").return_value == 1 def test_deploy_with_overriden_template_values( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, template_values={ "VERSION": 1, }, app_name=get_unique_name(), ) new_version = 2 client.deploy( allow_delete=True, allow_update=True, template_values={"VERSION": new_version}, create_args=algokit_utils.ABICreateCallArgs(method="create"), ) assert client.call("version").return_value == new_version def test_deploy_with_no_initialize_template_values( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, app_name=get_unique_name(), ) new_version = 3 client.deploy( allow_delete=True, allow_update=True, template_values={"VERSION": new_version}, create_args=algokit_utils.ABICreateCallArgs(method="create"), ) assert client.call("version").return_value == new_version def test_deploy_with_missing_template_values( algod_client: "AlgodClient", indexer_client: "IndexerClient", funded_account: algokit_utils.Account, ) -> None: app_spec = read_spec("app_client_test.json") client = algokit_utils.ApplicationClient( algod_client, app_spec, creator=funded_account, indexer_client=indexer_client, app_name=get_unique_name(), ) with pytest.raises( expected_exception=algokit_utils.DeploymentFailedError, match=r"The following template values were not provided: TMPL_VERSION", ): client.deploy( allow_delete=True, allow_update=True, create_args=algokit_utils.ABICreateCallArgs(method="create") )
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_template_values.py
Python
MIT
4,446
from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, LogicError, ) from legacy_v2_tests.conftest import check_output_stability if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient @pytest.fixture(scope="module") def client_fixture( algod_client: "AlgodClient", indexer_client: "IndexerClient", app_spec: ApplicationSpecification, funded_account: Account, ) -> ApplicationClient: client = ApplicationClient(algod_client, app_spec, creator=funded_account, indexer_client=indexer_client) client.create("create") return client def test_abi_update(client_fixture: ApplicationClient) -> None: update_response = client_fixture.update("update") assert update_response.tx_id assert client_fixture.call("hello", name="test").return_value == "Updated ABI, test" def test_bare_update(client_fixture: ApplicationClient) -> None: update_response = client_fixture.update(call_abi_method=False) assert update_response.tx_id assert client_fixture.call("hello", name="test").return_value == "Updated Bare, test" def test_abi_update_args(client_fixture: ApplicationClient) -> None: update_response = client_fixture.update("update_args", check="Yes") assert update_response.tx_id assert client_fixture.call("hello", name="test").return_value == "Updated Args, test" def test_abi_update_args_fails(client_fixture: ApplicationClient) -> None: with pytest.raises(LogicError) as ex: client_fixture.update("update_args", check="No") check_output_stability(str(ex.value).replace(ex.value.transaction_id, "{txn}"))
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_app_client_update.py
Python
MIT
1,748
import re from typing import TYPE_CHECKING import pytest from algokit_utils import ( Account, EnsureBalanceParameters, TransferAssetParameters, create_kmd_wallet_account, ensure_funded, transfer_asset, ) from algokit_utils.asset import opt_in, opt_out if TYPE_CHECKING: from algosdk.kmd import KMDClient from algosdk.v2client.algod import AlgodClient from legacy_v2_tests.conftest import assure_funds, generate_test_asset, get_unique_name @pytest.fixture def to_account(kmd_client: "KMDClient") -> Account: return create_kmd_wallet_account(kmd_client, get_unique_name()) def test_opt_in_assets_succeed(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 1) account_info = algod_client.account_info(to_account.address) assert isinstance(account_info, dict) assert account_info["total-assets-opted-in"] == 0 assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == 1 def test_opt_in_assets_to_account_second_attempt_failed( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 1) account_info = algod_client.account_info(to_account.address) assert isinstance(account_info, dict) assert account_info["total-assets-opted-in"] == 0 assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == 1 with pytest.raises( ValueError, match=re.escape( f"Assets {[dummy_asset_id]} cannot be opted in. Ensure that they are valid and " "that the account has not previously opted into them." ), ): opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) def test_opt_in_two_batches_of_assets_succeed( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: account_info = algod_client.account_info(to_account.address) assert isinstance(account_info, dict) assert account_info["total-assets-opted-in"] == 0 dummy_asset_ids = [] for _ in range(20): dummy_asset_id = generate_test_asset(algod_client, funded_account, 1) dummy_asset_ids.append(dummy_asset_id) ensure_funded( algod_client, EnsureBalanceParameters( account_to_fund=to_account, min_spending_balance_micro_algos=3000000, min_funding_increment_micro_algos=1, ), ) opt_in(algod_client=algod_client, account=to_account, asset_ids=dummy_asset_ids) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == len(dummy_asset_ids) def test_opt_out_asset_succeed(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) account_info = algod_client.account_info(to_account.address) assert isinstance(account_info, dict) assert account_info["total-assets-opted-in"] == 0 assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == 1 opt_out(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) def test_opt_out_two_batches_of_assets_succeed( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_ids = [] for _ in range(20): dummy_asset_id = generate_test_asset(algod_client, funded_account, 1) dummy_asset_ids.append(dummy_asset_id) ensure_funded( algod_client, EnsureBalanceParameters( account_to_fund=to_account, min_spending_balance_micro_algos=3000000, min_funding_increment_micro_algos=1, ), ) opt_in(algod_client=algod_client, account=to_account, asset_ids=dummy_asset_ids) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == len(dummy_asset_ids) opt_out(algod_client=algod_client, account=to_account, asset_ids=dummy_asset_ids) account_info_after_opt_out = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_out, dict) assert account_info_after_opt_out["total-assets-opted-in"] == 0 def test_opt_out_of_not_opted_in_asset_failed( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 1) account_info = algod_client.account_info(to_account.address) assert isinstance(account_info, dict) assert account_info["total-assets-opted-in"] == 0 with pytest.raises( ValueError, match=re.escape( f"Assets {[dummy_asset_id]} cannot be opted out. Ensure that their amount is zero " "and that the account has previously opted into them." ), ): opt_out(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) def test_opt_out_of_non_zero_balance_asset_failed( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) account_info_after_opt_in = algod_client.account_info(to_account.address) assert isinstance(account_info_after_opt_in, dict) assert account_info_after_opt_in["total-assets-opted-in"] == 1 transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) with pytest.raises( ValueError, match=re.escape( f"Assets {[dummy_asset_id]} cannot be opted out. Ensure that their amount is zero " "and that the account has previously opted into them." ), ): opt_out(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id])
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_asset.py
Python
MIT
7,263
import json from typing import TYPE_CHECKING from unittest.mock import Mock import pytest from algosdk.atomic_transaction_composer import ( AccountTransactionSigner, AtomicTransactionComposer, TransactionWithSigner, ) from algosdk.transaction import PaymentTxn from algokit_utils._debugging import ( PersistSourceMapInput, persist_sourcemaps, simulate_and_persist_response, ) from algokit_utils._legacy_v2.account import get_account from algokit_utils._legacy_v2.application_client import ApplicationClient from algokit_utils._legacy_v2.application_specification import ApplicationSpecification from algokit_utils._legacy_v2.models import Account from algokit_utils.common import Program from legacy_v2_tests.conftest import get_unique_name if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient @pytest.fixture def client_fixture(algod_client: "AlgodClient", app_spec: ApplicationSpecification) -> ApplicationClient: creator_name = get_unique_name() creator = get_account(algod_client, creator_name) client = ApplicationClient(algod_client, app_spec, signer=creator) create_response = client.create("create") assert create_response.tx_id return client def test_legacy_build_teal_sourcemaps(algod_client: "AlgodClient", tmp_path_factory: pytest.TempPathFactory) -> None: cwd = tmp_path_factory.mktemp("cwd") approval = """ #pragma version 9 int 1 """ clear = """ #pragma version 9 int 1 """ sources = [ PersistSourceMapInput(raw_teal=approval, app_name="cool_app", file_name="approval.teal"), PersistSourceMapInput(raw_teal=clear, app_name="cool_app", file_name="clear"), ] persist_sourcemaps(sources=sources, project_root=cwd, client=algod_client) root_path = cwd / ".algokit" / "sources" sourcemap_file_path = root_path / "sources.avm.json" app_output_path = root_path / "cool_app" assert not (sourcemap_file_path).exists() assert (app_output_path / "approval.teal").exists() assert (app_output_path / "approval.teal.map").exists() assert (app_output_path / "clear.teal").exists() assert (app_output_path / "clear.teal.map").exists() def test_legacy_build_teal_sourcemaps_without_sources( algod_client: "AlgodClient", tmp_path_factory: pytest.TempPathFactory ) -> None: cwd = tmp_path_factory.mktemp("cwd") approval = """ #pragma version 9 int 1 """ clear = """ #pragma version 9 int 1 """ compiled_approval = Program(approval, algod_client) compiled_clear = Program(clear, algod_client) sources = [ PersistSourceMapInput(compiled_teal=compiled_approval, app_name="cool_app", file_name="approval.teal"), PersistSourceMapInput(compiled_teal=compiled_clear, app_name="cool_app", file_name="clear"), ] persist_sourcemaps(sources=sources, project_root=cwd, client=algod_client, with_sources=False) root_path = cwd / ".algokit" / "sources" sourcemap_file_path = root_path / "sources.avm.json" app_output_path = root_path / "cool_app" assert not (sourcemap_file_path).exists() assert not (app_output_path / "approval.teal").exists() assert (app_output_path / "approval.teal.map").exists() assert json.loads((app_output_path / "approval.teal.map").read_text())["sources"] == [] assert not (app_output_path / "clear.teal").exists() assert (app_output_path / "clear.teal.map").exists() assert json.loads((app_output_path / "clear.teal.map").read_text())["sources"] == [] def test_legacy_simulate_and_persist_response_via_app_call( tmp_path_factory: pytest.TempPathFactory, client_fixture: ApplicationClient, mocker: Mock, ) -> None: mock_config = mocker.patch("algokit_utils._legacy_v2.application_client.config") mock_config.debug = True mock_config.trace_all = True mock_config.trace_buffer_size_mb = 256 cwd = tmp_path_factory.mktemp("cwd") mock_config.project_root = cwd client_fixture.call("hello", name="test") output_path = cwd / "debug_traces" content = list(output_path.iterdir()) assert len(list(output_path.iterdir())) == 1 trace_file_content = json.loads(content[0].read_text()) simulated_txn = trace_file_content["txn-groups"][0]["txn-results"][0]["txn-result"]["txn"]["txn"] assert simulated_txn["type"] == "appl" assert simulated_txn["apid"] == client_fixture.app_id def test_legacy_simulate_and_persist_response( tmp_path_factory: pytest.TempPathFactory, client_fixture: ApplicationClient, mocker: Mock, funded_account: Account ) -> None: mock_config = mocker.patch("algokit_utils._legacy_v2.application_client.config") mock_config.debug = True mock_config.trace_all = True cwd = tmp_path_factory.mktemp("cwd") mock_config.project_root = cwd payment = PaymentTxn( sender=funded_account.address, receiver=client_fixture.app_address, amt=1_000_000, note=b"Payment", sp=client_fixture.algod_client.suggested_params(), ) # type: ignore[no-untyped-call] txn_with_signer = TransactionWithSigner(payment, AccountTransactionSigner(funded_account.private_key)) atc = AtomicTransactionComposer() atc.add_transaction(txn_with_signer) simulate_and_persist_response(atc, cwd, client_fixture.algod_client) output_path = cwd / "debug_traces" content = list(output_path.iterdir()) assert len(list(output_path.iterdir())) == 1 trace_file_content = json.loads(content[0].read_text()) simulated_txn = trace_file_content["txn-groups"][0]["txn-results"][0]["txn-result"]["txn"]["txn"] assert simulated_txn["type"] == "pay" trace_file_path = content[0] while trace_file_path.exists(): tmp_atc = atc.clone() simulate_and_persist_response(tmp_atc, cwd, client_fixture.algod_client, buffer_size_mb=0.01)
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_debug_utils.py
Python
MIT
5,847
from algokit_utils import ( replace_template_variables, ) from algokit_utils._legacy_v2.deploy import strip_comments from legacy_v2_tests.conftest import check_output_stability def test_template_substitution() -> None: program = """ test TMPL_INT // TMPL_INT test TMPL_INT no change test TMPL_STR // TMPL_STR TMPL_STR TMPL_STR // TMPL_INT TMPL_STR // foo // TMPL_STR // bar test "TMPL_STR" // not replaced test "TMPL_STRING" // not replaced test TMPL_STRING // not replaced test TMPL_STRI // not replaced test TMPL_STR TMPL_INT TMPL_INT TMPL_STR // TMPL_STR TMPL_INT TMPL_INT TMPL_STR test TMPL_INT TMPL_STR TMPL_STRING "TMPL_INT TMPL_STR TMPL_STRING" //TMPL_INT TMPL_STR TMPL_STRING test TMPL_INT TMPL_INT TMPL_STRING TMPL_STRING TMPL_STRING TMPL_INT TMPL_STRING //keep TMPL_STR TMPL_STR TMPL_STR TMPL_STRING test NOTTMPL_STR // not replaced NOTTMPL_STR // not replaced TMPL_STR // replaced """ result = replace_template_variables(program, {"INT": 123, "STR": "ABC"}) check_output_stability(result) def test_comment_stripping() -> None: program = r""" //comment op arg //comment op "arg" //comment op "//" //comment op " //comment " //comment op "\" //" //comment op "// \" //" //comment op "" //comment // op 123 op 123 // something op "" // more comments op "//" //op "//" op "//" pushbytes base64(//8=) pushbytes b64(//8=) pushbytes base64(//8=) // pushbytes base64(//8=) pushbytes b64(//8=) // pushbytes b64(//8=) pushbytes "base64(//8=)" // pushbytes "base64(//8=)" pushbytes "b64(//8=)" // pushbytes "b64(//8=)" pushbytes base64 //8= pushbytes b64 //8= pushbytes base64 //8= // pushbytes base64 //8= pushbytes b64 //8= // pushbytes b64 //8= pushbytes "base64 //8=" // pushbytes "base64 //8=" pushbytes "b64 //8=" // pushbytes "b64 //8=" """ result = strip_comments(program) check_output_stability(result)
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_deploy.py
Python
MIT
1,870
import logging import re import time from collections.abc import Generator from enum import Enum from unittest.mock import Mock, patch import pytest from algokit_utils import ( Account, ApplicationClient, ApplicationSpecification, DeploymentFailedError, LogicError, OnSchemaBreak, OnUpdate, get_account, get_algod_client, get_indexer_client, get_localnet_default_account, ) from legacy_v2_tests.conftest import check_output_stability, get_specs, get_unique_name, read_spec logger = logging.getLogger(__name__) # This fixture is automatically applied to all application deployment tests. # If you need to run a test without debug mode, you can reference this mock within the test and disable it explicitly. @pytest.fixture(autouse=True) def mock_config(tmp_path_factory: pytest.TempPathFactory) -> Generator[Mock, None, None]: with patch("algokit_utils._legacy_v2.application_client.config", new_callable=Mock) as mock_config: mock_config.debug = True cwd = tmp_path_factory.mktemp("cwd") mock_config.project_root = cwd mock_config.trace_all = True mock_config.trace_buffer_size_mb = 256 yield mock_config class DeployFixture: def __init__( self, *, caplog: pytest.LogCaptureFixture, request: pytest.FixtureRequest, creator_name: str, creator: Account, ): self.app_ids: list[int] = [] self.caplog = caplog self.request = request self.algod_client = get_algod_client() self.indexer_client = get_indexer_client() self.creator_name = creator_name self.creator = creator self.app_name = get_unique_name() def deploy( self, app_spec: ApplicationSpecification, *, version: str | None = None, on_update: OnUpdate = OnUpdate.UpdateApp, on_schema_break: OnSchemaBreak = OnSchemaBreak.Fail, allow_delete: bool | None = None, allow_update: bool | None = None, ) -> ApplicationClient: app_client = ApplicationClient( self.algod_client, app_spec, indexer_client=self.indexer_client, creator=self.creator, app_name=self.app_name, ) response = app_client.deploy( version=version, on_update=on_update, on_schema_break=on_schema_break, allow_update=allow_update, allow_delete=allow_delete, ) self._wait_for_indexer_round(response.app.updated_round) self.app_ids.append(app_client.app_id) return app_client def check_log_stability(self, replacements: dict[str, str] | None = None, suffix: str = "") -> None: if replacements is None: replacements = {} replacements[self.app_name] = "SampleApp" records = self.caplog.get_records("call") logs = "\n".join(f"{r.levelname}: {r.message}" for r in records) logs = self._normalize_logs(logs) for find, replace in (replacements or {}).items(): logs = logs.replace(find, replace) check_output_stability(logs, test_name=self.request.node.name + suffix) def _normalize_logs(self, logs: str) -> str: dispenser = get_localnet_default_account(self.algod_client) logs = logs.replace(self.creator_name, "{creator}") logs = logs.replace(self.creator.address, "{creator_account}") logs = logs.replace(dispenser.address, "{dispenser_account}") for index, app_id in enumerate(self.app_ids): logs = logs.replace(f"app id {app_id}", f"app id {{app{index}}}") return re.sub(r"app id \d+", r"{appN_failed}", logs) def _wait_for_indexer_round(self, round_target: int, max_attempts: int = 100) -> None: for _ in range(max_attempts): health = self.indexer_client.health() # type: ignore[no-untyped-call] if health["round"] >= round_target: break # With v3 indexer a small delay is needed # not to exhaust attempts before target round is reached # NOTE: setting lower timeout may result in algod throttling # if run concurrently via pytest-xdist (which causes inconsistent snapshots) time.sleep(1) @pytest.fixture(scope="module") def creator_name() -> str: return get_unique_name() @pytest.fixture(scope="module") def creator(creator_name: str) -> Account: return get_account(get_algod_client(), creator_name) @pytest.fixture def app_name() -> str: return get_unique_name() @pytest.fixture def deploy_fixture( caplog: pytest.LogCaptureFixture, request: pytest.FixtureRequest, creator_name: str, creator: Account ) -> DeployFixture: caplog.set_level(logging.DEBUG) return DeployFixture(caplog=caplog, request=request, creator_name=creator_name, creator=creator) def test_deploy_app_with_no_existing_app_succeeds(deploy_fixture: DeployFixture) -> None: v1, _, _ = get_specs() app = deploy_fixture.deploy(v1, version="1.0", allow_update=False, allow_delete=False) assert app.app_id deploy_fixture.check_log_stability() def test_deploy_app_with_existing_updatable_app_succeeds(deploy_fixture: DeployFixture) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_update=True, allow_delete=False) assert app_v1.app_id app_v2 = deploy_fixture.deploy(v2, version="2.0", allow_update=True, allow_delete=False) assert app_v1.app_id == app_v2.app_id deploy_fixture.check_log_stability() def test_deploy_app_with_existing_immutable_app_fails(deploy_fixture: DeployFixture) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_update=False, allow_delete=False) assert app_v1.app_id with pytest.raises(LogicError) as error: deploy_fixture.deploy(v2, version="2.0", allow_update=False, allow_delete=False) logger.error(f"LogicException: {error.value.message}") deploy_fixture.check_log_stability() def test_deploy_app_with_existing_immutable_app_and_on_update_equals_replace_app_succeeds( deploy_fixture: DeployFixture, ) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_update=False, allow_delete=True) assert app_v1.app_id app_v2 = deploy_fixture.deploy( v2, version="2.0", allow_update=False, allow_delete=True, on_update=OnUpdate.ReplaceApp ) assert app_v1.app_id != app_v2.app_id deploy_fixture.check_log_stability() def test_deploy_app_with_existing_permanent_app_fails(deploy_fixture: DeployFixture) -> None: v1, _, v3 = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_update=False, allow_delete=False) assert app_v1.app_id with pytest.raises(DeploymentFailedError) as error: deploy_fixture.deploy(v3, version="3.0", allow_update=False, allow_delete=False) logger.error(f"DeploymentFailedError: {error.value}") deploy_fixture.check_log_stability() def test_deploy_app_with_existing_immutable_app_cannot_determine_if_updatable(deploy_fixture: DeployFixture) -> None: v1, v2, _ = get_specs(updatable=False, deletable=False) app_v1 = deploy_fixture.deploy(v1) assert app_v1.app_id with pytest.raises(LogicError) as error: deploy_fixture.deploy(v2, on_update=OnUpdate.UpdateApp) logger.error(f"LogicError: {error.value.message}") deploy_fixture.check_log_stability() def test_deploy_app_with_existing_permanent_app_cannot_determine_if_deletable(deploy_fixture: DeployFixture) -> None: v1, v2, _ = get_specs(updatable=False, deletable=False) app_v1 = deploy_fixture.deploy(v1) assert app_v1.app_id with pytest.raises(LogicError) as error: deploy_fixture.deploy(v2, on_update=OnUpdate.ReplaceApp) logger.error(f"LogicError: {error.value.message}") deploy_fixture.check_log_stability() def test_deploy_app_with_existing_permanent_app_on_update_equals_replace_app_fails_and_doesnt_create_2nd_app( deploy_fixture: DeployFixture, ) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_update=False, allow_delete=False) assert app_v1.app_id apps_before = deploy_fixture.indexer_client.lookup_account_application_by_creator(deploy_fixture.creator.address) # type: ignore[no-untyped-call] with pytest.raises(LogicError) as error: deploy_fixture.deploy(v2, version="3.0", allow_update=False, allow_delete=False, on_update=OnUpdate.ReplaceApp) apps_after = deploy_fixture.indexer_client.lookup_account_application_by_creator(deploy_fixture.creator.address) # type: ignore[no-untyped-call] # ensure no other apps were created assert len(apps_before["applications"]) == len(apps_after["applications"]) logger.error(f"DeploymentFailedError: {error.value.message}") deploy_fixture.check_log_stability() def test_deploy_app_with_existing_permanent_app_and_on_schema_break_equals_replace_app_fails( deploy_fixture: DeployFixture, ) -> None: v1, _, v3 = get_specs() app_v1 = deploy_fixture.deploy(v1, allow_update=False, allow_delete=False, version="1.0") assert app_v1.app_id with pytest.raises(LogicError) as exc_info: deploy_fixture.deploy( v3, allow_update=False, allow_delete=False, version="3.0", on_schema_break=OnSchemaBreak.ReplaceApp ) logger.error(f"Deployment failed: {exc_info.value.message}") deploy_fixture.check_log_stability() def test_deploy_templated_app_with_changing_parameters_succeeds(deploy_fixture: DeployFixture) -> None: app_spec = read_spec("app_v1.json") logger.info("Deploy V1 as updatable, deletable") app_client = deploy_fixture.deploy( app_spec, version="1", allow_delete=True, allow_update=True, ) response = app_client.call("hello", name="call_1") logger.info(f"Called hello: {response.return_value}") logger.info("Deploy V2 as immutable, deletable") app_client = deploy_fixture.deploy( app_spec, allow_delete=True, allow_update=False, ) response = app_client.call("hello", name="call_2") logger.info(f"Called hello: {response.return_value}") logger.info("Attempt to deploy V3 as updatable, deletable, it will fail because V2 was immutable") with pytest.raises(LogicError) as exc_info: # try to make it updatable again deploy_fixture.deploy( app_spec, allow_delete=True, allow_update=True, ) logger.error(f"LogicException: {exc_info.value.message}") response = app_client.call("hello", name="call_3") logger.info(f"Called hello: {response.return_value}") logger.info("2nd Attempt to deploy V3 as updatable, deletable, it will succeed as on_update=OnUpdate.DeleteApp") # deploy with allow_delete=True, so we can replace it app_client = deploy_fixture.deploy( app_spec, version="4", on_update=OnUpdate.ReplaceApp, allow_delete=True, allow_update=True, ) response = app_client.call("hello", name="call_4") logger.info(f"Called hello: {response.return_value}") app_id = app_client.app_id app_client = ApplicationClient( deploy_fixture.algod_client, app_spec, app_id=app_id, signer=deploy_fixture.creator, ) response = app_client.call("hello", name="call_5") logger.info(f"Called hello: {response.return_value}") deploy_fixture.check_log_stability() class Deletable(Enum): No = 0 Yes = 1 class Updatable(Enum): No = 0 Yes = 1 @pytest.mark.parametrize("deletable", [Deletable.No, Deletable.Yes]) @pytest.mark.parametrize("updatable", [Updatable.No, Updatable.Yes]) @pytest.mark.parametrize("on_schema_break", [OnSchemaBreak.Fail, OnSchemaBreak.ReplaceApp]) def test_deploy_with_schema_breaking_change( deploy_fixture: DeployFixture, *, deletable: Deletable, updatable: Updatable, on_schema_break: OnSchemaBreak, ) -> None: v1, _, v3 = get_specs() app_v1 = deploy_fixture.deploy( v1, version="1.0", allow_delete=deletable == Deletable.Yes, allow_update=updatable == Updatable.Yes ) assert app_v1.app_id try: deploy_fixture.deploy( v3, version="3.0", allow_delete=deletable == Deletable.Yes, allow_update=updatable == Updatable.Yes, on_schema_break=on_schema_break, ) except DeploymentFailedError as error: logger.error(f"DeploymentFailedError: {error}") except LogicError as error: logger.error(f"LogicException: {error.message}") deploy_fixture.check_log_stability() @pytest.mark.parametrize("deletable", [Deletable.No, Deletable.Yes]) @pytest.mark.parametrize("updatable", [Updatable.No, Updatable.Yes]) @pytest.mark.parametrize("on_update", [OnUpdate.Fail, OnUpdate.UpdateApp, OnUpdate.ReplaceApp]) def test_deploy_with_update( deploy_fixture: DeployFixture, *, deletable: Deletable, updatable: Updatable, on_update: OnUpdate, ) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy( v1, version="1.0", allow_delete=deletable == Deletable.Yes, allow_update=updatable == Updatable.Yes ) assert app_v1.app_id try: deploy_fixture.deploy( v2, version="2.0", allow_delete=deletable == Deletable.Yes, allow_update=updatable == Updatable.Yes, on_update=on_update, ) except DeploymentFailedError as error: logger.error(f"DeploymentFailedError: {error}") except LogicError as error: logger.error(f"LogicException: {error.message}") deploy_fixture.check_log_stability() def test_deploy_with_schema_breaking_change_append(deploy_fixture: DeployFixture) -> None: v1, _, v3 = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_delete=False, allow_update=False) assert app_v1.app_id try: deploy_fixture.deploy( v3, version="2.0", allow_delete=False, allow_update=False, on_schema_break=OnSchemaBreak.AppendApp, ) except DeploymentFailedError as error: logger.error(f"DeploymentFailedError: {error}") except LogicError as error: logger.error(f"LogicException: {error.message}") deploy_fixture.check_log_stability() def test_deploy_with_update_append(deploy_fixture: DeployFixture) -> None: v1, v2, _ = get_specs() app_v1 = deploy_fixture.deploy(v1, version="1.0", allow_delete=False, allow_update=False) assert app_v1.app_id try: deploy_fixture.deploy( v2, version="2.0", allow_delete=False, allow_update=False, on_update=OnUpdate.AppendApp, ) except DeploymentFailedError as error: logger.error(f"DeploymentFailedError: {error}") except LogicError as error: logger.error(f"LogicException: {error.message}") deploy_fixture.check_log_stability()
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_deploy_scenarios.py
Python
MIT
15,254
import json import pytest from pytest_httpx import HTTPXMock from algokit_utils.dispenser_api import ( DISPENSER_ASSETS, DispenserApiConfig, DispenserAssetName, TestNetDispenserApiClient, ) class TestDispenserApiTestnetClient: def test_fund_account_with_algos_with_auth_token(self, httpx_mock: HTTPXMock) -> None: mock_response = {"txID": "dummy_tx_id", "amount": 1} httpx_mock.add_response( url=f"{DispenserApiConfig.BASE_URL}/fund/{DispenserAssetName.ALGO}", method="POST", json=mock_response, ) dispenser_client = TestNetDispenserApiClient(auth_token="dummy_auth_token") address = "dummy_address" amount = 1 asset_id = DispenserAssetName.ALGO response = dispenser_client.fund(address, amount, asset_id) assert response.tx_id == "dummy_tx_id" assert response.amount == 1 def test_register_refund_with_auth_token(self, httpx_mock: HTTPXMock) -> None: httpx_mock.add_response( url=f"{DispenserApiConfig.BASE_URL}/refund", method="POST", json={}, ) dispenser_client = TestNetDispenserApiClient(auth_token="dummy_auth_token") refund_txn_id = "dummy_txn_id" dispenser_client.refund(refund_txn_id) assert len(httpx_mock.get_requests()) == 1 request = httpx_mock.get_requests()[0] assert request.method == "POST" assert request.url.path == "/refund" assert request.headers["Authorization"] == f"Bearer {dispenser_client.auth_token}" assert json.loads(request.read().decode()) == {"refundTransactionID": refund_txn_id} def test_limit_with_auth_token(self, httpx_mock: HTTPXMock) -> None: amount = 10000000 mock_response = {"amount": amount} httpx_mock.add_response( url=f"{DispenserApiConfig.BASE_URL}/fund/{DISPENSER_ASSETS[DispenserAssetName.ALGO].asset_id}/limit", method="GET", json=mock_response, ) dispenser_client = TestNetDispenserApiClient("dummy_auth_token") address = "dummy_address" response = dispenser_client.get_limit(address) assert response.amount == amount def test_dispenser_api_init(self) -> None: with pytest.raises( Exception, match="Can't init AlgoKit TestNet Dispenser API client because neither environment variable", ): TestNetDispenserApiClient() def test_dispenser_api_init_with_ci_(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("ALGOKIT_DISPENSER_ACCESS_TOKEN", "test_value") client = TestNetDispenserApiClient() assert client.auth_token == "test_value" def test_dispenser_api_init_with_ci_and_arg(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("ALGOKIT_DISPENSER_ACCESS_TOKEN", "test_value") client = TestNetDispenserApiClient("test_value_2") assert client.auth_token == "test_value_2"
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_dispenser_api_client.py
Python
MIT
3,042
import os from unittest import mock from algokit_utils import ( get_algod_client, get_algonode_config, get_default_localnet_config, get_indexer_client, ) DEFAULT_TOKEN = "a" * 64 def test_localnet_algod() -> None: algod_client = get_algod_client(get_default_localnet_config("algod")) health_response = algod_client.health() assert health_response is None def test_localnet_indexer() -> None: indexer_client = get_indexer_client(get_default_localnet_config("indexer")) health_response = indexer_client.health() # type: ignore[no-untyped-call] assert isinstance(health_response, dict) @mock.patch.dict( os.environ, { "ALGOD_SERVER": "https://testnet-api.algonode.cloud", "ALGOD_PORT": "443", "ALGOD_TOKEN": DEFAULT_TOKEN, }, ) def test_environment_config() -> None: algod_client = get_algod_client() assert algod_client.algod_address == "https://testnet-api.algonode.cloud:443" def test_cloudnode_algod_headers() -> None: algod_client = get_algod_client(get_algonode_config("testnet", "algod", DEFAULT_TOKEN)) assert algod_client.headers == {"X-Algo-API-Token": DEFAULT_TOKEN} def test_cloudnode_indexer_headers() -> None: indexer_client = get_indexer_client(get_algonode_config("testnet", "indexer", DEFAULT_TOKEN)) assert indexer_client.headers == {"X-Indexer-API-Token": DEFAULT_TOKEN}
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_network_clients.py
Python
MIT
1,403
from typing import TYPE_CHECKING import algosdk import httpx import pytest from algosdk.atomic_transaction_composer import AccountTransactionSigner from algosdk.transaction import PaymentTxn from algosdk.util import algos_to_microalgos from pytest_httpx import HTTPXMock from algokit_utils import ( Account, EnsureBalanceParameters, EnsureFundedResponse, TestNetDispenserApiClient, TransferAssetParameters, TransferParameters, create_kmd_wallet_account, ensure_funded, get_dispenser_account, opt_in, transfer, transfer_asset, ) from algokit_utils.dispenser_api import DispenserApiConfig from algokit_utils.network_clients import get_algod_client, get_algonode_config from legacy_v2_tests.conftest import assure_funds, check_output_stability, generate_test_asset, get_unique_name from legacy_v2_tests.test_network_clients import DEFAULT_TOKEN if TYPE_CHECKING: from algosdk.kmd import KMDClient from algosdk.v2client.algod import AlgodClient MINIMUM_BALANCE = 100_000 # see https://developer.algorand.org/docs/get-details/accounts/#minimum-balance @pytest.fixture def to_account(kmd_client: "KMDClient") -> Account: return create_kmd_wallet_account(kmd_client, get_unique_name()) @pytest.fixture def rekeyed_from_account(algod_client: "AlgodClient", kmd_client: "KMDClient") -> Account: account = create_kmd_wallet_account(kmd_client, get_unique_name()) rekey_account = create_kmd_wallet_account(kmd_client, get_unique_name()) ensure_funded( algod_client, EnsureBalanceParameters( account_to_fund=account, min_spending_balance_micro_algos=300000, min_funding_increment_micro_algos=1, ), ) rekey_txn = PaymentTxn( sender=account.address, receiver=account.address, amt=0, note="rekey account", rekey_to=rekey_account.address, sp=algod_client.suggested_params(), ) # type: ignore[no-untyped-call] signed_rekey_txn = rekey_txn.sign(account.private_key) # type: ignore[no-untyped-call] algod_client.send_transaction(signed_rekey_txn) return Account(address=account.address, private_key=rekey_account.private_key) @pytest.fixture def transaction_signer_from_account( kmd_client: "KMDClient", algod_client: "AlgodClient", ) -> AccountTransactionSigner: account = create_kmd_wallet_account(kmd_client, get_unique_name()) ensure_funded( algod_client, EnsureBalanceParameters( account_to_fund=account, min_spending_balance_micro_algos=300000, min_funding_increment_micro_algos=1, ), ) return AccountTransactionSigner(private_key=account.private_key) @pytest.fixture def clawback_account(kmd_client: "KMDClient") -> Account: return create_kmd_wallet_account(kmd_client, get_unique_name()) def test_transfer_algo(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: requested_amount = 100_000 transfer( algod_client, TransferParameters( from_account=funded_account, to_address=to_account.address, micro_algos=requested_amount, ), ) to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == requested_amount def test_transfer_algo_rekey_account( algod_client: "AlgodClient", to_account: Account, rekeyed_from_account: Account ) -> None: requested_amount = 100_000 transfer( algod_client, TransferParameters( from_account=rekeyed_from_account, to_address=to_account.address, micro_algos=requested_amount, ), ) to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == requested_amount def test_transfer_algo_transaction_signer_account( algod_client: "AlgodClient", to_account: Account, transaction_signer_from_account: AccountTransactionSigner ) -> None: requested_amount = 100_000 transfer( algod_client, TransferParameters( from_account=transaction_signer_from_account, to_address=to_account.address, micro_algos=requested_amount, ), ) to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == requested_amount def test_transfer_algo_max_fee_fails(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: requested_amount = 100_000 max_fee = 123 with pytest.raises(Exception, match="Cancelled transaction due to high network congestion fees") as ex: transfer( algod_client, TransferParameters( from_account=funded_account, to_address=to_account.address, micro_algos=requested_amount, max_fee_micro_algos=max_fee, ), ) check_output_stability(str(ex.value)) def test_transfer_algo_fee(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: requested_amount = 100_000 fee = 1234 txn = transfer( algod_client, TransferParameters( from_account=funded_account, to_address=to_account.address, micro_algos=requested_amount, fee_micro_algos=fee, ), ) assert txn.fee == fee def test_transfer_asa_receiver_not_optin( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) with pytest.raises(algosdk.error.AlgodHTTPError, match="receiver error: must optin"): transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) def test_transfer_asa_asset_doesnt_exist( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) with pytest.raises(algosdk.error.AlgodHTTPError, match="asset 1 missing from"): transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, asset_id=1, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) def test_transfer_asa_asset_is_transfered( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) to_account_info = algod_client.account_asset_info(to_account.address, dummy_asset_id) assert isinstance(to_account_info, dict) assert to_account_info["asset-holding"]["amount"] == 5 # noqa: PLR2004 funded_account_info = algod_client.account_asset_info(funded_account.address, dummy_asset_id) assert isinstance(funded_account_info, dict) assert funded_account_info["asset-holding"]["amount"] == 95 # noqa: PLR2004 def test_transfer_asa_asset_is_transfered_from_revocation_target( algod_client: "AlgodClient", to_account: Account, clawback_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) assure_funds(algod_client=algod_client, account=to_account) opt_in(algod_client=algod_client, account=to_account, asset_ids=[dummy_asset_id]) assure_funds(algod_client=algod_client, account=clawback_account) opt_in(algod_client=algod_client, account=clawback_account, asset_ids=[dummy_asset_id]) transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=clawback_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) clawback_account_info = algod_client.account_asset_info(clawback_account.address, dummy_asset_id) assert isinstance(clawback_account_info, dict) assert clawback_account_info["asset-holding"]["amount"] == 5 # noqa: PLR2004 transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, clawback_from=clawback_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", ), ) to_account_info = algod_client.account_asset_info(to_account.address, dummy_asset_id) assert isinstance(to_account_info, dict) assert to_account_info["asset-holding"]["amount"] == 5 # noqa: PLR2004 clawback_account_info = algod_client.account_asset_info(clawback_account.address, dummy_asset_id) assert isinstance(clawback_account_info, dict) assert clawback_account_info["asset-holding"]["amount"] == 0 funded_account_info = algod_client.account_asset_info(funded_account.address, dummy_asset_id) assert isinstance(funded_account_info, dict) assert funded_account_info["asset-holding"]["amount"] == 95 # noqa: PLR2004 def test_transfer_asset_max_fee_fails( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: dummy_asset_id = generate_test_asset(algod_client, funded_account, 100) with pytest.raises(Exception, match="Cancelled transaction due to high network congestion fees") as ex: transfer_asset( algod_client, TransferAssetParameters( from_account=funded_account, to_address=to_account.address, asset_id=dummy_asset_id, amount=5, note=f"Transfer 5 assets wit id ${dummy_asset_id}", max_fee_micro_algos=123, ), ) check_output_stability(str(ex.value)) def test_ensure_funded(algod_client: "AlgodClient", to_account: Account, funded_account: Account) -> None: parameters = EnsureBalanceParameters( funding_source=funded_account, account_to_fund=to_account, min_spending_balance_micro_algos=1, ) response = ensure_funded(algod_client, parameters) assert response is not None to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == MINIMUM_BALANCE + 1 def test_ensure_funded_uses_dispenser_by_default(algod_client: "AlgodClient", to_account: Account) -> None: dispenser = get_dispenser_account(algod_client) parameters = EnsureBalanceParameters( account_to_fund=to_account, min_spending_balance_micro_algos=1, ) response = ensure_funded(algod_client, parameters) assert response is not None assert isinstance(response, EnsureFundedResponse) txn_info = algod_client.pending_transaction_info(response.transaction_id) assert isinstance(txn_info, dict) assert txn_info["txn"]["txn"]["snd"] == dispenser.address to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == MINIMUM_BALANCE + 1 def test_ensure_funded_correct_amount( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: parameters = EnsureBalanceParameters( funding_source=funded_account, account_to_fund=to_account, min_spending_balance_micro_algos=1, ) response = ensure_funded(algod_client, parameters) assert response is not None to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == MINIMUM_BALANCE + 1 def test_ensure_funded_respects_minimum_funding( algod_client: "AlgodClient", to_account: Account, funded_account: Account ) -> None: parameters = EnsureBalanceParameters( funding_source=funded_account, account_to_fund=to_account, min_spending_balance_micro_algos=1, min_funding_increment_micro_algos=algos_to_microalgos(1), # type: ignore[no-untyped-call] ) response = ensure_funded(algod_client, parameters) assert response is not None to_account_info = algod_client.account_info(to_account.address) assert isinstance(to_account_info, dict) actual_amount = to_account_info.get("amount") assert actual_amount == algos_to_microalgos(1) # type: ignore[no-untyped-call] def test_ensure_funded_testnet_api_success( to_account: Account, monkeypatch: pytest.MonkeyPatch, httpx_mock: HTTPXMock ) -> None: monkeypatch.setenv( "ALGOKIT_DISPENSER_ACCESS_TOKEN", "dummy", ) httpx_mock.add_response( url=f"{DispenserApiConfig.BASE_URL}/fund/0", method="POST", json={"amount": 1, "txID": "dummy_tx_id"}, ) algod_client = get_algod_client(get_algonode_config("testnet", "algod", DEFAULT_TOKEN)) dispenser_client = TestNetDispenserApiClient() parameters = EnsureBalanceParameters( funding_source=dispenser_client, account_to_fund=to_account, min_spending_balance_micro_algos=1, ) response = ensure_funded(algod_client, parameters) assert response is not None assert response.transaction_id == "dummy_tx_id" assert response.amount == 1 def test_ensure_funded_testnet_api_bad_response( to_account: Account, monkeypatch: pytest.MonkeyPatch, httpx_mock: HTTPXMock ) -> None: monkeypatch.setenv( "ALGOKIT_DISPENSER_ACCESS_TOKEN", "dummy", ) httpx_mock.add_exception( httpx.HTTPStatusError( "Limit exceeded", request=httpx.Request("POST", f"{DispenserApiConfig.BASE_URL}/fund"), response=httpx.Response( 400, request=httpx.Request("POST", f"{DispenserApiConfig.BASE_URL}/fund"), json={ "code": "fund_limit_exceeded", "limit": 10_000_000, "resetsAt": "2023-09-19T10:07:34.024Z", }, ), ), url=f"{DispenserApiConfig.BASE_URL}/fund/0", method="POST", ) algod_client = get_algod_client(get_algonode_config("testnet", "algod", DEFAULT_TOKEN)) dispenser_client = TestNetDispenserApiClient() parameters = EnsureBalanceParameters( funding_source=dispenser_client, account_to_fund=to_account, min_spending_balance_micro_algos=1, ) with pytest.raises(Exception, match="fund_limit_exceeded"): ensure_funded(algod_client, parameters)
algorandfoundation/algokit-utils-py
legacy_v2_tests/test_transfer.py
Python
MIT
15,970
"""AlgoKit Python Utilities - a set of utilities for building solutions on Algorand This module provides commonly used utilities and types at the root level for convenience. For more specific functionality, import directly from the relevant submodules: from algokit_utils.accounts import KmdAccountManager from algokit_utils.applications import AppClient from algokit_utils.applications.app_spec import Arc52Contract etc. """ # Core types and utilities that are commonly used from algokit_utils.applications import * # noqa: F403 from algokit_utils.assets import * # noqa: F403 from algokit_utils.protocols import * # noqa: F403 from algokit_utils.models import * # noqa: F403 from algokit_utils.accounts import * # noqa: F403 from algokit_utils.clients import * # noqa: F403 from algokit_utils.transactions import * # noqa: F403 from algokit_utils.errors import * # noqa: F403 from algokit_utils.algorand import * # noqa: F403 # Legacy types and utilities from algokit_utils._legacy_v2 import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/__init__.py
Python
MIT
1,039
import base64 import json import logging import typing from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from algosdk.atomic_transaction_composer import ( AtomicTransactionComposer, EmptySigner, SimulateAtomicTransactionResponse, ) from algosdk.encoding import checksum from algosdk.v2client.models import SimulateRequest, SimulateRequestTransactionGroup, SimulateTraceConfig from algokit_utils._legacy_v2.common import Program from algokit_utils.models.application import CompiledTeal if typing.TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient logger = logging.getLogger(__name__) ALGOKIT_DIR = ".algokit" SOURCES_DIR = "sources" SOURCES_FILE = "sources.avm.json" TRACES_FILE_EXT = ".trace.avm.json" DEBUG_TRACES_DIR = "debug_traces" TEAL_FILE_EXT = ".teal" TEAL_SOURCEMAP_EXT = ".teal.map" @dataclass class AVMDebuggerSourceMapEntry: location: str = field(metadata={"json": "sourcemap-location"}) program_hash: str = field(metadata={"json": "hash"}) def __eq__(self, other: object) -> bool: if isinstance(other, AVMDebuggerSourceMapEntry): return self.location == other.location and self.program_hash == other.program_hash return False def __str__(self) -> str: return json.dumps({"sourcemap-location": self.location, "hash": self.program_hash}) @dataclass class AVMDebuggerSourceMap: txn_group_sources: list[AVMDebuggerSourceMapEntry] = field(metadata={"json": "txn-group-sources"}) @classmethod def from_dict(cls, data: dict) -> "AVMDebuggerSourceMap": return cls( txn_group_sources=[ AVMDebuggerSourceMapEntry(location=item["sourcemap-location"], program_hash=item["hash"]) for item in data.get("txn-group-sources", []) ] ) def to_dict(self) -> dict: return {"txn-group-sources": [json.loads(str(item)) for item in self.txn_group_sources]} @dataclass class PersistSourceMapInput: def __init__( self, app_name: str, file_name: str, raw_teal: str | None = None, compiled_teal: CompiledTeal | Program | None = None, ): self.compiled_teal = compiled_teal self.app_name = app_name self._raw_teal = raw_teal self._file_name = self.strip_teal_extension(file_name) @classmethod def from_raw_teal(cls, raw_teal: str, app_name: str, file_name: str) -> "PersistSourceMapInput": return cls(app_name, file_name, raw_teal=raw_teal) @classmethod def from_compiled_teal( cls, compiled_teal: CompiledTeal | Program, app_name: str, file_name: str ) -> "PersistSourceMapInput": return cls(app_name, file_name, compiled_teal=compiled_teal) @property def raw_teal(self) -> str: if self._raw_teal: return self._raw_teal elif self.compiled_teal: return self.compiled_teal.teal else: raise ValueError("No teal content found") @property def file_name(self) -> str: return self._file_name @staticmethod def strip_teal_extension(file_name: str) -> str: if file_name.endswith(".teal"): return file_name[:-5] return file_name def _load_or_create_sources(sources_path: Path) -> AVMDebuggerSourceMap: if not sources_path.exists(): return AVMDebuggerSourceMap(txn_group_sources=[]) with sources_path.open() as f: return AVMDebuggerSourceMap.from_dict(json.load(f)) def _write_to_file(path: Path, content: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content) def _build_avm_sourcemap( *, app_name: str, file_name: str, output_path: Path, client: "AlgodClient", raw_teal: str | None = None, compiled_teal: CompiledTeal | Program | None = None, with_sources: bool = True, ) -> AVMDebuggerSourceMapEntry: if not raw_teal and not compiled_teal: raise ValueError("Either raw teal or compiled teal must be provided") # Handle both legacy Program and new CompiledTeal if isinstance(compiled_teal, Program): program_hash = base64.b64encode(checksum(compiled_teal.raw_binary)).decode() source_map = compiled_teal.source_map.__dict__ teal_content = compiled_teal.teal elif isinstance(compiled_teal, CompiledTeal): program_hash = base64.b64encode(checksum(compiled_teal.compiled_base64_to_bytes)).decode() source_map = compiled_teal.source_map.__dict__ if compiled_teal.source_map else {} teal_content = compiled_teal.teal else: # Handle raw TEAL case result = Program(str(raw_teal), client=client) program_hash = base64.b64encode(checksum(result.raw_binary)).decode() source_map = result.source_map.__dict__ teal_content = result.teal source_map["sources"] = [f"{file_name}{TEAL_FILE_EXT}"] if with_sources else [] output_dir_path = output_path / ALGOKIT_DIR / SOURCES_DIR / app_name source_map_output_path = output_dir_path / f"{file_name}{TEAL_SOURCEMAP_EXT}" teal_output_path = output_dir_path / f"{file_name}{TEAL_FILE_EXT}" _write_to_file(source_map_output_path, json.dumps(source_map)) if with_sources: _write_to_file(teal_output_path, teal_content) return AVMDebuggerSourceMapEntry(str(source_map_output_path), program_hash) def cleanup_old_trace_files(output_dir: Path, buffer_size_mb: float) -> None: """ Cleanup old trace files if total size exceeds buffer size limit. Args: output_dir (Path): Directory containing trace files buffer_size_mb (float): Maximum allowed size in megabytes """ total_size = sum(f.stat().st_size for f in output_dir.glob("*") if f.is_file()) if total_size > buffer_size_mb * 1024 * 1024: sorted_files = sorted(output_dir.glob("*"), key=lambda p: p.stat().st_mtime) while total_size > buffer_size_mb * 1024 * 1024 and sorted_files: oldest_file = sorted_files.pop(0) total_size -= oldest_file.stat().st_size oldest_file.unlink() def persist_sourcemaps( *, sources: list[PersistSourceMapInput], project_root: Path, client: "AlgodClient", with_sources: bool = True, ) -> None: """ Persist the sourcemaps for the given sources as an AlgoKit AVM Debugger compliant artifacts. :param sources: A list of PersistSourceMapInput objects. :param project_root: The root directory of the project. :param client: An AlgodClient object for interacting with the Algorand blockchain. :param with_sources: If True, it will dump teal source files along with sourcemaps. """ for source in sources: _build_avm_sourcemap( raw_teal=source.raw_teal, compiled_teal=source.compiled_teal, app_name=source.app_name, file_name=source.file_name, output_path=project_root, client=client, with_sources=with_sources, ) def simulate_response( atc: AtomicTransactionComposer, algod_client: "AlgodClient", allow_more_logs: bool | None = None, allow_empty_signatures: bool | None = None, allow_unnamed_resources: bool | None = None, extra_opcode_budget: int | None = None, exec_trace_config: SimulateTraceConfig | None = None, simulation_round: int | None = None, ) -> SimulateAtomicTransactionResponse: """Simulate atomic transaction group execution""" unsigned_txn_groups = atc.build_group() empty_signer = EmptySigner() txn_list = [txn_group.txn for txn_group in unsigned_txn_groups] fake_signed_transactions = empty_signer.sign_transactions(txn_list, []) txn_group = [SimulateRequestTransactionGroup(txns=fake_signed_transactions)] trace_config = SimulateTraceConfig(enable=True, stack_change=True, scratch_change=True, state_change=True) simulate_request = SimulateRequest( txn_groups=txn_group, allow_more_logs=allow_more_logs if allow_more_logs is not None else True, round=simulation_round, extra_opcode_budget=extra_opcode_budget if extra_opcode_budget is not None else 0, allow_unnamed_resources=allow_unnamed_resources if allow_unnamed_resources is not None else True, allow_empty_signatures=allow_empty_signatures if allow_empty_signatures is not None else True, exec_trace_config=exec_trace_config if exec_trace_config is not None else trace_config, ) return atc.simulate(algod_client, simulate_request) def simulate_and_persist_response( atc: AtomicTransactionComposer, project_root: Path, algod_client: "AlgodClient", buffer_size_mb: float = 256, allow_more_logs: bool | None = None, allow_empty_signatures: bool | None = None, allow_unnamed_resources: bool | None = None, extra_opcode_budget: int | None = None, exec_trace_config: SimulateTraceConfig | None = None, simulation_round: int | None = None, ) -> SimulateAtomicTransactionResponse: """Simulates atomic transactions and persists simulation response to a JSON file. Simulates the atomic transactions using the provided AtomicTransactionComposer and AlgodClient, then persists the simulation response to an AlgoKit AVM Debugger compliant JSON file. :param atc: AtomicTransactionComposer containing transactions to simulate and persist :param project_root: Root directory path of the project :param algod_client: Algorand client instance :param buffer_size_mb: Size of trace buffer in megabytes, defaults to 256 :param allow_more_logs: Flag to allow additional logs, defaults to None :param allow_empty_signatures: Flag to allow empty signatures, defaults to None :param allow_unnamed_resources: Flag to allow unnamed resources, defaults to None :param extra_opcode_budget: Additional opcode budget, defaults to None :param exec_trace_config: Execution trace configuration, defaults to None :param simulation_round: Round number for simulation, defa ults to None :return: Simulated response after persisting for AlgoKit AVM Debugger consumption """ atc_to_simulate = atc.clone() sp = algod_client.suggested_params() for txn_with_sign in atc_to_simulate.txn_list: txn_with_sign.txn.first_valid_round = sp.first txn_with_sign.txn.last_valid_round = sp.last txn_with_sign.txn.genesis_hash = sp.gh response = simulate_response( atc_to_simulate, algod_client, allow_more_logs, allow_empty_signatures, allow_unnamed_resources, extra_opcode_budget, exec_trace_config, simulation_round, ) txn_results = response.simulate_response["txn-groups"] txn_types = [ txn["txn-result"]["txn"]["txn"]["type"] for txn_result in txn_results for txn in txn_result["txn-results"] ] txn_types_count = {} for txn_type in txn_types: if txn_type not in txn_types_count: txn_types_count[txn_type] = txn_types.count(txn_type) txn_types_str = "_".join([f"{count}{txn_type}" for txn_type, count in txn_types_count.items()]) last_round = response.simulate_response["last-round"] timestamp = datetime.now(tz=timezone.utc).strftime("%Y%m%d_%H%M%S") output_file = project_root / DEBUG_TRACES_DIR / f"{timestamp}_lr{last_round}_{txn_types_str}{TRACES_FILE_EXT}" output_file.parent.mkdir(parents=True, exist_ok=True) cleanup_old_trace_files(output_file.parent, buffer_size_mb) output_file.write_text(json.dumps(response.simulate_response, indent=2)) return response
algorandfoundation/algokit-utils-py
src/algokit_utils/_debugging.py
Python
MIT
11,703
"""AlgoKit Python Utilities (Legacy V2) - a set of utilities for building solutions on Algorand This module provides commonly used utilities and types at the root level for convenience. For more specific functionality, import directly from the relevant submodules: from algokit_utils.accounts import KmdAccountManager from algokit_utils.applications import AppClient from algokit_utils.applications.app_spec import Arc52Contract etc. """ # Debugging utilities from algokit_utils._legacy_v2._ensure_funded import ( EnsureBalanceParameters, EnsureFundedResponse, ensure_funded, ) from algokit_utils._legacy_v2._transfer import ( TransferAssetParameters, TransferParameters, transfer, transfer_asset, ) from algokit_utils._legacy_v2.account import ( create_kmd_wallet_account, get_account, get_account_from_mnemonic, get_dispenser_account, get_kmd_wallet_account, get_localnet_default_account, get_or_create_kmd_wallet_account, ) from algokit_utils._legacy_v2.application_client import ( ApplicationClient, execute_atc_with_logic_error, get_next_version, get_sender_from_signer, num_extra_program_pages, ) from algokit_utils._legacy_v2.application_specification import ( ApplicationSpecification, AppSpecStateDict, CallConfig, DefaultArgumentDict, DefaultArgumentType, MethodConfigDict, MethodHints, OnCompleteActionName, ) from algokit_utils._legacy_v2.asset import opt_in, opt_out from algokit_utils._legacy_v2.common import Program from algokit_utils._legacy_v2.deploy import ( NOTE_PREFIX, ABICallArgs, ABICallArgsDict, ABICreateCallArgs, ABICreateCallArgsDict, AppDeployMetaData, AppLookup, AppMetaData, AppReference, DeployCallArgs, DeployCallArgsDict, DeployCreateCallArgs, DeployCreateCallArgsDict, DeploymentFailedError, DeployResponse, TemplateValueDict, TemplateValueMapping, get_app_id_from_tx_id, get_creator_apps, replace_template_variables, ) from algokit_utils._legacy_v2.models import ( ABIArgsDict, ABIMethod, ABITransactionResponse, Account, CommonCallParameters, CommonCallParametersDict, CreateCallParameters, CreateCallParametersDict, CreateTransactionParameters, OnCompleteCallParameters, OnCompleteCallParametersDict, TransactionParameters, TransactionParametersDict, TransactionResponse, ) from algokit_utils._legacy_v2.network_clients import ( AlgoClientConfig, get_algod_client, get_algonode_config, get_default_localnet_config, get_indexer_client, get_kmd_client_from_algod_client, is_localnet, is_mainnet, is_testnet, ) __all__ = [ "NOTE_PREFIX", "ABIArgsDict", "ABICallArgs", "ABICallArgsDict", "ABICreateCallArgs", "ABICreateCallArgsDict", "ABIMethod", "ABITransactionResponse", "Account", "AlgoClientConfig", "AppDeployMetaData", "AppLookup", "AppMetaData", "AppReference", "AppSpecStateDict", "ApplicationClient", "ApplicationSpecification", "CallConfig", "CommonCallParameters", "CommonCallParametersDict", "CreateCallParameters", "CreateCallParametersDict", "CreateTransactionParameters", "DefaultArgumentDict", "DefaultArgumentType", "DeployCallArgs", "DeployCallArgsDict", "DeployCreateCallArgs", "DeployCreateCallArgsDict", "DeployResponse", "DeploymentFailedError", "EnsureBalanceParameters", "EnsureFundedResponse", "MethodConfigDict", "MethodHints", "OnCompleteActionName", "OnCompleteCallParameters", "OnCompleteCallParametersDict", "Program", "TemplateValueDict", "TemplateValueMapping", "TransactionParameters", "TransactionParametersDict", "TransactionResponse", "TransferAssetParameters", "TransferParameters", # Legacy v2 functions "create_kmd_wallet_account", "ensure_funded", "execute_atc_with_logic_error", "get_account", "get_account_from_mnemonic", "get_algod_client", "get_algonode_config", "get_app_id_from_tx_id", "get_creator_apps", "get_default_localnet_config", "get_dispenser_account", "get_indexer_client", "get_kmd_client_from_algod_client", "get_kmd_wallet_account", "get_localnet_default_account", "get_next_version", "get_or_create_kmd_wallet_account", "get_sender_from_signer", "is_localnet", "is_mainnet", "is_testnet", "num_extra_program_pages", "opt_in", "opt_out", "replace_template_variables", "transfer", "transfer_asset", ]
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/__init__.py
Python
MIT
4,689
from dataclasses import dataclass from algosdk.account import address_from_private_key from algosdk.atomic_transaction_composer import AccountTransactionSigner from algosdk.transaction import SuggestedParams from algosdk.v2client.algod import AlgodClient from typing_extensions import deprecated from algokit_utils._legacy_v2._transfer import TransferParameters, transfer from algokit_utils._legacy_v2.account import get_dispenser_account from algokit_utils._legacy_v2.models import Account from algokit_utils._legacy_v2.network_clients import is_testnet from algokit_utils.clients.dispenser_api_client import ( DispenserAssetName, TestNetDispenserApiClient, ) @dataclass(kw_only=True) class EnsureBalanceParameters: """Parameters for ensuring an account has a minimum number of µALGOs""" account_to_fund: Account | AccountTransactionSigner | str """The account address that will receive the µALGOs""" min_spending_balance_micro_algos: int """The minimum balance of ALGOs that the account should have available to spend (i.e. on top of minimum balance requirement)""" min_funding_increment_micro_algos: int = 0 """When issuing a funding amount, the minimum amount to transfer (avoids many small transfers if this gets called often on an active account)""" funding_source: Account | AccountTransactionSigner | TestNetDispenserApiClient | None = None """The account (with private key) or signer that will send the µALGOs, will use `get_dispenser_account` by default. Alternatively you can pass an instance of [`TestNetDispenserApiClient`](https://github.com/algorandfoundation/algokit-utils-py/blob/main/docs/source/capabilities/dispenser-client.md) which will allow you to interact with [AlgoKit TestNet Dispenser API](https://github.com/algorandfoundation/algokit-cli/blob/main/docs/features/dispenser.md).""" suggested_params: SuggestedParams | None = None """(optional) transaction parameters""" note: str | bytes | None = None """The (optional) transaction note, default: "Funding account to meet minimum requirement""" fee_micro_algos: int | None = None """(optional) The flat fee you want to pay, useful for covering extra fees in a transaction group or app call""" max_fee_micro_algos: int | None = None """(optional)The maximum fee that you are happy to pay (default: unbounded) - if this is set it's possible the transaction could get rejected during network congestion""" @dataclass(kw_only=True) class EnsureFundedResponse: """Response for ensuring an account has a minimum number of µALGOs""" """The transaction ID of the funding transaction""" transaction_id: str """The amount of µALGOs that were funded""" amount: int def _get_address_to_fund(parameters: EnsureBalanceParameters) -> str: if isinstance(parameters.account_to_fund, str): return parameters.account_to_fund else: return str(address_from_private_key(parameters.account_to_fund.private_key)) def _get_account_info(client: AlgodClient, address_to_fund: str) -> dict: account_info = client.account_info(address_to_fund) assert isinstance(account_info, dict) return account_info def _calculate_fund_amount( parameters: EnsureBalanceParameters, current_spending_balance_micro_algos: int ) -> int | None: if parameters.min_spending_balance_micro_algos > current_spending_balance_micro_algos: min_fund_amount_micro_algos = parameters.min_spending_balance_micro_algos - current_spending_balance_micro_algos return max(min_fund_amount_micro_algos, parameters.min_funding_increment_micro_algos) else: return None def _fund_using_dispenser_api( dispenser_client: TestNetDispenserApiClient, address_to_fund: str, fund_amount_micro_algos: int ) -> EnsureFundedResponse | None: response = dispenser_client.fund( address=address_to_fund, amount=fund_amount_micro_algos, asset_id=DispenserAssetName.ALGO ) return EnsureFundedResponse(transaction_id=response.tx_id, amount=response.amount) def _fund_using_transfer( client: AlgodClient, parameters: EnsureBalanceParameters, address_to_fund: str, fund_amount_micro_algos: int ) -> EnsureFundedResponse: if isinstance(parameters.funding_source, TestNetDispenserApiClient): raise Exception(f"Invalid funding source: {parameters.funding_source}") funding_source = parameters.funding_source or get_dispenser_account(client) response = transfer( client, TransferParameters( from_account=funding_source, to_address=address_to_fund, micro_algos=fund_amount_micro_algos, note=parameters.note or "Funding account to meet minimum requirement", suggested_params=parameters.suggested_params, max_fee_micro_algos=parameters.max_fee_micro_algos, fee_micro_algos=parameters.fee_micro_algos, ), ) transaction_id = response.get_txid() return EnsureFundedResponse(transaction_id=transaction_id, amount=response.amt) @deprecated( "Use `algorand.account.ensure_funded()`, `algorand.account.ensure_funded_from_environment()`, " "or `algorand.account.ensure_funded_from_testnet_dispenser_api()` instead" ) def ensure_funded( client: AlgodClient, parameters: EnsureBalanceParameters, ) -> EnsureFundedResponse | None: """ Funds a given account using a funding source to ensure it has sufficient spendable ALGOs. Ensures the target account has enough ALGOs free to spend after accounting for ALGOs locked in minimum balance requirements. See https://developer.algorand.org/docs/get-details/accounts/#minimum-balance for details on minimum balance requirements. :param client: An instance of the AlgodClient class from the AlgoSDK library :param parameters: Parameters specifying the account to fund and minimum spending balance requirements :return: If funds are needed, returns payment transaction details or dispenser API response. Returns None if no funding needed """ address_to_fund = _get_address_to_fund(parameters) account_info = _get_account_info(client, address_to_fund) balance_micro_algos = account_info.get("amount", 0) minimum_balance_micro_algos = account_info.get("min-balance", 0) current_spending_balance_micro_algos = balance_micro_algos - minimum_balance_micro_algos fund_amount_micro_algos = _calculate_fund_amount(parameters, current_spending_balance_micro_algos) if fund_amount_micro_algos is not None: if is_testnet(client) and isinstance(parameters.funding_source, TestNetDispenserApiClient): return _fund_using_dispenser_api(parameters.funding_source, address_to_fund, fund_amount_micro_algos) else: return _fund_using_transfer(client, parameters, address_to_fund, fund_amount_micro_algos) return None
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/_ensure_funded.py
Python
MIT
6,931
import dataclasses import logging from typing import TYPE_CHECKING import algosdk.transaction from algosdk.account import address_from_private_key from algosdk.atomic_transaction_composer import AccountTransactionSigner from algosdk.transaction import AssetTransferTxn, PaymentTxn, SuggestedParams from typing_extensions import deprecated from algokit_utils._legacy_v2.models import Account if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient __all__ = ["TransferAssetParameters", "TransferParameters", "transfer", "transfer_asset"] logger = logging.getLogger(__name__) @dataclasses.dataclass(kw_only=True) class TransferParametersBase: """Parameters for transferring µALGOs between accounts. This class contains the base parameters needed for transferring µALGOs between Algorand accounts. :ivar from_account: The account (with private key) or signer that will send the µALGOs :ivar to_address: The account address that will receive the µALGOs :ivar suggested_params: Transaction parameters, defaults to None :ivar note: Transaction note, defaults to None :ivar fee_micro_algos: The flat fee you want to pay, useful for covering extra fees in a transaction group or app call, defaults to None :ivar max_fee_micro_algos: The maximum fee that you are happy to pay - if this is set it's possible the transaction could get rejected during network congestion, defaults to None """ from_account: Account | AccountTransactionSigner to_address: str suggested_params: SuggestedParams | None = None note: str | bytes | None = None fee_micro_algos: int | None = None max_fee_micro_algos: int | None = None @dataclasses.dataclass(kw_only=True) class TransferParameters(TransferParametersBase): """Parameters for transferring µALGOs between accounts""" micro_algos: int @dataclasses.dataclass(kw_only=True) class TransferAssetParameters(TransferParametersBase): """Parameters for transferring assets between accounts. Defines the parameters needed to transfer Algorand Standard Assets (ASAs) between accounts. :param asset_id: The asset id that will be transferred :param amount: The amount of the asset to send :param clawback_from: An address of a target account from which to perform a clawback operation. Please note, in such cases senderAccount must be equal to clawback field on ASA metadata, defaults to None """ asset_id: int amount: int clawback_from: str | None = None def _check_fee(transaction: PaymentTxn | AssetTransferTxn, max_fee: int | None) -> None: if max_fee is not None: # Once a transaction has been constructed by algosdk, transaction.fee indicates what the total transaction fee # Will be based on the current suggested fee-per-byte value. if transaction.fee > max_fee: raise Exception( f"Cancelled transaction due to high network congestion fees. " f"Algorand suggested fees would cause this transaction to cost {transaction.fee} µALGOs. " f"Cap for this transaction is {max_fee} µALGOs." ) if transaction.fee > algosdk.constants.MIN_TXN_FEE: logger.warning( f"Algorand network congestion fees are in effect. " f"This transaction will incur a fee of {transaction.fee} µALGOs." ) @deprecated("Use the `TransactionComposer` abstraction instead to construct appropriate transfer transactions") def transfer(client: "AlgodClient", parameters: TransferParameters) -> PaymentTxn: """Transfer µALGOs between accounts""" params = parameters params.suggested_params = parameters.suggested_params or client.suggested_params() from_account = params.from_account sender = _get_address(from_account) transaction = PaymentTxn( sender=sender, receiver=params.to_address, amt=params.micro_algos, note=params.note.encode("utf-8") if isinstance(params.note, str) else params.note, sp=params.suggested_params, ) result = _send_transaction(client=client, transaction=transaction, parameters=params) assert isinstance(result, PaymentTxn) return result @deprecated("Use the `TransactionComposer` abstraction instead to construct appropriate transfer transactions") def transfer_asset(client: "AlgodClient", parameters: TransferAssetParameters) -> AssetTransferTxn: """Transfer assets between accounts""" params = parameters params.suggested_params = parameters.suggested_params or client.suggested_params() sender = _get_address(parameters.from_account) suggested_params = parameters.suggested_params or client.suggested_params() xfer_txn = AssetTransferTxn( sp=suggested_params, sender=sender, receiver=params.to_address, close_assets_to=None, revocation_target=params.clawback_from, amt=params.amount, note=params.note, index=params.asset_id, rekey_to=None, ) result = _send_transaction(client=client, transaction=xfer_txn, parameters=params) assert isinstance(result, AssetTransferTxn) return result def _send_transaction( client: "AlgodClient", transaction: PaymentTxn | AssetTransferTxn, parameters: TransferAssetParameters | TransferParameters, ) -> PaymentTxn | AssetTransferTxn: if parameters.fee_micro_algos: transaction.fee = parameters.fee_micro_algos if parameters.suggested_params is not None and not parameters.suggested_params.flat_fee: _check_fee(transaction, parameters.max_fee_micro_algos) signed_transaction = transaction.sign(parameters.from_account.private_key) # type: ignore[no-untyped-call] client.send_transaction(signed_transaction) txid = transaction.get_txid() # type: ignore[no-untyped-call] logger.debug(f"Sent transaction {txid} type={transaction.type} from {_get_address(parameters.from_account)}") return transaction def _get_address(account: Account | AccountTransactionSigner) -> str: if type(account) is Account: return account.address else: address = address_from_private_key(account.private_key) return str(address)
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/_transfer.py
Python
MIT
6,256
import logging import os from typing import TYPE_CHECKING, Any from algosdk.account import address_from_private_key from algosdk.mnemonic import from_private_key, to_private_key from algosdk.util import algos_to_microalgos from typing_extensions import deprecated from algokit_utils._legacy_v2._transfer import TransferParameters, transfer from algokit_utils._legacy_v2.models import Account from algokit_utils._legacy_v2.network_clients import get_kmd_client_from_algod_client, is_localnet if TYPE_CHECKING: from collections.abc import Callable from algosdk.kmd import KMDClient from algosdk.v2client.algod import AlgodClient __all__ = [ "create_kmd_wallet_account", "get_account", "get_account_from_mnemonic", "get_dispenser_account", "get_kmd_wallet_account", "get_localnet_default_account", "get_or_create_kmd_wallet_account", ] logger = logging.getLogger(__name__) _DEFAULT_ACCOUNT_MINIMUM_BALANCE = 1_000_000_000 @deprecated( "Use `algorand.account.from_mnemonic()` instead. Example: " "`account = algorand.account.from_mnemonic(mnemonic)`" ) def get_account_from_mnemonic(mnemonic: str) -> Account: """Convert a mnemonic (25 word passphrase) into an Account""" private_key = to_private_key(mnemonic) address = str(address_from_private_key(private_key)) return Account(private_key=private_key, address=address) @deprecated("Use `algorand.account.from_kmd()` instead. Example: " "`account = algorand.account.from_kmd(name)`") def create_kmd_wallet_account(kmd_client: "KMDClient", name: str) -> Account: """Creates a wallet with specified name""" wallet_id = kmd_client.create_wallet(name, "")["id"] wallet_handle = kmd_client.init_wallet_handle(wallet_id, "") kmd_client.generate_key(wallet_handle) key_ids: list[str] = kmd_client.list_keys(wallet_handle) account_key = key_ids[0] private_account_key = kmd_client.export_key(wallet_handle, "", account_key) return get_account_from_mnemonic(from_private_key(private_account_key)) @deprecated( "Use `algorand.account.from_kmd()` instead. Example: " "`account = algorand.account.from_kmd(name, fund_with=AlgoAmount.from_algo(1000))`" ) def get_or_create_kmd_wallet_account( client: "AlgodClient", name: str, fund_with_algos: float = 1000, kmd_client: "KMDClient | None" = None ) -> Account: """Returns a wallet with specified name, or creates one if not found""" kmd_client = kmd_client or get_kmd_client_from_algod_client(client) account = get_kmd_wallet_account(client, kmd_client, name) if account: account_info = client.account_info(account.address) assert isinstance(account_info, dict) if account_info["amount"] > 0: return account logger.debug(f"Found existing account in LocalNet with name '{name}', but no funds in the account.") else: account = create_kmd_wallet_account(kmd_client, name) logger.debug( f"Couldn't find existing account in LocalNet with name '{name}'. " f"So created account {account.address} with keys stored in KMD." ) logger.debug(f"Funding account {account.address} with {fund_with_algos} ALGOs") if fund_with_algos: transfer( client, TransferParameters( from_account=get_dispenser_account(client), to_address=account.address, micro_algos=algos_to_microalgos(fund_with_algos), ), ) return account def _is_default_account(account: dict[str, Any]) -> bool: return bool(account["status"] != "Offline" and account["amount"] > _DEFAULT_ACCOUNT_MINIMUM_BALANCE) @deprecated( "Use `algorand.account.from_kmd()` instead. Example: " "`account = algorand.account.from_kmd('unencrypted-default-wallet', lambda a: a['status'] != 'Offline' and a['amount'] > 1_000_000_000)`" ) def get_localnet_default_account(client: "AlgodClient") -> Account: """Returns the default Account in a LocalNet instance""" if not is_localnet(client): raise Exception("Can't get a default account from non LocalNet network") account = get_kmd_wallet_account( client, get_kmd_client_from_algod_client(client), "unencrypted-default-wallet", _is_default_account ) assert account return account @deprecated( "Use `algorand.account.dispenser_from_environment()` or `algorand.account.localnet_dispenser()` instead. " "Example: `dispenser = algorand.account.dispenser_from_environment()`" ) def get_dispenser_account(client: "AlgodClient") -> Account: """Returns an Account based on DISPENSER_MNENOMIC environment variable or the default account on LocalNet""" if is_localnet(client): return get_localnet_default_account(client) return get_account(client, "DISPENSER") @deprecated( "Use `algorand.account.from_kmd()` instead. Example: " "`account = algorand.account.from_kmd(name, predicate)`" ) def get_kmd_wallet_account( client: "AlgodClient", kmd_client: "KMDClient", name: str, predicate: "Callable[[dict[str, Any]], bool] | None" = None, ) -> Account | None: """Returns wallet matching specified name and predicate or None if not found""" wallets: list[dict] = kmd_client.list_wallets() wallet = next((w for w in wallets if w["name"] == name), None) if wallet is None: return None wallet_id = wallet["id"] wallet_handle = kmd_client.init_wallet_handle(wallet_id, "") key_ids: list[str] = kmd_client.list_keys(wallet_handle) matched_account_key = None if predicate: for key in key_ids: account = client.account_info(key) assert isinstance(account, dict) if predicate(account): matched_account_key = key else: matched_account_key = next(key_ids.__iter__(), None) if not matched_account_key: return None private_account_key = kmd_client.export_key(wallet_handle, "", matched_account_key) return get_account_from_mnemonic(from_private_key(private_account_key)) @deprecated( "Use `algorand.account.from_environment()` or `algorand.account.from_kmd()` or `algorand.account.random()` instead. " "Example: " "`account = algorand.account.from_environment('ACCOUNT', AlgoAmount.from_algo(1000))`" ) def get_account( client: "AlgodClient", name: str, fund_with_algos: float = 1000, kmd_client: "KMDClient | None" = None ) -> Account: """Returns an Algorand account with private key loaded by convention based on the given name identifier. Returns an Algorand account with private key loaded by convention based on the given name identifier. For non-LocalNet environments, loads the mnemonic secret from environment variable {name}_MNEMONIC. For LocalNet environments, loads or creates an account from a KMD wallet named {name}. :example: >>> # If you have a mnemonic secret loaded into `os.environ["ACCOUNT_MNEMONIC"]` then you can call: >>> account = get_account('ACCOUNT', algod) >>> # If that code runs against LocalNet then a wallet called 'ACCOUNT' will automatically be created >>> # with an account that is automatically funded with 1000 (default) ALGOs from the default LocalNet dispenser. :param client: The Algorand client to use :param name: The name identifier to use for loading/creating the account :param fund_with_algos: Amount of Algos to fund new LocalNet accounts with, defaults to 1000 :param kmd_client: Optional KMD client to use for LocalNet wallet operations :raises Exception: If required environment variable is missing in non-LocalNet environment :return: An Account object with loaded private key """ mnemonic_key = f"{name.upper()}_MNEMONIC" mnemonic = os.getenv(mnemonic_key) if mnemonic: return get_account_from_mnemonic(mnemonic) if is_localnet(client): account = get_or_create_kmd_wallet_account(client, name, fund_with_algos, kmd_client) os.environ[mnemonic_key] = from_private_key(account.private_key) return account raise Exception(f"Missing environment variable '{mnemonic_key}' when looking for account '{name}'")
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/account.py
Python
MIT
8,224
from __future__ import annotations import base64 import copy import json import logging import re import typing from math import ceil from pathlib import Path from typing import Any, Literal, cast, overload import algosdk from algosdk import transaction from algosdk.abi import ABIType, Method, Returns from algosdk.account import address_from_private_key from algosdk.atomic_transaction_composer import ( ABI_RETURN_HASH, ABIResult, AccountTransactionSigner, AtomicTransactionComposer, AtomicTransactionResponse, LogicSigTransactionSigner, MultisigTransactionSigner, SimulateAtomicTransactionResponse, TransactionSigner, TransactionWithSigner, ) from algosdk.constants import APP_PAGE_MAX_SIZE from algosdk.logic import get_application_address from algosdk.source_map import SourceMap from typing_extensions import deprecated import algokit_utils._legacy_v2.application_specification as au_spec import algokit_utils._legacy_v2.deploy as au_deploy from algokit_utils._legacy_v2.common import Program from algokit_utils._legacy_v2.logic_error import LogicError, parse_logic_error from algokit_utils._legacy_v2.models import ( ABIArgsDict, ABIArgType, ABIMethod, ABITransactionResponse, Account, CreateCallParameters, CreateCallParametersDict, OnCompleteCallParameters, OnCompleteCallParametersDict, SimulationTrace, TransactionParameters, TransactionParametersDict, TransactionResponse, ) from algokit_utils.config import config if typing.TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient logger = logging.getLogger(__name__) """A dictionary `dict[str, Any]` representing ABI argument names and values""" __all__ = [ "ApplicationClient", "execute_atc_with_logic_error", "get_next_version", "get_sender_from_signer", "num_extra_program_pages", ] """Alias for {py:class}`pyteal.ABIReturnSubroutine`, {py:class}`algosdk.abi.method.Method` or a {py:class}`str` representing an ABI method name or signature""" def num_extra_program_pages(approval: bytes, clear: bytes) -> int: """Calculate minimum number of extra_pages required for provided approval and clear programs""" return ceil(((len(approval) + len(clear)) - APP_PAGE_MAX_SIZE) / APP_PAGE_MAX_SIZE) @deprecated( "Use AppClient from algokit_utils.applications instead. Example:\n" "```python\n" "from algokit_utils import AlgorandClient\n" "from algokit_utils.models.application import Arc56Contract\n" "algorand_client = AlgorandClient.from_environment()\n" "app_client = AppClient.from_network(app_spec=Arc56Contract.from_json(app_spec_json), " "algorand=algorand_client, app_id=123)\n" "```" ) class ApplicationClient: """A class that wraps an ARC-0032 app spec and provides high productivity methods to deploy and call the app ApplicationClient can be created with an app_id to interact with an existing application, alternatively it can be created with a creator and indexer_client specified to find existing applications by name and creator. :param AlgodClient algod_client: AlgoSDK algod client :param ApplicationSpecification | Path app_spec: An Application Specification or the path to one :param int app_id: The app_id of an existing application, to instead find the application by creator and name use the creator and indexer_client parameters :param str | Account creator: The address or Account of the app creator to resolve the app_id :param IndexerClient indexer_client: AlgoSDK indexer client, only required if deploying or finding app_id by creator and app name :param AppLookup existing_deployments: :param TransactionSigner | Account signer: Account or signer to use to sign transactions, if not specified and creator was passed as an Account will use that. :param str sender: Address to use as the sender for all transactions, will use the address associated with the signer if not specified. :param TemplateValueMapping template_values: Values to use for TMPL_* template variables, dictionary keys should *NOT* include the TMPL_ prefix :param str | None app_name: Name of application to use when deploying, defaults to name defined on the Application Specification """ @overload def __init__( self, algod_client: AlgodClient, app_spec: au_spec.ApplicationSpecification | Path, *, app_id: int = 0, signer: TransactionSigner | Account | None = None, sender: str | None = None, suggested_params: transaction.SuggestedParams | None = None, template_values: au_deploy.TemplateValueMapping | None = None, ): ... @overload def __init__( self, algod_client: AlgodClient, app_spec: au_spec.ApplicationSpecification | Path, *, creator: str | Account, indexer_client: IndexerClient | None = None, existing_deployments: au_deploy.AppLookup | None = None, signer: TransactionSigner | Account | None = None, sender: str | None = None, suggested_params: transaction.SuggestedParams | None = None, template_values: au_deploy.TemplateValueMapping | None = None, app_name: str | None = None, ): ... def __init__( # noqa: PLR0913 self, algod_client: AlgodClient, app_spec: au_spec.ApplicationSpecification | Path, *, app_id: int = 0, creator: str | Account | None = None, indexer_client: IndexerClient | None = None, existing_deployments: au_deploy.AppLookup | None = None, signer: TransactionSigner | Account | None = None, sender: str | None = None, suggested_params: transaction.SuggestedParams | None = None, template_values: au_deploy.TemplateValueMapping | None = None, app_name: str | None = None, ): self.algod_client = algod_client self.app_spec = ( au_spec.ApplicationSpecification.from_json(app_spec.read_text()) if isinstance(app_spec, Path) else app_spec ) self._app_name = app_name self._approval_program: Program | None = None self._approval_source_map: SourceMap | None = None self._clear_program: Program | None = None self.template_values: au_deploy.TemplateValueMapping = template_values or {} self.existing_deployments = existing_deployments self._indexer_client = indexer_client if creator is not None: if not self.existing_deployments and not self._indexer_client: raise Exception( "If using the creator parameter either existing_deployments or indexer_client must also be provided" ) self._creator: str | None = creator.address if isinstance(creator, Account) else creator if self.existing_deployments and self.existing_deployments.creator != self._creator: raise Exception( "Attempt to create application client with invalid existing_deployments against" f"a different creator ({self.existing_deployments.creator} instead of " f"expected creator {self._creator}" ) self.app_id = 0 else: self.app_id = app_id self._creator = None self.signer: TransactionSigner | None if signer: self.signer = ( signer if isinstance(signer, TransactionSigner) else AccountTransactionSigner(signer.private_key) ) elif isinstance(creator, Account): self.signer = AccountTransactionSigner(creator.private_key) else: self.signer = None self.sender = sender self.suggested_params = suggested_params @property def app_name(self) -> str: return self._app_name or self.app_spec.contract.name @app_name.setter def app_name(self, value: str) -> None: self._app_name = value @property def app_address(self) -> str: return get_application_address(self.app_id) @property def approval(self) -> Program | None: return self._approval_program @property def approval_source_map(self) -> SourceMap | None: if self._approval_source_map: return self._approval_source_map if self._approval_program: return self._approval_program.source_map return None @approval_source_map.setter def approval_source_map(self, value: SourceMap) -> None: self._approval_source_map = value @property def clear(self) -> Program | None: return self._clear_program def prepare( self, signer: TransactionSigner | Account | None = None, sender: str | None = None, app_id: int | None = None, template_values: au_deploy.TemplateValueDict | None = None, ) -> ApplicationClient: """Creates a copy of this ApplicationClient, using the new signer, sender and app_id values if provided. Will also substitute provided template_values into the associated app_spec in the copy""" new_client: ApplicationClient = copy.copy(self) new_client._prepare( # noqa: SLF001 new_client, signer=signer, sender=sender, app_id=app_id, template_values=template_values ) return new_client def _prepare( self, target: ApplicationClient, *, signer: TransactionSigner | Account | None = None, sender: str | None = None, app_id: int | None = None, template_values: au_deploy.TemplateValueDict | None = None, ) -> None: target.app_id = self.app_id if app_id is None else app_id target.signer, target.sender = target.get_signer_sender( AccountTransactionSigner(signer.private_key) if isinstance(signer, Account) else signer, sender ) target.template_values = {**self.template_values, **(template_values or {})} def deploy( # noqa: PLR0913 self, version: str | None = None, *, signer: TransactionSigner | None = None, sender: str | None = None, allow_update: bool | None = None, allow_delete: bool | None = None, on_update: au_deploy.OnUpdate = au_deploy.OnUpdate.Fail, on_schema_break: au_deploy.OnSchemaBreak = au_deploy.OnSchemaBreak.Fail, template_values: au_deploy.TemplateValueMapping | None = None, create_args: au_deploy.ABICreateCallArgs | au_deploy.ABICreateCallArgsDict | au_deploy.DeployCreateCallArgs | None = None, update_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None, delete_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None, ) -> au_deploy.DeployResponse: """Deploy an application and update client to reference it. Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions. To understand the architecture decisions behind this functionality please see <https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md> ```{note} If there is a breaking state schema change to an existing app (and `on_schema_break` is set to 'ReplaceApp' the existing app will be deleted and re-created. ``` ```{note} If there is an update (different TEAL code) to an existing app (and `on_update` is set to 'ReplaceApp') the existing app will be deleted and re-created. ``` :param str version: version to use when creating or updating app, if None version will be auto incremented :param algosdk.atomic_transaction_composer.TransactionSigner signer: signer to use when deploying app , if None uses self.signer :param str sender: sender address to use when deploying app, if None uses self.sender :param bool allow_delete: Used to set the `TMPL_DELETABLE` template variable to conditionally control if an app can be deleted :param bool allow_update: Used to set the `TMPL_UPDATABLE` template variable to conditionally control if an app can be updated :param OnUpdate on_update: Determines what action to take if an application update is required :param OnSchemaBreak on_schema_break: Determines what action to take if an application schema requirements has increased beyond the current allocation :param dict[str, int|str|bytes] template_values: Values to use for `TMPL_*` template variables, dictionary keys should *NOT* include the TMPL_ prefix :param ABICreateCallArgs create_args: Arguments used when creating an application :param ABICallArgs | ABICallArgsDict update_args: Arguments used when updating an application :param ABICallArgs | ABICallArgsDict delete_args: Arguments used when deleting an application :return DeployResponse: details action taken and relevant transactions :raises DeploymentError: If the deployment failed """ # check inputs if self.app_id: raise au_deploy.DeploymentFailedError( f"Attempt to deploy app which already has an app index of {self.app_id}" ) try: resolved_signer, resolved_sender = self.resolve_signer_sender(signer, sender) except ValueError as ex: raise au_deploy.DeploymentFailedError(f"{ex}, unable to deploy app") from None if not self._creator: raise au_deploy.DeploymentFailedError("No creator provided, unable to deploy app") if self._creator != resolved_sender: raise au_deploy.DeploymentFailedError( f"Attempt to deploy contract with a sender address {resolved_sender} that differs " f"from the given creator address for this application client: {self._creator}" ) # make a copy and prepare variables template_values = {**self.template_values, **(template_values or {})} au_deploy.add_deploy_template_variables(template_values, allow_update=allow_update, allow_delete=allow_delete) existing_app_metadata_or_reference = self._load_app_reference() self._approval_program, self._clear_program = substitute_template_and_compile( self.algod_client, self.app_spec, template_values ) if config.debug and config.project_root: from algokit_utils._debugging import PersistSourceMapInput, persist_sourcemaps persist_sourcemaps( sources=[ PersistSourceMapInput( compiled_teal=self._approval_program, app_name=self.app_name, file_name="approval.teal" ), PersistSourceMapInput( compiled_teal=self._clear_program, app_name=self.app_name, file_name="clear.teal" ), ], project_root=config.project_root, client=self.algod_client, with_sources=True, ) deployer = au_deploy.Deployer( app_client=self, creator=self._creator, signer=resolved_signer, sender=resolved_sender, new_app_metadata=self._get_app_deploy_metadata(version, allow_update, allow_delete), existing_app_metadata_or_reference=existing_app_metadata_or_reference, on_update=on_update, on_schema_break=on_schema_break, create_args=create_args, update_args=update_args, delete_args=delete_args, ) return deployer.deploy() def compose_create( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with application id == 0 and the schema and source of client's app_spec to atc""" approval_program, clear_program = self._check_is_compiled() transaction_parameters = _convert_transaction_parameters(transaction_parameters) extra_pages = transaction_parameters.extra_pages or num_extra_program_pages( approval_program.raw_binary, clear_program.raw_binary ) self.add_method_call( atc, app_id=0, abi_method=call_abi_method, abi_args=abi_kwargs, on_complete=transaction_parameters.on_complete or transaction.OnComplete.NoOpOC, call_config=au_spec.CallConfig.CREATE, parameters=transaction_parameters, approval_program=approval_program.raw_binary, clear_program=clear_program.raw_binary, global_schema=self.app_spec.global_state_schema, local_schema=self.app_spec.local_state_schema, extra_pages=extra_pages, ) @overload def create( self, call_abi_method: Literal[False], transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ..., ) -> TransactionResponse: ... @overload def create( self, call_abi_method: ABIMethod | Literal[True], transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def create( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def create( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with application id == 0 and the schema and source of client's app_spec""" atc = AtomicTransactionComposer() self.compose_create( atc, call_abi_method, transaction_parameters, **abi_kwargs, ) create_result = self._execute_atc_tr(atc) self.app_id = au_deploy.get_app_id_from_tx_id(self.algod_client, create_result.tx_id) return create_result def compose_update( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with on_complete=UpdateApplication to atc""" approval_program, clear_program = self._check_is_compiled() self.add_method_call( atc=atc, abi_method=call_abi_method, abi_args=abi_kwargs, parameters=transaction_parameters, on_complete=transaction.OnComplete.UpdateApplicationOC, approval_program=approval_program.raw_binary, clear_program=clear_program.raw_binary, ) @overload def update( self, call_abi_method: ABIMethod | Literal[True], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def update( self, call_abi_method: Literal[False], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., ) -> TransactionResponse: ... @overload def update( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def update( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with on_complete=UpdateApplication""" atc = AtomicTransactionComposer() self.compose_update( atc, call_abi_method, transaction_parameters=transaction_parameters, **abi_kwargs, ) return self._execute_atc_tr(atc) def compose_delete( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with on_complete=DeleteApplication to atc""" self.add_method_call( atc, call_abi_method, abi_args=abi_kwargs, parameters=transaction_parameters, on_complete=transaction.OnComplete.DeleteApplicationOC, ) @overload def delete( self, call_abi_method: ABIMethod | Literal[True], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def delete( self, call_abi_method: Literal[False], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., ) -> TransactionResponse: ... @overload def delete( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def delete( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with on_complete=DeleteApplication""" atc = AtomicTransactionComposer() self.compose_delete( atc, call_abi_method, transaction_parameters=transaction_parameters, **abi_kwargs, ) return self._execute_atc_tr(atc) def compose_call( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with specified parameters to atc""" _parameters = _convert_transaction_parameters(transaction_parameters) self.add_method_call( atc, abi_method=call_abi_method, abi_args=abi_kwargs, parameters=_parameters, on_complete=_parameters.on_complete or transaction.OnComplete.NoOpOC, ) @overload def call( self, call_abi_method: ABIMethod | Literal[True], transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def call( self, call_abi_method: Literal[False], transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ..., ) -> TransactionResponse: ... @overload def call( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def call( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with specified parameters""" atc = AtomicTransactionComposer() _parameters = _convert_transaction_parameters(transaction_parameters) self.compose_call( atc, call_abi_method=call_abi_method, transaction_parameters=_parameters, **abi_kwargs, ) method = self._resolve_method( call_abi_method, abi_kwargs, _parameters.on_complete or transaction.OnComplete.NoOpOC ) if method: hints = self._method_hints(method) if hints and hints.read_only: if config.debug and config.project_root and config.trace_all: from algokit_utils._debugging import simulate_and_persist_response simulate_and_persist_response( atc, config.project_root, self.algod_client, config.trace_buffer_size_mb ) return self._simulate_readonly_call(method, atc) return self._execute_atc_tr(atc) def compose_opt_in( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with on_complete=OptIn to atc""" self.add_method_call( atc, abi_method=call_abi_method, abi_args=abi_kwargs, parameters=transaction_parameters, on_complete=transaction.OnComplete.OptInOC, ) @overload def opt_in( self, call_abi_method: ABIMethod | Literal[True] = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def opt_in( self, call_abi_method: Literal[False] = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, ) -> TransactionResponse: ... @overload def opt_in( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def opt_in( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with on_complete=OptIn""" atc = AtomicTransactionComposer() self.compose_opt_in( atc, call_abi_method=call_abi_method, transaction_parameters=transaction_parameters, **abi_kwargs, ) return self._execute_atc_tr(atc) def compose_close_out( self, atc: AtomicTransactionComposer, /, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> None: """Adds a signed transaction with on_complete=CloseOut to ac""" self.add_method_call( atc, abi_method=call_abi_method, abi_args=abi_kwargs, parameters=transaction_parameters, on_complete=transaction.OnComplete.CloseOutOC, ) @overload def close_out( self, call_abi_method: ABIMethod | Literal[True], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> ABITransactionResponse: ... @overload def close_out( self, call_abi_method: Literal[False], transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., ) -> TransactionResponse: ... @overload def close_out( self, call_abi_method: ABIMethod | bool | None = ..., transaction_parameters: TransactionParameters | TransactionParametersDict | None = ..., **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: ... def close_out( self, call_abi_method: ABIMethod | bool | None = None, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, **abi_kwargs: ABIArgType, ) -> TransactionResponse | ABITransactionResponse: """Submits a signed transaction with on_complete=CloseOut""" atc = AtomicTransactionComposer() self.compose_close_out( atc, call_abi_method=call_abi_method, transaction_parameters=transaction_parameters, **abi_kwargs, ) return self._execute_atc_tr(atc) def compose_clear_state( self, atc: AtomicTransactionComposer, /, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, app_args: list[bytes] | None = None, ) -> None: """Adds a signed transaction with on_complete=ClearState to atc""" return self.add_method_call( atc, parameters=transaction_parameters, on_complete=transaction.OnComplete.ClearStateOC, app_args=app_args, ) def clear_state( self, transaction_parameters: TransactionParameters | TransactionParametersDict | None = None, app_args: list[bytes] | None = None, ) -> TransactionResponse: """Submits a signed transaction with on_complete=ClearState""" atc = AtomicTransactionComposer() self.compose_clear_state( atc, transaction_parameters=transaction_parameters, app_args=app_args, ) return self._execute_atc_tr(atc) def get_global_state(self, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]: """Gets the global state info associated with app_id""" global_state = self.algod_client.application_info(self.app_id) assert isinstance(global_state, dict) return cast( dict[bytes | str, bytes | str | int], _decode_state(global_state.get("params", {}).get("global-state", {}), raw=raw), ) def get_local_state(self, account: str | None = None, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]: """Gets the local state info for associated app_id and account/sender""" if account is None: _, account = self.resolve_signer_sender(self.signer, self.sender) acct_state = self.algod_client.account_application_info(account, self.app_id) assert isinstance(acct_state, dict) return cast( dict[bytes | str, bytes | str | int], _decode_state(acct_state.get("app-local-state", {}).get("key-value", {}), raw=raw), ) def resolve(self, to_resolve: au_spec.DefaultArgumentDict) -> int | str | bytes: """Resolves the default value for an ABI method, based on app_spec""" def _data_check(value: object) -> int | str | bytes: if isinstance(value, int | str | bytes): return value raise ValueError(f"Unexpected type for constant data: {value}") match to_resolve: case {"source": "constant", "data": data}: return _data_check(data) case {"source": "global-state", "data": str() as key}: global_state = self.get_global_state(raw=True) return global_state[key.encode()] case {"source": "local-state", "data": str() as key}: _, sender = self.resolve_signer_sender(self.signer, self.sender) acct_state = self.get_local_state(sender, raw=True) return acct_state[key.encode()] case {"source": "abi-method", "data": dict() as method_dict}: method = Method.undictify(method_dict) response = self.call(method) assert isinstance(response, ABITransactionResponse) return _data_check(response.return_value) case {"source": source}: raise ValueError(f"Unrecognized default argument source: {source}") case _: raise TypeError("Unable to interpret default argument specification") def _get_app_deploy_metadata( self, version: str | None, allow_update: bool | None, allow_delete: bool | None ) -> au_deploy.AppDeployMetaData: updatable = ( allow_update if allow_update is not None else au_deploy.get_deploy_control( self.app_spec, au_deploy.UPDATABLE_TEMPLATE_NAME, transaction.OnComplete.UpdateApplicationOC ) ) deletable = ( allow_delete if allow_delete is not None else au_deploy.get_deploy_control( self.app_spec, au_deploy.DELETABLE_TEMPLATE_NAME, transaction.OnComplete.DeleteApplicationOC ) ) app = self._load_app_reference() if version is None: if app.app_id == 0: version = "v1.0" else: assert isinstance(app, au_deploy.AppDeployMetaData) version = get_next_version(app.version) return au_deploy.AppDeployMetaData(self.app_name, version, updatable=updatable, deletable=deletable) def _check_is_compiled(self) -> tuple[Program, Program]: if self._approval_program is None or self._clear_program is None: self._approval_program, self._clear_program = substitute_template_and_compile( self.algod_client, self.app_spec, self.template_values ) if config.debug and config.project_root: from algokit_utils._debugging import PersistSourceMapInput, persist_sourcemaps persist_sourcemaps( sources=[ PersistSourceMapInput( compiled_teal=self._approval_program, app_name=self.app_name, file_name="approval.teal" ), PersistSourceMapInput( compiled_teal=self._clear_program, app_name=self.app_name, file_name="clear.teal" ), ], project_root=config.project_root, client=self.algod_client, with_sources=True, ) return self._approval_program, self._clear_program def _simulate_readonly_call( self, method: Method, atc: AtomicTransactionComposer ) -> ABITransactionResponse | TransactionResponse: from algokit_utils._debugging import simulate_response response = simulate_response(atc, self.algod_client) traces = None if config.debug: traces = _create_simulate_traces(response) if response.failure_message: raise _try_convert_to_logic_error( response.failure_message, self.app_spec.approval_program, self._get_approval_source_map, traces, ) or Exception(f"Simulate failed for readonly method {method.get_signature()}: {response.failure_message}") return TransactionResponse.from_atr(response) def _load_reference_and_check_app_id(self) -> None: self._load_app_reference() self._check_app_id() def _load_app_reference(self) -> au_deploy.AppReference | au_deploy.AppMetaData: if not self.existing_deployments and self._creator: assert self._indexer_client self.existing_deployments = au_deploy.get_creator_apps(self._indexer_client, self._creator) if self.existing_deployments: app = self.existing_deployments.apps.get(self.app_name) if app: if self.app_id == 0: self.app_id = app.app_id return app return au_deploy.AppReference(self.app_id, self.app_address) def _check_app_id(self) -> None: if self.app_id == 0: raise Exception( "ApplicationClient is not associated with an app instance, to resolve either:\n" "1.provide an app_id on construction OR\n" "2.provide a creator address so an app can be searched for OR\n" "3.create an app first using create or deploy methods" ) def _resolve_method( self, abi_method: ABIMethod | bool | None, args: ABIArgsDict | None, on_complete: transaction.OnComplete, call_config: au_spec.CallConfig = au_spec.CallConfig.CALL, ) -> Method | None: matches: list[Method | None] = [] match abi_method: case str() | Method(): # abi method specified return self._resolve_abi_method(abi_method) case bool() | None: # find abi method has_bare_config = ( call_config in au_deploy.get_call_config(self.app_spec.bare_call_config, on_complete) or on_complete == transaction.OnComplete.ClearStateOC ) abi_methods = self._find_abi_methods(args, on_complete, call_config) if abi_method is not False: matches += abi_methods if has_bare_config and abi_method is not True: matches += [None] case _: return abi_method.method_spec() if len(matches) == 1: # exact match return matches[0] elif len(matches) > 1: # ambiguous match signatures = ", ".join((m.get_signature() if isinstance(m, Method) else "bare") for m in matches) raise Exception( f"Could not find an exact method to use for {on_complete.name} with call_config of {call_config.name}, " f"specify the exact method using abi_method and args parameters, considered: {signatures}" ) else: # no match raise Exception( f"Could not find any methods to use for {on_complete.name} with call_config of {call_config.name}" ) def _get_approval_source_map(self) -> SourceMap | None: if self.approval_source_map: return self.approval_source_map try: approval, _ = self._check_is_compiled() except au_deploy.DeploymentFailedError: return None return approval.source_map def export_source_map(self) -> str | None: """Export approval source map to JSON, can be later re-imported with `import_source_map`""" source_map = self._get_approval_source_map() if source_map: return json.dumps( { "version": source_map.version, "sources": source_map.sources, "mappings": source_map.mappings, } ) return None def import_source_map(self, source_map_json: str) -> None: """Import approval source from JSON exported by `export_source_map`""" source_map = json.loads(source_map_json) self._approval_source_map = SourceMap(source_map) def add_method_call( # noqa: PLR0913 self, atc: AtomicTransactionComposer, abi_method: ABIMethod | bool | None = None, *, abi_args: ABIArgsDict | None = None, app_id: int | None = None, parameters: TransactionParameters | TransactionParametersDict | None = None, on_complete: transaction.OnComplete = transaction.OnComplete.NoOpOC, local_schema: transaction.StateSchema | None = None, global_schema: transaction.StateSchema | None = None, approval_program: bytes | None = None, clear_program: bytes | None = None, extra_pages: int | None = None, app_args: list[bytes] | None = None, call_config: au_spec.CallConfig = au_spec.CallConfig.CALL, ) -> None: """Adds a transaction to the AtomicTransactionComposer passed""" if app_id is None: self._load_reference_and_check_app_id() app_id = self.app_id parameters = _convert_transaction_parameters(parameters) method = self._resolve_method(abi_method, abi_args, on_complete, call_config) sp = parameters.suggested_params or self.suggested_params or self.algod_client.suggested_params() signer, sender = self.resolve_signer_sender(parameters.signer, parameters.sender) if parameters.boxes is not None: # TODO: algosdk actually does this, but it's type hints say otherwise... encoded_boxes = [(id_, algosdk.encoding.encode_as_bytes(name)) for id_, name in parameters.boxes] else: encoded_boxes = None encoded_lease = parameters.lease.encode("utf-8") if isinstance(parameters.lease, str) else parameters.lease if not method: # not an abi method, treat as a regular call if abi_args: raise Exception(f"ABI arguments specified on a bare call: {', '.join(abi_args)}") atc.add_transaction( TransactionWithSigner( txn=transaction.ApplicationCallTxn( sender=sender, sp=sp, index=app_id, on_complete=on_complete, approval_program=approval_program, clear_program=clear_program, global_schema=global_schema, local_schema=local_schema, extra_pages=extra_pages, accounts=parameters.accounts, foreign_apps=parameters.foreign_apps, foreign_assets=parameters.foreign_assets, boxes=encoded_boxes, note=parameters.note, lease=encoded_lease, rekey_to=parameters.rekey_to, app_args=app_args, ), signer=signer, ) ) return # resolve ABI method args args = self._get_abi_method_args(abi_args, method) atc.add_method_call( app_id, method, sender, sp, signer, method_args=args, on_complete=on_complete, local_schema=local_schema, global_schema=global_schema, approval_program=approval_program, clear_program=clear_program, extra_pages=extra_pages or 0, accounts=parameters.accounts, foreign_apps=parameters.foreign_apps, foreign_assets=parameters.foreign_assets, boxes=encoded_boxes, note=parameters.note.encode("utf-8") if isinstance(parameters.note, str) else parameters.note, lease=encoded_lease, rekey_to=parameters.rekey_to, ) def _get_abi_method_args(self, abi_args: ABIArgsDict | None, method: Method) -> list: args: list = [] hints = self._method_hints(method) # copy args so we don't mutate original abi_args = dict(abi_args or {}) for method_arg in method.args: name = method_arg.name if name in abi_args: argument = abi_args.pop(name) if isinstance(argument, dict): if hints.structs is None or name not in hints.structs: raise Exception(f"Argument missing struct hint: {name}. Check argument name and type") elements = hints.structs[name]["elements"] argument_tuple = tuple(argument[field_name] for field_name, field_type in elements) args.append(argument_tuple) else: args.append(argument) elif hints.default_arguments is not None and name in hints.default_arguments: default_arg = hints.default_arguments[name] if default_arg is not None: args.append(self.resolve(default_arg)) else: raise Exception(f"Unspecified argument: {name}") if abi_args: raise Exception(f"Unused arguments specified: {', '.join(abi_args)}") return args def _method_matches( self, method: Method, args: ABIArgsDict | None, on_complete: transaction.OnComplete, call_config: au_spec.CallConfig, ) -> bool: hints = self._method_hints(method) if call_config not in au_deploy.get_call_config(hints.call_config, on_complete): return False method_args = {m.name for m in method.args} provided_args = set(args or {}) | set(hints.default_arguments) # TODO: also match on types? return method_args == provided_args def _find_abi_methods( self, args: ABIArgsDict | None, on_complete: transaction.OnComplete, call_config: au_spec.CallConfig ) -> list[Method]: return [ method for method in self.app_spec.contract.methods if self._method_matches(method, args, on_complete, call_config) ] def _resolve_abi_method(self, method: ABIMethod) -> Method: if isinstance(method, str): try: return next(iter(m for m in self.app_spec.contract.methods if m.get_signature() == method)) except StopIteration: pass return self.app_spec.contract.get_method_by_name(method) elif hasattr(method, "method_spec"): return method.method_spec() else: return method def _method_hints(self, method: Method) -> au_spec.MethodHints: sig = method.get_signature() if sig not in self.app_spec.hints: return au_spec.MethodHints() return self.app_spec.hints[sig] def _execute_atc_tr(self, atc: AtomicTransactionComposer) -> TransactionResponse: result = self.execute_atc(atc) return TransactionResponse.from_atr(result) def execute_atc(self, atc: AtomicTransactionComposer) -> AtomicTransactionResponse: return execute_atc_with_logic_error( atc, self.algod_client, approval_program=self.app_spec.approval_program, approval_source_map=self._get_approval_source_map, ) def get_signer_sender( self, signer: TransactionSigner | None = None, sender: str | None = None ) -> tuple[TransactionSigner | None, str | None]: """Return signer and sender, using default values on client if not specified Will use provided values if given, otherwise will fall back to values defined on client. If no sender is specified then will attempt to obtain sender from signer""" resolved_signer = signer or self.signer resolved_sender = sender or get_sender_from_signer(signer) or self.sender or get_sender_from_signer(self.signer) return resolved_signer, resolved_sender def resolve_signer_sender( self, signer: TransactionSigner | None = None, sender: str | None = None ) -> tuple[TransactionSigner, str]: """Return signer and sender, using default values on client if not specified Will use provided values if given, otherwise will fall back to values defined on client. If no sender is specified then will attempt to obtain sender from signer :raises ValueError: Raised if a signer or sender is not provided. See `get_signer_sender` for variant with no exception""" resolved_signer, resolved_sender = self.get_signer_sender(signer, sender) if not resolved_signer: raise ValueError("No signer provided") if not resolved_sender: raise ValueError("No sender provided") return resolved_signer, resolved_sender # TODO: remove private implementation, kept in the 1.0.2 release to not impact existing beaker 1.0 installs _resolve_signer_sender = resolve_signer_sender def substitute_template_and_compile( algod_client: AlgodClient, app_spec: au_spec.ApplicationSpecification, template_values: au_deploy.TemplateValueMapping, ) -> tuple[Program, Program]: """Substitutes the provided template_values into app_spec and compiles""" template_values = dict(template_values or {}) clear = au_deploy.replace_template_variables(app_spec.clear_program, template_values) au_deploy.check_template_variables(app_spec.approval_program, template_values) approval = au_deploy.replace_template_variables(app_spec.approval_program, template_values) approval_app, clear_app = Program(approval, algod_client), Program(clear, algod_client) return approval_app, clear_app def get_next_version(current_version: str) -> str: """Calculates the next version from `current_version` Next version is calculated by finding a semver like version string and incrementing the lower. This function is used by {py:meth}`ApplicationClient.deploy` when a version is not specified, and is intended mostly for convenience during local development. :params str current_version: An existing version string with a semver like version contained within it, some valid inputs and incremented outputs: `1` -> `2` `1.0` -> `1.1` `v1.1` -> `v1.2` `v1.1-beta1` -> `v1.2-beta1` `v1.2.3.4567` -> `v1.2.3.4568` `v1.2.3.4567-alpha` -> `v1.2.3.4568-alpha` :raises DeploymentFailedError: If `current_version` cannot be parsed""" pattern = re.compile(r"(?P<prefix>\w*)(?P<version>(?:\d+\.)*\d+)(?P<suffix>\w*)") match = pattern.match(current_version) if match: version = match.group("version") new_version = _increment_version(version) def replacement(m: re.Match) -> str: return f"{m.group('prefix')}{new_version}{m.group('suffix')}" return re.sub(pattern, replacement, current_version) raise au_deploy.DeploymentFailedError( f"Could not auto increment {current_version}, please specify the next version using the version parameter" ) def _try_convert_to_logic_error( source_ex: Exception | str, approval_program: str, approval_source_map: SourceMap | typing.Callable[[], SourceMap | None] | None = None, simulate_traces: list[SimulationTrace] | None = None, ) -> Exception | None: source_ex_str = str(source_ex) logic_error_data = parse_logic_error(source_ex_str) if logic_error_data: return LogicError( logic_error_str=source_ex_str, logic_error=source_ex if isinstance(source_ex, Exception) else None, program=approval_program, source_map=approval_source_map() if callable(approval_source_map) else approval_source_map, **logic_error_data, traces=simulate_traces, ) return None @deprecated( "The execute_atc_with_logic_error function is deprecated; use AppClient's error handling and TransactionComposer's " "send method for equivalent functionality and improved error management." ) def execute_atc_with_logic_error( atc: AtomicTransactionComposer, algod_client: AlgodClient, approval_program: str, wait_rounds: int = 4, approval_source_map: SourceMap | typing.Callable[[], SourceMap | None] | None = None, ) -> AtomicTransactionResponse: """Calls {py:meth}`AtomicTransactionComposer.execute` on provided `atc`, but will parse any errors and raise a {py:class}`LogicError` if possible ```{note} `approval_program` and `approval_source_map` are required to be able to parse any errors into a {py:class}`LogicError` ``` """ from algokit_utils._debugging import simulate_and_persist_response, simulate_response try: if config.debug and config.project_root and config.trace_all: simulate_and_persist_response(atc, config.project_root, algod_client, config.trace_buffer_size_mb) return atc.execute(algod_client, wait_rounds=wait_rounds) except Exception as ex: if config.debug: simulate = None if config.project_root and not config.trace_all: # if trace_all is enabled, we already have the traces executed above # hence we only need to simulate if trace_all is disabled and # project_root is set simulate = simulate_and_persist_response( atc, config.project_root, algod_client, config.trace_buffer_size_mb ) else: simulate = simulate_response(atc, algod_client) traces = _create_simulate_traces(simulate) else: traces = None logger.info("An error occurred while executing the transaction.") logger.info("To see more details, enable debug mode by setting config.debug = True ") logic_error = _try_convert_to_logic_error(ex, approval_program, approval_source_map, traces) if logic_error: raise logic_error from ex raise ex def _create_simulate_traces(simulate: SimulateAtomicTransactionResponse) -> list[SimulationTrace]: traces = [] if hasattr(simulate, "simulate_response") and hasattr(simulate, "failed_at") and simulate.failed_at: for txn_group in simulate.simulate_response["txn-groups"]: app_budget_added = txn_group.get("app-budget-added", None) app_budget_consumed = txn_group.get("app-budget-consumed", None) failure_message = txn_group.get("failure-message", None) txn_result = txn_group.get("txn-results", [{}])[0] exec_trace = txn_result.get("exec-trace", {}) traces.append( SimulationTrace( app_budget_added=app_budget_added, app_budget_consumed=app_budget_consumed, failure_message=failure_message, exec_trace=exec_trace, ) ) return traces def _convert_transaction_parameters( args: TransactionParameters | TransactionParametersDict | None, ) -> CreateCallParameters: _args = args.__dict__ if isinstance(args, TransactionParameters) else (args or {}) return CreateCallParameters(**_args) def get_sender_from_signer(signer: TransactionSigner | None) -> str | None: """Returns the associated address of a signer, return None if no address found""" if isinstance(signer, AccountTransactionSigner): sender = address_from_private_key(signer.private_key) assert isinstance(sender, str) return sender elif isinstance(signer, MultisigTransactionSigner): sender = signer.msig.address() assert isinstance(sender, str) return sender elif isinstance(signer, LogicSigTransactionSigner): return signer.lsig.address() return None # TEMPORARY, use SDK one when available def _parse_result( methods: dict[int, Method], txns: list[dict[str, Any]], txids: list[str], ) -> list[ABIResult]: method_results = [] for i, tx_info in enumerate(txns): raw_value = b"" return_value = None decode_error = None if i not in methods: continue # Parse log for ABI method return value try: if methods[i].returns.type == Returns.VOID: method_results.append( ABIResult( tx_id=txids[i], raw_value=raw_value, return_value=return_value, decode_error=decode_error, tx_info=tx_info, method=methods[i], ) ) continue logs = tx_info.get("logs", []) # Look for the last returned value in the log if not logs: raise Exception("No logs") result = logs[-1] # Check that the first four bytes is the hash of "return" result_bytes = base64.b64decode(result) if len(result_bytes) < len(ABI_RETURN_HASH) or result_bytes[: len(ABI_RETURN_HASH)] != ABI_RETURN_HASH: raise Exception("no logs") raw_value = result_bytes[4:] abi_return_type = methods[i].returns.type if isinstance(abi_return_type, ABIType): return_value = abi_return_type.decode(raw_value) else: return_value = raw_value except Exception as e: decode_error = e method_results.append( ABIResult( tx_id=txids[i], raw_value=raw_value, return_value=return_value, decode_error=decode_error, tx_info=tx_info, method=methods[i], ) ) return method_results def _increment_version(version: str) -> str: split = list(map(int, version.split("."))) split[-1] = split[-1] + 1 return ".".join(str(x) for x in split) def _str_or_hex(v: bytes) -> str: decoded: str try: decoded = v.decode("utf-8") except UnicodeDecodeError: decoded = v.hex() return decoded def _decode_state(state: list[dict[str, Any]], *, raw: bool = False) -> dict[str | bytes, bytes | str | int | None]: decoded_state: dict[str | bytes, bytes | str | int | None] = {} for state_value in state: raw_key = base64.b64decode(state_value["key"]) key: str | bytes = raw_key if raw else _str_or_hex(raw_key) val: str | bytes | int | None action = state_value["value"]["action"] if "action" in state_value["value"] else state_value["value"]["type"] match action: case 1: raw_val = base64.b64decode(state_value["value"]["bytes"]) val = raw_val if raw else _str_or_hex(raw_val) case 2: val = state_value["value"]["uint"] case 3: val = None case _: raise NotImplementedError decoded_state[key] = val return decoded_state
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/application_client.py
Python
MIT
59,536
from algokit_utils.applications.app_spec.arc32 import ( AppSpecStateDict, CallConfig, DefaultArgumentDict, DefaultArgumentType, MethodConfigDict, MethodHints, OnCompleteActionName, ) from algokit_utils.applications.app_spec.arc32 import Arc32Contract as ApplicationSpecification __all__ = [ "AppSpecStateDict", "ApplicationSpecification", "CallConfig", "DefaultArgumentDict", "DefaultArgumentType", "MethodConfigDict", "MethodHints", "OnCompleteActionName", ]
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/application_specification.py
Python
MIT
521
import logging from enum import Enum, auto from algosdk.atomic_transaction_composer import AtomicTransactionComposer, TransactionWithSigner from algosdk.constants import TX_GROUP_LIMIT from algosdk.transaction import AssetTransferTxn from algosdk.v2client.algod import AlgodClient from typing_extensions import deprecated from algokit_utils._legacy_v2.models import Account __all__ = ["opt_in", "opt_out"] logger = logging.getLogger(__name__) class ValidationType(Enum): OPTIN = auto() OPTOUT = auto() def _ensure_account_is_valid(algod_client: "AlgodClient", account: Account) -> None: try: algod_client.account_info(account.address) except Exception as err: error_message = f"Account address{account.address} does not exist" logger.debug(error_message) raise err def _ensure_asset_balance_conditions( algod_client: "AlgodClient", account: Account, asset_ids: list, validation_type: ValidationType ) -> None: invalid_asset_ids = [] account_info = algod_client.account_info(account.address) account_assets = account_info.get("assets", []) # type: ignore # noqa: PGH003 for asset_id in asset_ids: asset_exists_in_account_info = any(asset["asset-id"] == asset_id for asset in account_assets) if validation_type == ValidationType.OPTIN: if asset_exists_in_account_info: logger.debug(f"Asset {asset_id} is already opted in for account {account.address}") invalid_asset_ids.append(asset_id) elif validation_type == ValidationType.OPTOUT: if not account_assets or not asset_exists_in_account_info: logger.debug(f"Account {account.address} does not have asset {asset_id}") invalid_asset_ids.append(asset_id) else: asset_balance = next((asset["amount"] for asset in account_assets if asset["asset-id"] == asset_id), 0) if asset_balance != 0: logger.debug(f"Asset {asset_id} balance is not zero") invalid_asset_ids.append(asset_id) if len(invalid_asset_ids) > 0: action = "opted out" if validation_type == ValidationType.OPTOUT else "opted in" condition_message = ( "their amount is zero and that the account has" if validation_type == ValidationType.OPTOUT else "they are valid and that the account has not" ) error_message = ( f"Assets {invalid_asset_ids} cannot be {action}. Ensure that " f"{condition_message} previously opted into them." ) raise ValueError(error_message) @deprecated( "Use TransactionComposer.add_asset_opt_in() or AlgorandClient.asset.bulk_opt_in() instead. " "Example: composer.add_asset_opt_in(AssetOptInParams(sender=account.address, asset_id=123))" ) def opt_in(algod_client: "AlgodClient", account: Account, asset_ids: list[int]) -> dict[int, str]: """ Opt-in to a list of assets on the Algorand blockchain. Before an account can receive a specific asset, it must `opt-in` to receive it. An opt-in transaction places an asset holding of 0 into the account and increases its minimum balance by [100,000 microAlgos](https://developer.algorand.org/docs/get-details/asa/#assets-overview). :param algod_client: An instance of the AlgodClient class from the algosdk library. :param account: An instance of the Account class representing the account that wants to opt-in to the assets. :param asset_ids: A list of integers representing the asset IDs to opt-in to. :return: A dictionary where the keys are the asset IDs and the values are the transaction IDs for opting-in to each asset. :rtype: dict[int, str] """ _ensure_account_is_valid(algod_client, account) _ensure_asset_balance_conditions(algod_client, account, asset_ids, ValidationType.OPTIN) suggested_params = algod_client.suggested_params() result = {} for i in range(0, len(asset_ids), TX_GROUP_LIMIT): atc = AtomicTransactionComposer() chunk = asset_ids[i : i + TX_GROUP_LIMIT] for asset_id in chunk: asset = algod_client.asset_info(asset_id) xfer_txn = AssetTransferTxn( sp=suggested_params, sender=account.address, receiver=account.address, close_assets_to=None, revocation_target=None, amt=0, note=f"opt in asset id ${asset_id}", index=asset["index"], # type: ignore # noqa: PGH003 rekey_to=None, ) transaction_with_signer = TransactionWithSigner( txn=xfer_txn, signer=account.signer, ) atc.add_transaction(transaction_with_signer) atc.execute(algod_client, 4) for index, asset_id in enumerate(chunk): result[asset_id] = atc.tx_ids[index] return result @deprecated( "Use TransactionComposer.add_asset_opt_out() or AlgorandClient.asset.bulk_opt_out() instead. " "Example: composer.add_asset_opt_out(AssetOptOutParams(sender=account.address, asset_id=123, creator=creator_address))" ) def opt_out(algod_client: "AlgodClient", account: Account, asset_ids: list[int]) -> dict[int, str]: """ Opt out from a list of Algorand Standard Assets (ASAs) by transferring them back to their creators. The account also recovers the Minimum Balance Requirement for the asset (100,000 microAlgos) The `optOut` function manages the opt-out process, permitting the account to discontinue holding a group of assets. It's essential to note that an account can only opt_out of an asset if its balance of that asset is zero. :param AlgodClient algod_client: An instance of the AlgodClient class from the algosdk library. :param Account account: An instance of the Account class representing the account that wants to opt-out from the assets. :param list[int] asset_ids: A list of integers representing the asset IDs to opt-out from. :return dict[int, str]: A dictionary where the keys are the asset IDs and the values are the transaction IDs of the executed transactions. """ _ensure_account_is_valid(algod_client, account) _ensure_asset_balance_conditions(algod_client, account, asset_ids, ValidationType.OPTOUT) suggested_params = algod_client.suggested_params() result = {} for i in range(0, len(asset_ids), TX_GROUP_LIMIT): atc = AtomicTransactionComposer() chunk = asset_ids[i : i + TX_GROUP_LIMIT] for asset_id in chunk: asset = algod_client.asset_info(asset_id) asset_creator = asset["params"]["creator"] # type: ignore # noqa: PGH003 xfer_txn = AssetTransferTxn( sp=suggested_params, sender=account.address, receiver=account.address, close_assets_to=asset_creator, revocation_target=None, amt=0, note=f"opt out asset id ${asset_id}", index=asset["index"], # type: ignore # noqa: PGH003 rekey_to=None, ) transaction_with_signer = TransactionWithSigner( txn=xfer_txn, signer=account.signer, ) atc.add_transaction(transaction_with_signer) atc.execute(algod_client, 4) for index, asset_id in enumerate(chunk): result[asset_id] = atc.tx_ids[index] return result
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/asset.py
Python
MIT
7,594
""" This module contains common classes and methods that are reused in more than one file. """ import base64 import typing from algosdk.source_map import SourceMap from algokit_utils._legacy_v2.deploy import strip_comments if typing.TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient class Program: """A compiled TEAL program :param program: The TEAL program source code :param client: The AlgodClient instance to use for compiling the program """ def __init__(self, program: str, client: "AlgodClient"): self.teal = program result: dict = client.compile(strip_comments(self.teal), source_map=True) self.raw_binary = base64.b64decode(result["result"]) self.binary_hash: str = result["hash"] self.source_map = SourceMap(result["sourcemap"])
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/common.py
Python
MIT
823
import base64 import dataclasses import json import logging import re from collections.abc import Iterable, Mapping, Sequence from typing import TYPE_CHECKING, TypeAlias, TypedDict import algosdk from algosdk import transaction from algosdk.atomic_transaction_composer import AtomicTransactionComposer, TransactionSigner from algosdk.transaction import StateSchema from typing_extensions import deprecated from algokit_utils._legacy_v2.application_specification import ( ApplicationSpecification, CallConfig, MethodConfigDict, OnCompleteActionName, ) from algokit_utils._legacy_v2.models import ( ABIArgsDict, ABIMethod, Account, CreateCallParameters, TransactionResponse, ) from algokit_utils.applications.app_manager import AppManager from algokit_utils.applications.enums import OnSchemaBreak, OnUpdate, OperationPerformed if TYPE_CHECKING: from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient from algokit_utils._legacy_v2.application_client import ApplicationClient __all__ = [ "DELETABLE_TEMPLATE_NAME", "NOTE_PREFIX", "UPDATABLE_TEMPLATE_NAME", "ABICallArgs", "ABICallArgsDict", "ABICreateCallArgs", "ABICreateCallArgsDict", "AppDeployMetaData", "AppLookup", "AppMetaData", "AppReference", "DeployCallArgs", "DeployCallArgsDict", "DeployCreateCallArgs", "DeployCreateCallArgsDict", "DeployResponse", "Deployer", "DeploymentFailedError", "OnSchemaBreak", "OnUpdate", "OperationPerformed", "TemplateValueDict", "TemplateValueMapping", "get_app_id_from_tx_id", "get_creator_apps", "replace_template_variables", ] logger = logging.getLogger(__name__) DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT = 1000 _UPDATABLE = "UPDATABLE" _DELETABLE = "DELETABLE" UPDATABLE_TEMPLATE_NAME = f"TMPL_{_UPDATABLE}" """Template variable name used to control if a smart contract is updatable or not at deployment""" DELETABLE_TEMPLATE_NAME = f"TMPL_{_DELETABLE}" """Template variable name used to control if a smart contract is deletable or not at deployment""" _TOKEN_PATTERN = re.compile(r"TMPL_[A-Z_]+") TemplateValue: TypeAlias = int | str | bytes TemplateValueDict: TypeAlias = dict[str, TemplateValue] """Dictionary of `dict[str, int | str | bytes]` representing template variable names and values""" TemplateValueMapping: TypeAlias = Mapping[str, TemplateValue] """Mapping of `str` to `int | str | bytes` representing template variable names and values""" NOTE_PREFIX = "ALGOKIT_DEPLOYER:j" """ARC-0002 compliant note prefix for algokit_utils deployed applications""" # This prefix is also used to filter for parsable transaction notes in get_creator_apps. # However, as the note is base64 encoded first we need to consider it's base64 representation. # When base64 encoding bytes, 3 bytes are stored in every 4 characters. # So then we don't need to worry about the padding/changing characters of the prefix if it was followed by # additional characters, assert the NOTE_PREFIX length is a multiple of 3. assert len(NOTE_PREFIX) % 3 == 0 class DeploymentFailedError(Exception): pass @dataclasses.dataclass class AppReference: """Information about an Algorand app""" app_id: int app_address: str @dataclasses.dataclass class AppDeployMetaData: """Metadata about an application stored in a transaction note during creation. The note is serialized as JSON and prefixed with {py:data}`NOTE_PREFIX` and stored in the transaction note field as part of {py:meth}`ApplicationClient.deploy` """ name: str version: str deletable: bool | None updatable: bool | None @staticmethod def from_json(value: str) -> "AppDeployMetaData": json_value: dict = json.loads(value) json_value.setdefault("deletable", None) json_value.setdefault("updatable", None) return AppDeployMetaData(**json_value) @classmethod def from_b64(cls: type["AppDeployMetaData"], b64: str) -> "AppDeployMetaData": return cls.decode(base64.b64decode(b64)) @classmethod def decode(cls: type["AppDeployMetaData"], value: bytes) -> "AppDeployMetaData": note = value.decode("utf-8") assert note.startswith(NOTE_PREFIX) return cls.from_json(note[len(NOTE_PREFIX) :]) def encode(self) -> bytes: json_str = json.dumps(self.__dict__) return f"{NOTE_PREFIX}{json_str}".encode() @dataclasses.dataclass class AppMetaData(AppReference, AppDeployMetaData): """Metadata about a deployed app""" created_round: int updated_round: int created_metadata: AppDeployMetaData deleted: bool @dataclasses.dataclass class AppLookup: """Cache of {py:class}`AppMetaData` for a specific `creator` Can be used as an argument to {py:class}`ApplicationClient` to reduce the number of calls when deploying multiple apps or discovering multiple app_ids """ creator: str apps: dict[str, AppMetaData] = dataclasses.field(default_factory=dict) def _sort_by_round(txn: dict) -> tuple[int, int]: confirmed = txn["confirmed-round"] offset = txn["intra-round-offset"] return confirmed, offset def _parse_note(metadata_b64: str | None) -> AppDeployMetaData | None: if not metadata_b64: return None # noinspection PyBroadException try: return AppDeployMetaData.from_b64(metadata_b64) except Exception: return None @deprecated("Use algorand.appDeployer.get_creator_apps_by_name() instead. ") def get_creator_apps(indexer: "IndexerClient", creator_account: Account | str) -> AppLookup: """Returns a mapping of Application names to {py:class}`AppMetaData` for all Applications created by specified creator that have a transaction note containing {py:class}`AppDeployMetaData` """ apps: dict[str, AppMetaData] = {} creator_address = creator_account if isinstance(creator_account, str) else creator_account.address token = None # TODO: paginated indexer call instead of N + 1 calls while True: response = indexer.lookup_account_application_by_creator( creator_address, limit=DEFAULT_INDEXER_MAX_API_RESOURCES_PER_ACCOUNT, next_page=token ) if "message" in response: # an error occurred raise Exception(f"Error querying applications for {creator_address}: {response}") for app in response["applications"]: app_id = app["id"] app_created_at_round = app["created-at-round"] app_deleted = app.get("deleted", False) search_transactions_response = indexer.search_transactions( min_round=app_created_at_round, txn_type="appl", application_id=app_id, address=creator_address, address_role="sender", note_prefix=NOTE_PREFIX.encode("utf-8"), ) transactions: list[dict] = search_transactions_response["transactions"] if not transactions: continue created_transaction = next( t for t in transactions if t["application-transaction"]["application-id"] == 0 and t["sender"] == creator_address ) transactions.sort(key=_sort_by_round, reverse=True) latest_transaction = transactions[0] app_updated_at_round = latest_transaction["confirmed-round"] create_metadata = _parse_note(created_transaction.get("note")) update_metadata = _parse_note(latest_transaction.get("note")) if create_metadata and create_metadata.name: apps[create_metadata.name] = AppMetaData( app_id=app_id, app_address=algosdk.logic.get_application_address(app_id), created_metadata=create_metadata, created_round=app_created_at_round, **(update_metadata or create_metadata).__dict__, updated_round=app_updated_at_round, deleted=app_deleted, ) token = response.get("next-token") if not token: break return AppLookup(creator_address, apps) def _state_schema(schema: dict[str, int]) -> StateSchema: return StateSchema(schema.get("num-uint", 0), schema.get("num-byte-slice", 0)) def _describe_schema_breaks(prefix: str, from_schema: StateSchema, to_schema: StateSchema) -> Iterable[str]: if to_schema.num_uints > from_schema.num_uints: yield f"{prefix} uints increased from {from_schema.num_uints} to {to_schema.num_uints}" if to_schema.num_byte_slices > from_schema.num_byte_slices: yield f"{prefix} byte slices increased from {from_schema.num_byte_slices} to {to_schema.num_byte_slices}" @dataclasses.dataclass(kw_only=True) class AppChanges: app_updated: bool schema_breaking_change: bool schema_change_description: str | None @deprecated("The algokit_utils.AppDeployer now handles checking for app changes implicitly as part of `deploy` method") def check_for_app_changes( algod_client: "AlgodClient", *, new_approval: bytes, new_clear: bytes, new_global_schema: StateSchema, new_local_schema: StateSchema, app_id: int, ) -> AppChanges: application_info = algod_client.application_info(app_id) assert isinstance(application_info, dict) application_create_params = application_info["params"] current_approval = base64.b64decode(application_create_params["approval-program"]) current_clear = base64.b64decode(application_create_params["clear-state-program"]) current_global_schema = _state_schema(application_create_params["global-state-schema"]) current_local_schema = _state_schema(application_create_params["local-state-schema"]) app_updated = current_approval != new_approval or current_clear != new_clear schema_changes: list[str] = [] schema_changes.extend(_describe_schema_breaks("Global", current_global_schema, new_global_schema)) schema_changes.extend(_describe_schema_breaks("Local", current_local_schema, new_local_schema)) return AppChanges( app_updated=app_updated, schema_breaking_change=bool(schema_changes), schema_change_description=", ".join(schema_changes), ) def _is_valid_token_character(char: str) -> bool: return char.isalnum() or char == "_" def add_deploy_template_variables( template_values: TemplateValueDict, allow_update: bool | None, allow_delete: bool | None ) -> None: if allow_update is not None: template_values[_UPDATABLE] = int(allow_update) if allow_delete is not None: template_values[_DELETABLE] = int(allow_delete) def _find_unquoted_string(line: str, token: str, start: int = 0, end: int = -1) -> int | None: """Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned. Returns None if not found""" if end < 0: end = len(line) idx = start in_quotes = in_base64 = False while idx < end: current_char = line[idx] match current_char: # enter base64 case " " | "(" if not in_quotes and _last_token_base64(line, idx): in_base64 = True # exit base64 case " " | ")" if not in_quotes and in_base64: in_base64 = False # escaped char case "\\" if in_quotes: # skip next character idx += 1 # quote boundary case '"': in_quotes = not in_quotes # can test for match case _ if not in_quotes and not in_base64 and line.startswith(token, idx): # only match if not in quotes and string matches return idx idx += 1 return None def _last_token_base64(line: str, idx: int) -> bool: try: *_, last = line[:idx].split() except ValueError: return False return last in ("base64", "b64") def _find_template_token(line: str, token: str, start: int = 0, end: int = -1) -> int | None: """Find the first template token within a line of TEAL. Only matches outside of quotes are returned. Only full token matches are returned, i.e. TMPL_STR will not match against TMPL_STRING Returns None if not found""" if end < 0: end = len(line) idx = start while idx < end: token_idx = _find_unquoted_string(line, token, idx, end) if token_idx is None: break trailing_idx = token_idx + len(token) if (token_idx == 0 or not _is_valid_token_character(line[token_idx - 1])) and ( # word boundary at start trailing_idx >= len(line) or not _is_valid_token_character(line[trailing_idx]) # word boundary at end ): return token_idx idx = trailing_idx return None def _strip_comment(line: str) -> str: comment_idx = _find_unquoted_string(line, "//") if comment_idx is None: return line return line[:comment_idx].rstrip() def strip_comments(program: str) -> str: return "\n".join(_strip_comment(line) for line in program.splitlines()) def _has_token(program_without_comments: str, token: str) -> bool: for line in program_without_comments.splitlines(): token_idx = _find_template_token(line, token) if token_idx is not None: return True return False def _find_tokens(stripped_approval_program: str) -> list[str]: return _TOKEN_PATTERN.findall(stripped_approval_program) def check_template_variables(approval_program: str, template_values: TemplateValueDict) -> None: approval_program = strip_comments(approval_program) if _has_token(approval_program, UPDATABLE_TEMPLATE_NAME) and _UPDATABLE not in template_values: raise DeploymentFailedError( "allow_update must be specified if deploy time configuration of update is being used" ) if _has_token(approval_program, DELETABLE_TEMPLATE_NAME) and _DELETABLE not in template_values: raise DeploymentFailedError( "allow_delete must be specified if deploy time configuration of delete is being used" ) all_tokens = _find_tokens(approval_program) missing_values = [token for token in all_tokens if token[len("TMPL_") :] not in template_values] if missing_values: raise DeploymentFailedError(f"The following template values were not provided: {', '.join(missing_values)}") for template_variable_name in template_values: tmpl_variable = f"TMPL_{template_variable_name}" if not _has_token(approval_program, tmpl_variable): if template_variable_name == _UPDATABLE: raise DeploymentFailedError( "allow_update must only be specified if deploy time configuration of update is being used" ) if template_variable_name == _DELETABLE: raise DeploymentFailedError( "allow_delete must only be specified if deploy time configuration of delete is being used" ) logger.warning(f"{tmpl_variable} not found in approval program, but variable was provided") @deprecated("Use `AppManager.replace_template_variables` instead") def replace_template_variables(program: str, template_values: TemplateValueMapping) -> str: """Replaces `TMPL_*` variables in `program` with `template_values` ```{note} `template_values` keys should *NOT* be prefixed with `TMPL_` ``` """ return AppManager.replace_template_variables(program, template_values) def has_template_vars(app_spec: ApplicationSpecification) -> bool: return "TMPL_" in strip_comments(app_spec.approval_program) or "TMPL_" in strip_comments(app_spec.clear_program) def get_deploy_control( app_spec: ApplicationSpecification, template_var: str, on_complete: transaction.OnComplete ) -> bool | None: if template_var not in strip_comments(app_spec.approval_program): return None return get_call_config(app_spec.bare_call_config, on_complete) != CallConfig.NEVER or any( h for h in app_spec.hints.values() if get_call_config(h.call_config, on_complete) != CallConfig.NEVER ) def get_call_config(method_config: MethodConfigDict, on_complete: transaction.OnComplete) -> CallConfig: def get(key: OnCompleteActionName) -> CallConfig: return method_config.get(key, CallConfig.NEVER) match on_complete: case transaction.OnComplete.NoOpOC: return get("no_op") case transaction.OnComplete.UpdateApplicationOC: return get("update_application") case transaction.OnComplete.DeleteApplicationOC: return get("delete_application") case transaction.OnComplete.OptInOC: return get("opt_in") case transaction.OnComplete.CloseOutOC: return get("close_out") case transaction.OnComplete.ClearStateOC: return get("clear_state") @dataclasses.dataclass(kw_only=True) class DeployResponse: """Describes the action taken during deployment, related transactions and the {py:class}`AppMetaData`""" app: AppMetaData create_response: TransactionResponse | None = None delete_response: TransactionResponse | None = None update_response: TransactionResponse | None = None action_taken: OperationPerformed = OperationPerformed.Nothing @dataclasses.dataclass(kw_only=True) class DeployCallArgs: """Parameters used to update or delete an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" suggested_params: transaction.SuggestedParams | None = None lease: bytes | str | None = None accounts: list[str] | None = None foreign_apps: list[int] | None = None foreign_assets: list[int] | None = None boxes: Sequence[tuple[int, bytes | bytearray | str | int]] | None = None rekey_to: str | None = None @dataclasses.dataclass(kw_only=True) class ABICall: method: ABIMethod | bool | None = None args: ABIArgsDict = dataclasses.field(default_factory=dict) @dataclasses.dataclass(kw_only=True) class DeployCreateCallArgs(DeployCallArgs): """Parameters used to create an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" extra_pages: int | None = None on_complete: transaction.OnComplete | None = None @dataclasses.dataclass(kw_only=True) class ABICallArgs(DeployCallArgs, ABICall): """ABI Parameters used to update or delete an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" @dataclasses.dataclass(kw_only=True) class ABICreateCallArgs(DeployCreateCallArgs, ABICall): """ABI Parameters used to create an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" class DeployCallArgsDict(TypedDict, total=False): """Parameters used to update or delete an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" suggested_params: transaction.SuggestedParams lease: bytes | str accounts: list[str] foreign_apps: list[int] foreign_assets: list[int] boxes: Sequence[tuple[int, bytes | bytearray | str | int]] rekey_to: str class ABICallArgsDict(DeployCallArgsDict, TypedDict, total=False): """ABI Parameters used to update or delete an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" method: ABIMethod | bool args: ABIArgsDict class DeployCreateCallArgsDict(DeployCallArgsDict, TypedDict, total=False): """Parameters used to create an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" extra_pages: int | None on_complete: transaction.OnComplete class ABICreateCallArgsDict(DeployCreateCallArgsDict, TypedDict, total=False): """ABI Parameters used to create an application when calling {py:meth}`~algokit_utils.ApplicationClient.deploy`""" method: ABIMethod | bool args: ABIArgsDict @dataclasses.dataclass(kw_only=True) class Deployer: app_client: "ApplicationClient" creator: str signer: TransactionSigner sender: str existing_app_metadata_or_reference: AppReference | AppMetaData new_app_metadata: AppDeployMetaData on_update: OnUpdate on_schema_break: OnSchemaBreak create_args: ABICreateCallArgs | ABICreateCallArgsDict | DeployCreateCallArgs | None update_args: ABICallArgs | ABICallArgsDict | DeployCallArgs | None delete_args: ABICallArgs | ABICallArgsDict | DeployCallArgs | None def deploy(self) -> DeployResponse: """Ensures app associated with app client's creator is present and up to date""" assert self.app_client.approval assert self.app_client.clear if self.existing_app_metadata_or_reference.app_id == 0: logger.info(f"{self.new_app_metadata.name} not found in {self.creator} account, deploying app.") return self._create_app() assert isinstance(self.existing_app_metadata_or_reference, AppMetaData) logger.debug( f"{self.existing_app_metadata_or_reference.name} found in {self.creator} account, " f"with app id {self.existing_app_metadata_or_reference.app_id}, " f"version={self.existing_app_metadata_or_reference.version}." ) app_changes = check_for_app_changes( self.app_client.algod_client, new_approval=self.app_client.approval.raw_binary, new_clear=self.app_client.clear.raw_binary, new_global_schema=self.app_client.app_spec.global_state_schema, new_local_schema=self.app_client.app_spec.local_state_schema, app_id=self.existing_app_metadata_or_reference.app_id, ) if app_changes.schema_breaking_change: logger.warning(f"Detected a breaking app schema change: {app_changes.schema_change_description}") return self._deploy_breaking_change() if app_changes.app_updated: logger.info(f"Detected a TEAL update in app id {self.existing_app_metadata_or_reference.app_id}") return self._deploy_update() logger.info("No detected changes in app, nothing to do.") return DeployResponse(app=self.existing_app_metadata_or_reference) def _deploy_breaking_change(self) -> DeployResponse: assert isinstance(self.existing_app_metadata_or_reference, AppMetaData) if self.on_schema_break == OnSchemaBreak.Fail: raise DeploymentFailedError( "Schema break detected and on_schema_break=OnSchemaBreak.Fail, stopping deployment. " "If you want to try deleting and recreating the app then " "re-run with on_schema_break=OnSchemaBreak.ReplaceApp" ) if self.on_schema_break == OnSchemaBreak.AppendApp: logger.info("Schema break detected and on_schema_break=AppendApp, will attempt to create new app") return self._create_app() if self.existing_app_metadata_or_reference.deletable: logger.info( "App is deletable and on_schema_break=ReplaceApp, will attempt to create new app and delete old app" ) elif self.existing_app_metadata_or_reference.deletable is False: logger.warning( "App is not deletable but on_schema_break=ReplaceApp, " "will attempt to delete app, delete will most likely fail" ) else: logger.warning( "Cannot determine if App is deletable but on_schema_break=ReplaceApp, will attempt to delete app" ) return self._create_and_delete_app() def _deploy_update(self) -> DeployResponse: assert isinstance(self.existing_app_metadata_or_reference, AppMetaData) if self.on_update == OnUpdate.Fail: raise DeploymentFailedError( "Update detected and on_update=Fail, stopping deployment. " "If you want to try updating the app then re-run with on_update=UpdateApp" ) if self.on_update == OnUpdate.AppendApp: logger.info("Update detected and on_update=AppendApp, will attempt to create new app") return self._create_app() elif self.existing_app_metadata_or_reference.updatable and self.on_update == OnUpdate.UpdateApp: logger.info("App is updatable and on_update=UpdateApp, will update app") return self._update_app() elif self.existing_app_metadata_or_reference.updatable and self.on_update == OnUpdate.ReplaceApp: logger.warning( "App is updatable but on_update=ReplaceApp, will attempt to create new app and delete old app" ) return self._create_and_delete_app() elif self.on_update == OnUpdate.ReplaceApp: if self.existing_app_metadata_or_reference.updatable is False: logger.warning( "App is not updatable and on_update=ReplaceApp, " "will attempt to create new app and delete old app" ) else: logger.warning( "Cannot determine if App is updatable and on_update=ReplaceApp, " "will attempt to create new app and delete old app" ) return self._create_and_delete_app() else: if self.existing_app_metadata_or_reference.updatable is False: logger.warning( "App is not updatable but on_update=UpdateApp, " "will attempt to update app, update will most likely fail" ) else: logger.warning( "Cannot determine if App is updatable and on_update=UpdateApp, will attempt to update app" ) return self._update_app() def _create_app(self) -> DeployResponse: assert self.app_client.existing_deployments method, abi_args, parameters = _convert_deploy_args( self.create_args, self.new_app_metadata, self.signer, self.sender ) create_response = self.app_client.create( method, parameters, **abi_args, ) logger.info( f"{self.new_app_metadata.name} ({self.new_app_metadata.version}) deployed successfully, " f"with app id {self.app_client.app_id}." ) assert create_response.confirmed_round is not None app_metadata = _create_metadata(self.new_app_metadata, self.app_client.app_id, create_response.confirmed_round) self.app_client.existing_deployments.apps[self.new_app_metadata.name] = app_metadata return DeployResponse(app=app_metadata, create_response=create_response, action_taken=OperationPerformed.Create) def _create_and_delete_app(self) -> DeployResponse: assert self.app_client.existing_deployments assert isinstance(self.existing_app_metadata_or_reference, AppMetaData) logger.info( f"Replacing {self.existing_app_metadata_or_reference.name} " f"({self.existing_app_metadata_or_reference.version}) with " f"{self.new_app_metadata.name} ({self.new_app_metadata.version}) in {self.creator} account." ) atc = AtomicTransactionComposer() create_method, create_abi_args, create_parameters = _convert_deploy_args( self.create_args, self.new_app_metadata, self.signer, self.sender ) self.app_client.compose_create( atc, create_method, create_parameters, **create_abi_args, ) create_txn_index = len(atc.txn_list) - 1 delete_method, delete_abi_args, delete_parameters = _convert_deploy_args( self.delete_args, self.new_app_metadata, self.signer, self.sender ) self.app_client.compose_delete( atc, delete_method, delete_parameters, **delete_abi_args, ) delete_txn_index = len(atc.txn_list) - 1 create_delete_response = self.app_client.execute_atc(atc) create_response = TransactionResponse.from_atr(create_delete_response, create_txn_index) delete_response = TransactionResponse.from_atr(create_delete_response, delete_txn_index) self.app_client.app_id = get_app_id_from_tx_id(self.app_client.algod_client, create_response.tx_id) logger.info( f"{self.new_app_metadata.name} ({self.new_app_metadata.version}) deployed successfully, " f"with app id {self.app_client.app_id}." ) logger.info( f"{self.existing_app_metadata_or_reference.name} " f"({self.existing_app_metadata_or_reference.version}) with app id " f"{self.existing_app_metadata_or_reference.app_id}, deleted successfully." ) app_metadata = _create_metadata( self.new_app_metadata, self.app_client.app_id, create_delete_response.confirmed_round ) self.app_client.existing_deployments.apps[self.new_app_metadata.name] = app_metadata return DeployResponse( app=app_metadata, create_response=create_response, delete_response=delete_response, action_taken=OperationPerformed.Replace, ) def _update_app(self) -> DeployResponse: assert self.app_client.existing_deployments assert isinstance(self.existing_app_metadata_or_reference, AppMetaData) logger.info( f"Updating {self.existing_app_metadata_or_reference.name} to {self.new_app_metadata.version} in " f"{self.creator} account, with app id {self.existing_app_metadata_or_reference.app_id}" ) method, abi_args, parameters = _convert_deploy_args( self.update_args, self.new_app_metadata, self.signer, self.sender ) update_response = self.app_client.update( method, parameters, **abi_args, ) app_metadata = _create_metadata( self.new_app_metadata, self.app_client.app_id, self.existing_app_metadata_or_reference.created_round, updated_round=update_response.confirmed_round, original_metadata=self.existing_app_metadata_or_reference.created_metadata, ) self.app_client.existing_deployments.apps[self.new_app_metadata.name] = app_metadata return DeployResponse(app=app_metadata, update_response=update_response, action_taken=OperationPerformed.Update) def _create_metadata( app_spec_note: AppDeployMetaData, app_id: int, created_round: int, updated_round: int | None = None, original_metadata: AppDeployMetaData | None = None, ) -> AppMetaData: return AppMetaData( app_id=app_id, app_address=algosdk.logic.get_application_address(app_id), created_metadata=original_metadata or app_spec_note, created_round=created_round, updated_round=updated_round or created_round, name=app_spec_note.name, version=app_spec_note.version, deletable=app_spec_note.deletable, updatable=app_spec_note.updatable, deleted=False, ) def _convert_deploy_args( _args: DeployCallArgs | DeployCallArgsDict | None, note: AppDeployMetaData, signer: TransactionSigner | None, sender: str | None, ) -> tuple[ABIMethod | bool | None, ABIArgsDict, CreateCallParameters]: args = _args.__dict__ if isinstance(_args, DeployCallArgs) else dict(_args or {}) # return most derived type, unused parameters are ignored parameters = CreateCallParameters( note=note.encode(), signer=signer, sender=sender, suggested_params=args.get("suggested_params"), lease=args.get("lease"), accounts=args.get("accounts"), foreign_assets=args.get("foreign_assets"), foreign_apps=args.get("foreign_apps"), boxes=args.get("boxes"), rekey_to=args.get("rekey_to"), extra_pages=args.get("extra_pages"), on_complete=args.get("on_complete"), ) return args.get("method"), args.get("args") or {}, parameters def get_app_id_from_tx_id(algod_client: "AlgodClient", tx_id: str) -> int: """Finds the app_id for provided transaction id""" result = algod_client.pending_transaction_info(tx_id) assert isinstance(result, dict) app_id = result["application-index"] assert isinstance(app_id, int) return app_id
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/deploy.py
Python
MIT
32,777
from typing_extensions import deprecated from algokit_utils.errors.logic_error import LogicError as NewLogicError from algokit_utils.errors.logic_error import parse_logic_error __all__ = [ "LogicError", "parse_logic_error", ] @deprecated("Use algokit_utils.models.error.LogicError instead") class LogicError(NewLogicError): pass
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/logic_error.py
Python
MIT
345
import dataclasses from collections.abc import Sequence from typing import Any, Generic, Protocol, TypeAlias, TypedDict, TypeVar from algosdk import transaction from algosdk.abi import Method from algosdk.atomic_transaction_composer import ( AtomicTransactionResponse, SimulateAtomicTransactionResponse, TransactionSigner, ) from typing_extensions import deprecated from algokit_utils.models.account import SigningAccount from algokit_utils.models.simulate import SimulationTrace # Imports from latest sdk version that rely on models previously used in legacy v2 (but moved to root models/*) __all__ = [ "ABIArgsDict", "ABIMethod", "ABITransactionResponse", "Account", "CreateCallParameters", "CreateCallParametersDict", "CreateTransactionParameters", "OnCompleteCallParameters", "OnCompleteCallParametersDict", "SimulationTrace", "TransactionParameters", "TransactionResponse", ] ReturnType = TypeVar("ReturnType") @deprecated("Use 'SigningAccount' instead") @dataclasses.dataclass(kw_only=True) class Account(SigningAccount): """An account that can be used to sign transactions""" @dataclasses.dataclass(kw_only=True) class TransactionResponse: """Response for a non ABI call""" tx_id: str """Transaction Id""" confirmed_round: int | None """Round transaction was confirmed, `None` if call was a from a dry-run""" @staticmethod def from_atr( result: AtomicTransactionResponse | SimulateAtomicTransactionResponse, transaction_index: int = -1 ) -> "TransactionResponse": """Returns either an ABITransactionResponse or a TransactionResponse based on the type of the transaction referred to by transaction_index :param AtomicTransactionResponse result: Result containing one or more transactions :param int transaction_index: Which transaction in the result to return, defaults to -1 (the last transaction) """ tx_id = result.tx_ids[transaction_index] abi_result = next((r for r in result.abi_results if r.tx_id == tx_id), None) confirmed_round = None if isinstance(result, SimulateAtomicTransactionResponse) else result.confirmed_round if abi_result: return ABITransactionResponse( tx_id=tx_id, raw_value=abi_result.raw_value, return_value=abi_result.return_value, decode_error=abi_result.decode_error, tx_info=abi_result.tx_info, method=abi_result.method, confirmed_round=confirmed_round, ) else: return TransactionResponse( tx_id=tx_id, confirmed_round=confirmed_round, ) @dataclasses.dataclass(kw_only=True) class ABITransactionResponse(TransactionResponse, Generic[ReturnType]): """Response for an ABI call""" raw_value: bytes """The raw response before ABI decoding""" return_value: ReturnType """Decoded ABI result""" decode_error: Exception | None """Details of error that occurred when attempting to decode raw_value""" tx_info: dict """Details of transaction""" method: Method """ABI method used to make call""" ABIArgType = Any ABIArgsDict = dict[str, ABIArgType] class ABIReturnSubroutine(Protocol): def method_spec(self) -> Method: ... ABIMethod: TypeAlias = ABIReturnSubroutine | Method | str @dataclasses.dataclass(kw_only=True) class TransactionParameters: """Additional parameters that can be included in a transaction""" signer: TransactionSigner | None = None """Signer to use when signing this transaction""" sender: str | None = None """Sender of this transaction""" suggested_params: transaction.SuggestedParams | None = None """SuggestedParams to use for this transaction""" note: bytes | str | None = None """Note for this transaction""" lease: bytes | str | None = None """Lease value for this transaction""" boxes: Sequence[tuple[int, bytes | bytearray | str | int]] | None = None """Box references to include in transaction. A sequence of (app id, box key) tuples""" accounts: list[str] | None = None """Accounts to include in transaction""" foreign_apps: list[int] | None = None """List of foreign apps (by app id) to include in transaction""" foreign_assets: list[int] | None = None """List of foreign assets (by asset id) to include in transaction""" rekey_to: str | None = None """Address to rekey to""" # CreateTransactionParameters is used by algokit-client-generator clients @dataclasses.dataclass(kw_only=True) class CreateTransactionParameters(TransactionParameters): """Additional parameters that can be included in a transaction when calling a create method""" extra_pages: int | None = None @dataclasses.dataclass(kw_only=True) class OnCompleteCallParameters(TransactionParameters): """Additional parameters that can be included in a transaction when using the ApplicationClient.call/compose_call methods""" on_complete: transaction.OnComplete | None = None @dataclasses.dataclass(kw_only=True) class CreateCallParameters(OnCompleteCallParameters): """Additional parameters that can be included in a transaction when using the ApplicationClient.create/compose_create methods""" extra_pages: int | None = None class TransactionParametersDict(TypedDict, total=False): """Additional parameters that can be included in a transaction""" signer: TransactionSigner """Signer to use when signing this transaction""" sender: str """Sender of this transaction""" suggested_params: transaction.SuggestedParams """SuggestedParams to use for this transaction""" note: bytes | str """Note for this transaction""" lease: bytes | str """Lease value for this transaction""" boxes: Sequence[tuple[int, bytes | bytearray | str | int]] """Box references to include in transaction. A sequence of (app id, box key) tuples""" accounts: list[str] """Accounts to include in transaction""" foreign_apps: list[int] """List of foreign apps (by app id) to include in transaction""" foreign_assets: list[int] """List of foreign assets (by asset id) to include in transaction""" rekey_to: str """Address to rekey to""" class OnCompleteCallParametersDict(TransactionParametersDict, total=False): """Additional parameters that can be included in a transaction when using the ApplicationClient.call/compose_call methods""" on_complete: transaction.OnComplete class CreateCallParametersDict(OnCompleteCallParametersDict, total=False): """Additional parameters that can be included in a transaction when using the ApplicationClient.create/compose_create methods""" extra_pages: int # Pre 1.3.1 backwards compatibility @deprecated("Use TransactionParameters instead") class RawTransactionParameters(TransactionParameters): """Deprecated, use TransactionParameters instead""" @deprecated("Use TransactionParameters instead") class CommonCallParameters(TransactionParameters): """Deprecated, use TransactionParameters instead""" @deprecated("Use TransactionParametersDict instead") class CommonCallParametersDict(TransactionParametersDict): """Deprecated, use TransactionParametersDict instead"""
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/models.py
Python
MIT
7,403
import dataclasses import os from typing import Literal from urllib import parse from algosdk.kmd import KMDClient from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient from typing_extensions import deprecated __all__ = [ "AlgoClientConfig", "AlgoClientConfigs", "get_algod_client", "get_algonode_config", "get_default_localnet_config", "get_indexer_client", "get_kmd_client", "get_kmd_client_from_algod_client", "is_localnet", "is_mainnet", "is_testnet", ] @dataclasses.dataclass class AlgoClientConfig: """Connection details for connecting to an {py:class}`algosdk.v2client.algod.AlgodClient` or {py:class}`algosdk.v2client.indexer.IndexerClient`""" server: str """URL for the service e.g. `http://localhost:4001` or `https://testnet-api.algonode.cloud`""" token: str """API Token to authenticate with the service""" @dataclasses.dataclass class AlgoClientConfigs: algod_config: AlgoClientConfig indexer_config: AlgoClientConfig kmd_config: AlgoClientConfig | None @deprecated("Use AlgorandClient.client.algod") def get_default_localnet_config(config: Literal["algod", "indexer", "kmd"]) -> AlgoClientConfig: """Returns the client configuration to point to the default LocalNet""" port = {"algod": 4001, "indexer": 8980, "kmd": 4002}[config] return AlgoClientConfig(server=f"http://localhost:{port}", token="a" * 64) @deprecated("Use AlgorandClient.testnet() or AlgorandClient.mainnet() instead") def get_algonode_config( network: Literal["testnet", "mainnet"], config: Literal["algod", "indexer"], token: str ) -> AlgoClientConfig: client = "api" if config == "algod" else "idx" return AlgoClientConfig( server=f"https://{network}-{client}.algonode.cloud", token=token, ) @deprecated("Use AlgorandClient.from_environment() instead.") def get_algod_client(config: AlgoClientConfig | None = None) -> AlgodClient: """Returns an {py:class}`algosdk.v2client.algod.AlgodClient` from `config` or environment If no configuration provided will use environment variables `ALGOD_SERVER`, `ALGOD_PORT` and `ALGOD_TOKEN`""" config = config or _get_config_from_environment("ALGOD") headers = {"X-Algo-API-Token": config.token} return AlgodClient(config.token, config.server, headers) @deprecated("Use AlgorandClient.default_localnet().kmd instead") def get_kmd_client(config: AlgoClientConfig | None = None) -> KMDClient: """Returns an {py:class}`algosdk.kmd.KMDClient` from `config` or environment If no configuration provided will use environment variables `KMD_SERVER`, `KMD_PORT` and `KMD_TOKEN`""" config = config or _get_config_from_environment("KMD") return KMDClient(config.token, config.server) @deprecated("Use AlgorandClient.client.from_environment().indexer instead") def get_indexer_client(config: AlgoClientConfig | None = None) -> IndexerClient: """Returns an {py:class}`algosdk.v2client.indexer.IndexerClient` from `config` or environment. If no configuration provided will use environment variables `INDEXER_SERVER`, `INDEXER_PORT` and `INDEXER_TOKEN`""" config = config or _get_config_from_environment("INDEXER") headers = {"X-Indexer-API-Token": config.token} return IndexerClient(config.token, config.server, headers) @deprecated("Use AlgorandClient.client.is_localnet() instead") def is_localnet(client: AlgodClient) -> bool: """Returns True if client genesis is `devnet-v1` or `sandnet-v1`""" params = client.suggested_params() return params.gen in ["devnet-v1", "sandnet-v1", "dockernet-v1"] @deprecated("Use AlgorandClient.client.is_mainnet() instead") def is_mainnet(client: AlgodClient) -> bool: """Returns True if client genesis is `mainnet-v1`""" params = client.suggested_params() return params.gen in ["mainnet-v1.0", "mainnet-v1", "mainnet"] @deprecated("Use AlgorandClient.client.is_testnet() instead") def is_testnet(client: AlgodClient) -> bool: """Returns True if client genesis is `testnet-v1`""" params = client.suggested_params() return params.gen in ["testnet-v1.0", "testnet-v1", "testnet"] @deprecated("Use AlgorandClient.default_localnet().kmd instead") def get_kmd_client_from_algod_client(client: AlgodClient) -> KMDClient: """Returns an {py:class}`algosdk.kmd.KMDClient` from supplied `client` Will use the same address as provided `client` but on port specified by `KMD_PORT` environment variable, or 4002 by default""" # We can only use Kmd on the LocalNet otherwise it's not exposed so this makes some assumptions # (e.g. same token and server as algod and port 4002 by default) port = os.getenv("KMD_PORT", "4002") server = _replace_kmd_port(client.algod_address, port) return KMDClient(client.algod_token, server) def _replace_kmd_port(address: str, port: str) -> str: parsed_algod = parse.urlparse(address) kmd_host = parsed_algod.netloc.split(":", maxsplit=1)[0] + f":{port}" kmd_parsed = parsed_algod._replace(netloc=kmd_host) return parse.urlunparse(kmd_parsed) def _get_config_from_environment(environment_prefix: str) -> AlgoClientConfig: server = os.getenv(f"{environment_prefix}_SERVER") if server is None: raise Exception(f"Server environment variable not set: {environment_prefix}_SERVER") port = os.getenv(f"{environment_prefix}_PORT") if port: parsed = parse.urlparse(server) server = parsed._replace(netloc=f"{parsed.hostname}:{port}").geturl() return AlgoClientConfig(server, os.getenv(f"{environment_prefix}_TOKEN", ""))
algorandfoundation/algokit-utils-py
src/algokit_utils/_legacy_v2/network_clients.py
Python
MIT
5,660
import warnings warnings.warn( """The legacy v2 account module is deprecated and will be removed in a future version. Use `SigningAccount` abstraction from `algokit_utils.models` instead or classes compliant with `TransactionSignerAccountProtocol` obtained from `AccountManager`. """, DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.account import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/account.py
Python
MIT
410
from algokit_utils.accounts.account_manager import * # noqa: F403 from algokit_utils.accounts.kmd_account_manager import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/accounts/__init__.py
Python
MIT
138
import os from collections.abc import Callable from dataclasses import dataclass from typing import Any import algosdk from algosdk import mnemonic from algosdk.atomic_transaction_composer import TransactionSigner from algosdk.mnemonic import to_private_key from algosdk.transaction import LogicSigAccount as AlgosdkLogicSigAccount from algosdk.transaction import SuggestedParams from typing_extensions import Self from algokit_utils.accounts.kmd_account_manager import KmdAccountManager from algokit_utils.clients.client_manager import ClientManager from algokit_utils.clients.dispenser_api_client import DispenserAssetName, TestNetDispenserApiClient from algokit_utils.config import config from algokit_utils.models.account import ( DISPENSER_ACCOUNT_NAME, LogicSigAccount, MultiSigAccount, MultisigMetadata, SigningAccount, TransactionSignerAccount, ) from algokit_utils.models.amount import AlgoAmount from algokit_utils.models.transaction import SendParams from algokit_utils.protocols.account import TransactionSignerAccountProtocol from algokit_utils.transactions.transaction_composer import ( PaymentParams, SendAtomicTransactionComposerResults, TransactionComposer, ) from algokit_utils.transactions.transaction_sender import SendSingleTransactionResult logger = config.logger __all__ = [ "AccountInformation", "AccountManager", "EnsureFundedFromTestnetDispenserApiResult", "EnsureFundedResult", ] @dataclass(frozen=True, kw_only=True) class _CommonEnsureFundedParams: """ Common parameters for ensure funded responses. """ transaction_id: str amount_funded: AlgoAmount @dataclass(frozen=True, kw_only=True) class EnsureFundedResult(SendSingleTransactionResult, _CommonEnsureFundedParams): """ Result from performing an ensure funded call. """ @dataclass(frozen=True, kw_only=True) class EnsureFundedFromTestnetDispenserApiResult(_CommonEnsureFundedParams): """ Result from performing an ensure funded call using TestNet dispenser API. """ @dataclass(frozen=True, kw_only=True) class AccountInformation: """ Information about an Algorand account's current status, balance and other properties. See `https://developer.algorand.org/docs/rest-apis/algod/#account` for detailed field descriptions. :ivar str address: The account's address :ivar AlgoAmount amount: The account's current balance :ivar AlgoAmount amount_without_pending_rewards: The account's balance without the pending rewards :ivar AlgoAmount min_balance: The account's minimum required balance :ivar AlgoAmount pending_rewards: The amount of pending rewards :ivar AlgoAmount rewards: The amount of rewards earned :ivar int round: The round for which this information is relevant :ivar str status: The account's status (e.g., 'Offline', 'Online') :ivar int|None total_apps_opted_in: Number of applications this account has opted into :ivar int|None total_assets_opted_in: Number of assets this account has opted into :ivar int|None total_box_bytes: Total number of box bytes used by this account :ivar int|None total_boxes: Total number of boxes used by this account :ivar int|None total_created_apps: Number of applications created by this account :ivar int|None total_created_assets: Number of assets created by this account :ivar list[dict]|None apps_local_state: Local state of applications this account has opted into :ivar int|None apps_total_extra_pages: Number of extra pages allocated to applications :ivar dict|None apps_total_schema: Total schema for all applications :ivar list[dict]|None assets: Assets held by this account :ivar str|None auth_addr: If rekeyed, the authorized address :ivar int|None closed_at_round: Round when this account was closed :ivar list[dict]|None created_apps: Applications created by this account :ivar list[dict]|None created_assets: Assets created by this account :ivar int|None created_at_round: Round when this account was created :ivar bool|None deleted: Whether this account is deleted :ivar bool|None incentive_eligible: Whether this account is eligible for incentives :ivar int|None last_heartbeat: Last heartbeat round for this account :ivar int|None last_proposed: Last round this account proposed a block :ivar dict|None participation: Participation information for this account :ivar int|None reward_base: Base reward for this account :ivar str|None sig_type: Signature type for this account """ address: str amount: AlgoAmount amount_without_pending_rewards: AlgoAmount min_balance: AlgoAmount pending_rewards: AlgoAmount rewards: AlgoAmount round: int status: str total_apps_opted_in: int | None = None total_assets_opted_in: int | None = None total_box_bytes: int | None = None total_boxes: int | None = None total_created_apps: int | None = None total_created_assets: int | None = None apps_local_state: list[dict] | None = None apps_total_extra_pages: int | None = None apps_total_schema: dict | None = None assets: list[dict] | None = None auth_addr: str | None = None closed_at_round: int | None = None created_apps: list[dict] | None = None created_assets: list[dict] | None = None created_at_round: int | None = None deleted: bool | None = None incentive_eligible: bool | None = None last_heartbeat: int | None = None last_proposed: int | None = None participation: dict | None = None reward_base: int | None = None sig_type: str | None = None class AccountManager: """ Creates and keeps track of signing accounts that can sign transactions for a sending address. This class provides functionality to create, track, and manage various types of accounts including mnemonic-based, rekeyed, multisig, and logic signature accounts. :param client_manager: The ClientManager client to use for algod and kmd clients :example: >>> account_manager = AccountManager(client_manager) """ def __init__(self, client_manager: ClientManager): self._client_manager = client_manager self._kmd_account_manager = KmdAccountManager(client_manager) self._accounts = dict[str, TransactionSignerAccountProtocol]() self._default_signer: TransactionSigner | None = None @property def kmd(self) -> KmdAccountManager: return self._kmd_account_manager def set_default_signer(self, signer: TransactionSigner | TransactionSignerAccountProtocol) -> Self: """ Sets the default signer to use if no other signer is specified. If this isn't set and a transaction needs signing for a given sender then an error will be thrown from `get_signer` / `get_account`. :param signer: A `TransactionSigner` signer to use. :returns: The `AccountManager` so method calls can be chained :example: >>> signer_account = account_manager.random() >>> account_manager.set_default_signer(signer_account.signer) >>> # When signing a transaction, if there is no signer registered for the sender >>> # then the default signer will be used >>> signer = account_manager.get_signer("{SENDERADDRESS}") """ self._default_signer = signer if isinstance(signer, TransactionSigner) else signer.signer return self def set_signer(self, sender: str, signer: TransactionSigner) -> Self: """ Tracks the given `TransactionSigner` against the given sender address for later signing. :param sender: The sender address to use this signer for :param signer: The `TransactionSigner` to sign transactions with for the given sender :returns: The `AccountManager` instance for method chaining :example: >>> account_manager.set_signer("SENDERADDRESS", transaction_signer) """ self._accounts[sender] = TransactionSignerAccount(address=sender, signer=signer) return self def set_signers(self, *, another_account_manager: "AccountManager", overwrite_existing: bool = True) -> Self: """ Merges the given `AccountManager` into this one. :param another_account_manager: The `AccountManager` to merge into this one :param overwrite_existing: Whether to overwrite existing signers in this manager :returns: The `AccountManager` instance for method chaining """ self._accounts = ( {**self._accounts, **another_account_manager._accounts} # noqa: SLF001 if overwrite_existing else {**another_account_manager._accounts, **self._accounts} # noqa: SLF001 ) return self def set_signer_from_account(self, account: TransactionSignerAccountProtocol) -> Self: """ Tracks the given account for later signing. Note: If you are generating accounts via the various methods on `AccountManager` (like `random`, `from_mnemonic`, `logic_sig`, etc.) then they automatically get tracked. :param account: The account to register :returns: The `AccountManager` instance for method chaining :example: >>> account_manager = AccountManager(client_manager) >>> account_manager.set_signer_from_account(SigningAccount(private_key=algosdk.account.generate_account()[0])) >>> account_manager.set_signer_from_account(LogicSigAccount(AlgosdkLogicSigAccount(program, args))) >>> account_manager.set_signer_from_account(MultiSigAccount(multisig_params, [account1, account2])) """ self._accounts[account.address] = account return self def get_signer(self, sender: str | TransactionSignerAccountProtocol) -> TransactionSigner: """ Returns the `TransactionSigner` for the given sender address. If no signer has been registered for that address then the default signer is used if registered. :param sender: The sender address or account :returns: The `TransactionSigner` :raises ValueError: If no signer is found and no default signer is set :example: >>> signer = account_manager.get_signer("SENDERADDRESS") """ signer = self._accounts.get(self._get_address(sender)) or self._default_signer if not signer: raise ValueError(f"No signer found for address {sender}") return signer if isinstance(signer, TransactionSigner) else signer.signer def get_account(self, sender: str) -> TransactionSignerAccountProtocol: """ Returns the `TransactionSignerAccountProtocol` for the given sender address. :param sender: The sender address :returns: The `TransactionSignerAccountProtocol` :raises ValueError: If no account is found or if the account is not a regular account :example: >>> sender = account_manager.random().address >>> # ... >>> # Returns the `TransactionSignerAccountProtocol` for `sender` that has previously been registered >>> account = account_manager.get_account(sender) """ account = self._accounts.get(sender) if not account: raise ValueError(f"No account found for address {sender}") if not isinstance(account, SigningAccount): raise ValueError(f"Account {sender} is not a regular account") return account def get_information(self, sender: str | TransactionSignerAccountProtocol) -> AccountInformation: """ Returns the given sender account's current status, balance and spendable amounts. See `<https://developer.algorand.org/docs/rest-apis/algod/#get-v2accountsaddress>`_ for response data schema details. :param sender: The address or account compliant with `TransactionSignerAccountProtocol` protocol to look up :returns: The account information :example: >>> address = "XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA" >>> account_info = account_manager.get_information(address) """ info = self._client_manager.algod.account_info(self._get_address(sender)) assert isinstance(info, dict) info = {k.replace("-", "_"): v for k, v in info.items()} for key, value in info.items(): if key in ("amount", "amount_without_pending_rewards", "min_balance", "pending_rewards", "rewards"): info[key] = AlgoAmount.from_micro_algo(value) return AccountInformation(**info) def _register_account(self, private_key: str, address: str | None = None) -> SigningAccount: """ Helper method to create and register an account with its signer. :param private_key: The private key for the account :param address: The address for the account :returns: The registered Account instance """ address = address or str(algosdk.account.address_from_private_key(private_key)) account = SigningAccount(private_key=private_key, address=address) self._accounts[address or account.address] = TransactionSignerAccount( address=account.address, signer=account.signer ) return account def _register_logicsig(self, program: bytes, args: list[bytes] | None = None) -> LogicSigAccount: """ Helper method to create and register a logic signature account. :param program: The bytes that make up the compiled logic signature :param args: The (binary) arguments to pass into the logic signature :returns: The registered AlgosdkLogicSigAccount instance """ logic_sig = LogicSigAccount(AlgosdkLogicSigAccount(program, args)) self._accounts[logic_sig.address] = logic_sig return logic_sig def _register_multisig(self, metadata: MultisigMetadata, signing_accounts: list[SigningAccount]) -> MultiSigAccount: """ Helper method to create and register a multisig account. :param metadata: The metadata for the multisig account :param signing_accounts: The list of accounts that are present to sign :returns: The registered MultisigAccount instance """ msig_account = MultiSigAccount(metadata, signing_accounts) self._accounts[str(msig_account.address)] = MultiSigAccount(metadata, signing_accounts) return msig_account def from_mnemonic(self, *, mnemonic: str, sender: str | None = None) -> SigningAccount: """ Tracks and returns an Algorand account with secret key loaded by taking the mnemonic secret. :param mnemonic: The mnemonic secret representing the private key of an account :param sender: Optional address to use as the sender :returns: The account .. warning:: Be careful how the mnemonic is handled. Never commit it into source control and ideally load it from the environment (ideally via a secret storage service) rather than the file system. :example: >>> account = account_manager.from_mnemonic("mnemonic secret ...") """ return self._register_account(to_private_key(mnemonic), sender) def from_environment(self, name: str, fund_with: AlgoAmount | None = None) -> SigningAccount: """ Tracks and returns an Algorand account with private key loaded by convention from environment variables. This allows you to write code that will work seamlessly in production and local development (LocalNet) without manual config locally (including when you reset the LocalNet). :param name: The name identifier of the account :param fund_with: Optional amount to fund the account with when it gets created (when targeting LocalNet) :returns: The account :raises ValueError: If environment variable {NAME}_MNEMONIC is missing when looking for account {NAME} .. note:: Convention: * **Non-LocalNet:** will load `{NAME}_MNEMONIC` as a mnemonic secret. If `{NAME}_SENDER` is defined then it will use that for the sender address (i.e. to support rekeyed accounts) * **LocalNet:** will load the account from a KMD wallet called {NAME} and if that wallet doesn't exist it will create it and fund the account for you :example: >>> # If you have a mnemonic secret loaded into `MY_ACCOUNT_MNEMONIC` then you can call: >>> account = account_manager.from_environment('MY_ACCOUNT') >>> # If that code runs against LocalNet then a wallet called `MY_ACCOUNT` will automatically be created >>> # with an account that is automatically funded with the specified amount from the default LocalNet dispenser """ account_mnemonic = os.getenv(f"{name.upper()}_MNEMONIC") if account_mnemonic: private_key = mnemonic.to_private_key(account_mnemonic) return self._register_account(private_key) if self._client_manager.is_localnet(): kmd_account = self._kmd_account_manager.get_or_create_wallet_account(name, fund_with) return self._register_account(kmd_account.private_key) raise ValueError(f"Missing environment variable {name.upper()}_MNEMONIC when looking for account {name}") def from_kmd( self, name: str, predicate: Callable[[dict[str, Any]], bool] | None = None, sender: str | None = None ) -> SigningAccount: """ Tracks and returns an Algorand account with private key loaded from the given KMD wallet. :param name: The name of the wallet to retrieve an account from :param predicate: Optional filter to use to find the account :param sender: Optional sender address to use this signer for (aka a rekeyed account) :returns: The account :raises ValueError: If unable to find KMD account with given name and predicate :example: >>> # Get default funded account in a LocalNet: >>> defaultDispenserAccount = account.from_kmd('unencrypted-default-wallet', ... lambda a: a.status != 'Offline' and a.amount > 1_000_000_000 ... ) """ kmd_account = self._kmd_account_manager.get_wallet_account(name, predicate, sender) if not kmd_account: raise ValueError(f"Unable to find KMD account {name}{' with predicate' if predicate else ''}") return self._register_account(kmd_account.private_key) def logicsig(self, program: bytes, args: list[bytes] | None = None) -> LogicSigAccount: """ Tracks and returns an account that represents a logic signature. :param program: The bytes that make up the compiled logic signature :param args: Optional (binary) arguments to pass into the logic signature :returns: A logic signature account wrapper :example: >>> account = account.logic_sig(program, [new Uint8Array(3, ...)]) """ return self._register_logicsig(program, args) def multisig(self, metadata: MultisigMetadata, signing_accounts: list[SigningAccount]) -> MultiSigAccount: """ Tracks and returns an account that supports partial or full multisig signing. :param metadata: The metadata for the multisig account :param signing_accounts: The signers that are currently present :returns: A multisig account wrapper :example: >>> account = account_manager.multi_sig( ... version=1, ... threshold=1, ... addrs=["ADDRESS1...", "ADDRESS2..."], ... signing_accounts=[account1, account2] ... ) """ return self._register_multisig(metadata, signing_accounts) def random(self) -> SigningAccount: """ Tracks and returns a new, random Algorand account. :returns: The account :example: >>> account = account_manager.random() """ private_key, _ = algosdk.account.generate_account() return self._register_account(private_key) def localnet_dispenser(self) -> SigningAccount: """ Returns an Algorand account with private key loaded for the default LocalNet dispenser account. This account can be used to fund other accounts. :returns: The account :example: >>> account = account_manager.localnet_dispenser() """ kmd_account = self._kmd_account_manager.get_localnet_dispenser_account() return self._register_account(kmd_account.private_key) def dispenser_from_environment(self) -> SigningAccount: """ Returns an account (with private key loaded) that can act as a dispenser from environment variables. If environment variables are not present, returns the default LocalNet dispenser account. :returns: The account :example: >>> account = account_manager.dispenser_from_environment() """ name = os.getenv(f"{DISPENSER_ACCOUNT_NAME}_MNEMONIC") if name: return self.from_environment(DISPENSER_ACCOUNT_NAME) return self.localnet_dispenser() def rekeyed( self, *, sender: str, account: TransactionSignerAccountProtocol ) -> TransactionSignerAccount | SigningAccount: """ Tracks and returns an Algorand account that is a rekeyed version of the given account to a new sender. :param sender: The account or address to use as the sender :param account: The account to use as the signer for this new rekeyed account :returns: The rekeyed account :example: >>> account = account.from_mnemonic("mnemonic secret ...") >>> rekeyed_account = account_manager.rekeyed(account, "SENDERADDRESS...") """ sender_address = sender.address if isinstance(sender, SigningAccount) else sender self._accounts[sender_address] = TransactionSignerAccount(address=sender_address, signer=account.signer) if isinstance(account, SigningAccount): return SigningAccount(address=sender_address, private_key=account.private_key) return TransactionSignerAccount(address=sender_address, signer=account.signer) def rekey_account( # noqa: PLR0913 self, account: str, rekey_to: str | TransactionSignerAccountProtocol, *, # Common transaction parameters signer: TransactionSigner | None = None, note: bytes | None = None, lease: bytes | None = None, static_fee: AlgoAmount | None = None, extra_fee: AlgoAmount | None = None, max_fee: AlgoAmount | None = None, validity_window: int | None = None, first_valid_round: int | None = None, last_valid_round: int | None = None, suppress_log: bool | None = None, ) -> SendAtomicTransactionComposerResults: """ Rekey an account to a new address. :param account: The account to rekey :param rekey_to: The address or account to rekey to :param signer: Optional transaction signer :param note: Optional transaction note :param lease: Optional transaction lease :param static_fee: Optional static fee :param extra_fee: Optional extra fee :param max_fee: Optional max fee :param validity_window: Optional validity window :param first_valid_round: Optional first valid round :param last_valid_round: Optional last valid round :param suppress_log: Optional flag to suppress logging :returns: The result of the transaction and the transaction that was sent .. warning:: Please be careful with this function and be sure to read the `official rekey guidance <https://developer.algorand.org/docs/get-details/accounts/rekey/>`_. :example: >>> # Basic example (with string addresses): >>> algorand.account.rekey_account({account: "ACCOUNTADDRESS", rekey_to: "NEWADDRESS"}) >>> # Basic example (with signer accounts): >>> algorand.account.rekey_account({account: account1, rekey_to: newSignerAccount}) >>> # Advanced example: >>> algorand.account.rekey_account({ ... account: "ACCOUNTADDRESS", ... rekey_to: "NEWADDRESS", ... lease: 'lease', ... note: 'note', ... first_valid_round: 1000, ... validity_window: 10, ... extra_fee: AlgoAmount.from_micro_algo(1000), ... static_fee: AlgoAmount.from_micro_algo(1000), ... max_fee: AlgoAmount.from_micro_algo(3000), ... suppress_log: True, ... }) """ sender_address = self._get_address(account) rekey_address = self._get_address(rekey_to) result = ( self._get_composer() .add_payment( PaymentParams( sender=sender_address, receiver=sender_address, amount=AlgoAmount.from_micro_algo(0), rekey_to=rekey_address, signer=signer, note=note, lease=lease, static_fee=static_fee, extra_fee=extra_fee, max_fee=max_fee, validity_window=validity_window, first_valid_round=first_valid_round, last_valid_round=last_valid_round, ) ) .send() ) # If rekey_to is a signing account, set it as the signer for this account if isinstance(rekey_to, SigningAccount): self.rekeyed(sender=account, account=rekey_to) if not suppress_log: logger.info(f"Rekeyed {sender_address} to {rekey_address} via transaction {result.tx_ids[-1]}") return result def ensure_funded( # noqa: PLR0913 self, account_to_fund: str | SigningAccount, dispenser_account: str | SigningAccount, min_spending_balance: AlgoAmount, min_funding_increment: AlgoAmount | None = None, # Sender params send_params: SendParams | None = None, # Common txn params signer: TransactionSigner | None = None, rekey_to: str | None = None, note: bytes | None = None, lease: bytes | None = None, static_fee: AlgoAmount | None = None, extra_fee: AlgoAmount | None = None, max_fee: AlgoAmount | None = None, validity_window: int | None = None, first_valid_round: int | None = None, last_valid_round: int | None = None, ) -> EnsureFundedResult | None: """ Funds a given account using a dispenser account as a funding source. Ensures the given account has a certain amount of Algo free to spend (accounting for Algo locked in minimum balance requirement). See `<https://developer.algorand.org/docs/get-details/accounts/#minimum-balance>`_ for details. :param account_to_fund: The account to fund :param dispenser_account: The account to use as a dispenser funding source :param min_spending_balance: The minimum balance of Algo that the account should have available to spend :param min_funding_increment: Optional minimum funding increment :param send_params: Parameters for the send operation, defaults to None :param signer: Optional transaction signer :param rekey_to: Optional rekey address :param note: Optional transaction note :param lease: Optional transaction lease :param static_fee: Optional static fee :param extra_fee: Optional extra fee :param max_fee: Optional maximum fee :param validity_window: Optional validity window :param first_valid_round: Optional first valid round :param last_valid_round: Optional last valid round :returns: The result of executing the dispensing transaction and the `amountFunded` if funds were needed, or None if no funds were needed :example: >>> # Basic example: >>> algorand.account.ensure_funded("ACCOUNTADDRESS", "DISPENSERADDRESS", algokit.algo(1)) >>> # With configuration: >>> algorand.account.ensure_funded( ... "ACCOUNTADDRESS", ... "DISPENSERADDRESS", ... algokit.algo(1), ... min_funding_increment=algokit.algo(2), ... fee=AlgoAmount.from_micro_algo(1000), ... suppress_log=True ... ) """ account_to_fund = self._get_address(account_to_fund) dispenser_account = self._get_address(dispenser_account) amount_funded = self._get_ensure_funded_amount(account_to_fund, min_spending_balance, min_funding_increment) if not amount_funded: return None result = ( self._get_composer() .add_payment( PaymentParams( sender=dispenser_account, receiver=account_to_fund, amount=amount_funded, signer=signer, rekey_to=rekey_to, note=note, lease=lease, static_fee=static_fee, extra_fee=extra_fee, max_fee=max_fee, validity_window=validity_window, first_valid_round=first_valid_round, last_valid_round=last_valid_round, ) ) .send(send_params) ) return EnsureFundedResult( returns=result.returns, transactions=result.transactions, confirmations=result.confirmations, tx_ids=result.tx_ids, group_id=result.group_id, transaction_id=result.tx_ids[0], confirmation=result.confirmations[0], transaction=result.transactions[0], amount_funded=amount_funded, ) def ensure_funded_from_environment( # noqa: PLR0913 self, account_to_fund: str | SigningAccount, min_spending_balance: AlgoAmount, *, # Force remaining params to be keyword-only min_funding_increment: AlgoAmount | None = None, # SendParams send_params: SendParams | None = None, # Common transaction params (omitting sender) signer: TransactionSigner | None = None, rekey_to: str | None = None, note: bytes | None = None, lease: bytes | None = None, static_fee: AlgoAmount | None = None, extra_fee: AlgoAmount | None = None, max_fee: AlgoAmount | None = None, validity_window: int | None = None, first_valid_round: int | None = None, last_valid_round: int | None = None, ) -> EnsureFundedResult | None: """ Ensure an account is funded from a dispenser account configured in environment. Uses a dispenser account retrieved from the environment, per the `dispenser_from_environment` method, as a funding source such that the given account has a certain amount of Algo free to spend (accounting for Algo locked in minimum balance requirement). See `<https://developer.algorand.org/docs/get-details/accounts/#minimum-balance>`_ for details. :param account_to_fund: The account to fund :param min_spending_balance: The minimum balance of Algo that the account should have available to spend :param min_funding_increment: Optional minimum funding increment :param send_params: Parameters for the send operation, defaults to None :param signer: Optional transaction signer :param rekey_to: Optional rekey address :param note: Optional transaction note :param lease: Optional transaction lease :param static_fee: Optional static fee :param extra_fee: Optional extra fee :param max_fee: Optional maximum fee :param validity_window: Optional validity window :param first_valid_round: Optional first valid round :param last_valid_round: Optional last valid round :returns: The result of executing the dispensing transaction and the `amountFunded` if funds were needed, or None if no funds were needed .. note:: The dispenser account is retrieved from the account mnemonic stored in process.env.DISPENSER_MNEMONIC and optionally process.env.DISPENSER_SENDER if it's a rekeyed account, or against default LocalNet if no environment variables present. :example: >>> # Basic example: >>> algorand.account.ensure_funded_from_environment("ACCOUNTADDRESS", algokit.algo(1)) >>> # With configuration: >>> algorand.account.ensure_funded_from_environment( ... "ACCOUNTADDRESS", ... algokit.algo(1), ... min_funding_increment=algokit.algo(2), ... fee=AlgoAmount.from_micro_algo(1000), ... suppress_log=True ... ) """ account_to_fund = self._get_address(account_to_fund) dispenser_account = self.dispenser_from_environment() amount_funded = self._get_ensure_funded_amount(account_to_fund, min_spending_balance, min_funding_increment) if not amount_funded: return None result = ( self._get_composer() .add_payment( PaymentParams( sender=dispenser_account.address, receiver=account_to_fund, amount=amount_funded, signer=signer, rekey_to=rekey_to, note=note, lease=lease, static_fee=static_fee, extra_fee=extra_fee, max_fee=max_fee, validity_window=validity_window, first_valid_round=first_valid_round, last_valid_round=last_valid_round, ) ) .send(send_params) ) return EnsureFundedResult( returns=result.returns, transactions=result.transactions, confirmations=result.confirmations, tx_ids=result.tx_ids, group_id=result.group_id, transaction_id=result.tx_ids[0], confirmation=result.confirmations[0], transaction=result.transactions[0], amount_funded=amount_funded, ) def ensure_funded_from_testnet_dispenser_api( self, account_to_fund: str | SigningAccount, dispenser_client: TestNetDispenserApiClient, min_spending_balance: AlgoAmount, *, min_funding_increment: AlgoAmount | None = None, ) -> EnsureFundedFromTestnetDispenserApiResult | None: """ Ensure an account is funded using the TestNet Dispenser API. Uses the TestNet Dispenser API as a funding source such that the account has a certain amount of Algo free to spend (accounting for Algo locked in minimum balance requirement). See `<https://developer.algorand.org/docs/get-details/accounts/#minimum-balance>`_ for details. :param account_to_fund: The account to fund :param dispenser_client: The TestNet dispenser funding client :param min_spending_balance: The minimum balance of Algo that the account should have available to spend :param min_funding_increment: Optional minimum funding increment :returns: The result of executing the dispensing transaction and the `amountFunded` if funds were needed, or None if no funds were needed :raises ValueError: If attempting to fund on non-TestNet network :example: >>> # Basic example: >>> algorand.account.ensure_funded_from_testnet_dispenser_api( ... "ACCOUNTADDRESS", ... algorand.client.get_testnet_dispenser_from_environment(), ... algokit.algo(1) ... ) >>> # With configuration: >>> algorand.account.ensure_funded_from_testnet_dispenser_api( ... "ACCOUNTADDRESS", ... algorand.client.get_testnet_dispenser_from_environment(), ... algokit.algo(1), ... min_funding_increment=algokit.algo(2) ... ) """ account_to_fund = self._get_address(account_to_fund) if not self._client_manager.is_testnet(): raise ValueError("Attempt to fund using TestNet dispenser API on non TestNet network.") amount_funded = self._get_ensure_funded_amount(account_to_fund, min_spending_balance, min_funding_increment) if not amount_funded: return None result = dispenser_client.fund( address=account_to_fund, amount=amount_funded.micro_algo, asset_id=DispenserAssetName.ALGO, ) return EnsureFundedFromTestnetDispenserApiResult( transaction_id=result.tx_id, amount_funded=AlgoAmount.from_micro_algo(result.amount), ) def _get_address(self, sender: str | TransactionSignerAccountProtocol) -> str: match sender: case TransactionSignerAccountProtocol(): return sender.address case str(): return sender case _: raise ValueError(f"Unknown sender type: {type(sender)}") def _get_composer(self, get_suggested_params: Callable[[], SuggestedParams] | None = None) -> TransactionComposer: if get_suggested_params is None: def _get_suggested_params() -> SuggestedParams: return self._client_manager.algod.suggested_params() get_suggested_params = _get_suggested_params return TransactionComposer( algod=self._client_manager.algod, get_signer=self.get_signer, get_suggested_params=get_suggested_params ) def _calculate_fund_amount( self, min_spending_balance: int, current_spending_balance: AlgoAmount, min_funding_increment: int, ) -> int | None: if min_spending_balance > current_spending_balance: min_fund_amount = (min_spending_balance - current_spending_balance).micro_algo return max(min_fund_amount, min_funding_increment) return None def _get_ensure_funded_amount( self, sender: str, min_spending_balance: AlgoAmount, min_funding_increment: AlgoAmount | None = None, ) -> AlgoAmount | None: account_info = self.get_information(sender) current_spending_balance = account_info.amount - account_info.min_balance min_increment = min_funding_increment.micro_algo if min_funding_increment else 0 amount_funded = self._calculate_fund_amount( min_spending_balance.micro_algo, current_spending_balance, min_increment ) return AlgoAmount.from_micro_algo(amount_funded) if amount_funded is not None else None
algorandfoundation/algokit-utils-py
src/algokit_utils/accounts/account_manager.py
Python
MIT
39,369
from collections.abc import Callable from typing import Any, cast from algosdk.kmd import KMDClient from algokit_utils.clients.client_manager import ClientManager from algokit_utils.config import config from algokit_utils.models.account import SigningAccount from algokit_utils.models.amount import AlgoAmount from algokit_utils.transactions.transaction_composer import PaymentParams, TransactionComposer __all__ = ["KmdAccount", "KmdAccountManager"] logger = config.logger class KmdAccount(SigningAccount): """Account retrieved from KMD with signing capabilities, extending base Account. Provides an account implementation that can be used to sign transactions using keys stored in KMD. :param private_key: Base64 encoded private key :param address: Optional address override for rekeyed accounts, defaults to None """ def __init__(self, private_key: str, address: str | None = None) -> None: super().__init__(private_key=private_key, address=address or "") class KmdAccountManager: """Provides abstractions over KMD that makes it easier to get and manage accounts.""" _kmd: KMDClient | None def __init__(self, client_manager: ClientManager) -> None: self._client_manager = client_manager try: self._kmd = client_manager.kmd except ValueError: self._kmd = None def kmd(self) -> KMDClient: """Returns the KMD client, initializing it if needed. :raises Exception: If KMD client is not configured and not running against LocalNet :return: The KMD client """ if self._kmd is None: if self._client_manager.is_localnet(): kmd_config = ClientManager.get_config_from_environment_or_localnet() self._kmd = ClientManager.get_kmd_client(kmd_config.kmd_config) return self._kmd raise Exception("Attempt to use KMD client with no KMD configured") return self._kmd def get_wallet_account( self, wallet_name: str, predicate: Callable[[dict[str, Any]], bool] | None = None, sender: str | None = None, ) -> KmdAccount | None: """Returns an Algorand signing account with private key loaded from the given KMD wallet. Retrieves an account from a KMD wallet that matches the given predicate, or a random account if no predicate is provided. :param wallet_name: The name of the wallet to retrieve an account from :param predicate: Optional filter to use to find the account (otherwise gets a random account from the wallet) :param sender: Optional sender address to use this signer for (aka a rekeyed account) :return: The signing account or None if no matching wallet or account was found """ kmd_client = self.kmd() wallets = kmd_client.list_wallets() wallet = next((w for w in wallets if w["name"] == wallet_name), None) if not wallet: return None wallet_id = wallet["id"] wallet_handle = kmd_client.init_wallet_handle(wallet_id, "") addresses = kmd_client.list_keys(wallet_handle) matched_address = None if predicate: for address in addresses: account_info = self._client_manager.algod.account_info(address) if predicate(cast(dict[str, Any], account_info)): matched_address = address break else: matched_address = next(iter(addresses), None) if not matched_address: return None private_key = kmd_client.export_key(wallet_handle, "", matched_address) return KmdAccount(private_key=private_key, address=sender) def get_or_create_wallet_account(self, name: str, fund_with: AlgoAmount | None = None) -> KmdAccount: """Gets or creates a funded account in a KMD wallet of the given name. Provides idempotent access to accounts from LocalNet without specifying the private key. :param name: The name of the wallet to retrieve / create :param fund_with: The number of Algos to fund the account with when created :return: An Algorand account with private key loaded """ fund_with = fund_with or AlgoAmount.from_algo(1000) existing = self.get_wallet_account(name) if existing: return existing kmd_client = self.kmd() wallet_id = kmd_client.create_wallet(name, "")["id"] wallet_handle = kmd_client.init_wallet_handle(wallet_id, "") kmd_client.generate_key(wallet_handle) account = self.get_wallet_account(name) assert account is not None logger.info( f"LocalNet account '{name}' doesn't yet exist; created account {account.address} " f"with keys stored in KMD and funding with {fund_with} ALGO" ) dispenser = self.get_localnet_dispenser_account() TransactionComposer( algod=self._client_manager.algod, get_signer=lambda _: dispenser.signer, get_suggested_params=self._client_manager.algod.suggested_params, ).add_payment( PaymentParams( sender=dispenser.address, receiver=account.address, amount=fund_with, ) ).send() return account def get_localnet_dispenser_account(self) -> KmdAccount: """Returns an Algorand account with private key loaded for the default LocalNet dispenser account. Retrieves the default funded account from LocalNet that can be used to fund other accounts. :raises Exception: If not running against LocalNet or dispenser account not found :return: The default LocalNet dispenser account """ if not self._client_manager.is_localnet(): raise Exception("Can't get LocalNet dispenser account from non LocalNet network") dispenser = self.get_wallet_account( "unencrypted-default-wallet", lambda a: a["status"] != "Offline" and a["amount"] > 1_000_000_000, # noqa: PLR2004 ) if not dispenser: raise Exception("Error retrieving LocalNet dispenser account; couldn't find the default account in KMD") return dispenser
algorandfoundation/algokit-utils-py
src/algokit_utils/accounts/kmd_account_manager.py
Python
MIT
6,342
import copy import time import typing_extensions from algosdk.atomic_transaction_composer import TransactionSigner from algosdk.kmd import KMDClient from algosdk.transaction import SuggestedParams from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient from algokit_utils.accounts.account_manager import AccountManager from algokit_utils.applications.app_deployer import AppDeployer from algokit_utils.applications.app_manager import AppManager from algokit_utils.assets.asset_manager import AssetManager from algokit_utils.clients.client_manager import AlgoSdkClients, ClientManager from algokit_utils.models.network import AlgoClientConfigs, AlgoClientNetworkConfig from algokit_utils.protocols.account import TransactionSignerAccountProtocol from algokit_utils.transactions.transaction_composer import ( TransactionComposer, ) from algokit_utils.transactions.transaction_creator import AlgorandClientTransactionCreator from algokit_utils.transactions.transaction_sender import AlgorandClientTransactionSender __all__ = [ "AlgorandClient", ] class AlgorandClient: """A client that brokers easy access to Algorand functionality.""" def __init__(self, config: AlgoClientConfigs | AlgoSdkClients): self._client_manager: ClientManager = ClientManager(clients_or_configs=config, algorand_client=self) self._account_manager: AccountManager = AccountManager(self._client_manager) self._asset_manager: AssetManager = AssetManager(self._client_manager.algod, lambda: self.new_group()) self._app_manager: AppManager = AppManager(self._client_manager.algod) self._transaction_sender = AlgorandClientTransactionSender( new_group=lambda: self.new_group(), asset_manager=self._asset_manager, app_manager=self._app_manager, algod_client=self._client_manager.algod, ) self._app_deployer: AppDeployer = AppDeployer( self._app_manager, self._transaction_sender, self._client_manager.indexer_if_present ) self._transaction_creator = AlgorandClientTransactionCreator( new_group=lambda: self.new_group(), ) self._cached_suggested_params: SuggestedParams | None = None self._cached_suggested_params_expiry: float | None = None self._cached_suggested_params_timeout: int = 3_000 # three seconds self._default_validity_window: int | None = None def set_default_validity_window(self, validity_window: int) -> typing_extensions.Self: """ Sets the default validity window for transactions. :param validity_window: The number of rounds between the first and last valid rounds :return: The `AlgorandClient` so method calls can be chained """ self._default_validity_window = validity_window return self def set_default_signer( self, signer: TransactionSigner | TransactionSignerAccountProtocol ) -> typing_extensions.Self: """ Sets the default signer to use if no other signer is specified. :param signer: The signer to use, either a `TransactionSigner` or a `TransactionSignerAccountProtocol` :return: The `AlgorandClient` so method calls can be chained """ self._account_manager.set_default_signer(signer) return self def set_signer(self, sender: str, signer: TransactionSigner) -> typing_extensions.Self: """ Tracks the given account for later signing. :param sender: The sender address to use this signer for :param signer: The signer to sign transactions with for the given sender :return: The `AlgorandClient` so method calls can be chained """ self._account_manager.set_signer(sender, signer) return self def set_signer_account(self, signer: TransactionSignerAccountProtocol) -> typing_extensions.Self: """ Sets the default signer to use if no other signer is specified. :param signer: The signer to use, either a `TransactionSigner` or a `TransactionSignerAccountProtocol` :return: The `AlgorandClient` so method calls can be chained """ self._account_manager.set_default_signer(signer) return self def set_suggested_params( self, suggested_params: SuggestedParams, until: float | None = None ) -> typing_extensions.Self: """ Sets a cache value to use for suggested params. :param suggested_params: The suggested params to use :param until: A timestamp until which to cache, or if not specified then the timeout is used :return: The `AlgorandClient` so method calls can be chained """ self._cached_suggested_params = suggested_params self._cached_suggested_params_expiry = until or time.time() + self._cached_suggested_params_timeout return self def set_suggested_params_timeout(self, timeout: int) -> typing_extensions.Self: """ Sets the timeout for caching suggested params. :param timeout: The timeout in milliseconds :return: The `AlgorandClient` so method calls can be chained """ self._cached_suggested_params_timeout = timeout return self def get_suggested_params(self) -> SuggestedParams: """Get suggested params for a transaction (either cached or from algod if the cache is stale or empty)""" if self._cached_suggested_params and ( self._cached_suggested_params_expiry is None or self._cached_suggested_params_expiry > time.time() ): return copy.deepcopy(self._cached_suggested_params) self._cached_suggested_params = self._client_manager.algod.suggested_params() self._cached_suggested_params_expiry = time.time() + self._cached_suggested_params_timeout return copy.deepcopy(self._cached_suggested_params) def new_group(self) -> TransactionComposer: """Start a new `TransactionComposer` transaction group""" return TransactionComposer( algod=self.client.algod, get_signer=lambda addr: self.account.get_signer(addr), get_suggested_params=self.get_suggested_params, default_validity_window=self._default_validity_window, ) @property def client(self) -> ClientManager: """Get clients, including algosdk clients and app clients.""" return self._client_manager @property def account(self) -> AccountManager: """Get or create accounts that can sign transactions.""" return self._account_manager @property def asset(self) -> AssetManager: """Get or create assets.""" return self._asset_manager @property def app(self) -> AppManager: return self._app_manager @property def app_deployer(self) -> AppDeployer: """Get or create applications.""" return self._app_deployer @property def send(self) -> AlgorandClientTransactionSender: """Methods for sending a transaction and waiting for confirmation""" return self._transaction_sender @property def create_transaction(self) -> AlgorandClientTransactionCreator: """Methods for building transactions""" return self._transaction_creator @staticmethod def default_localnet() -> "AlgorandClient": """ Returns an `AlgorandClient` pointing at default LocalNet ports and API token. :return: The `AlgorandClient` """ return AlgorandClient( AlgoClientConfigs( algod_config=ClientManager.get_default_localnet_config("algod"), indexer_config=ClientManager.get_default_localnet_config("indexer"), kmd_config=ClientManager.get_default_localnet_config("kmd"), ) ) @staticmethod def testnet() -> "AlgorandClient": """ Returns an `AlgorandClient` pointing at TestNet using AlgoNode. :return: The `AlgorandClient` """ return AlgorandClient( AlgoClientConfigs( algod_config=ClientManager.get_algonode_config("testnet", "algod"), indexer_config=ClientManager.get_algonode_config("testnet", "indexer"), kmd_config=None, ) ) @staticmethod def mainnet() -> "AlgorandClient": """ Returns an `AlgorandClient` pointing at MainNet using AlgoNode. :return: The `AlgorandClient` """ return AlgorandClient( AlgoClientConfigs( algod_config=ClientManager.get_algonode_config("mainnet", "algod"), indexer_config=ClientManager.get_algonode_config("mainnet", "indexer"), kmd_config=None, ) ) @staticmethod def from_clients( algod: AlgodClient, indexer: IndexerClient | None = None, kmd: KMDClient | None = None ) -> "AlgorandClient": """ Returns an `AlgorandClient` pointing to the given client(s). :param algod: The algod client to use :param indexer: The indexer client to use :param kmd: The kmd client to use :return: The `AlgorandClient` """ return AlgorandClient(AlgoSdkClients(algod=algod, indexer=indexer, kmd=kmd)) @staticmethod def from_environment() -> "AlgorandClient": """ Returns an `AlgorandClient` loading the configuration from environment variables. Retrieve configurations from environment variables when defined or get defaults. Expects to be called from a Python environment. :return: The `AlgorandClient` """ return AlgorandClient(ClientManager.get_config_from_environment_or_localnet()) @staticmethod def from_config( algod_config: AlgoClientNetworkConfig, indexer_config: AlgoClientNetworkConfig | None = None, kmd_config: AlgoClientNetworkConfig | None = None, ) -> "AlgorandClient": """ Returns an `AlgorandClient` from the given config. :param algod_config: The config to use for the algod client :param indexer_config: The config to use for the indexer client :param kmd_config: The config to use for the kmd client :return: The `AlgorandClient` """ return AlgorandClient( AlgoClientConfigs(algod_config=algod_config, indexer_config=indexer_config, kmd_config=kmd_config) )
algorandfoundation/algokit-utils-py
src/algokit_utils/algorand.py
Python
MIT
10,554
import warnings warnings.warn( """The legacy v2 application_client module is deprecated and will be removed in a future version. Use `AppClient` abstraction from `algokit_utils.applications` instead. """, DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.application_client import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/application_client.py
Python
MIT
337
import warnings from typing_extensions import deprecated warnings.warn( """The legacy v2 application_specification module is deprecated and will be removed in a future version. Use `from algokit_utils.applications.app_spec.arc32 import ...` to access Arc32 app spec instead. By default, the ARC52Contract is a recommended app spec to use, serving as a replacement for legacy 'ApplicationSpecification' class. To convert legacy app specs to ARC52, use `arc32_to_arc52` function from algokit_utils.applications.utils. """, DeprecationWarning, stacklevel=2, ) from algokit_utils.applications.app_spec.arc32 import ( # noqa: E402 # noqa: E402 AppSpecStateDict, Arc32Contract, CallConfig, DefaultArgumentDict, DefaultArgumentType, MethodConfigDict, MethodHints, OnCompleteActionName, ) @deprecated( "Use `Arc32Contract` from algokit_utils.applications instead. Example:\n" "```python\n" "from algokit_utils.applications import Arc32Contract\n" "app_spec = Arc32Contract.from_json(app_spec_json)\n" "```" ) class ApplicationSpecification(Arc32Contract): """Deprecated class for ARC-0032 application specification""" __all__ = [ "AppSpecStateDict", "ApplicationSpecification", "CallConfig", "DefaultArgumentDict", "DefaultArgumentType", "MethodConfigDict", "MethodHints", "OnCompleteActionName", ]
algorandfoundation/algokit-utils-py
src/algokit_utils/application_specification.py
Python
MIT
1,416
from algokit_utils.applications.abi import * # noqa: F403 from algokit_utils.applications.app_client import * # noqa: F403 from algokit_utils.applications.app_deployer import * # noqa: F403 from algokit_utils.applications.app_factory import * # noqa: F403 from algokit_utils.applications.app_manager import * # noqa: F403 from algokit_utils.applications.app_spec import * # noqa: F403 from algokit_utils.applications.enums import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/__init__.py
Python
MIT
452
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypeAlias import algosdk from algosdk.abi.method import Method as AlgorandABIMethod from algosdk.atomic_transaction_composer import ABIResult from algokit_utils.applications.app_spec.arc56 import Arc56Contract, StructField from algokit_utils.applications.app_spec.arc56 import Method as Arc56Method if TYPE_CHECKING: from algokit_utils.models.state import BoxName ABIValue: TypeAlias = ( bool | int | str | bytes | bytearray | list["ABIValue"] | tuple["ABIValue"] | dict[str, "ABIValue"] ) ABIStruct: TypeAlias = dict[str, list[dict[str, "ABIValue"]]] Arc56ReturnValueType: TypeAlias = ABIValue | ABIStruct | None ABIType: TypeAlias = algosdk.abi.ABIType ABIArgumentType: TypeAlias = algosdk.abi.ABIType | algosdk.abi.ABITransactionType | algosdk.abi.ABIReferenceType __all__ = [ "ABIArgumentType", "ABIReturn", "ABIStruct", "ABIType", "ABIValue", "Arc56ReturnValueType", "BoxABIValue", "get_abi_decoded_value", "get_abi_encoded_value", "get_abi_struct_from_abi_tuple", "get_abi_tuple_from_abi_struct", "get_abi_tuple_type_from_abi_struct_definition", "get_arc56_value", ] @dataclass(kw_only=True) class ABIReturn: """Represents the return value from an ABI method call. Wraps the raw return value and decoded value along with any decode errors. :ivar result: The ABIResult object containing the method call results :ivar raw_value: The raw return value from the method call :ivar value: The decoded return value from the method call :ivar method: The ABI method definition :ivar decode_error: The exception that occurred during decoding, if any """ raw_value: bytes | None = None value: ABIValue | None = None method: AlgorandABIMethod | None = None decode_error: Exception | None = None def __init__(self, result: ABIResult) -> None: self.decode_error = result.decode_error if not self.decode_error: self.raw_value = result.raw_value self.value = result.return_value self.method = result.method @property def is_success(self) -> bool: """Returns True if the ABI call was successful (no decode error) :return: True if no decode error occurred, False otherwise """ return self.decode_error is None def get_arc56_value( self, method: Arc56Method | AlgorandABIMethod, structs: dict[str, list[StructField]] ) -> Arc56ReturnValueType: """Gets the ARC-56 formatted return value. :param method: The ABI method definition :param structs: Dictionary of struct definitions :return: The decoded return value in ARC-56 format """ return get_arc56_value(self, method, structs) def get_arc56_value( abi_return: ABIReturn, method: Arc56Method | AlgorandABIMethod, structs: dict[str, list[StructField]] ) -> Arc56ReturnValueType: """Gets the ARC-56 formatted return value from an ABI return. :param abi_return: The ABI return value to decode :param method: The ABI method definition :param structs: Dictionary of struct definitions :raises ValueError: If there was an error decoding the return value :return: The decoded return value in ARC-56 format """ if isinstance(method, AlgorandABIMethod): type_str = method.returns.type struct = None # AlgorandABIMethod doesn't have struct info else: type_str = method.returns.type struct = method.returns.struct if type_str == "void" or abi_return.value is None: return None if abi_return.decode_error: raise ValueError(abi_return.decode_error) raw_value = abi_return.raw_value # Handle AVM types if type_str == "AVMBytes": return raw_value if type_str == "AVMString" and raw_value: return raw_value.decode("utf-8") if type_str == "AVMUint64" and raw_value: return ABIType.from_string("uint64").decode(raw_value) # type: ignore[no-any-return] # Handle structs if struct and struct in structs: return_tuple = abi_return.value return Arc56Contract.get_abi_struct_from_abi_tuple(return_tuple, structs[struct], structs) # Return as-is return abi_return.value def get_abi_encoded_value(value: Any, type_str: str, structs: dict[str, list[StructField]]) -> bytes: # noqa: PLR0911, ANN401 """Encodes a value according to its ABI type. :param value: The value to encode :param type_str: The ABI type string :param structs: Dictionary of struct definitions :raises ValueError: If the value cannot be encoded for the given type :return: The ABI encoded bytes """ if isinstance(value, (bytes | bytearray)): return value if type_str == "AVMUint64": return ABIType.from_string("uint64").encode(value) if type_str in ("AVMBytes", "AVMString"): if isinstance(value, str): return value.encode("utf-8") if not isinstance(value, (bytes | bytearray)): raise ValueError(f"Expected bytes value for {type_str}, but got {type(value)}") return value if type_str in structs: tuple_type = get_abi_tuple_type_from_abi_struct_definition(structs[type_str], structs) if isinstance(value, (list | tuple)): return tuple_type.encode(value) # type: ignore[arg-type] else: tuple_values = get_abi_tuple_from_abi_struct(value, structs[type_str], structs) return tuple_type.encode(tuple_values) else: abi_type = ABIType.from_string(type_str) return abi_type.encode(value) def get_abi_decoded_value( value: bytes | int | str, type_str: str | ABIArgumentType, structs: dict[str, list[StructField]] ) -> ABIValue: """Decodes a value according to its ABI type. :param value: The value to decode :param type_str: The ABI type string or type object :param structs: Dictionary of struct definitions :return: The decoded ABI value """ type_value = str(type_str) if type_value == "AVMBytes" or not isinstance(value, bytes): return value if type_value == "AVMString": return value.decode("utf-8") if type_value == "AVMUint64": return ABIType.from_string("uint64").decode(value) # type: ignore[no-any-return] if type_value in structs: tuple_type = get_abi_tuple_type_from_abi_struct_definition(structs[type_value], structs) decoded_tuple = tuple_type.decode(value) return get_abi_struct_from_abi_tuple(decoded_tuple, structs[type_value], structs) return ABIType.from_string(type_value).decode(value) # type: ignore[no-any-return] def get_abi_tuple_from_abi_struct( struct_value: dict[str, Any], struct_fields: list[StructField], structs: dict[str, list[StructField]], ) -> list[Any]: """Converts an ABI struct to a tuple representation. :param struct_value: The struct value as a dictionary :param struct_fields: List of struct field definitions :param structs: Dictionary of struct definitions :raises ValueError: If a required field is missing from the struct :return: The struct as a tuple """ result = [] for field in struct_fields: key = field.name if key not in struct_value: raise ValueError(f"Missing value for field '{key}'") value = struct_value[key] field_type = field.type if isinstance(field_type, str): if field_type in structs: value = get_abi_tuple_from_abi_struct(value, structs[field_type], structs) elif isinstance(field_type, list): value = get_abi_tuple_from_abi_struct(value, field_type, structs) result.append(value) return result def get_abi_tuple_type_from_abi_struct_definition( struct_def: list[StructField], structs: dict[str, list[StructField]] ) -> algosdk.abi.TupleType: """Creates a TupleType from a struct definition. :param struct_def: The struct field definitions :param structs: Dictionary of struct definitions :raises ValueError: If a field type is invalid :return: The TupleType representing the struct """ types = [] for field in struct_def: field_type = field.type if isinstance(field_type, str): if field_type in structs: types.append(get_abi_tuple_type_from_abi_struct_definition(structs[field_type], structs)) else: types.append(ABIType.from_string(field_type)) # type: ignore[arg-type] elif isinstance(field_type, list): types.append(get_abi_tuple_type_from_abi_struct_definition(field_type, structs)) else: raise ValueError(f"Invalid field type: {field_type}") return algosdk.abi.TupleType(types) def get_abi_struct_from_abi_tuple( decoded_tuple: Any, # noqa: ANN401 struct_fields: list[StructField], structs: dict[str, list[StructField]], ) -> dict[str, Any]: """Converts a decoded tuple to an ABI struct. :param decoded_tuple: The tuple to convert :param struct_fields: List of struct field definitions :param structs: Dictionary of struct definitions :return: The tuple as a struct dictionary """ result = {} for i, field in enumerate(struct_fields): key = field.name field_type = field.type value = decoded_tuple[i] if isinstance(field_type, str): if field_type in structs: value = get_abi_struct_from_abi_tuple(value, structs[field_type], structs) elif isinstance(field_type, list): value = get_abi_struct_from_abi_tuple(value, field_type, structs) result[key] = value return result @dataclass(kw_only=True, frozen=True) class BoxABIValue: """Represents an ABI value stored in a box. :ivar name: The name of the box :ivar value: The ABI value stored in the box """ name: BoxName value: ABIValue
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/abi.py
Python
MIT
10,087
from __future__ import annotations import base64 import copy import json import os from collections.abc import Sequence from dataclasses import asdict, dataclass, fields from typing import TYPE_CHECKING, Any, Generic, Literal, TypedDict, TypeVar import algosdk from algosdk.source_map import SourceMap from algosdk.transaction import OnComplete, Transaction from algokit_utils._debugging import PersistSourceMapInput, persist_sourcemaps from algokit_utils.applications.abi import ( ABIReturn, ABIStruct, ABIType, ABIValue, Arc56ReturnValueType, BoxABIValue, get_abi_decoded_value, get_abi_encoded_value, get_abi_tuple_from_abi_struct, ) from algokit_utils.applications.app_spec.arc32 import Arc32Contract from algokit_utils.applications.app_spec.arc56 import ( Arc56Contract, Method, PcOffsetMethod, ProgramSourceInfo, SourceInfo, StorageKey, StorageMap, ) from algokit_utils.config import config from algokit_utils.errors.logic_error import LogicError, parse_logic_error from algokit_utils.models.application import ( AppSourceMaps, AppState, CompiledTeal, ) from algokit_utils.models.state import BoxName, BoxValue from algokit_utils.models.transaction import SendParams from algokit_utils.protocols.account import TransactionSignerAccountProtocol from algokit_utils.transactions.transaction_composer import ( AppCallMethodCallParams, AppCallParams, AppCreateSchema, AppDeleteMethodCallParams, AppMethodCallTransactionArgument, AppUpdateMethodCallParams, AppUpdateParams, BuiltTransactions, PaymentParams, ) from algokit_utils.transactions.transaction_sender import ( SendAppTransactionResult, SendAppUpdateTransactionResult, SendSingleTransactionResult, ) if TYPE_CHECKING: from collections.abc import Callable from algosdk.atomic_transaction_composer import TransactionSigner from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.app_deployer import ApplicationLookup from algokit_utils.applications.app_manager import AppManager from algokit_utils.models.amount import AlgoAmount from algokit_utils.models.state import BoxIdentifier, BoxReference, TealTemplateParams __all__ = [ "AppClient", "AppClientBareCallCreateParams", "AppClientBareCallParams", "AppClientCompilationParams", "AppClientCompilationResult", "AppClientCreateSchema", "AppClientMethodCallCreateParams", "AppClientMethodCallParams", "AppClientParams", "AppSourceMaps", "BaseAppClientMethodCallParams", "CommonAppCallCreateParams", "CommonAppCallParams", "CreateOnComplete", "FundAppAccountParams", "get_constant_block_offset", ] # TEAL opcodes for constant blocks BYTE_CBLOCK = 38 # bytecblock opcode INT_CBLOCK = 32 # intcblock opcode T = TypeVar("T") # For generic return type in _handle_call_errors # Sentinel to detect missing arguments in clone() method of AppClient _MISSING = object() def get_constant_block_offset(program: bytes) -> int: # noqa: C901 """Calculate the offset after constant blocks in TEAL program. Analyzes a compiled TEAL program to find the ending offset position after any bytecblock and intcblock operations. :param program: The compiled TEAL program as bytes :return: The maximum offset position after any constant block operations """ bytes_list = list(program) program_size = len(bytes_list) # Remove version byte bytes_list.pop(0) # Track offsets bytecblock_offset: int | None = None intcblock_offset: int | None = None while bytes_list: # Get current byte byte = bytes_list.pop(0) # Check if byte is a constant block opcode if byte in (BYTE_CBLOCK, INT_CBLOCK): is_bytecblock = byte == BYTE_CBLOCK # Get number of values in constant block if not bytes_list: break values_remaining = bytes_list.pop(0) # Process each value in the block for _ in range(values_remaining): if is_bytecblock: # For bytecblock, next byte is length of element if not bytes_list: break length = bytes_list.pop(0) # Remove the bytes for this element bytes_list = bytes_list[length:] else: # For intcblock, read until we find end of uvarint (MSB not set) while bytes_list: byte = bytes_list.pop(0) if not (byte & 0x80): # Check if MSB is not set break # Update appropriate offset if is_bytecblock: bytecblock_offset = program_size - len(bytes_list) - 1 else: intcblock_offset = program_size - len(bytes_list) - 1 # If next byte isn't a constant block opcode, we're done if not bytes_list or bytes_list[0] not in (BYTE_CBLOCK, INT_CBLOCK): break # Return maximum offset return max(bytecblock_offset or 0, intcblock_offset or 0) CreateOnComplete = Literal[ OnComplete.NoOpOC, OnComplete.UpdateApplicationOC, OnComplete.DeleteApplicationOC, OnComplete.OptInOC, OnComplete.CloseOutOC, ] @dataclass(kw_only=True, frozen=True) class AppClientCompilationResult: """Result of compiling an application's TEAL code. Contains the compiled approval and clear state programs along with optional compilation artifacts. :ivar approval_program: The compiled approval program bytes :ivar clear_state_program: The compiled clear state program bytes :ivar compiled_approval: Optional compilation artifacts for approval program :ivar compiled_clear: Optional compilation artifacts for clear state program """ approval_program: bytes clear_state_program: bytes compiled_approval: CompiledTeal | None = None compiled_clear: CompiledTeal | None = None class AppClientCompilationParams(TypedDict, total=False): """Parameters for compiling an application's TEAL code. :ivar deploy_time_params: Optional template parameters to use during compilation :ivar updatable: Optional flag indicating if app should be updatable :ivar deletable: Optional flag indicating if app should be deletable """ deploy_time_params: TealTemplateParams | None updatable: bool | None deletable: bool | None ArgsT = TypeVar("ArgsT") MethodT = TypeVar("MethodT") @dataclass(kw_only=True, frozen=True) class CommonAppCallParams: """Common configuration for app call transaction parameters :ivar account_references: List of account addresses to reference :ivar app_references: List of app IDs to reference :ivar asset_references: List of asset IDs to reference :ivar box_references: List of box references to include :ivar extra_fee: Additional fee to add to transaction :ivar lease: Transaction lease value :ivar max_fee: Maximum fee allowed for transaction :ivar note: Arbitrary note for the transaction :ivar rekey_to: Address to rekey account to :ivar sender: Sender address override :ivar signer: Custom transaction signer :ivar static_fee: Fixed fee for transaction :ivar validity_window: Number of rounds valid :ivar first_valid_round: First valid round number :ivar last_valid_round: Last valid round number""" account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None extra_fee: AlgoAmount | None = None lease: bytes | None = None max_fee: AlgoAmount | None = None note: bytes | None = None rekey_to: str | None = None sender: str | None = None signer: TransactionSigner | None = None static_fee: AlgoAmount | None = None validity_window: int | None = None first_valid_round: int | None = None last_valid_round: int | None = None on_complete: OnComplete | None = None @dataclass(frozen=True) class AppClientCreateSchema: """Schema for application creation. :ivar extra_program_pages: Optional number of extra program pages :ivar schema: Optional application creation schema """ extra_program_pages: int | None = None schema: AppCreateSchema | None = None @dataclass(kw_only=True, frozen=True) class CommonAppCallCreateParams(AppClientCreateSchema, CommonAppCallParams): """Common configuration for app create call transaction parameters.""" on_complete: CreateOnComplete | None = None @dataclass(kw_only=True, frozen=True) class FundAppAccountParams(CommonAppCallParams): """Parameters for funding an application's account. :ivar amount: Amount to fund :ivar close_remainder_to: Optional address to close remainder to """ amount: AlgoAmount close_remainder_to: str | None = None @dataclass(kw_only=True, frozen=True) class AppClientBareCallParams(CommonAppCallParams): """Parameters for bare application calls. :ivar args: Optional arguments """ args: list[bytes] | None = None @dataclass(frozen=True) class AppClientBareCallCreateParams(CommonAppCallCreateParams): """Parameters for creating application with bare call.""" on_complete: CreateOnComplete | None = None @dataclass(kw_only=True, frozen=True) class BaseAppClientMethodCallParams(Generic[ArgsT, MethodT], CommonAppCallParams): """Base parameters for application method calls. :ivar method: Method to call :ivar args: Optional arguments to pass to method :ivar on_complete: Optional on complete action """ method: MethodT args: ArgsT | None = None @dataclass(kw_only=True, frozen=True) class AppClientMethodCallParams( BaseAppClientMethodCallParams[ Sequence[ABIValue | ABIStruct | AppMethodCallTransactionArgument | None], str, ] ): """Parameters for application method calls.""" @dataclass(frozen=True) class AppClientMethodCallCreateParams(AppClientCreateSchema, AppClientMethodCallParams): """Parameters for creating application with method call""" on_complete: CreateOnComplete | None = None class _AppClientStateMethods: def __init__( self, *, get_all: Callable[[], dict[str, Any]], get_value: Callable[[str, dict[str, AppState] | None], ABIValue | None], get_map_value: Callable[[str, bytes | Any, dict[str, AppState] | None], Any], get_map: Callable[[str], dict[str, ABIValue]], ) -> None: self._get_all = get_all self._get_value = get_value self._get_map_value = get_map_value self._get_map = get_map def get_all(self) -> dict[str, Any]: return self._get_all() def get_value(self, name: str, app_state: dict[str, AppState] | None = None) -> ABIValue | None: return self._get_value(name, app_state) def get_map_value(self, map_name: str, key: bytes | Any, app_state: dict[str, AppState] | None = None) -> Any: # noqa: ANN401 return self._get_map_value(map_name, key, app_state) def get_map(self, map_name: str) -> dict[str, ABIValue]: return self._get_map(map_name) class _AppClientBoxMethods: def __init__( self, *, get_all: Callable[[], dict[str, Any]], get_value: Callable[[str], ABIValue | None], get_map_value: Callable[[str, bytes | Any], Any], get_map: Callable[[str], dict[str, ABIValue]], ) -> None: self._get_all = get_all self._get_value = get_value self._get_map_value = get_map_value self._get_map = get_map def get_all(self) -> dict[str, Any]: return self._get_all() def get_value(self, name: str) -> ABIValue | None: return self._get_value(name) def get_map_value(self, map_name: str, key: bytes | Any) -> Any: # noqa: ANN401 return self._get_map_value(map_name, key) def get_map(self, map_name: str) -> dict[str, ABIValue]: return self._get_map(map_name) class _StateAccessor: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec def local_state(self, address: str) -> _AppClientStateMethods: """Methods to access local state for the current app for a given address""" return self._get_state_methods( state_getter=lambda: self._algorand.app.get_local_state(self._app_id, address), key_getter=lambda: self._app_spec.state.keys.local_state, map_getter=lambda: self._app_spec.state.maps.local_state, ) @property def global_state(self) -> _AppClientStateMethods: """Methods to access global state for the current app""" return self._get_state_methods( state_getter=lambda: self._algorand.app.get_global_state(self._app_id), key_getter=lambda: self._app_spec.state.keys.global_state, map_getter=lambda: self._app_spec.state.maps.global_state, ) @property def box(self) -> _AppClientBoxMethods: """Methods to access box storage for the current app""" return self._get_box_methods() def _get_box_methods(self) -> _AppClientBoxMethods: def get_all() -> dict[str, Any]: """Returns all single-key box values in a dict keyed by the key name.""" return {key: get_value(key) for key in self._app_spec.state.keys.box} def get_value(name: str) -> ABIValue | None: """Returns a single box value for the current app with the value a decoded ABI value. :param name: The name of the box value to retrieve :return: The decoded ABI value from the box storage, or None if not found """ metadata = self._app_spec.state.keys.box[name] value = self._algorand.app.get_box_value(self._app_id, base64.b64decode(metadata.key)) return get_abi_decoded_value(value, metadata.value_type, self._app_spec.structs) def get_map_value(map_name: str, key: bytes | Any) -> Any: # noqa: ANN401 """Get a value from a box map. Retrieves a value from a box map storage using the provided map name and key. :param map_name: The name of the map to read from :param key: The key within the map (without any map prefix) as either bytes or a value that will be converted to bytes by encoding it using the specified ABI key type :return: The decoded value from the box map storage """ metadata = self._app_spec.state.maps.box[map_name] prefix = base64.b64decode(metadata.prefix or "") encoded_key = get_abi_encoded_value(key, metadata.key_type, self._app_spec.structs) full_key = base64.b64encode(prefix + encoded_key).decode("utf-8") value = self._algorand.app.get_box_value(self._app_id, base64.b64decode(full_key)) return get_abi_decoded_value(value, metadata.value_type, self._app_spec.structs) def get_map(map_name: str) -> dict[str, ABIValue]: """Get all key-value pairs from a box map. Retrieves all key-value pairs stored in a box map for the current app. :param map_name: The name of the map to read from :return: A dictionary mapping string keys to their corresponding ABI-decoded values :raises ValueError: If there is an error decoding any key or value in the map """ metadata = self._app_spec.state.maps.box[map_name] prefix = base64.b64decode(metadata.prefix or "") box_names = self._algorand.app.get_box_names(self._app_id) result = {} for box in box_names: if not box.name_raw.startswith(prefix): continue encoded_key = prefix + box.name_raw base64_key = base64.b64encode(encoded_key).decode("utf-8") try: key = get_abi_decoded_value(box.name_raw[len(prefix) :], metadata.key_type, self._app_spec.structs) value = get_abi_decoded_value( self._algorand.app.get_box_value(self._app_id, base64.b64decode(base64_key)), metadata.value_type, self._app_spec.structs, ) result[str(key)] = value except Exception as e: if "Failed to decode key" in str(e): raise ValueError(f"Failed to decode key {base64_key}") from e raise ValueError(f"Failed to decode value for key {base64_key}") from e return result return _AppClientBoxMethods( get_all=get_all, get_value=get_value, get_map_value=get_map_value, get_map=get_map, ) def _get_state_methods( # noqa: C901 self, state_getter: Callable[[], dict[str, AppState]], key_getter: Callable[[], dict[str, StorageKey]], map_getter: Callable[[], dict[str, StorageMap]], ) -> _AppClientStateMethods: def get_all() -> dict[str, Any]: state = state_getter() keys = key_getter() return {key: get_value(key, state) for key in keys} def get_value(name: str, app_state: dict[str, AppState] | None = None) -> ABIValue | None: state = app_state or state_getter() key_info = key_getter()[name] value = next((s for s in state.values() if s.key_base64 == key_info.key), None) if value and value.value_raw: return get_abi_decoded_value(value.value_raw, key_info.value_type, self._app_spec.structs) return value.value if value else None def get_map_value(map_name: str, key: bytes | Any, app_state: dict[str, AppState] | None = None) -> Any: # noqa: ANN401 state = app_state or state_getter() metadata = map_getter()[map_name] prefix = base64.b64decode(metadata.prefix or "") encoded_key = get_abi_encoded_value(key, metadata.key_type, self._app_spec.structs) full_key = base64.b64encode(prefix + encoded_key).decode("utf-8") value = next((s for s in state.values() if s.key_base64 == full_key), None) if value and value.value_raw: return get_abi_decoded_value(value.value_raw, metadata.value_type, self._app_spec.structs) return value.value if value else None def get_map(map_name: str) -> dict[str, ABIValue]: state = state_getter() metadata = map_getter()[map_name] prefix = base64.b64decode(metadata.prefix or "").decode("utf-8") prefixed_state = {k: v for k, v in state.items() if k.startswith(prefix)} decoded_map = {} for key_encoded, value in prefixed_state.items(): key_bytes = key_encoded[len(prefix) :] try: decoded_key = get_abi_decoded_value(key_bytes, metadata.key_type, self._app_spec.structs) except Exception as e: raise ValueError(f"Failed to decode key {key_encoded}") from e try: if value and value.value_raw: decoded_value = get_abi_decoded_value( value.value_raw, metadata.value_type, self._app_spec.structs ) else: decoded_value = get_abi_decoded_value(value.value, metadata.value_type, self._app_spec.structs) except Exception as e: raise ValueError(f"Failed to decode value {value}") from e decoded_map[str(decoded_key)] = decoded_value return decoded_map return _AppClientStateMethods( get_all=get_all, get_value=get_value, get_map_value=get_map_value, get_map=get_map, ) def get_local_state(self, address: str) -> dict[str, AppState]: return self._algorand.app.get_local_state(self._app_id, address) def get_global_state(self) -> dict[str, AppState]: return self._algorand.app.get_global_state(self._app_id) class _BareParamsBuilder: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec def _get_bare_params( self, params: dict[str, Any] | None, on_complete: algosdk.transaction.OnComplete | None = None ) -> dict[str, Any]: params = params or {} sender = self._client._get_sender(params.get("sender")) return { **params, "app_id": self._app_id, "sender": sender, "signer": self._client._get_signer(params.get("sender"), params.get("signer")), "on_complete": on_complete or OnComplete.NoOpOC, } def update( self, params: AppClientBareCallParams | None = None, ) -> AppUpdateParams: """Create parameters for updating an application. :param params: Optional compilation and send parameters, defaults to None :return: Parameters for updating the application """ call_params: AppUpdateParams = AppUpdateParams( **self._get_bare_params(params.__dict__ if params else {}, OnComplete.UpdateApplicationOC) ) return call_params def opt_in(self, params: AppClientBareCallParams | None = None) -> AppCallParams: """Create parameters for opting into an application. :param params: Optional send parameters, defaults to None :return: Parameters for opting into the application """ call_params: AppCallParams = AppCallParams( **self._get_bare_params(params.__dict__ if params else {}, OnComplete.OptInOC) ) return call_params def delete(self, params: AppClientBareCallParams | None = None) -> AppCallParams: """Create parameters for deleting an application. :param params: Optional send parameters, defaults to None :return: Parameters for deleting the application """ call_params: AppCallParams = AppCallParams( **self._get_bare_params(params.__dict__ if params else {}, OnComplete.DeleteApplicationOC) ) return call_params def clear_state(self, params: AppClientBareCallParams | None = None) -> AppCallParams: """Create parameters for clearing application state. :param params: Optional send parameters, defaults to None :return: Parameters for clearing application state """ call_params: AppCallParams = AppCallParams( **self._get_bare_params(params.__dict__ if params else {}, OnComplete.ClearStateOC) ) return call_params def close_out(self, params: AppClientBareCallParams | None = None) -> AppCallParams: """Create parameters for closing out of an application. :param params: Optional send parameters, defaults to None :return: Parameters for closing out of the application """ call_params: AppCallParams = AppCallParams( **self._get_bare_params(params.__dict__ if params else {}, OnComplete.CloseOutOC) ) return call_params def call( self, params: AppClientBareCallParams | None = None, on_complete: OnComplete | None = OnComplete.NoOpOC ) -> AppCallParams: """Create parameters for calling an application. :param params: Optional call parameters with on complete action, defaults to None :param on_complete: The OnComplete action, defaults to OnComplete.NoOpOC :return: Parameters for calling the application """ call_params: AppCallParams = AppCallParams( **self._get_bare_params(params.__dict__ if params else {}, on_complete or OnComplete.NoOpOC) ) return call_params class _MethodParamsBuilder: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec self._bare_params_accessor = _BareParamsBuilder(client) @property def bare(self) -> _BareParamsBuilder: return self._bare_params_accessor def fund_app_account(self, params: FundAppAccountParams) -> PaymentParams: """Create parameters for funding an application account. :param params: Parameters for funding the application account :return: Parameters for sending a payment transaction to fund the application account """ def random_note() -> bytes: return base64.b64encode(os.urandom(16)) return PaymentParams( sender=self._client._get_sender(params.sender), signer=self._client._get_signer(params.sender, params.signer), receiver=self._client.app_address, amount=params.amount, rekey_to=params.rekey_to, note=params.note or random_note(), lease=params.lease, static_fee=params.static_fee, extra_fee=params.extra_fee, max_fee=params.max_fee, validity_window=params.validity_window, first_valid_round=params.first_valid_round, last_valid_round=params.last_valid_round, close_remainder_to=params.close_remainder_to, ) def opt_in(self, params: AppClientMethodCallParams) -> AppCallMethodCallParams: """Create parameters for opting into an application. :param params: Parameters for the opt-in call :return: Parameters for opting into the application """ input_params = self._get_abi_params( params.__dict__, on_complete=params.on_complete or algosdk.transaction.OnComplete.OptInOC ) return AppCallMethodCallParams(**input_params) def call(self, params: AppClientMethodCallParams) -> AppCallMethodCallParams: """Create parameters for calling an application method. :param params: Parameters for the method call :return: Parameters for calling the application method """ input_params = self._get_abi_params( params.__dict__, on_complete=params.on_complete or algosdk.transaction.OnComplete.NoOpOC ) return AppCallMethodCallParams(**input_params) def delete(self, params: AppClientMethodCallParams) -> AppDeleteMethodCallParams: """Create parameters for deleting an application. :param params: Parameters for the delete call :return: Parameters for deleting the application """ input_params = self._get_abi_params( params.__dict__, on_complete=params.on_complete or algosdk.transaction.OnComplete.DeleteApplicationOC ) return AppDeleteMethodCallParams(**input_params) def update( self, params: AppClientMethodCallParams, compilation_params: AppClientCompilationParams | None = None ) -> AppUpdateMethodCallParams: """Create parameters for updating an application. :param params: Parameters for the update call, optionally including compilation parameters :param compilation_params: Parameters for the compilation, defaults to None :return: Parameters for updating the application """ compile_params = asdict( self._client.compile( app_spec=self._client.app_spec, app_manager=self._algorand.app, compilation_params=compilation_params, ) ) input_params = { **self._get_abi_params( params.__dict__, on_complete=params.on_complete or algosdk.transaction.OnComplete.UpdateApplicationOC ), **compile_params, } # Filter input_params to include only fields valid for AppUpdateMethodCallParams app_update_method_call_fields = {field.name for field in fields(AppUpdateMethodCallParams)} filtered_input_params = {k: v for k, v in input_params.items() if k in app_update_method_call_fields} return AppUpdateMethodCallParams(**filtered_input_params) def close_out(self, params: AppClientMethodCallParams) -> AppCallMethodCallParams: """Create parameters for closing out of an application. :param params: Parameters for the close-out call :return: Parameters for closing out of the application """ input_params = self._get_abi_params( params.__dict__, on_complete=params.on_complete or algosdk.transaction.OnComplete.CloseOutOC ) return AppCallMethodCallParams(**input_params) def _get_abi_params(self, params: dict[str, Any], on_complete: algosdk.transaction.OnComplete) -> dict[str, Any]: input_params = copy.deepcopy(params) input_params["app_id"] = self._app_id input_params["on_complete"] = on_complete input_params["sender"] = self._client._get_sender(params["sender"]) input_params["signer"] = self._client._get_signer(params["sender"], params["signer"]) if params.get("method"): input_params["method"] = self._app_spec.get_arc56_method(params["method"]).to_abi_method() input_params["args"] = self._client._get_abi_args_with_default_values( method_name_or_signature=params["method"], args=params.get("args"), sender=self._client._get_sender(input_params["sender"]), ) return input_params class _AppClientBareCallCreateTransactionMethods: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand def update(self, params: AppClientBareCallParams | None = None) -> Transaction: """Create a transaction to update an application. Creates a transaction that will update an existing application with new approval and clear state programs. :param params: Parameters for the update call including compilation and transaction options, defaults to None :return: The constructed application update transaction """ return self._algorand.create_transaction.app_update( self._client.params.bare.update(params or AppClientBareCallParams()) ) def opt_in(self, params: AppClientBareCallParams | None = None) -> Transaction: """Create a transaction to opt into an application. Creates a transaction that will opt the sender account into using this application. :param params: Parameters for the opt-in call including transaction options, defaults to None :return: The constructed opt-in transaction """ return self._algorand.create_transaction.app_call( self._client.params.bare.opt_in(params or AppClientBareCallParams()) ) def delete(self, params: AppClientBareCallParams | None = None) -> Transaction: """Create a transaction to delete an application. Creates a transaction that will delete this application from the blockchain. :param params: Parameters for the delete call including transaction options, defaults to None :return: The constructed delete transaction """ return self._algorand.create_transaction.app_call( self._client.params.bare.delete(params or AppClientBareCallParams()) ) def clear_state(self, params: AppClientBareCallParams | None = None) -> Transaction: """Create a transaction to clear application state. Creates a transaction that will clear the sender's local state for this application. :param params: Parameters for the clear state call including transaction options, defaults to None :return: The constructed clear state transaction """ return self._algorand.create_transaction.app_call( self._client.params.bare.clear_state(params or AppClientBareCallParams()) ) def close_out(self, params: AppClientBareCallParams | None = None) -> Transaction: """Create a transaction to close out of an application. Creates a transaction that will close out the sender's participation in this application. :param params: Parameters for the close out call including transaction options, defaults to None :return: The constructed close out transaction """ return self._algorand.create_transaction.app_call( self._client.params.bare.close_out(params or AppClientBareCallParams()) ) def call( self, params: AppClientBareCallParams | None = None, on_complete: OnComplete | None = OnComplete.NoOpOC ) -> Transaction: """Create a transaction to call an application. Creates a transaction that will call this application with the specified parameters. :param params: Parameters for the application call including on complete action, defaults to None :param on_complete: The OnComplete action, defaults to OnComplete.NoOpOC :return: The constructed application call transaction """ return self._algorand.create_transaction.app_call( self._client.params.bare.call(params or AppClientBareCallParams(), on_complete or OnComplete.NoOpOC) ) class _TransactionCreator: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec self._bare_create_transaction_methods = _AppClientBareCallCreateTransactionMethods(client) @property def bare(self) -> _AppClientBareCallCreateTransactionMethods: return self._bare_create_transaction_methods def fund_app_account(self, params: FundAppAccountParams) -> Transaction: """Create a transaction to fund an application account. Creates a payment transaction to fund the application account with the specified parameters. :param params: Parameters for funding the application account including amount and transaction options :return: The constructed payment transaction """ return self._algorand.create_transaction.payment(self._client.params.fund_app_account(params)) def opt_in(self, params: AppClientMethodCallParams) -> BuiltTransactions: """Create a transaction to opt into an application. Creates a transaction that will opt the sender into this application with the specified parameters. :param params: Parameters for the opt-in call including method arguments and transaction options :return: The constructed opt-in transaction(s) """ return self._algorand.create_transaction.app_call_method_call(self._client.params.opt_in(params)) def update(self, params: AppClientMethodCallParams) -> BuiltTransactions: """Create a transaction to update an application. Creates a transaction that will update this application with new approval and clear state programs. :param params: Parameters for the update call including method arguments and transaction options :return: The constructed update transaction(s) """ return self._algorand.create_transaction.app_update_method_call(self._client.params.update(params)) def delete(self, params: AppClientMethodCallParams) -> BuiltTransactions: """Create a transaction to delete an application. Creates a transaction that will delete this application. :param params: Parameters for the delete call including method arguments and transaction options :return: The constructed delete transaction(s) """ return self._algorand.create_transaction.app_delete_method_call(self._client.params.delete(params)) def close_out(self, params: AppClientMethodCallParams) -> BuiltTransactions: """Create a transaction to close out of an application. Creates a transaction that will close out the sender's participation in this application. :param params: Parameters for the close out call including method arguments and transaction options :return: The constructed close out transaction(s) """ return self._algorand.create_transaction.app_call_method_call(self._client.params.close_out(params)) def call(self, params: AppClientMethodCallParams) -> BuiltTransactions: """Create a transaction to call an application. Creates a transaction that will call this application with the specified parameters. :param params: Parameters for the application call including method arguments and transaction options :return: The constructed application call transaction(s) """ return self._algorand.create_transaction.app_call_method_call(self._client.params.call(params)) class _AppClientBareSendAccessor: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec def update( self, params: AppClientBareCallParams | None = None, send_params: SendParams | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> SendAppTransactionResult[ABIReturn]: """Send an application update transaction. Sends a transaction to update an existing application with new approval and clear state programs. :param params: The parameters for the update call, including optional compilation parameters, deploy time parameters, and transaction configuration :param send_params: Send parameters, defaults to None :param compilation_params: Parameters for the compilation, defaults to None :return: The result of sending the transaction, including compilation artifacts and ABI return value if applicable """ params = params or AppClientBareCallParams() compilation = compilation_params or AppClientCompilationParams() compiled = self._client.compile_app( { "deploy_time_params": compilation.get("deploy_time_params"), "updatable": compilation.get("updatable"), "deletable": compilation.get("deletable"), } ) bare_params = self._client.params.bare.update(params) bare_params.__setattr__("approval_program", bare_params.approval_program or compiled.compiled_approval) bare_params.__setattr__("clear_state_program", bare_params.clear_state_program or compiled.compiled_clear) call_result = self._client._handle_call_errors(lambda: self._algorand.send.app_update(bare_params, send_params)) return SendAppTransactionResult[ABIReturn]( **{**call_result.__dict__, **(compiled.__dict__ if compiled else {})}, abi_return=AppManager.get_abi_return(call_result.confirmation, getattr(params, "method", None)), ) def opt_in( self, params: AppClientBareCallParams | None = None, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Send an application opt-in transaction. Creates and sends a transaction that will opt the sender's account into this application. :param params: Parameters for the opt-in call including transaction options, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._algorand.send.app_call( self._client.params.bare.opt_in(params or AppClientBareCallParams()), send_params ) ) def delete( self, params: AppClientBareCallParams | None = None, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Send an application delete transaction. Creates and sends a transaction that will delete this application. :param params: Parameters for the delete call including transaction options, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._algorand.send.app_call( self._client.params.bare.delete(params or AppClientBareCallParams()), send_params ) ) def clear_state( self, params: AppClientBareCallParams | None = None, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Send an application clear state transaction. Creates and sends a transaction that will clear the sender's local state for this application. :param params: Parameters for the clear state call including transaction options, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._algorand.send.app_call( self._client.params.bare.clear_state(params or AppClientBareCallParams()), send_params ) ) def close_out( self, params: AppClientBareCallParams | None = None, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Send an application close out transaction. Creates and sends a transaction that will close out the sender's participation in this application. :param params: Parameters for the close out call including transaction options, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._algorand.send.app_call( self._client.params.bare.close_out(params or AppClientBareCallParams()), send_params ) ) def call( self, params: AppClientBareCallParams | None = None, on_complete: OnComplete | None = None, send_params: SendParams | None = None, ) -> SendAppTransactionResult[ABIReturn]: """Send an application call transaction. Creates and sends a transaction that will call this application with the specified parameters. :param params: Parameters for the application call including transaction options, defaults to None :param on_complete: The OnComplete action, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._algorand.send.app_call( self._client.params.bare.call(params or AppClientBareCallParams(), on_complete), send_params ) ) class _TransactionSender: def __init__(self, client: AppClient) -> None: self._client = client self._algorand = client._algorand self._app_id = client._app_id self._app_spec = client._app_spec self._bare_send_accessor = _AppClientBareSendAccessor(client) @property def bare(self) -> _AppClientBareSendAccessor: """Get accessor for bare application calls. :return: Accessor for making bare application calls without ABI encoding """ return self._bare_send_accessor def fund_app_account( self, params: FundAppAccountParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Send funds to the application account. Creates and sends a payment transaction to fund the application account. :param params: Parameters for funding the app account including amount and transaction options :param send_params: Send parameters, defaults to None :return: The result of sending the payment transaction """ return self._client._handle_call_errors( # type: ignore[no-any-return] lambda: self._algorand.send.payment(self._client.params.fund_app_account(params), send_params) ) def opt_in( self, params: AppClientMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[Arc56ReturnValueType]: """Send an application opt-in transaction. Creates and sends a transaction that will opt the sender into this application. :param params: Parameters for the opt-in call including method and transaction options :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._client._process_method_call_return( lambda: self._algorand.send.app_call_method_call(self._client.params.opt_in(params), send_params), self._app_spec.get_arc56_method(params.method), ) ) def delete( self, params: AppClientMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[Arc56ReturnValueType]: """Send an application delete transaction. Creates and sends a transaction that will delete this application. :param params: Parameters for the delete call including method and transaction options :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._client._process_method_call_return( lambda: self._algorand.send.app_delete_method_call(self._client.params.delete(params), send_params), self._app_spec.get_arc56_method(params.method), ) ) def update( self, params: AppClientMethodCallParams, compilation_params: AppClientCompilationParams | None = None, send_params: SendParams | None = None, ) -> SendAppUpdateTransactionResult[Arc56ReturnValueType]: """Send an application update transaction. Creates and sends a transaction that will update this application's program. :param params: Parameters for the update call including method, compilation and transaction options :param compilation_params: Parameters for the compilation, defaults to None :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ result = self._client._handle_call_errors( lambda: self._client._process_method_call_return( lambda: self._algorand.send.app_update_method_call( self._client.params.update(params, compilation_params), send_params ), self._app_spec.get_arc56_method(params.method), ) ) assert isinstance(result, SendAppUpdateTransactionResult) return result def close_out( self, params: AppClientMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[Arc56ReturnValueType]: """Send an application close out transaction. Creates and sends a transaction that will close out the sender's participation in this application. :param params: Parameters for the close out call including method and transaction options :param send_params: Send parameters, defaults to None :return: The result of sending the transaction, including ABI return value if applicable """ return self._client._handle_call_errors( lambda: self._client._process_method_call_return( lambda: self._algorand.send.app_call_method_call(self._client.params.close_out(params), send_params), self._app_spec.get_arc56_method(params.method), ) ) def call( self, params: AppClientMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[Arc56ReturnValueType]: """Send an application call transaction. Creates and sends a transaction that will call this application with the specified parameters. For read-only calls, simulates the transaction instead of sending it. :param params: Parameters for the application call including method and transaction options :param send_params: Send parameters :return: The result of sending or simulating the transaction, including ABI return value if applicable """ is_read_only_call = ( params.on_complete == algosdk.transaction.OnComplete.NoOpOC or params.on_complete is None ) and self._app_spec.get_arc56_method(params.method).readonly if is_read_only_call: method_call_to_simulate = self._algorand.new_group().add_app_call_method_call( self._client.params.call(params) ) send_params = send_params or SendParams() simulate_response = self._client._handle_call_errors( lambda: method_call_to_simulate.simulate( allow_unnamed_resources=send_params.get("populate_app_call_resources") or True, skip_signatures=True, allow_more_logs=True, allow_empty_signatures=True, extra_opcode_budget=None, exec_trace_config=None, simulation_round=None, ) ) return SendAppTransactionResult[Arc56ReturnValueType]( tx_ids=simulate_response.tx_ids, transactions=simulate_response.transactions, transaction=simulate_response.transactions[-1], confirmation=simulate_response.confirmations[-1] if simulate_response.confirmations else b"", confirmations=simulate_response.confirmations, group_id=simulate_response.group_id or "", returns=simulate_response.returns, abi_return=simulate_response.returns[-1].get_arc56_value( self._app_spec.get_arc56_method(params.method), self._app_spec.structs ), ) return self._client._handle_call_errors( lambda: self._client._process_method_call_return( lambda: self._algorand.send.app_call_method_call(self._client.params.call(params), send_params), self._app_spec.get_arc56_method(params.method), ) ) @dataclass(kw_only=True, frozen=True) class AppClientParams: """Full parameters for creating an app client""" app_spec: Arc56Contract | Arc32Contract | str algorand: AlgorandClient app_id: int app_name: str | None = None default_sender: str | None = None default_signer: TransactionSigner | None = None approval_source_map: SourceMap | None = None clear_source_map: SourceMap | None = None class AppClient: """A client for interacting with an Algorand smart contract application. Provides a high-level interface for interacting with Algorand smart contracts, including methods for calling application methods, managing state, and handling transactions. :param params: Parameters for creating the app client """ def __init__(self, params: AppClientParams) -> None: self._app_id = params.app_id self._app_spec = self.normalise_app_spec(params.app_spec) self._algorand = params.algorand self._app_address = algosdk.logic.get_application_address(self._app_id) self._app_name = params.app_name or self._app_spec.name self._default_sender = params.default_sender self._default_signer = params.default_signer self._approval_source_map = params.approval_source_map self._clear_source_map = params.clear_source_map self._state_accessor = _StateAccessor(self) self._params_accessor = _MethodParamsBuilder(self) self._send_accessor = _TransactionSender(self) self._create_transaction_accessor = _TransactionCreator(self) @property def algorand(self) -> AlgorandClient: """Get the Algorand client instance. :return: The Algorand client used by this app client """ return self._algorand @property def app_id(self) -> int: """Get the application ID. :return: The ID of the Algorand application """ return self._app_id @property def app_address(self) -> str: """Get the application's Algorand address. :return: The Algorand address associated with this application """ return self._app_address @property def app_name(self) -> str: """Get the application name. :return: The name of the application """ return self._app_name @property def app_spec(self) -> Arc56Contract: """Get the application specification. :return: The ARC-56 contract specification for this application """ return self._app_spec @property def state(self) -> _StateAccessor: """Get the state accessor. :return: The state accessor for this application """ return self._state_accessor @property def params(self) -> _MethodParamsBuilder: """Get the method parameters builder. :return: The method parameters builder for this application """ return self._params_accessor @property def send(self) -> _TransactionSender: """Get the transaction sender. :return: The transaction sender for this application """ return self._send_accessor @property def create_transaction(self) -> _TransactionCreator: """Get the transaction creator. :return: The transaction creator for this application """ return self._create_transaction_accessor @staticmethod def normalise_app_spec(app_spec: Arc56Contract | Arc32Contract | str) -> Arc56Contract: """Normalize an application specification to ARC-56 format. :param app_spec: The application specification to normalize :return: The normalized ARC-56 contract specification :raises ValueError: If the app spec format is invalid """ if isinstance(app_spec, str): spec_dict = json.loads(app_spec) spec = Arc32Contract.from_json(app_spec) if "hints" in spec_dict else spec_dict else: spec = app_spec match spec: case Arc56Contract(): return spec case Arc32Contract(): return Arc56Contract.from_arc32(spec.to_json()) case dict(): return Arc56Contract.from_dict(spec) case _: raise ValueError("Invalid app spec format") @staticmethod def from_network( app_spec: Arc56Contract | Arc32Contract | str, algorand: AlgorandClient, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: """Create an AppClient instance from network information. :param app_spec: The application specification :param algorand: The Algorand client instance :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :return: A new AppClient instance :raises Exception: If no app ID is found for the network """ network = algorand.client.network() app_spec = AppClient.normalise_app_spec(app_spec) network_names = [network.genesis_hash] if network.is_localnet: network_names.append("localnet") if network.is_mainnet: network_names.append("mainnet") if network.is_testnet: network_names.append("testnet") available_app_spec_networks = list(app_spec.networks.keys()) if app_spec.networks else [] network_index = next((i for i, n in enumerate(available_app_spec_networks) if n in network_names), None) if network_index is None: raise Exception(f"No app ID found for network {json.dumps(network_names)} in the app spec") app_id = app_spec.networks[available_app_spec_networks[network_index]].app_id # type: ignore[index] return AppClient( AppClientParams( app_id=app_id, app_spec=app_spec, algorand=algorand, app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, ) ) @staticmethod def from_creator_and_name( creator_address: str, app_name: str, app_spec: Arc56Contract | Arc32Contract | str, algorand: AlgorandClient, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ignore_cache: bool | None = None, app_lookup_cache: ApplicationLookup | None = None, ) -> AppClient: """Create an AppClient instance from creator address and application name. :param creator_address: The address of the application creator :param app_name: The name of the application :param app_spec: The application specification :param algorand: The Algorand client instance :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :param ignore_cache: Optional flag to ignore cache :param app_lookup_cache: Optional app lookup cache :return: A new AppClient instance :raises ValueError: If the app is not found for the creator and name """ app_spec_ = AppClient.normalise_app_spec(app_spec) app_lookup = app_lookup_cache or algorand.app_deployer.get_creator_apps_by_name( creator_address=creator_address, ignore_cache=ignore_cache or False ) app_metadata = app_lookup.apps.get(app_name or app_spec_.name) if not app_metadata: raise ValueError(f"App not found for creator {creator_address} and name {app_name or app_spec_.name}") return AppClient( AppClientParams( app_id=app_metadata.app_id, app_spec=app_spec_, algorand=algorand, app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, ) ) @staticmethod def compile( app_spec: Arc56Contract, app_manager: AppManager, compilation_params: AppClientCompilationParams | None = None, ) -> AppClientCompilationResult: """Compile the application's TEAL code. :param app_spec: The application specification :param app_manager: The application manager instance :param compilation_params: Optional compilation parameters :return: The compilation result :raises ValueError: If attempting to compile without source or byte code """ compilation_params = compilation_params or AppClientCompilationParams() deploy_time_params = compilation_params.get("deploy_time_params") updatable = compilation_params.get("updatable") deletable = compilation_params.get("deletable") def is_base64(s: str) -> bool: try: return base64.b64encode(base64.b64decode(s)).decode() == s except Exception: return False if not app_spec.source: if not app_spec.byte_code or not app_spec.byte_code.approval or not app_spec.byte_code.clear: raise ValueError(f"Attempt to compile app {app_spec.name} without source or byte_code") return AppClientCompilationResult( approval_program=base64.b64decode(app_spec.byte_code.approval), clear_state_program=base64.b64decode(app_spec.byte_code.clear), ) compiled_approval = app_manager.compile_teal_template( app_spec.source.get_decoded_approval(), template_params=deploy_time_params, deployment_metadata=( {"updatable": updatable, "deletable": deletable} if updatable is not None or deletable is not None else None ), ) compiled_clear = app_manager.compile_teal_template( app_spec.source.get_decoded_clear(), template_params=deploy_time_params, ) if config.debug and config.project_root: persist_sourcemaps( sources=[ PersistSourceMapInput( compiled_teal=compiled_approval, app_name=app_spec.name, file_name="approval.teal" ), PersistSourceMapInput(compiled_teal=compiled_clear, app_name=app_spec.name, file_name="clear.teal"), ], project_root=config.project_root, client=app_manager._algod, with_sources=True, ) return AppClientCompilationResult( approval_program=compiled_approval.compiled_base64_to_bytes, compiled_approval=compiled_approval, clear_state_program=compiled_clear.compiled_base64_to_bytes, compiled_clear=compiled_clear, ) @staticmethod def _expose_logic_error_static( # noqa: C901 *, e: Exception, app_spec: Arc56Contract, is_clear_state_program: bool = False, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, program: bytes | None = None, approval_source_info: ProgramSourceInfo | None = None, clear_source_info: ProgramSourceInfo | None = None, ) -> LogicError | Exception: source_map = clear_source_map if is_clear_state_program else approval_source_map error_details = parse_logic_error(str(e)) if not error_details: return e # The PC value to find in the ARC56 SourceInfo arc56_pc = error_details["pc"] program_source_info = clear_source_info if is_clear_state_program else approval_source_info # The offset to apply to the PC if using the cblocks pc offset method cblocks_offset = 0 # If the program uses cblocks offset, then we need to adjust the PC accordingly if program_source_info and program_source_info.pc_offset_method == PcOffsetMethod.CBLOCKS: if not program: raise Exception("Program bytes are required to calculate the ARC56 cblocks PC offset") cblocks_offset = get_constant_block_offset(program) arc56_pc = error_details["pc"] - cblocks_offset # Find the source info for this PC and get the error message source_info = None if program_source_info and program_source_info.source_info: source_info = next( (s for s in program_source_info.source_info if isinstance(s, SourceInfo) and arc56_pc in s.pc), None, ) error_message = source_info.error_message if source_info else None # If we have the source we can display the TEAL in the error message if hasattr(app_spec, "source"): program_source = ( ( app_spec.source.get_decoded_clear() if is_clear_state_program else app_spec.source.get_decoded_approval() ) if app_spec.source else None ) custom_get_line_for_pc = None def get_line_for_pc(input_pc: int) -> int | None: if not program_source_info: return None teal = [line.teal for line in program_source_info.source_info if input_pc - cblocks_offset in line.pc] return teal[0] if teal else None if not source_map: custom_get_line_for_pc = get_line_for_pc if program_source: e = LogicError( logic_error_str=str(e), program=program_source, source_map=source_map, transaction_id=error_details["transaction_id"], message=error_details["message"], pc=error_details["pc"], logic_error=e, get_line_for_pc=custom_get_line_for_pc, traces=None, ) if error_message: import re message = e.logic_error_str if isinstance(e, LogicError) else str(e) app_id = re.search(r"(?<=app=)\d+", message) tx_id = re.search(r"(?<=transaction )\S+(?=:)", message) runtime_error_message = ( f"Runtime error when executing {app_spec.name} " f"(appId: {app_id.group() if app_id else 'N/A'}) in transaction " f"{tx_id.group() if tx_id else 'N/A'}: {error_message}" ) if isinstance(e, LogicError): e.message = runtime_error_message return e else: error = Exception(runtime_error_message) error.__cause__ = e return error return e def compile_app( self, compilation_params: AppClientCompilationParams | None = None, ) -> AppClientCompilationResult: """Compile the application's TEAL code. :param compilation_params: Optional compilation parameters :return: The compilation result """ result = AppClient.compile(self._app_spec, self._algorand.app, compilation_params) if result.compiled_approval: self._approval_source_map = result.compiled_approval.source_map if result.compiled_clear: self._clear_source_map = result.compiled_clear.source_map return result def clone( self, app_name: str | None = _MISSING, # type: ignore[assignment] default_sender: str | None = _MISSING, # type: ignore[assignment] default_signer: TransactionSigner | None = _MISSING, # type: ignore[assignment] approval_source_map: SourceMap | None = _MISSING, # type: ignore[assignment] clear_source_map: SourceMap | None = _MISSING, # type: ignore[assignment] ) -> AppClient: """Create a cloned AppClient instance with optionally overridden parameters. :param app_name: Optional new application name :param default_sender: Optional new default sender :param default_signer: Optional new default signer :param approval_source_map: Optional new approval source map :param clear_source_map: Optional new clear source map :return: A new AppClient instance with the specified parameters """ return AppClient( AppClientParams( app_id=self._app_id, algorand=self._algorand, app_spec=self._app_spec, app_name=self._app_name if app_name is _MISSING else app_name, default_sender=self._default_sender if default_sender is _MISSING else default_sender, default_signer=self._default_signer if default_signer is _MISSING else default_signer, approval_source_map=( self._approval_source_map if approval_source_map is _MISSING else approval_source_map ), clear_source_map=(self._clear_source_map if clear_source_map is _MISSING else clear_source_map), ) ) def export_source_maps(self) -> AppSourceMaps: """Export the application's source maps. :return: The application's source maps :raises ValueError: If source maps haven't been loaded """ if not self._approval_source_map or not self._clear_source_map: raise ValueError( "Unable to export source maps; they haven't been loaded into this client - " "you need to call create, update, or deploy first" ) return AppSourceMaps( approval_source_map=self._approval_source_map, clear_source_map=self._clear_source_map, ) def import_source_maps(self, source_maps: AppSourceMaps) -> None: """Import source maps for the application. :param source_maps: The source maps to import :raises ValueError: If source maps are invalid or missing """ if not source_maps.approval_source_map: raise ValueError("Approval source map is required") if not source_maps.clear_source_map: raise ValueError("Clear source map is required") if not isinstance(source_maps.approval_source_map, dict | SourceMap): raise ValueError( "Approval source map supplied is of invalid type. Must be a raw dict or `algosdk.source_map.SourceMap`" ) if not isinstance(source_maps.clear_source_map, dict | SourceMap): raise ValueError( "Clear source map supplied is of invalid type. Must be a raw dict or `algosdk.source_map.SourceMap`" ) self._approval_source_map = ( SourceMap(source_map=source_maps.approval_source_map) if isinstance(source_maps.approval_source_map, dict) else source_maps.approval_source_map ) self._clear_source_map = ( SourceMap(source_map=source_maps.clear_source_map) if isinstance(source_maps.clear_source_map, dict) else source_maps.clear_source_map ) def get_local_state(self, address: str) -> dict[str, AppState]: """Get local state for an account. :param address: The account address :return: The account's local state for this application """ return self._state_accessor.get_local_state(address) def get_global_state(self) -> dict[str, AppState]: """Get the application's global state. :return: The application's global state """ return self._state_accessor.get_global_state() def get_box_names(self) -> list[BoxName]: """Get all box names for the application. :return: List of box names """ return self._algorand.app.get_box_names(self._app_id) def get_box_value(self, name: BoxIdentifier) -> bytes: """Get the value of a box. :param name: The box identifier :return: The box value as bytes """ return self._algorand.app.get_box_value(self._app_id, name) def get_box_value_from_abi_type(self, name: BoxIdentifier, abi_type: ABIType) -> ABIValue: """Get a box value decoded according to an ABI type. :param name: The box identifier :param abi_type: The ABI type to decode as :return: The decoded box value """ return self._algorand.app.get_box_value_from_abi_type(self._app_id, name, abi_type) def get_box_values(self, filter_func: Callable[[BoxName], bool] | None = None) -> list[BoxValue]: """Get values for multiple boxes. :param filter_func: Optional function to filter box names :return: List of box values """ names = [n for n in self.get_box_names() if not filter_func or filter_func(n)] values = self._algorand.app.get_box_values(self.app_id, [n.name_raw for n in names]) return [BoxValue(name=n, value=v) for n, v in zip(names, values, strict=False)] def get_box_values_from_abi_type( self, abi_type: ABIType, filter_func: Callable[[BoxName], bool] | None = None ) -> list[BoxABIValue]: """Get multiple box values decoded according to an ABI type. :param abi_type: The ABI type to decode as :param filter_func: Optional function to filter box names :return: List of decoded box values """ names = self.get_box_names() if filter_func: names = [name for name in names if filter_func(name)] values = self._algorand.app.get_box_values_from_abi_type( self.app_id, [name.name_raw for name in names], abi_type ) return [BoxABIValue(name=name, value=values[i]) for i, name in enumerate(names)] def fund_app_account( self, params: FundAppAccountParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Fund the application's account. :param params: The funding parameters :param send_params: Send parameters, defaults to None :return: The transaction result """ return self.send.fund_app_account(params, send_params) def _expose_logic_error(self, e: Exception, *, is_clear_state_program: bool = False) -> Exception: source_info = None if hasattr(self._app_spec, "source_info") and self._app_spec.source_info: source_info = ( self._app_spec.source_info.clear if is_clear_state_program else self._app_spec.source_info.approval ) pc_offset_method = source_info.pc_offset_method if source_info else None program: bytes | None = None if pc_offset_method == "cblocks": app_info = self._algorand.app.get_by_id(self.app_id) program = app_info.clear_state_program if is_clear_state_program else app_info.approval_program return AppClient._expose_logic_error_static( e=e, app_spec=self._app_spec, is_clear_state_program=is_clear_state_program, approval_source_map=self._approval_source_map, clear_source_map=self._clear_source_map, program=program, approval_source_info=(self._app_spec.source_info.approval if self._app_spec.source_info else None), clear_source_info=(self._app_spec.source_info.clear if self._app_spec.source_info else None), ) def _handle_call_errors(self, call: Callable[[], T]) -> T: try: return call() except Exception as e: raise self._expose_logic_error(e=e) from None def _get_sender(self, sender: str | None) -> str: if not sender and not self._default_sender: raise Exception( f"No sender provided and no default sender present in app client for call to app {self.app_name}" ) return sender or self._default_sender # type: ignore[return-value] def _get_signer( self, sender: str | None, signer: TransactionSigner | TransactionSignerAccountProtocol | None ) -> TransactionSigner | TransactionSignerAccountProtocol | None: return signer or (self._default_signer if not sender or sender == self._default_sender else None) def _get_bare_params(self, params: dict[str, Any], on_complete: algosdk.transaction.OnComplete) -> dict[str, Any]: sender = self._get_sender(params.get("sender")) return { **params, "app_id": self._app_id, "sender": sender, "signer": self._get_signer(params.get("sender"), params.get("signer")), "on_complete": on_complete, } def _get_abi_args_with_default_values( # noqa: C901, PLR0912 self, *, method_name_or_signature: str, args: Sequence[ABIValue | ABIStruct | AppMethodCallTransactionArgument | None] | None, sender: str, ) -> list[Any]: method = self._app_spec.get_arc56_method(method_name_or_signature) result: list[ABIValue | ABIStruct | AppMethodCallTransactionArgument | None] = [] for i, method_arg in enumerate(method.args): arg_value = args[i] if args and i < len(args) else None if arg_value is not None: if method_arg.struct and isinstance(arg_value, dict): arg_value = get_abi_tuple_from_abi_struct( arg_value, self._app_spec.structs[method_arg.struct], self._app_spec.structs ) result.append(arg_value) continue default_value = method_arg.default_value if default_value: match default_value.source: case "literal": value_raw = base64.b64decode(default_value.data) value_type = default_value.type or method_arg.type result.append(get_abi_decoded_value(value_raw, value_type, self._app_spec.structs)) case "method": default_method = self._app_spec.get_arc56_method(default_value.data) empty_args = [None] * len(default_method.args) call_result = self.send.call( AppClientMethodCallParams( method=default_value.data, args=empty_args, sender=sender, ) ) if not call_result.abi_return: raise ValueError("Default value method call did not return a value") if isinstance(call_result.abi_return, dict): result.append( get_abi_tuple_from_abi_struct( call_result.abi_return, self._app_spec.structs[str(default_method.returns.struct)], self._app_spec.structs, ) ) elif call_result.abi_return: result.append(call_result.abi_return) case "local" | "global": state = ( self.get_global_state() if default_value.source == "global" else self.get_local_state(sender) ) value = next((s for s in state.values() if s.key_base64 == default_value.data), None) if not value: raise ValueError( f"Key '{default_value.data}' not found in {default_value.source} " f"storage for argument {method_arg.name or f'arg{i+1}'}" ) if value.value_raw: value_type = default_value.type or method_arg.type result.append(get_abi_decoded_value(value.value_raw, value_type, self._app_spec.structs)) else: result.append(value.value) case "box": box_name = base64.b64decode(default_value.data) box_value = self._algorand.app.get_box_value(self._app_id, box_name) value_type = default_value.type or method_arg.type result.append(get_abi_decoded_value(box_value, value_type, self._app_spec.structs)) elif not algosdk.abi.is_abi_transaction_type(method_arg.type): raise ValueError( f"No value provided for required argument " f"{method_arg.name or f'arg{i+1}'} in call to method {method.name}" ) elif arg_value is None and default_value is None: # At this point only allow explicit None values if no default value was identified result.append(None) return result def _get_abi_params(self, params: dict[str, Any], on_complete: algosdk.transaction.OnComplete) -> dict[str, Any]: sender = self._get_sender(params.get("sender")) method = self._app_spec.get_arc56_method(params["method"]) args = self._get_abi_args_with_default_values( method_name_or_signature=params["method"], args=params.get("args"), sender=sender ) return { **params, "appId": self._app_id, "sender": sender, "signer": self._get_signer(params.get("sender"), params.get("signer")), "method": method, "onComplete": on_complete, "args": args, } def _process_method_call_return( self, result: Callable[[], SendAppUpdateTransactionResult[ABIReturn] | SendAppTransactionResult[ABIReturn]], method: Method, ) -> SendAppUpdateTransactionResult[Arc56ReturnValueType] | SendAppTransactionResult[Arc56ReturnValueType]: result_value = result() abi_return = ( result_value.abi_return.get_arc56_value(method, self._app_spec.structs) if isinstance(result_value.abi_return, ABIReturn) else None ) if isinstance(result_value, SendAppUpdateTransactionResult): return SendAppUpdateTransactionResult[Arc56ReturnValueType]( **{**result_value.__dict__, "abi_return": abi_return} ) return SendAppTransactionResult[Arc56ReturnValueType](**{**result_value.__dict__, "abi_return": abi_return})
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_client.py
Python
MIT
83,432
import base64 import dataclasses import json from dataclasses import asdict, dataclass from typing import Literal from algosdk.logic import get_application_address from algosdk.v2client.indexer import IndexerClient from algokit_utils.applications.abi import ABIReturn from algokit_utils.applications.app_manager import AppManager from algokit_utils.applications.enums import OnSchemaBreak, OnUpdate, OperationPerformed from algokit_utils.config import config from algokit_utils.models.state import TealTemplateParams from algokit_utils.models.transaction import SendParams from algokit_utils.transactions.transaction_composer import ( AppCreateMethodCallParams, AppCreateParams, AppDeleteMethodCallParams, AppDeleteParams, AppUpdateMethodCallParams, AppUpdateParams, TransactionComposer, ) from algokit_utils.transactions.transaction_sender import ( AlgorandClientTransactionSender, SendAppCreateTransactionResult, SendAppTransactionResult, SendAppUpdateTransactionResult, ) __all__ = [ "APP_DEPLOY_NOTE_DAPP", "AppDeployParams", "AppDeployResult", "AppDeployer", "AppDeploymentMetaData", "ApplicationLookup", "ApplicationMetaData", "ApplicationReference", "OnSchemaBreak", "OnUpdate", "OperationPerformed", ] APP_DEPLOY_NOTE_DAPP: str = "ALGOKIT_DEPLOYER" logger = config.logger @dataclasses.dataclass class AppDeploymentMetaData: """Metadata about an application stored in a transaction note during creation.""" name: str version: str deletable: bool | None updatable: bool | None def dictify(self) -> dict[str, str | bool]: return {k: v for k, v in asdict(self).items() if v is not None} @dataclasses.dataclass(frozen=True) class ApplicationReference: """Information about an Algorand app""" app_id: int app_address: str @dataclasses.dataclass(frozen=True) class ApplicationMetaData: """Complete metadata about a deployed app""" reference: ApplicationReference deploy_metadata: AppDeploymentMetaData created_round: int updated_round: int deleted: bool = False @property def app_id(self) -> int: return self.reference.app_id @property def app_address(self) -> str: return self.reference.app_address @property def name(self) -> str: return self.deploy_metadata.name @property def version(self) -> str: return self.deploy_metadata.version @property def deletable(self) -> bool | None: return self.deploy_metadata.deletable @property def updatable(self) -> bool | None: return self.deploy_metadata.updatable @dataclasses.dataclass class ApplicationLookup: """Cache of {py:class}`ApplicationMetaData` for a specific `creator` Can be used as an argument to {py:class}`ApplicationClient` to reduce the number of calls when deploying multiple apps or discovering multiple app_ids """ creator: str apps: dict[str, ApplicationMetaData] = dataclasses.field(default_factory=dict) @dataclass(kw_only=True) class AppDeployParams: """Parameters for deploying an app""" metadata: AppDeploymentMetaData deploy_time_params: TealTemplateParams | None = None on_schema_break: (Literal["replace", "fail", "append"] | OnSchemaBreak) | None = None on_update: (Literal["update", "replace", "fail", "append"] | OnUpdate) | None = None create_params: AppCreateParams | AppCreateMethodCallParams update_params: AppUpdateParams | AppUpdateMethodCallParams delete_params: AppDeleteParams | AppDeleteMethodCallParams existing_deployments: ApplicationLookup | None = None ignore_cache: bool = False max_fee: int | None = None send_params: SendParams | None = None # Union type for all possible deploy results @dataclass(frozen=True) class AppDeployResult: app: ApplicationMetaData operation_performed: OperationPerformed create_result: SendAppCreateTransactionResult[ABIReturn] | None = None update_result: SendAppUpdateTransactionResult[ABIReturn] | None = None delete_result: SendAppTransactionResult[ABIReturn] | None = None class AppDeployer: """Manages deployment and deployment metadata of applications""" def __init__( self, app_manager: AppManager, transaction_sender: AlgorandClientTransactionSender, indexer: IndexerClient | None = None, ): self._app_manager = app_manager self._transaction_sender = transaction_sender self._indexer = indexer self._app_lookups: dict[str, ApplicationLookup] = {} def deploy(self, deployment: AppDeployParams) -> AppDeployResult: # Create new instances with updated notes send_params = deployment.send_params or SendParams() suppress_log = send_params.get("suppress_log") or False logger.info( f"Idempotently deploying app \"{deployment.metadata.name}\" from creator " f"{deployment.create_params.sender} using {len(deployment.create_params.approval_program)} bytes of " f"{'teal code' if isinstance(deployment.create_params.approval_program, str) else 'AVM bytecode'} and " f"{len(deployment.create_params.clear_state_program)} bytes of " f"{'teal code' if isinstance(deployment.create_params.clear_state_program, str) else 'AVM bytecode'}", suppress_log=suppress_log, ) note = TransactionComposer.arc2_note( { "dapp_name": APP_DEPLOY_NOTE_DAPP, "format": "j", "data": deployment.metadata.dictify(), } ) create_params = dataclasses.replace(deployment.create_params, note=note) update_params = dataclasses.replace(deployment.update_params, note=note) deployment = dataclasses.replace( deployment, create_params=create_params, update_params=update_params, ) # Validate inputs if ( deployment.existing_deployments and deployment.existing_deployments.creator != deployment.create_params.sender ): raise ValueError( f"Received invalid existingDeployments value for creator " f"{deployment.existing_deployments.creator} when attempting to deploy " f"for creator {deployment.create_params.sender}" ) if not deployment.existing_deployments and not self._indexer: raise ValueError( "Didn't receive an indexer client when this AppManager was created, " "but also didn't receive an existingDeployments cache - one of them must be provided" ) # Compile code if needed approval_program = deployment.create_params.approval_program clear_program = deployment.create_params.clear_state_program if isinstance(approval_program, str): compiled_approval = self._app_manager.compile_teal_template( approval_program, deployment.deploy_time_params, deployment.metadata.__dict__, ) approval_program = compiled_approval.compiled_base64_to_bytes if isinstance(clear_program, str): compiled_clear = self._app_manager.compile_teal_template( clear_program, deployment.deploy_time_params, ) clear_program = compiled_clear.compiled_base64_to_bytes # Get existing app metadata apps = deployment.existing_deployments or self.get_creator_apps_by_name( creator_address=deployment.create_params.sender, ignore_cache=deployment.ignore_cache, ) existing_app = apps.apps.get(deployment.metadata.name) if not existing_app or existing_app.deleted: return self._create_app( deployment=deployment, approval_program=approval_program, clear_program=clear_program, ) # Check for changes existing_app_record = self._app_manager.get_by_id(existing_app.app_id) existing_approval = base64.b64encode(existing_app_record.approval_program).decode() existing_clear = base64.b64encode(existing_app_record.clear_state_program).decode() new_approval = base64.b64encode(approval_program).decode() new_clear = base64.b64encode(clear_program).decode() is_update = new_approval != existing_approval or new_clear != existing_clear is_schema_break = ( existing_app_record.local_ints < (deployment.create_params.schema.get("local_ints", 0) if deployment.create_params.schema else 0) or existing_app_record.global_ints < (deployment.create_params.schema.get("global_ints", 0) if deployment.create_params.schema else 0) or existing_app_record.local_byte_slices < (deployment.create_params.schema.get("local_byte_slices", 0) if deployment.create_params.schema else 0) or existing_app_record.global_byte_slices < (deployment.create_params.schema.get("global_byte_slices", 0) if deployment.create_params.schema else 0) ) if is_schema_break: logger.warning( f"Detected a breaking app schema change in app {existing_app.app_id}:", extra={ "from": { "global_ints": existing_app_record.global_ints, "global_byte_slices": existing_app_record.global_byte_slices, "local_ints": existing_app_record.local_ints, "local_byte_slices": existing_app_record.local_byte_slices, }, "to": deployment.create_params.schema, }, suppress_log=suppress_log, ) return self._handle_schema_break( deployment=deployment, existing_app=existing_app, approval_program=approval_program, clear_program=clear_program, ) if is_update: return self._handle_update( deployment=deployment, existing_app=existing_app, approval_program=approval_program, clear_program=clear_program, ) logger.debug("No detected changes in app, nothing to do.", suppress_log=suppress_log) return AppDeployResult( app=existing_app, operation_performed=OperationPerformed.Nothing, ) def _create_app( self, deployment: AppDeployParams, approval_program: bytes, clear_program: bytes, ) -> AppDeployResult: """Create a new application""" if isinstance(deployment.create_params, AppCreateMethodCallParams): create_result = self._transaction_sender.app_create_method_call( AppCreateMethodCallParams( **{ **asdict(deployment.create_params), "approval_program": approval_program, "clear_state_program": clear_program, } ), send_params=deployment.send_params, ) else: create_result = self._transaction_sender.app_create( AppCreateParams( **{ **asdict(deployment.create_params), "approval_program": approval_program, "clear_state_program": clear_program, } ), send_params=deployment.send_params, ) app_metadata = ApplicationMetaData( reference=ApplicationReference( app_id=create_result.app_id, app_address=get_application_address(create_result.app_id) ), deploy_metadata=deployment.metadata, created_round=create_result.confirmation.get("confirmed-round", 0) if isinstance(create_result.confirmation, dict) else 0, updated_round=create_result.confirmation.get("confirmed-round", 0) if isinstance(create_result.confirmation, dict) else 0, deleted=False, ) self._update_app_lookup(deployment.create_params.sender, app_metadata) return AppDeployResult( app=app_metadata, operation_performed=OperationPerformed.Create, create_result=create_result, ) def _replace_app( self, deployment: AppDeployParams, existing_app: ApplicationMetaData, approval_program: bytes, clear_program: bytes, ) -> AppDeployResult: composer = self._transaction_sender.new_group() # Add create transaction if isinstance(deployment.create_params, AppCreateMethodCallParams): composer.add_app_create_method_call( AppCreateMethodCallParams( **{ **deployment.create_params.__dict__, "approval_program": approval_program, "clear_state_program": clear_program, } ) ) else: composer.add_app_create( AppCreateParams( **{ **deployment.create_params.__dict__, "approval_program": approval_program, "clear_state_program": clear_program, } ) ) create_txn_index = composer.count() - 1 # Add delete transaction if isinstance(deployment.delete_params, AppDeleteMethodCallParams): delete_call_params = AppDeleteMethodCallParams( **{ **deployment.delete_params.__dict__, "app_id": existing_app.app_id, } ) composer.add_app_delete_method_call(delete_call_params) else: delete_params = AppDeleteParams( **{ **deployment.delete_params.__dict__, "app_id": existing_app.app_id, } ) composer.add_app_delete(delete_params) delete_txn_index = composer.count() - 1 result = composer.send() create_result = SendAppCreateTransactionResult[ABIReturn].from_composer_result(result, create_txn_index) delete_result = SendAppTransactionResult[ABIReturn].from_composer_result(result, delete_txn_index) app_id = int(result.confirmations[0]["application-index"]) # type: ignore[call-overload] app_metadata = ApplicationMetaData( reference=ApplicationReference(app_id=app_id, app_address=get_application_address(app_id)), deploy_metadata=deployment.metadata, created_round=result.confirmations[0]["confirmed-round"], # type: ignore[call-overload] updated_round=result.confirmations[0]["confirmed-round"], # type: ignore[call-overload] deleted=False, ) self._update_app_lookup(deployment.create_params.sender, app_metadata) return AppDeployResult( app=app_metadata, operation_performed=OperationPerformed.Replace, create_result=create_result, update_result=None, delete_result=delete_result, ) def _update_app( self, deployment: AppDeployParams, existing_app: ApplicationMetaData, approval_program: bytes, clear_program: bytes, ) -> AppDeployResult: """Update an existing application""" if isinstance(deployment.update_params, AppUpdateMethodCallParams): result = self._transaction_sender.app_update_method_call( AppUpdateMethodCallParams( **{ **deployment.update_params.__dict__, "app_id": existing_app.app_id, "approval_program": approval_program, "clear_state_program": clear_program, } ), send_params=deployment.send_params, ) else: result = self._transaction_sender.app_update( AppUpdateParams( **{ **deployment.update_params.__dict__, "app_id": existing_app.app_id, "approval_program": approval_program, "clear_state_program": clear_program, } ), send_params=deployment.send_params, ) app_metadata = ApplicationMetaData( reference=ApplicationReference(app_id=existing_app.app_id, app_address=existing_app.app_address), deploy_metadata=deployment.metadata, created_round=existing_app.created_round, updated_round=result.confirmation.get("confirmed-round", 0) if isinstance(result.confirmation, dict) else 0, deleted=False, ) self._update_app_lookup(deployment.create_params.sender, app_metadata) return AppDeployResult( app=app_metadata, operation_performed=OperationPerformed.Update, update_result=result, ) def _handle_schema_break( self, deployment: AppDeployParams, existing_app: ApplicationMetaData, approval_program: bytes, clear_program: bytes, ) -> AppDeployResult: if deployment.on_schema_break in (OnSchemaBreak.Fail, "fail") or deployment.on_schema_break is None: raise ValueError( "Schema break detected and onSchemaBreak=OnSchemaBreak.Fail, stopping deployment. " "If you want to try deleting and recreating the app then " "re-run with onSchemaBreak=OnSchemaBreak.ReplaceApp" ) if deployment.on_schema_break in (OnSchemaBreak.AppendApp, "append"): return self._create_app(deployment, approval_program, clear_program) if existing_app.deletable: return self._replace_app(deployment, existing_app, approval_program, clear_program) else: raise ValueError("App is not deletable but onSchemaBreak=ReplaceApp, " "cannot delete and recreate app") def _handle_update( self, deployment: AppDeployParams, existing_app: ApplicationMetaData, approval_program: bytes, clear_program: bytes, ) -> AppDeployResult: if deployment.on_update in (OnUpdate.Fail, "fail") or deployment.on_update is None: raise ValueError( "Update detected and onUpdate=Fail, stopping deployment. " "Try a different onUpdate value to not fail." ) if deployment.on_update in (OnUpdate.AppendApp, "append"): return self._create_app(deployment, approval_program, clear_program) if deployment.on_update in (OnUpdate.UpdateApp, "update"): if existing_app.updatable: return self._update_app(deployment, existing_app, approval_program, clear_program) else: raise ValueError("App is not updatable but onUpdate=UpdateApp, cannot update app") if deployment.on_update in (OnUpdate.ReplaceApp, "replace"): if existing_app.deletable: return self._replace_app(deployment, existing_app, approval_program, clear_program) else: raise ValueError("App is not deletable but onUpdate=ReplaceApp, " "cannot delete and recreate app") raise ValueError(f"Unsupported onUpdate value: {deployment.on_update}") def _update_app_lookup(self, sender: str, app_metadata: ApplicationMetaData) -> None: """Update the app lookup cache""" lookup = self._app_lookups.get(sender) if not lookup: self._app_lookups[sender] = ApplicationLookup( creator=sender, apps={app_metadata.name: app_metadata}, ) else: lookup.apps[app_metadata.name] = app_metadata def get_creator_apps_by_name(self, *, creator_address: str, ignore_cache: bool = False) -> ApplicationLookup: """Get apps created by an account""" if not ignore_cache and creator_address in self._app_lookups: return self._app_lookups[creator_address] if not self._indexer: raise ValueError( "Didn't receive an indexer client when this AppManager was created, " "but received a call to get_creator_apps" ) app_lookup: dict[str, ApplicationMetaData] = {} # Get all apps created by account created_apps = self._indexer.search_applications(creator=creator_address) for app in created_apps["applications"]: app_id = app["id"] # Get creation transaction creation_txns = self._indexer.search_transactions( application_id=app_id, min_round=app["created-at-round"], address=creator_address, address_role="sender", note_prefix=APP_DEPLOY_NOTE_DAPP.encode(), limit=1, ) if not creation_txns["transactions"]: continue creation_txn = creation_txns["transactions"][0] try: note = base64.b64decode(creation_txn["note"]).decode() if not note.startswith(f"{APP_DEPLOY_NOTE_DAPP}:j"): continue metadata = json.loads(note[len(APP_DEPLOY_NOTE_DAPP) + 2 :]) if metadata.get("name"): app_lookup[metadata["name"]] = ApplicationMetaData( reference=ApplicationReference(app_id=app_id, app_address=get_application_address(app_id)), deploy_metadata=AppDeploymentMetaData( name=metadata["name"], version=metadata.get("version", "1.0"), deletable=metadata.get("deletable"), updatable=metadata.get("updatable"), ), created_round=creation_txn["confirmed-round"], updated_round=creation_txn["confirmed-round"], deleted=app.get("deleted", False), ) except Exception as e: logger.warning( f"Error processing app {app_id} for creator {creator_address}: {e}", ) continue lookup = ApplicationLookup(creator=creator_address, apps=app_lookup) self._app_lookups[creator_address] = lookup return lookup
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_deployer.py
Python
MIT
23,099
import base64 import dataclasses from collections.abc import Callable, Sequence from dataclasses import asdict, dataclass from typing import Any, Generic, TypeVar from algosdk.atomic_transaction_composer import TransactionSigner from algosdk.source_map import SourceMap from algosdk.transaction import OnComplete, Transaction from typing_extensions import Self from algokit_utils._legacy_v2.application_specification import ApplicationSpecification from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.abi import ( ABIReturn, Arc56ReturnValueType, get_abi_decoded_value, get_abi_tuple_from_abi_struct, ) from algokit_utils.applications.app_client import ( AppClient, AppClientBareCallCreateParams, AppClientBareCallParams, AppClientCompilationParams, AppClientCompilationResult, AppClientMethodCallCreateParams, AppClientMethodCallParams, AppClientParams, CreateOnComplete, ) from algokit_utils.applications.app_deployer import ( AppDeploymentMetaData, AppDeployParams, AppDeployResult, ApplicationLookup, ApplicationMetaData, OnSchemaBreak, OnUpdate, OperationPerformed, ) from algokit_utils.applications.app_manager import DELETABLE_TEMPLATE_NAME, UPDATABLE_TEMPLATE_NAME from algokit_utils.applications.app_spec.arc56 import Arc56Contract, Method from algokit_utils.models.application import ( AppSourceMaps, ) from algokit_utils.models.transaction import SendParams from algokit_utils.transactions.transaction_composer import ( AppCreateMethodCallParams, AppCreateParams, AppDeleteMethodCallParams, AppDeleteParams, AppUpdateMethodCallParams, AppUpdateParams, BuiltTransactions, ) from algokit_utils.transactions.transaction_sender import ( SendAppCreateTransactionResult, SendAppTransactionResult, SendAppUpdateTransactionResult, SendSingleTransactionResult, ) T = TypeVar("T") __all__ = [ "AppFactory", "AppFactoryCreateMethodCallParams", "AppFactoryCreateMethodCallResult", "AppFactoryCreateParams", "AppFactoryDeployResult", "AppFactoryParams", "SendAppCreateFactoryTransactionResult", "SendAppFactoryTransactionResult", "SendAppUpdateFactoryTransactionResult", ] @dataclass(kw_only=True, frozen=True) class AppFactoryParams: algorand: AlgorandClient app_spec: Arc56Contract | ApplicationSpecification | str app_name: str | None = None default_sender: str | None = None default_signer: TransactionSigner | None = None version: str | None = None compilation_params: AppClientCompilationParams | None = None @dataclass(kw_only=True, frozen=True) class AppFactoryCreateParams(AppClientBareCallCreateParams): on_complete: CreateOnComplete | None = None @dataclass(kw_only=True, frozen=True) class AppFactoryCreateMethodCallParams(AppClientMethodCallCreateParams): pass ABIReturnT = TypeVar( "ABIReturnT", bound=Arc56ReturnValueType, ) @dataclass(frozen=True, kw_only=True) class AppFactoryCreateMethodCallResult(SendSingleTransactionResult, Generic[ABIReturnT]): app_id: int app_address: str compiled_approval: Any | None = None compiled_clear: Any | None = None abi_return: ABIReturnT | None = None @dataclass(frozen=True) class SendAppFactoryTransactionResult(SendAppTransactionResult[Arc56ReturnValueType]): pass @dataclass(frozen=True) class SendAppUpdateFactoryTransactionResult(SendAppUpdateTransactionResult[Arc56ReturnValueType]): pass @dataclass(frozen=True, kw_only=True) class SendAppCreateFactoryTransactionResult(SendAppCreateTransactionResult[Arc56ReturnValueType]): pass @dataclass(frozen=True) class AppFactoryDeployResult: """Result from deploying an application via AppFactory""" app: ApplicationMetaData operation_performed: OperationPerformed create_result: SendAppCreateFactoryTransactionResult | None = None update_result: SendAppUpdateFactoryTransactionResult | None = None delete_result: SendAppFactoryTransactionResult | None = None @classmethod def from_deploy_result( cls, response: AppDeployResult, deploy_params: AppDeployParams, app_spec: Arc56Contract, app_compilation_data: AppClientCompilationResult | None = None, ) -> Self: def to_factory_result( response_data: SendAppTransactionResult[ABIReturn] | SendAppCreateTransactionResult | SendAppUpdateTransactionResult | None, params: Any, # noqa: ANN401 ) -> Any | None: # noqa: ANN401 if not response_data: return None response_data_dict = asdict(response_data) abi_return = response_data.abi_return if abi_return and abi_return.method: response_data_dict["abi_return"] = abi_return.get_arc56_value(params.method, app_spec.structs) match response_data: case SendAppCreateTransactionResult(): return SendAppCreateFactoryTransactionResult(**response_data_dict) case SendAppUpdateTransactionResult(): response_data_dict["compiled_approval"] = ( app_compilation_data.compiled_approval if app_compilation_data else None ) response_data_dict["compiled_clear"] = ( app_compilation_data.compiled_clear if app_compilation_data else None ) return SendAppUpdateFactoryTransactionResult(**response_data_dict) case SendAppTransactionResult(): return SendAppFactoryTransactionResult(**response_data_dict) return cls( app=response.app, operation_performed=response.operation_performed, create_result=to_factory_result( response.create_result, deploy_params.create_params, ), update_result=to_factory_result( response.update_result, deploy_params.update_params, ), delete_result=to_factory_result( response.delete_result, deploy_params.delete_params, ), ) class _BareParamsBuilder: def __init__(self, factory: "AppFactory") -> None: self._factory = factory self._algorand = factory._algorand def create( self, params: AppFactoryCreateParams | None = None, compilation_params: AppClientCompilationParams | None = None ) -> AppCreateParams: base_params = params or AppFactoryCreateParams() compiled = self._factory.compile(compilation_params) return AppCreateParams( **{ **{ param: value for param, value in asdict(base_params).items() if param in {f.name for f in dataclasses.fields(AppCreateParams)} }, "approval_program": compiled.approval_program, "clear_state_program": compiled.clear_state_program, "schema": base_params.schema or { "global_byte_slices": self._factory._app_spec.state.schema.global_state.bytes, "global_ints": self._factory._app_spec.state.schema.global_state.ints, "local_byte_slices": self._factory._app_spec.state.schema.local_state.bytes, "local_ints": self._factory._app_spec.state.schema.local_state.ints, }, "sender": self._factory._get_sender(base_params.sender), "signer": self._factory._get_signer(base_params.sender, base_params.signer), "on_complete": base_params.on_complete or OnComplete.NoOpOC, } ) def deploy_update(self, params: AppClientBareCallParams | None = None) -> AppUpdateParams: return AppUpdateParams( **{ **{ param: value for param, value in asdict(params or AppClientBareCallParams()).items() if param in {f.name for f in dataclasses.fields(AppUpdateParams)} }, "app_id": 0, "approval_program": "", "clear_state_program": "", "sender": self._factory._get_sender(params.sender if params else None), "on_complete": OnComplete.UpdateApplicationOC, "signer": self._factory._get_signer( params.sender if params else None, params.signer if params else None ), } ) def deploy_delete(self, params: AppClientBareCallParams | None = None) -> AppDeleteParams: return AppDeleteParams( **{ **{ param: value for param, value in asdict(params or AppClientBareCallParams()).items() if param in {f.name for f in dataclasses.fields(AppDeleteParams)} }, "app_id": 0, "sender": self._factory._get_sender(params.sender if params else None), "signer": self._factory._get_signer( params.sender if params else None, params.signer if params else None ), "on_complete": OnComplete.DeleteApplicationOC, } ) class _MethodParamsBuilder: def __init__(self, factory: "AppFactory") -> None: self._factory = factory self._bare = _BareParamsBuilder(factory) @property def bare(self) -> _BareParamsBuilder: return self._bare def create( self, params: AppFactoryCreateMethodCallParams, compilation_params: AppClientCompilationParams | None = None ) -> AppCreateMethodCallParams: compiled = self._factory.compile(compilation_params) return AppCreateMethodCallParams( **{ **{ param: value for param, value in asdict(params).items() if param in {f.name for f in dataclasses.fields(AppCreateMethodCallParams)} }, "app_id": 0, "approval_program": compiled.approval_program, "clear_state_program": compiled.clear_state_program, "schema": params.schema or { "global_byte_slices": self._factory._app_spec.state.schema.global_state.bytes, "global_ints": self._factory._app_spec.state.schema.global_state.ints, "local_byte_slices": self._factory._app_spec.state.schema.local_state.bytes, "local_ints": self._factory._app_spec.state.schema.local_state.ints, }, "sender": self._factory._get_sender(params.sender), "signer": self._factory._get_signer( params.sender if params else None, params.signer if params else None ), "method": self._factory._app_spec.get_arc56_method(params.method).to_abi_method(), "args": self._factory._get_create_abi_args_with_default_values(params.method, params.args), "on_complete": params.on_complete or OnComplete.NoOpOC, } ) def deploy_update(self, params: AppClientMethodCallParams) -> AppUpdateMethodCallParams: return AppUpdateMethodCallParams( **{ **{ param: value for param, value in asdict(params).items() if param in {f.name for f in dataclasses.fields(AppUpdateMethodCallParams)} }, "app_id": 0, "approval_program": "", "clear_state_program": "", "sender": self._factory._get_sender(params.sender), "signer": self._factory._get_signer( params.sender if params else None, params.signer if params else None ), "method": self._factory._app_spec.get_arc56_method(params.method).to_abi_method(), "args": self._factory._get_create_abi_args_with_default_values(params.method, params.args), "on_complete": OnComplete.UpdateApplicationOC, } ) def deploy_delete(self, params: AppClientMethodCallParams) -> AppDeleteMethodCallParams: return AppDeleteMethodCallParams( **{ **{ param: value for param, value in asdict(params).items() if param in {f.name for f in dataclasses.fields(AppDeleteMethodCallParams)} }, "app_id": 0, "sender": self._factory._get_sender(params.sender), "signer": self._factory._get_signer( params.sender if params else None, params.signer if params else None ), "method": self._factory.app_spec.get_arc56_method(params.method).to_abi_method(), "args": self._factory._get_create_abi_args_with_default_values(params.method, params.args), "on_complete": OnComplete.DeleteApplicationOC, } ) class _AppFactoryBareCreateTransactionAccessor: def __init__(self, factory: "AppFactory") -> None: self._factory = factory def create(self, params: AppFactoryCreateParams | None = None) -> Transaction: return self._factory._algorand.create_transaction.app_create(self._factory.params.bare.create(params)) class _TransactionCreator: def __init__(self, factory: "AppFactory") -> None: self._factory = factory self._bare = _AppFactoryBareCreateTransactionAccessor(factory) @property def bare(self) -> _AppFactoryBareCreateTransactionAccessor: return self._bare def create(self, params: AppFactoryCreateMethodCallParams) -> BuiltTransactions: return self._factory._algorand.create_transaction.app_create_method_call(self._factory.params.create(params)) class _AppFactoryBareSendAccessor: def __init__(self, factory: "AppFactory") -> None: self._factory = factory self._algorand = factory._algorand def create( self, params: AppFactoryCreateParams | None = None, send_params: SendParams | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> tuple[AppClient, SendAppCreateTransactionResult]: compilation_params = compilation_params or AppClientCompilationParams() compilation_params["updatable"] = ( compilation_params.get("updatable") if compilation_params.get("updatable") is not None else self._factory._updatable ) compilation_params["deletable"] = ( compilation_params.get("deletable") if compilation_params.get("deletable") is not None else self._factory._deletable ) compilation_params["deploy_time_params"] = ( compilation_params.get("deploy_time_params") if compilation_params.get("deploy_time_params") is not None else self._factory._deploy_time_params ) compiled = self._factory.compile(compilation_params) result = self._factory._handle_call_errors( lambda: self._algorand.send.app_create( self._factory.params.bare.create(params, compilation_params), send_params ) ) return ( self._factory.get_app_client_by_id( app_id=result.app_id, ), SendAppCreateTransactionResult[ABIReturn]( transaction=result.transaction, confirmation=result.confirmation, app_id=result.app_id, app_address=result.app_address, compiled_approval=compiled.compiled_approval if compiled else None, compiled_clear=compiled.compiled_clear if compiled else None, group_id=result.group_id, tx_ids=result.tx_ids, transactions=result.transactions, confirmations=result.confirmations, ), ) class _TransactionSender: def __init__(self, factory: "AppFactory") -> None: self._factory = factory self._algorand = factory._algorand self._bare = _AppFactoryBareSendAccessor(factory) @property def bare(self) -> _AppFactoryBareSendAccessor: return self._bare def create( self, params: AppFactoryCreateMethodCallParams, send_params: SendParams | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> tuple[AppClient, AppFactoryCreateMethodCallResult[Arc56ReturnValueType]]: compilation_params = compilation_params or AppClientCompilationParams() compilation_params["updatable"] = ( compilation_params.get("updatable") if compilation_params.get("updatable") is not None else self._factory._updatable ) compilation_params["deletable"] = ( compilation_params.get("deletable") if compilation_params.get("deletable") is not None else self._factory._deletable ) compilation_params["deploy_time_params"] = ( compilation_params.get("deploy_time_params") if compilation_params.get("deploy_time_params") is not None else self._factory._deploy_time_params ) compiled = self._factory.compile(compilation_params) result = self._factory._handle_call_errors( lambda: self._factory._parse_method_call_return( lambda: self._algorand.send.app_create_method_call( self._factory.params.create(params, compilation_params), send_params ), self._factory._app_spec.get_arc56_method(params.method), ) ) return ( self._factory.get_app_client_by_id( app_id=result.app_id, ), AppFactoryCreateMethodCallResult[Arc56ReturnValueType]( transaction=result.transaction, confirmation=result.confirmation, tx_id=result.tx_id, app_id=result.app_id, app_address=result.app_address, abi_return=result.abi_return, compiled_approval=compiled.compiled_approval if compiled else None, compiled_clear=compiled.compiled_clear if compiled else None, group_id=result.group_id, tx_ids=result.tx_ids, transactions=result.transactions, confirmations=result.confirmations, returns=result.returns, ), ) class AppFactory: def __init__(self, params: AppFactoryParams) -> None: self._app_spec = AppClient.normalise_app_spec(params.app_spec) self._app_name = params.app_name or self._app_spec.name self._algorand = params.algorand self._version = params.version or "1.0" self._default_sender = params.default_sender self._default_signer = params.default_signer self._approval_source_map: SourceMap | None = None self._clear_source_map: SourceMap | None = None self._params_accessor = _MethodParamsBuilder(self) self._send_accessor = _TransactionSender(self) self._create_transaction_accessor = _TransactionCreator(self) compilation_params = params.compilation_params or AppClientCompilationParams() self._deploy_time_params = compilation_params.get("deploy_time_params") self._updatable = compilation_params.get("updatable") self._deletable = compilation_params.get("deletable") @property def app_name(self) -> str: return self._app_name @property def app_spec(self) -> Arc56Contract: return self._app_spec @property def algorand(self) -> AlgorandClient: return self._algorand @property def params(self) -> _MethodParamsBuilder: return self._params_accessor @property def send(self) -> _TransactionSender: return self._send_accessor @property def create_transaction(self) -> _TransactionCreator: return self._create_transaction_accessor def deploy( self, *, on_update: OnUpdate | None = None, on_schema_break: OnSchemaBreak | None = None, create_params: AppClientMethodCallCreateParams | AppClientBareCallCreateParams | None = None, update_params: AppClientMethodCallParams | AppClientBareCallParams | None = None, delete_params: AppClientMethodCallParams | AppClientBareCallParams | None = None, existing_deployments: ApplicationLookup | None = None, ignore_cache: bool = False, app_name: str | None = None, send_params: SendParams | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> tuple[AppClient, AppFactoryDeployResult]: """Deploy the application with the specified parameters.""" # Resolve control parameters with factory defaults send_params = send_params or SendParams() compilation_params = compilation_params or AppClientCompilationParams() resolved_updatable = ( upd if (upd := compilation_params.get("updatable")) is not None else self._updatable or self._get_deploy_time_control("updatable") ) resolved_deletable = ( dlb if (dlb := compilation_params.get("deletable")) is not None else self._deletable or self._get_deploy_time_control("deletable") ) resolved_deploy_time_params = compilation_params.get("deploy_time_params") or self._deploy_time_params def prepare_create_args() -> AppCreateMethodCallParams | AppCreateParams: """Prepare create arguments based on parameter type.""" if create_params and isinstance(create_params, AppClientMethodCallCreateParams): return self.params.create( AppFactoryCreateMethodCallParams( **asdict(create_params), ), compilation_params={ "updatable": resolved_updatable, "deletable": resolved_deletable, "deploy_time_params": resolved_deploy_time_params, }, ) base_params = create_params or AppClientBareCallCreateParams() return self.params.bare.create( AppFactoryCreateParams( **asdict(base_params) if base_params else {}, ), compilation_params={ "updatable": resolved_updatable, "deletable": resolved_deletable, "deploy_time_params": resolved_deploy_time_params, }, ) def prepare_update_args() -> AppUpdateMethodCallParams | AppUpdateParams: """Prepare update arguments based on parameter type.""" return ( self.params.deploy_update(update_params) if isinstance(update_params, AppClientMethodCallParams) else self.params.bare.deploy_update(update_params) ) def prepare_delete_args() -> AppDeleteMethodCallParams | AppDeleteParams: """Prepare delete arguments based on parameter type.""" return ( self.params.deploy_delete(delete_params) if isinstance(delete_params, AppClientMethodCallParams) else self.params.bare.deploy_delete(delete_params) ) # Execute deployment deploy_params = AppDeployParams( deploy_time_params=resolved_deploy_time_params, on_schema_break=on_schema_break, on_update=on_update, existing_deployments=existing_deployments, ignore_cache=ignore_cache, create_params=prepare_create_args(), update_params=prepare_update_args(), delete_params=prepare_delete_args(), metadata=AppDeploymentMetaData( name=app_name or self._app_name, version=self._version, updatable=resolved_updatable, deletable=resolved_deletable, ), send_params=send_params, ) deploy_result = self._algorand.app_deployer.deploy(deploy_params) # Prepare app client and factory deploy response app_client = self.get_app_client_by_id( app_id=deploy_result.app.app_id, app_name=app_name, default_sender=self._default_sender, default_signer=self._default_signer, ) factory_deploy_result = AppFactoryDeployResult.from_deploy_result( response=deploy_result, deploy_params=deploy_params, app_spec=app_client.app_spec, app_compilation_data=self.compile( AppClientCompilationParams( deploy_time_params=resolved_deploy_time_params, updatable=resolved_updatable, deletable=resolved_deletable, ) ), ) return app_client, factory_deploy_result def get_app_client_by_id( self, app_id: int, app_name: str | None = None, default_sender: str | None = None, # Address can be string or bytes default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: return AppClient( AppClientParams( app_id=app_id, algorand=self._algorand, app_spec=self._app_spec, app_name=app_name or self._app_name, default_sender=default_sender or self._default_sender, default_signer=default_signer or self._default_signer, approval_source_map=approval_source_map or self._approval_source_map, clear_source_map=clear_source_map or self._clear_source_map, ) ) def get_app_client_by_creator_and_name( self, creator_address: str, app_name: str, default_sender: str | None = None, default_signer: TransactionSigner | None = None, ignore_cache: bool | None = None, app_lookup_cache: ApplicationLookup | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: return AppClient.from_creator_and_name( creator_address=creator_address, app_name=app_name or self._app_name, default_sender=default_sender or self._default_sender, default_signer=default_signer or self._default_signer, approval_source_map=approval_source_map or self._approval_source_map, clear_source_map=clear_source_map or self._clear_source_map, ignore_cache=ignore_cache, app_lookup_cache=app_lookup_cache, app_spec=self._app_spec, algorand=self._algorand, ) def export_source_maps(self) -> AppSourceMaps: if not self._approval_source_map or not self._clear_source_map: raise ValueError( "Unable to export source maps; they haven't been loaded into this client - " "you need to call create, update, or deploy first" ) return AppSourceMaps( approval_source_map=self._approval_source_map, clear_source_map=self._clear_source_map, ) def import_source_maps(self, source_maps: AppSourceMaps) -> None: self._approval_source_map = source_maps.approval_source_map self._clear_source_map = source_maps.clear_source_map def compile(self, compilation_params: AppClientCompilationParams | None = None) -> AppClientCompilationResult: compilation = compilation_params or AppClientCompilationParams() result = AppClient.compile( app_spec=self._app_spec, app_manager=self._algorand.app, compilation_params=compilation, ) if result.compiled_approval: self._approval_source_map = result.compiled_approval.source_map if result.compiled_clear: self._clear_source_map = result.compiled_clear.source_map return result def _expose_logic_error(self, e: Exception, is_clear_state_program: bool = False) -> Exception: # noqa: FBT002 FBT001 return AppClient._expose_logic_error_static( e=e, app_spec=self._app_spec, is_clear_state_program=is_clear_state_program, approval_source_map=self._approval_source_map, clear_source_map=self._clear_source_map, program=None, approval_source_info=(self._app_spec.source_info.approval if self._app_spec.source_info else None), clear_source_info=(self._app_spec.source_info.clear if self._app_spec.source_info else None), ) def _get_deploy_time_control(self, control: str) -> bool | None: approval = self._app_spec.source.get_decoded_approval() if self._app_spec.source else None template_name = UPDATABLE_TEMPLATE_NAME if control == "updatable" else DELETABLE_TEMPLATE_NAME if not approval or template_name not in approval: return None on_complete = "UpdateApplication" if control == "updatable" else "DeleteApplication" return on_complete in self._app_spec.bare_actions.call or any( on_complete in m.actions.call for m in self._app_spec.methods if m.actions and m.actions.call ) def _get_sender(self, sender: str | None) -> str: if not sender and not self._default_sender: raise Exception( f"No sender provided and no default sender present in app client for call to app {self._app_name}" ) return str(sender or self._default_sender) def _get_signer(self, sender: str | None, signer: TransactionSigner | None) -> TransactionSigner | None: return signer or (self._default_signer if not sender or sender == self._default_sender else None) def _handle_call_errors(self, call: Callable[[], T]) -> T: try: return call() except Exception as e: raise self._expose_logic_error(e) from None def _parse_method_call_return( self, result: Callable[ [], SendAppTransactionResult | SendAppCreateTransactionResult | SendAppUpdateTransactionResult ], method: Method, ) -> AppFactoryCreateMethodCallResult[Arc56ReturnValueType]: result_value = result() return AppFactoryCreateMethodCallResult[Arc56ReturnValueType]( **{ **result_value.__dict__, "abi_return": result_value.abi_return.get_arc56_value(method, self._app_spec.structs) if isinstance(result_value.abi_return, ABIReturn) else None, } ) def _get_create_abi_args_with_default_values( self, method_name_or_signature: str, user_args: Sequence[Any] | None, ) -> list[Any]: """ Builds a list of ABI argument values for creation calls, applying default argument values when not provided. """ method = self._app_spec.get_arc56_method(method_name_or_signature) results: list[Any] = [] for i, param in enumerate(method.args): if user_args and i < len(user_args): arg_value = user_args[i] if param.struct and isinstance(arg_value, dict): arg_value = get_abi_tuple_from_abi_struct( arg_value, self._app_spec.structs[param.struct], self._app_spec.structs, ) results.append(arg_value) continue default_value = getattr(param, "default_value", None) if default_value: if default_value.source == "literal": raw_value = base64.b64decode(default_value.data) value_type = default_value.type or str(param.type) decoded_value = get_abi_decoded_value(raw_value, value_type, self._app_spec.structs) results.append(decoded_value) else: raise ValueError( f"Cannot provide default value from source={default_value.source} " "for a contract creation call." ) else: param_name = param.name or f"arg{i + 1}" raise ValueError( f"No value provided for required argument {param_name} " f"in call to method {method.name}" ) return results
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_factory.py
Python
MIT
33,425
import base64 from collections.abc import Mapping from typing import Any, cast import algosdk import algosdk.atomic_transaction_composer import algosdk.box_reference from algosdk.atomic_transaction_composer import AccountTransactionSigner from algosdk.box_reference import BoxReference as AlgosdkBoxReference from algosdk.logic import get_application_address from algosdk.source_map import SourceMap from algosdk.v2client import algod from algokit_utils.applications.abi import ABIReturn, ABIType, ABIValue from algokit_utils.models.application import ( AppInformation, AppState, CompiledTeal, ) from algokit_utils.models.state import BoxIdentifier, BoxName, BoxReference, DataTypeFlag, TealTemplateParams __all__ = [ "DELETABLE_TEMPLATE_NAME", "UPDATABLE_TEMPLATE_NAME", "AppManager", ] UPDATABLE_TEMPLATE_NAME = "TMPL_UPDATABLE" """The name of the TEAL template variable for deploy-time immutability control.""" DELETABLE_TEMPLATE_NAME = "TMPL_DELETABLE" """The name of the TEAL template variable for deploy-time permanence control.""" def _is_valid_token_character(char: str) -> bool: return char.isalnum() or char == "_" def _last_token_base64(line: str, idx: int) -> bool: try: *_, last = line[:idx].split() except ValueError: return False return last in ("base64", "b64") def _find_template_token(line: str, token: str, start: int = 0, end: int = -1) -> int | None: if end < 0: end = len(line) idx = start while idx < end: token_idx = _find_unquoted_string(line, token, idx, end) if token_idx is None: break trailing_idx = token_idx + len(token) if (token_idx == 0 or not _is_valid_token_character(line[token_idx - 1])) and ( trailing_idx >= len(line) or not _is_valid_token_character(line[trailing_idx]) ): return token_idx idx = trailing_idx return None def _find_unquoted_string(line: str, token: str, start: int = 0, end: int = -1) -> int | None: if end < 0: end = len(line) idx = start in_quotes = in_base64 = False while idx < end: current_char = line[idx] match current_char: case " " | "(" if not in_quotes and _last_token_base64(line, idx): in_base64 = True case " " | ")" if not in_quotes and in_base64: in_base64 = False case "\\" if in_quotes: idx += 1 case '"': in_quotes = not in_quotes case _ if not in_quotes and not in_base64 and line.startswith(token, idx): return idx idx += 1 return None def _replace_template_variable(program_lines: list[str], template_variable: str, value: str) -> tuple[list[str], int]: result: list[str] = [] match_count = 0 token = f"TMPL_{template_variable}" if not template_variable.startswith("TMPL_") else template_variable token_idx_offset = len(value) - len(token) for line in program_lines: comment_idx = _find_unquoted_string(line, "//") if comment_idx is None: comment_idx = len(line) code = line[:comment_idx] comment = line[comment_idx:] trailing_idx = 0 while True: token_idx = _find_template_token(code, token, trailing_idx) if token_idx is None: break trailing_idx = token_idx + len(token) prefix = code[:token_idx] suffix = code[trailing_idx:] code = f"{prefix}{value}{suffix}" match_count += 1 trailing_idx += token_idx_offset result.append(code + comment) return result, match_count class AppManager: """A manager class for interacting with Algorand applications. Provides functionality for compiling TEAL code, managing application state, and interacting with application boxes. :param algod_client: The Algorand client instance to use for interacting with the network """ def __init__(self, algod_client: algod.AlgodClient): self._algod = algod_client self._compilation_results: dict[str, CompiledTeal] = {} def compile_teal(self, teal_code: str) -> CompiledTeal: """Compile TEAL source code. :param teal_code: The TEAL source code to compile :return: The compiled TEAL code and associated metadata """ if teal_code in self._compilation_results: return self._compilation_results[teal_code] compiled = self._algod.compile(teal_code, source_map=True) result = CompiledTeal( teal=teal_code, compiled=compiled["result"], compiled_hash=compiled["hash"], compiled_base64_to_bytes=base64.b64decode(compiled["result"]), source_map=SourceMap(compiled.get("sourcemap", {})), ) self._compilation_results[teal_code] = result return result def compile_teal_template( self, teal_template_code: str, template_params: TealTemplateParams | None = None, deployment_metadata: Mapping[str, bool | None] | None = None, ) -> CompiledTeal: """Compile a TEAL template with parameters. :param teal_template_code: The TEAL template code to compile :param template_params: Parameters to substitute in the template :param deployment_metadata: Deployment control parameters :return: The compiled TEAL code and associated metadata """ teal_code = AppManager.strip_teal_comments(teal_template_code) teal_code = AppManager.replace_template_variables(teal_code, template_params or {}) if deployment_metadata: teal_code = AppManager.replace_teal_template_deploy_time_control_params(teal_code, deployment_metadata) return self.compile_teal(teal_code) def get_compilation_result(self, teal_code: str) -> CompiledTeal | None: """Get cached compilation result for TEAL code if available. :param teal_code: The TEAL source code :return: The cached compilation result if available, None otherwise """ return self._compilation_results.get(teal_code) def get_by_id(self, app_id: int) -> AppInformation: """Get information about an application by ID. :param app_id: The application ID :return: Information about the application """ app = self._algod.application_info(app_id) assert isinstance(app, dict) app_params = app["params"] return AppInformation( app_id=app_id, app_address=get_application_address(app_id), approval_program=base64.b64decode(app_params["approval-program"]), clear_state_program=base64.b64decode(app_params["clear-state-program"]), creator=app_params["creator"], local_ints=app_params["local-state-schema"]["num-uint"], local_byte_slices=app_params["local-state-schema"]["num-byte-slice"], global_ints=app_params["global-state-schema"]["num-uint"], global_byte_slices=app_params["global-state-schema"]["num-byte-slice"], extra_program_pages=app_params.get("extra-program-pages", 0), global_state=self.decode_app_state(app_params.get("global-state", [])), ) def get_global_state(self, app_id: int) -> dict[str, AppState]: """Get the global state of an application. :param app_id: The application ID :return: The application's global state """ return self.get_by_id(app_id).global_state def get_local_state(self, app_id: int, address: str) -> dict[str, AppState]: """Get the local state for an account in an application. :param app_id: The application ID :param address: The account address :return: The account's local state for the application :raises ValueError: If local state is not found """ app_info = self._algod.account_application_info(address, app_id) assert isinstance(app_info, dict) if not app_info.get("app-local-state", {}).get("key-value"): raise ValueError("Couldn't find local state") return self.decode_app_state(app_info["app-local-state"]["key-value"]) def get_box_names(self, app_id: int) -> list[BoxName]: """Get names of all boxes for an application. :param app_id: The application ID :return: List of box names """ box_result = self._algod.application_boxes(app_id) assert isinstance(box_result, dict) return [ BoxName( name_raw=base64.b64decode(b["name"]), name_base64=b["name"], name=base64.b64decode(b["name"]).decode("utf-8"), ) for b in box_result["boxes"] ] def get_box_value(self, app_id: int, box_name: BoxIdentifier) -> bytes: """Get the value stored in a box. :param app_id: The application ID :param box_name: The box identifier :return: The box value as bytes """ name = AppManager.get_box_reference(box_name)[1] box_result = self._algod.application_box_by_name(app_id, name) assert isinstance(box_result, dict) return base64.b64decode(box_result["value"]) def get_box_values(self, app_id: int, box_names: list[BoxIdentifier]) -> list[bytes]: """Get values for multiple boxes. :param app_id: The application ID :param box_names: List of box identifiers :return: List of box values as bytes """ return [self.get_box_value(app_id, box_name) for box_name in box_names] def get_box_value_from_abi_type(self, app_id: int, box_name: BoxIdentifier, abi_type: ABIType) -> ABIValue: """Get and decode a box value using an ABI type. :param app_id: The application ID :param box_name: The box identifier :param abi_type: The ABI type to decode with :return: The decoded box value :raises ValueError: If decoding fails """ value = self.get_box_value(app_id, box_name) try: parse_to_tuple = isinstance(abi_type, algosdk.abi.TupleType) decoded_value = abi_type.decode(value) return tuple(decoded_value) if parse_to_tuple else decoded_value except Exception as e: raise ValueError(f"Failed to decode box value {value.decode('utf-8')} with ABI type {abi_type}") from e def get_box_values_from_abi_type( self, app_id: int, box_names: list[BoxIdentifier], abi_type: ABIType ) -> list[ABIValue]: """Get and decode multiple box values using an ABI type. :param app_id: The application ID :param box_names: List of box identifiers :param abi_type: The ABI type to decode with :return: List of decoded box values """ return [self.get_box_value_from_abi_type(app_id, box_name, abi_type) for box_name in box_names] @staticmethod def get_box_reference(box_id: BoxIdentifier | BoxReference) -> tuple[int, bytes]: """Get standardized box reference from various identifier types. :param box_id: The box identifier :return: Tuple of (app_id, box_name_bytes) :raises ValueError: If box identifier type is invalid """ if isinstance(box_id, (BoxReference | AlgosdkBoxReference)): return box_id.app_index, box_id.name name = b"" if isinstance(box_id, str): name = box_id.encode("utf-8") elif isinstance(box_id, bytes): name = box_id elif isinstance(box_id, AccountTransactionSigner): name = cast( bytes, algosdk.encoding.decode_address(algosdk.account.address_from_private_key(box_id.private_key)) ) else: raise ValueError(f"Invalid box identifier type: {type(box_id)}") return 0, name @staticmethod def get_abi_return( confirmation: algosdk.v2client.algod.AlgodResponseType, method: algosdk.abi.Method | None = None ) -> ABIReturn | None: """Get the ABI return value from a transaction confirmation. :param confirmation: The transaction confirmation :param method: The ABI method :return: The parsed ABI return value, or None if not available """ if not method: return None atc = algosdk.atomic_transaction_composer.AtomicTransactionComposer() abi_result = atc.parse_result( method, "dummy_txn", confirmation, # type: ignore[arg-type] ) if not abi_result: return None return ABIReturn(abi_result) @staticmethod def decode_app_state(state: list[dict[str, Any]]) -> dict[str, AppState]: """Decode application state from raw format. :param state: The raw application state :return: Decoded application state :raises ValueError: If unknown state data type is encountered """ state_values: dict[str, AppState] = {} def decode_bytes_to_str(value: bytes) -> str: try: return value.decode("utf-8") except UnicodeDecodeError: return value.hex() for state_val in state: key_base64 = state_val["key"] key_raw = base64.b64decode(key_base64) key = decode_bytes_to_str(key_raw) teal_value = state_val["value"] data_type_flag = teal_value.get("action", teal_value.get("type")) if data_type_flag == DataTypeFlag.BYTES: value_base64 = teal_value.get("bytes", "") value_raw = base64.b64decode(value_base64) state_values[key] = AppState( key_raw=key_raw, key_base64=key_base64, value_raw=value_raw, value_base64=value_base64, value=decode_bytes_to_str(value_raw), ) elif data_type_flag == DataTypeFlag.UINT: value = teal_value.get("uint", 0) state_values[key] = AppState( key_raw=key_raw, key_base64=key_base64, value_raw=None, value_base64=None, value=int(value), ) else: raise ValueError(f"Received unknown state data type of {data_type_flag}") return state_values @staticmethod def replace_template_variables(program: str, template_values: TealTemplateParams) -> str: """Replace template variables in TEAL code. :param program: The TEAL program code :param template_values: Template variable values to substitute :return: TEAL code with substituted values :raises ValueError: If template value type is unexpected """ program_lines = program.splitlines() for template_variable_name, template_value in template_values.items(): match template_value: case int(): value = str(template_value) case str(): value = "0x" + template_value.encode("utf-8").hex() case bytes(): value = "0x" + template_value.hex() case _: raise ValueError( f"Unexpected template value type {template_variable_name}: {template_value.__class__}" ) program_lines, _ = _replace_template_variable(program_lines, template_variable_name, value) return "\n".join(program_lines) @staticmethod def replace_teal_template_deploy_time_control_params( teal_template_code: str, params: Mapping[str, bool | None] ) -> str: """Replace deploy-time control parameters in TEAL template. :param teal_template_code: The TEAL template code :param params: The deploy-time control parameters :return: TEAL code with substituted control parameters :raises ValueError: If template variables not found in code """ updatable = params.get("updatable") if updatable is not None: if UPDATABLE_TEMPLATE_NAME not in teal_template_code: raise ValueError( f"Deploy-time updatability control requested for app deployment, but {UPDATABLE_TEMPLATE_NAME} " "not present in TEAL code" ) teal_template_code = teal_template_code.replace(UPDATABLE_TEMPLATE_NAME, str(int(updatable))) deletable = params.get("deletable") if deletable is not None: if DELETABLE_TEMPLATE_NAME not in teal_template_code: raise ValueError( f"Deploy-time deletability control requested for app deployment, but {DELETABLE_TEMPLATE_NAME} " "not present in TEAL code" ) teal_template_code = teal_template_code.replace(DELETABLE_TEMPLATE_NAME, str(int(deletable))) return teal_template_code @staticmethod def strip_teal_comments(teal_code: str) -> str: def _strip_comment(line: str) -> str: comment_idx = _find_unquoted_string(line, "//") if comment_idx is None: return line return line[:comment_idx].rstrip() return "\n".join(_strip_comment(line) for line in teal_code.splitlines())
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_manager.py
Python
MIT
17,661
from algokit_utils.applications.app_spec.arc32 import * # noqa: F403 from algokit_utils.applications.app_spec.arc56 import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_spec/__init__.py
Python
MIT
140
import base64 import dataclasses import json from enum import IntFlag from pathlib import Path from typing import Any, Literal, TypeAlias, TypedDict from algosdk.abi import Contract from algosdk.abi.method import MethodDict from algosdk.transaction import StateSchema __all__ = [ "AppSpecStateDict", "Arc32Contract", "CallConfig", "DefaultArgumentDict", "DefaultArgumentType", "MethodConfigDict", "MethodHints", "OnCompleteActionName", "StateDict", "StructArgDict", ] AppSpecStateDict: TypeAlias = dict[str, dict[str, dict]] """Type defining Application Specification state entries""" class CallConfig(IntFlag): """Describes the type of calls a method can be used for based on {py:class}`algosdk.transaction.OnComplete` type""" NEVER = 0 """Never handle the specified on completion type""" CALL = 1 """Only handle the specified on completion type for application calls""" CREATE = 2 """Only handle the specified on completion type for application create calls""" ALL = 3 """Handle the specified on completion type for both create and normal application calls""" class StructArgDict(TypedDict): name: str elements: list[list[str]] OnCompleteActionName: TypeAlias = Literal[ "no_op", "opt_in", "close_out", "clear_state", "update_application", "delete_application" ] """String literals representing on completion transaction types""" MethodConfigDict: TypeAlias = dict[OnCompleteActionName, CallConfig] """Dictionary of `dict[OnCompletionActionName, CallConfig]` representing allowed actions for each on completion type""" DefaultArgumentType: TypeAlias = Literal["abi-method", "local-state", "global-state", "constant"] """Literal values describing the types of default argument sources""" class DefaultArgumentDict(TypedDict): """ DefaultArgument is a container for any arguments that may be resolved prior to calling some target method """ source: DefaultArgumentType data: int | str | bytes | MethodDict StateDict = TypedDict( # need to use function-form of TypedDict here since "global" is a reserved keyword "StateDict", {"global": AppSpecStateDict, "local": AppSpecStateDict} ) @dataclasses.dataclass(kw_only=True) class MethodHints: """MethodHints provides hints to the caller about how to call the method""" #: hint to indicate this method can be called through Dryrun read_only: bool = False #: hint to provide names for tuple argument indices #: method_name=>param_name=>{name:str, elements:[str,str]} structs: dict[str, StructArgDict] = dataclasses.field(default_factory=dict) #: defaults default_arguments: dict[str, DefaultArgumentDict] = dataclasses.field(default_factory=dict) call_config: MethodConfigDict = dataclasses.field(default_factory=dict) def empty(self) -> bool: return not self.dictify() def dictify(self) -> dict[str, Any]: d: dict[str, Any] = {} if self.read_only: d["read_only"] = True if self.default_arguments: d["default_arguments"] = self.default_arguments if self.structs: d["structs"] = self.structs if any(v for v in self.call_config.values() if v != CallConfig.NEVER): d["call_config"] = _encode_method_config(self.call_config) return d @staticmethod def undictify(data: dict[str, Any]) -> "MethodHints": return MethodHints( read_only=data.get("read_only", False), default_arguments=data.get("default_arguments", {}), structs=data.get("structs", {}), call_config=_decode_method_config(data.get("call_config", {})), ) def _encode_method_config(mc: MethodConfigDict) -> dict[str, str | None]: return {k: mc[k].name for k in sorted(mc) if mc[k] != CallConfig.NEVER} def _decode_method_config(data: dict[OnCompleteActionName, Any]) -> MethodConfigDict: return {k: CallConfig[v] for k, v in data.items()} def _encode_source(teal_text: str) -> str: return base64.b64encode(teal_text.encode()).decode("utf-8") def _decode_source(b64_text: str) -> str: return base64.b64decode(b64_text).decode("utf-8") def _encode_state_schema(schema: StateSchema) -> dict[str, int]: return { "num_byte_slices": schema.num_byte_slices, "num_uints": schema.num_uints, } # type: ignore[unused-ignore] def _decode_state_schema(data: dict[str, int]) -> StateSchema: return StateSchema( num_byte_slices=data.get("num_byte_slices", 0), num_uints=data.get("num_uints", 0), ) @dataclasses.dataclass(kw_only=True) class Arc32Contract: """ARC-0032 application specification See <https://github.com/algorandfoundation/ARCs/pull/150>""" approval_program: str clear_program: str contract: Contract hints: dict[str, MethodHints] schema: StateDict global_state_schema: StateSchema local_state_schema: StateSchema bare_call_config: MethodConfigDict def dictify(self) -> dict: return { "hints": {k: v.dictify() for k, v in self.hints.items() if not v.empty()}, "source": { "approval": _encode_source(self.approval_program), "clear": _encode_source(self.clear_program), }, "state": { "global": _encode_state_schema(self.global_state_schema), "local": _encode_state_schema(self.local_state_schema), }, "schema": self.schema, "contract": self.contract.dictify(), "bare_call_config": _encode_method_config(self.bare_call_config), } def to_json(self, indent: int | None = None) -> str: return json.dumps(self.dictify(), indent=indent) @staticmethod def from_json(application_spec: str) -> "Arc32Contract": json_spec = json.loads(application_spec) return Arc32Contract( approval_program=_decode_source(json_spec["source"]["approval"]), clear_program=_decode_source(json_spec["source"]["clear"]), schema=json_spec["schema"], global_state_schema=_decode_state_schema(json_spec["state"]["global"]), local_state_schema=_decode_state_schema(json_spec["state"]["local"]), contract=Contract.undictify(json_spec["contract"]), hints={k: MethodHints.undictify(v) for k, v in json_spec["hints"].items()}, bare_call_config=_decode_method_config(json_spec.get("bare_call_config", {})), ) def export(self, directory: Path | str | None = None) -> None: """Write out the artifacts generated by the application to disk. Writes the approval program, clear program, contract specification and application specification to files in the specified directory. :param directory: Path to the directory where the artifacts should be written. If not specified, uses the current working directory """ if directory is None: output_dir = Path.cwd() else: output_dir = Path(directory) output_dir.mkdir(exist_ok=True, parents=True) (output_dir / "approval.teal").write_text(self.approval_program) (output_dir / "clear.teal").write_text(self.clear_program) (output_dir / "contract.json").write_text(json.dumps(self.contract.dictify(), indent=4)) (output_dir / "application.json").write_text(self.to_json())
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_spec/arc32.py
Python
MIT
7,523
from __future__ import annotations import base64 import json from base64 import b64encode from collections.abc import Callable, Sequence from dataclasses import asdict, dataclass from enum import Enum from typing import Any, Literal, overload import algosdk from algosdk.abi import Method as AlgosdkMethod from algokit_utils.applications.app_spec.arc32 import Arc32Contract __all__ = [ "Actions", "Arc56Contract", "BareActions", "Boxes", "ByteCode", "CallEnum", "Compiler", "CompilerInfo", "CompilerVersion", "CreateEnum", "DefaultValue", "Event", "EventArg", "Global", "Keys", "Local", "Maps", "Method", "MethodArg", "Network", "PcOffsetMethod", "ProgramSourceInfo", "Recommendations", "Returns", "Schema", "ScratchVariables", "Source", "SourceInfo", "SourceInfoModel", "State", "StorageKey", "StorageMap", "StructField", "TemplateVariables", ] class _ActionType(str, Enum): CALL = "CALL" CREATE = "CREATE" @dataclass class StructField: """Represents a field in a struct type. :ivar name: Name of the struct field :ivar type: Type of the struct field, either a string or list of StructFields """ name: str type: list[StructField] | str @staticmethod def from_dict(data: dict[str, Any]) -> StructField: if isinstance(data["type"], list): data["type"] = [StructField.from_dict(item) for item in data["type"]] return StructField(**data) class CallEnum(str, Enum): """Enum representing different call types for application transactions.""" CLEAR_STATE = "ClearState" CLOSE_OUT = "CloseOut" DELETE_APPLICATION = "DeleteApplication" NO_OP = "NoOp" OPT_IN = "OptIn" UPDATE_APPLICATION = "UpdateApplication" class CreateEnum(str, Enum): """Enum representing different create types for application transactions.""" DELETE_APPLICATION = "DeleteApplication" NO_OP = "NoOp" OPT_IN = "OptIn" @dataclass class BareActions: """Represents bare call and create actions for an application. :ivar call: List of allowed call actions :ivar create: List of allowed create actions """ call: list[CallEnum] create: list[CreateEnum] @staticmethod def from_dict(data: dict[str, Any]) -> BareActions: return BareActions(**data) @dataclass class ByteCode: """Represents the approval and clear program bytecode. :ivar approval: Base64 encoded approval program bytecode :ivar clear: Base64 encoded clear program bytecode """ approval: str clear: str @staticmethod def from_dict(data: dict[str, Any]) -> ByteCode: return ByteCode(**data) class Compiler(str, Enum): """Enum representing different compiler types.""" ALGOD = "algod" PUYA = "puya" @dataclass class CompilerVersion: """Represents compiler version information. :ivar commit_hash: Git commit hash of the compiler :ivar major: Major version number :ivar minor: Minor version number :ivar patch: Patch version number """ commit_hash: str | None = None major: int | None = None minor: int | None = None patch: int | None = None @staticmethod def from_dict(data: dict[str, Any]) -> CompilerVersion: return CompilerVersion(**data) @dataclass class CompilerInfo: """Information about the compiler used. :ivar compiler: Type of compiler used :ivar compiler_version: Version information for the compiler """ compiler: Compiler compiler_version: CompilerVersion @staticmethod def from_dict(data: dict[str, Any]) -> CompilerInfo: data["compiler_version"] = CompilerVersion.from_dict(data["compiler_version"]) return CompilerInfo(**data) @dataclass class Network: """Network-specific application information. :ivar app_id: Application ID on the network """ app_id: int @staticmethod def from_dict(data: dict[str, Any]) -> Network: return Network(**data) @dataclass class ScratchVariables: """Information about scratch space variables. :ivar slot: Scratch slot number :ivar type: Type of the scratch variable """ slot: int type: str @staticmethod def from_dict(data: dict[str, Any]) -> ScratchVariables: return ScratchVariables(**data) @dataclass class Source: """Source code for approval and clear programs. :ivar approval: Base64 encoded approval program source :ivar clear: Base64 encoded clear program source """ approval: str clear: str @staticmethod def from_dict(data: dict[str, Any]) -> Source: return Source(**data) def get_decoded_approval(self) -> str: """Get decoded approval program source. :return: Decoded approval program source code """ return self._decode_source(self.approval) def get_decoded_clear(self) -> str: """Get decoded clear program source. :return: Decoded clear program source code """ return self._decode_source(self.clear) def _decode_source(self, b64_text: str) -> str: return base64.b64decode(b64_text).decode("utf-8") @dataclass class Global: """Global state schema. :ivar bytes: Number of byte slices in global state :ivar ints: Number of integers in global state """ bytes: int ints: int @staticmethod def from_dict(data: dict[str, Any]) -> Global: return Global(**data) @dataclass class Local: """Local state schema. :ivar bytes: Number of byte slices in local state :ivar ints: Number of integers in local state """ bytes: int ints: int @staticmethod def from_dict(data: dict[str, Any]) -> Local: return Local(**data) @dataclass class Schema: """Application state schema. :ivar global_state: Global state schema :ivar local_state: Local state schema """ global_state: Global # actual schema field is "global" since it's a reserved word local_state: Local # actual schema field is "local" for consistency with renamed "global" @staticmethod def from_dict(data: dict[str, Any]) -> Schema: global_state = Global.from_dict(data["global"]) local_state = Local.from_dict(data["local"]) return Schema(global_state=global_state, local_state=local_state) @dataclass class TemplateVariables: """Template variable information. :ivar type: Type of the template variable :ivar value: Optional value of the template variable """ type: str value: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> TemplateVariables: return TemplateVariables(**data) @dataclass class EventArg: """Event argument information. :ivar type: Type of the event argument :ivar desc: Optional description of the argument :ivar name: Optional name of the argument :ivar struct: Optional struct type name """ type: str desc: str | None = None name: str | None = None struct: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> EventArg: return EventArg(**data) @dataclass class Event: """Event information. :ivar args: List of event arguments :ivar name: Name of the event :ivar desc: Optional description of the event """ args: list[EventArg] name: str desc: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> Event: data["args"] = [EventArg.from_dict(item) for item in data["args"]] return Event(**data) @dataclass class Actions: """Method actions information. :ivar call: Optional list of allowed call actions :ivar create: Optional list of allowed create actions """ call: list[CallEnum] | None = None create: list[CreateEnum] | None = None @staticmethod def from_dict(data: dict[str, Any]) -> Actions: return Actions(**data) @dataclass class DefaultValue: """Default value information for method arguments. :ivar data: Default value data :ivar source: Source of the default value :ivar type: Optional type of the default value """ data: str source: Literal["box", "global", "local", "literal", "method"] type: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> DefaultValue: return DefaultValue(**data) @dataclass class MethodArg: """Method argument information. :ivar type: Type of the argument :ivar default_value: Optional default value :ivar desc: Optional description :ivar name: Optional name :ivar struct: Optional struct type name """ type: str default_value: DefaultValue | None = None desc: str | None = None name: str | None = None struct: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> MethodArg: if data.get("default_value"): data["default_value"] = DefaultValue.from_dict(data["default_value"]) return MethodArg(**data) @dataclass class Boxes: """Box storage requirements. :ivar key: Box key :ivar read_bytes: Number of bytes to read :ivar write_bytes: Number of bytes to write :ivar app: Optional application ID """ key: str read_bytes: int write_bytes: int app: int | None = None @staticmethod def from_dict(data: dict[str, Any]) -> Boxes: return Boxes(**data) @dataclass class Recommendations: """Method execution recommendations. :ivar accounts: Optional list of accounts :ivar apps: Optional list of applications :ivar assets: Optional list of assets :ivar boxes: Optional box storage requirements :ivar inner_transaction_count: Optional inner transaction count """ accounts: list[str] | None = None apps: list[int] | None = None assets: list[int] | None = None boxes: Boxes | None = None inner_transaction_count: int | None = None @staticmethod def from_dict(data: dict[str, Any]) -> Recommendations: if data.get("boxes"): data["boxes"] = Boxes.from_dict(data["boxes"]) return Recommendations(**data) @dataclass class Returns: """Method return information. :ivar type: Return type :ivar desc: Optional description :ivar struct: Optional struct type name """ type: str desc: str | None = None struct: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> Returns: return Returns(**data) @dataclass class Method: """Method information. :ivar actions: Allowed actions :ivar args: Method arguments :ivar name: Method name :ivar returns: Return information :ivar desc: Optional description :ivar events: Optional list of events :ivar readonly: Optional readonly flag :ivar recommendations: Optional execution recommendations """ actions: Actions args: list[MethodArg] name: str returns: Returns desc: str | None = None events: list[Event] | None = None readonly: bool | None = None recommendations: Recommendations | None = None _abi_method: AlgosdkMethod | None = None def __post_init__(self) -> None: self._abi_method = AlgosdkMethod.undictify(asdict(self)) def to_abi_method(self) -> AlgosdkMethod: """Convert to ABI method. :raises ValueError: If underlying ABI method is not initialized :return: ABI method """ if self._abi_method is None: raise ValueError("Underlying core ABI method class is not initialized!") return self._abi_method @staticmethod def from_dict(data: dict[str, Any]) -> Method: data["actions"] = Actions.from_dict(data["actions"]) data["args"] = [MethodArg.from_dict(item) for item in data["args"]] data["returns"] = Returns.from_dict(data["returns"]) if data.get("events"): data["events"] = [Event.from_dict(item) for item in data["events"]] if data.get("recommendations"): data["recommendations"] = Recommendations.from_dict(data["recommendations"]) return Method(**data) class PcOffsetMethod(str, Enum): """PC offset method types.""" CBLOCKS = "cblocks" NONE = "none" @dataclass class SourceInfo: """Source code location information. :ivar pc: List of program counter values :ivar error_message: Optional error message :ivar source: Optional source code :ivar teal: Optional TEAL version """ pc: list[int] error_message: str | None = None source: str | None = None teal: int | None = None @staticmethod def from_dict(data: dict[str, Any]) -> SourceInfo: return SourceInfo(**data) @dataclass class StorageKey: """Storage key information. :ivar key: Storage key :ivar key_type: Type of the key :ivar value_type: Type of the value :ivar desc: Optional description """ key: str key_type: str value_type: str desc: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> StorageKey: return StorageKey(**data) @dataclass class StorageMap: """Storage map information. :ivar key_type: Type of map keys :ivar value_type: Type of map values :ivar desc: Optional description :ivar prefix: Optional key prefix """ key_type: str value_type: str desc: str | None = None prefix: str | None = None @staticmethod def from_dict(data: dict[str, Any]) -> StorageMap: return StorageMap(**data) @dataclass class Keys: """Storage keys for different storage types. :ivar box: Box storage keys :ivar global_state: Global state storage keys :ivar local_state: Local state storage keys """ box: dict[str, StorageKey] global_state: dict[str, StorageKey] # actual schema field is "global" since it's a reserved word local_state: dict[str, StorageKey] # actual schema field is "local" for consistency with renamed "global" @staticmethod def from_dict(data: dict[str, Any]) -> Keys: box = {key: StorageKey.from_dict(value) for key, value in data["box"].items()} global_state = {key: StorageKey.from_dict(value) for key, value in data["global"].items()} local_state = {key: StorageKey.from_dict(value) for key, value in data["local"].items()} return Keys(box=box, global_state=global_state, local_state=local_state) @dataclass class Maps: """Storage maps for different storage types. :ivar box: Box storage maps :ivar global_state: Global state storage maps :ivar local_state: Local state storage maps """ box: dict[str, StorageMap] global_state: dict[str, StorageMap] # actual schema field is "global" since it's a reserved word local_state: dict[str, StorageMap] # actual schema field is "local" for consistency with renamed "global" @staticmethod def from_dict(data: dict[str, Any]) -> Maps: box = {key: StorageMap.from_dict(value) for key, value in data["box"].items()} global_state = {key: StorageMap.from_dict(value) for key, value in data["global"].items()} local_state = {key: StorageMap.from_dict(value) for key, value in data["local"].items()} return Maps(box=box, global_state=global_state, local_state=local_state) @dataclass class State: """Application state information. :ivar keys: Storage keys :ivar maps: Storage maps :ivar schema: State schema """ keys: Keys maps: Maps schema: Schema @staticmethod def from_dict(data: dict[str, Any]) -> State: data["keys"] = Keys.from_dict(data["keys"]) data["maps"] = Maps.from_dict(data["maps"]) data["schema"] = Schema.from_dict(data["schema"]) return State(**data) @dataclass class ProgramSourceInfo: """Program source information. :ivar pc_offset_method: PC offset method :ivar source_info: List of source info entries """ pc_offset_method: PcOffsetMethod source_info: list[SourceInfo] @staticmethod def from_dict(data: dict[str, Any]) -> ProgramSourceInfo: data["source_info"] = [SourceInfo.from_dict(item) for item in data["source_info"]] return ProgramSourceInfo(**data) @dataclass class SourceInfoModel: """Source information for approval and clear programs. :ivar approval: Approval program source info :ivar clear: Clear program source info """ approval: ProgramSourceInfo clear: ProgramSourceInfo @staticmethod def from_dict(data: dict[str, Any]) -> SourceInfoModel: data["approval"] = ProgramSourceInfo.from_dict(data["approval"]) data["clear"] = ProgramSourceInfo.from_dict(data["clear"]) return SourceInfoModel(**data) def _dict_keys_to_snake_case( value: Any, # noqa: ANN401 ) -> Any: # noqa: ANN401 def camel_to_snake(s: str) -> str: return "".join(["_" + c.lower() if c.isupper() else c for c in s]).lstrip("_") match value: case dict(): new_dict: dict[str, Any] = {} for key, val in value.items(): new_dict[camel_to_snake(str(key))] = _dict_keys_to_snake_case(val) return new_dict case list(): return [_dict_keys_to_snake_case(item) for item in value] case _: return value class _Arc32ToArc56Converter: def __init__(self, arc32_application_spec: str): self.arc32 = json.loads(arc32_application_spec) def convert(self) -> Arc56Contract: source_data = self.arc32.get("source") return Arc56Contract( name=self.arc32["contract"]["name"], desc=self.arc32["contract"].get("desc"), arcs=[], methods=self._convert_methods(self.arc32), structs=self._convert_structs(self.arc32), state=self._convert_state(self.arc32), source=Source(**source_data) if source_data else None, bare_actions=BareActions( call=self._convert_actions(self.arc32.get("bare_call_config"), _ActionType.CALL), create=self._convert_actions(self.arc32.get("bare_call_config"), _ActionType.CREATE), ), ) def _convert_storage_keys(self, schema: dict) -> dict[str, StorageKey]: """Convert ARC32 schema declared fields to ARC56 storage keys.""" return { name: StorageKey( key=b64encode(field["key"].encode()).decode(), key_type="AVMString", value_type="AVMUint64" if field["type"] == "uint64" else "AVMBytes", desc=field.get("descr"), ) for name, field in schema.items() } def _convert_state(self, arc32: dict) -> State: """Convert ARC32 state and schema to ARC56 state specification.""" state_data = arc32.get("state", {}) return State( schema=Schema( global_state=Global( ints=state_data.get("global", {}).get("num_uints", 0), bytes=state_data.get("global", {}).get("num_byte_slices", 0), ), local_state=Local( ints=state_data.get("local", {}).get("num_uints", 0), bytes=state_data.get("local", {}).get("num_byte_slices", 0), ), ), keys=Keys( global_state=self._convert_storage_keys(arc32.get("schema", {}).get("global", {}).get("declared", {})), local_state=self._convert_storage_keys(arc32.get("schema", {}).get("local", {}).get("declared", {})), box={}, ), maps=Maps(global_state={}, local_state={}, box={}), ) def _convert_structs(self, arc32: dict) -> dict[str, list[StructField]]: """Extract and convert struct definitions from hints.""" return { struct["name"]: [StructField(name=elem[0], type=elem[1]) for elem in struct["elements"]] for hint in arc32.get("hints", {}).values() for struct in hint.get("structs", {}).values() } def _convert_default_value(self, arg_type: str, default_arg: dict[str, Any] | None) -> DefaultValue | None: """Convert ARC32 default argument to ARC56 format.""" if not default_arg or not default_arg.get("source"): return None source_mapping = { "constant": "literal", "global-state": "global", "local-state": "local", "abi-method": "method", } mapped_source = source_mapping.get(default_arg["source"]) if not mapped_source: return None elif mapped_source == "method": return DefaultValue( source=mapped_source, # type: ignore[arg-type] data=default_arg.get("data", {}).get("name"), ) arg_data = default_arg.get("data") if isinstance(arg_data, int): arg_data = algosdk.abi.ABIType.from_string("uint64").encode(arg_data) elif isinstance(arg_data, str): arg_data = arg_data.encode() else: raise ValueError(f"Invalid default argument data type: {type(arg_data)}") return DefaultValue( source=mapped_source, # type: ignore[arg-type] data=base64.b64encode(arg_data).decode("utf-8"), type=arg_type if arg_type != "string" else "AVMString", ) @overload def _convert_actions(self, config: dict | None, action_type: Literal[_ActionType.CALL]) -> list[CallEnum]: ... @overload def _convert_actions(self, config: dict | None, action_type: Literal[_ActionType.CREATE]) -> list[CreateEnum]: ... def _convert_actions(self, config: dict | None, action_type: _ActionType) -> Sequence[CallEnum | CreateEnum]: """Extract supported actions from call config.""" if not config: return [] actions: list[CallEnum | CreateEnum] = [] mappings = { "no_op": (CallEnum.NO_OP, CreateEnum.NO_OP), "opt_in": (CallEnum.OPT_IN, CreateEnum.OPT_IN), "close_out": (CallEnum.CLOSE_OUT, None), "delete_application": (CallEnum.DELETE_APPLICATION, CreateEnum.DELETE_APPLICATION), "update_application": (CallEnum.UPDATE_APPLICATION, None), } for action, (call_enum, create_enum) in mappings.items(): if action in config and config[action] in ["ALL", action_type]: if action_type == "CALL" and call_enum: actions.append(call_enum) elif action_type == "CREATE" and create_enum: actions.append(create_enum) return actions def _convert_method_actions(self, hint: dict | None) -> Actions: """Convert method call config to ARC56 actions.""" config = hint.get("call_config", {}) if hint else {} return Actions( call=self._convert_actions(config, _ActionType.CALL), create=self._convert_actions(config, _ActionType.CREATE), ) def _convert_methods(self, arc32: dict) -> list[Method]: """Convert ARC32 methods to ARC56 format.""" methods = [] contract = arc32["contract"] hints = arc32.get("hints", {}) for method in contract["methods"]: args_sig = ",".join(a["type"] for a in method["args"]) signature = f"{method['name']}({args_sig}){method['returns']['type']}" hint = hints.get(signature, {}) methods.append( Method( name=method["name"], desc=method.get("desc"), readonly=hint.get("read_only"), args=[ MethodArg( name=arg.get("name"), type=arg["type"], desc=arg.get("desc"), struct=hint.get("structs", {}).get(arg.get("name", ""), {}).get("name"), default_value=self._convert_default_value( arg["type"], hint.get("default_arguments", {}).get(arg.get("name")) ), ) for arg in method["args"] ], returns=Returns( type=method["returns"]["type"], desc=method["returns"].get("desc"), struct=hint.get("structs", {}).get("output", {}).get("name"), ), actions=self._convert_method_actions(hint), events=[], # ARC32 doesn't specify events ) ) return methods def _arc56_dict_factory() -> Callable[[list[tuple[str, Any]]], dict[str, Any]]: """Creates a dict factory that handles ARC-56 JSON field naming conventions.""" word_map = {"global_state": "global", "local_state": "local"} blocklist = ["_abi_method"] def to_camel(key: str) -> str: key = word_map.get(key, key) words = key.split("_") return words[0] + "".join(word.capitalize() for word in words[1:]) def dict_factory(entries: list[tuple[str, Any]]) -> dict[str, Any]: return {to_camel(k): v for k, v in entries if v is not None and k not in blocklist} return dict_factory @dataclass class Arc56Contract: """ARC-0056 application specification. See https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0056.md :ivar arcs: List of supported ARC version numbers :ivar bare_actions: Bare call and create actions :ivar methods: List of contract methods :ivar name: Contract name :ivar state: Contract state information :ivar structs: Contract struct definitions :ivar byte_code: Optional bytecode for approval and clear programs :ivar compiler_info: Optional compiler information :ivar desc: Optional contract description :ivar events: Optional list of contract events :ivar networks: Optional network deployment information :ivar scratch_variables: Optional scratch variable information :ivar source: Optional source code :ivar source_info: Optional source code information :ivar template_variables: Optional template variable information """ arcs: list[int] bare_actions: BareActions methods: list[Method] name: str state: State structs: dict[str, list[StructField]] byte_code: ByteCode | None = None compiler_info: CompilerInfo | None = None desc: str | None = None events: list[Event] | None = None networks: dict[str, Network] | None = None scratch_variables: dict[str, ScratchVariables] | None = None source: Source | None = None source_info: SourceInfoModel | None = None template_variables: dict[str, TemplateVariables] | None = None @staticmethod def from_dict(application_spec: dict) -> Arc56Contract: """Create Arc56Contract from dictionary. :param application_spec: Dictionary containing contract specification :return: Arc56Contract instance """ data = _dict_keys_to_snake_case(application_spec) data["bare_actions"] = BareActions.from_dict(data["bare_actions"]) data["methods"] = [Method.from_dict(item) for item in data["methods"]] data["state"] = State.from_dict(data["state"]) data["structs"] = { key: [StructField.from_dict(item) for item in value] for key, value in application_spec["structs"].items() } if data.get("byte_code"): data["byte_code"] = ByteCode.from_dict(data["byte_code"]) if data.get("compiler_info"): data["compiler_info"] = CompilerInfo.from_dict(data["compiler_info"]) if data.get("events"): data["events"] = [Event.from_dict(item) for item in data["events"]] if data.get("networks"): data["networks"] = {key: Network.from_dict(value) for key, value in data["networks"].items()} if data.get("scratch_variables"): data["scratch_variables"] = { key: ScratchVariables.from_dict(value) for key, value in data["scratch_variables"].items() } if data.get("source"): data["source"] = Source.from_dict(data["source"]) if data.get("source_info"): data["source_info"] = SourceInfoModel.from_dict(data["source_info"]) if data.get("template_variables"): data["template_variables"] = { key: TemplateVariables.from_dict(value) for key, value in data["template_variables"].items() } return Arc56Contract(**data) @staticmethod def from_json(application_spec: str) -> Arc56Contract: return Arc56Contract.from_dict(json.loads(application_spec)) @staticmethod def from_arc32(arc32_application_spec: str | Arc32Contract) -> Arc56Contract: return _Arc32ToArc56Converter( arc32_application_spec.to_json() if isinstance(arc32_application_spec, Arc32Contract) else arc32_application_spec ).convert() @staticmethod def get_abi_struct_from_abi_tuple( decoded_tuple: Any, # noqa: ANN401 struct_fields: list[StructField], structs: dict[str, list[StructField]], ) -> dict[str, Any]: result = {} for i, field in enumerate(struct_fields): key = field.name field_type = field.type value = decoded_tuple[i] if isinstance(field_type, str): if field_type in structs: value = Arc56Contract.get_abi_struct_from_abi_tuple(value, structs[field_type], structs) elif isinstance(field_type, list): value = Arc56Contract.get_abi_struct_from_abi_tuple(value, field_type, structs) result[key] = value return result def to_json(self, indent: int | None = None) -> str: return json.dumps(self.dictify(), indent=indent) def dictify(self) -> dict: return asdict(self, dict_factory=_arc56_dict_factory()) def get_arc56_method(self, method_name_or_signature: str) -> Method: if "(" not in method_name_or_signature: # Filter by method name methods = [m for m in self.methods if m.name == method_name_or_signature] if not methods: raise ValueError(f"Unable to find method {method_name_or_signature} in {self.name} app.") if len(methods) > 1: signatures = [AlgosdkMethod.undictify(m.__dict__).get_signature() for m in self.methods] raise ValueError( f"Received a call to method {method_name_or_signature} in contract {self.name}, " f"but this resolved to multiple methods; please pass in an ABI signature instead: " f"{', '.join(signatures)}" ) method = methods[0] else: # Find by signature method = None for m in self.methods: abi_method = AlgosdkMethod.undictify(asdict(m)) if abi_method.get_signature() == method_name_or_signature: method = m break if method is None: raise ValueError(f"Unable to find method {method_name_or_signature} in {self.name} app.") return method
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/app_spec/arc56.py
Python
MIT
31,727
from enum import Enum # NOTE: this is moved to a separate file to avoid circular imports class OnSchemaBreak(Enum): """Action to take if an Application's schema has breaking changes""" Fail = 0 """Fail the deployment""" ReplaceApp = 2 """Create a new Application and delete the old Application in a single transaction""" AppendApp = 3 """Create a new Application""" class OnUpdate(Enum): """Action to take if an Application has been updated""" Fail = 0 """Fail the deployment""" UpdateApp = 1 """Update the Application with the new approval and clear programs""" ReplaceApp = 2 """Create a new Application and delete the old Application in a single transaction""" AppendApp = 3 """Create a new application""" class OperationPerformed(Enum): """Describes the actions taken during deployment""" Nothing = 0 """An existing Application was found""" Create = 1 """No existing Application was found, created a new Application""" Update = 2 """An existing Application was found, but was out of date, updated to latest version""" Replace = 3 """An existing Application was found, but was out of date, created a new Application and deleted the original"""
algorandfoundation/algokit-utils-py
src/algokit_utils/applications/enums.py
Python
MIT
1,257
import warnings warnings.warn( """The legacy v2 asset module is deprecated and will be removed in a future version. Replacements for opt_in/opt_out functionality: 1. Using TransactionComposer: composer.add_asset_opt_in(AssetOptInParams( sender=account.address, asset_id=123 )) composer.add_asset_opt_out(AssetOptOutParams( sender=account.address, asset_id=123, creator=creator_address )) 2. Using AlgorandClient: client.asset.opt_in(AssetOptInParams(...)) client.asset.opt_out(AssetOptOutParams(...)) 3. For bulk operations: client.asset.bulk_opt_in(account, [asset_ids]) client.asset.bulk_opt_out(account, [asset_ids]) Refer to AssetManager class from algokit_utils for more functionality.""", DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.asset import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/asset.py
Python
MIT
874
from algokit_utils.assets.asset_manager import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/assets/__init__.py
Python
MIT
63
from collections.abc import Callable from dataclasses import dataclass import algosdk from algosdk.atomic_transaction_composer import AccountTransactionSigner, TransactionSigner from algosdk.v2client import algod from algokit_utils.models.account import SigningAccount from algokit_utils.models.amount import AlgoAmount from algokit_utils.models.transaction import SendParams from algokit_utils.transactions.transaction_composer import ( AssetOptInParams, AssetOptOutParams, TransactionComposer, ) __all__ = ["AccountAssetInformation", "AssetInformation", "AssetManager", "BulkAssetOptInOutResult"] @dataclass(kw_only=True, frozen=True) class AccountAssetInformation: """Information about an account's holding of a particular asset. :ivar asset_id: The ID of the asset :ivar balance: The amount of the asset held by the account :ivar frozen: Whether the asset is frozen for this account :ivar round: The round this information was retrieved at """ asset_id: int balance: int frozen: bool round: int @dataclass(kw_only=True, frozen=True) class AssetInformation: """Information about an Algorand Standard Asset (ASA). :ivar asset_id: The ID of the asset :ivar creator: The address of the account that created the asset :ivar total: The total amount of the smallest divisible units that were created of the asset :ivar decimals: The amount of decimal places the asset was created with :ivar default_frozen: Whether the asset was frozen by default for all accounts, defaults to None :ivar manager: The address of the optional account that can manage the configuration of the asset and destroy it, defaults to None :ivar reserve: The address of the optional account that holds the reserve (uncirculated supply) units of the asset, defaults to None :ivar freeze: The address of the optional account that can be used to freeze or unfreeze holdings of this asset, defaults to None :ivar clawback: The address of the optional account that can clawback holdings of this asset from any account, defaults to None :ivar unit_name: The optional name of the unit of this asset (e.g. ticker name), defaults to None :ivar unit_name_b64: The optional name of the unit of this asset as bytes, defaults to None :ivar asset_name: The optional name of the asset, defaults to None :ivar asset_name_b64: The optional name of the asset as bytes, defaults to None :ivar url: Optional URL where more information about the asset can be retrieved, defaults to None :ivar url_b64: Optional URL where more information about the asset can be retrieved as bytes, defaults to None :ivar metadata_hash: 32-byte hash of some metadata that is relevant to the asset and/or asset holders, defaults to None """ asset_id: int creator: str total: int decimals: int default_frozen: bool | None = None manager: str | None = None reserve: str | None = None freeze: str | None = None clawback: str | None = None unit_name: str | None = None unit_name_b64: bytes | None = None asset_name: str | None = None asset_name_b64: bytes | None = None url: str | None = None url_b64: bytes | None = None metadata_hash: bytes | None = None @dataclass(kw_only=True, frozen=True) class BulkAssetOptInOutResult: """Result from performing a bulk opt-in or bulk opt-out for an account against a series of assets. :ivar asset_id: The ID of the asset opted into / out of :ivar transaction_id: The transaction ID of the resulting opt in / out """ asset_id: int transaction_id: str class AssetManager: """A manager for Algorand Standard Assets (ASAs). :param algod_client: An algod client :param new_group: A function that creates a new TransactionComposer transaction group """ def __init__(self, algod_client: algod.AlgodClient, new_group: Callable[[], TransactionComposer]): self._algod = algod_client self._new_group = new_group def get_by_id(self, asset_id: int) -> AssetInformation: """Returns the current asset information for the asset with the given ID. :param asset_id: The ID of the asset :return: The asset information """ asset = self._algod.asset_info(asset_id) assert isinstance(asset, dict) params = asset["params"] return AssetInformation( asset_id=asset_id, total=params["total"], decimals=params["decimals"], asset_name=params.get("name"), asset_name_b64=params.get("name-b64"), unit_name=params.get("unit-name"), unit_name_b64=params.get("unit-name-b64"), url=params.get("url"), url_b64=params.get("url-b64"), creator=params["creator"], manager=params.get("manager"), clawback=params.get("clawback"), freeze=params.get("freeze"), reserve=params.get("reserve"), default_frozen=params.get("default-frozen"), metadata_hash=params.get("metadata-hash"), ) def get_account_information( self, sender: str | SigningAccount | TransactionSigner, asset_id: int ) -> AccountAssetInformation: """Returns the given sender account's asset holding for a given asset. :param sender: The address of the sender/account to look up :param asset_id: The ID of the asset to return a holding for :return: The account asset holding information """ address = self._get_address_from_sender(sender) info = self._algod.account_asset_info(address, asset_id) assert isinstance(info, dict) return AccountAssetInformation( asset_id=asset_id, balance=info["asset-holding"]["amount"], frozen=info["asset-holding"]["is-frozen"], round=info["round"], ) def bulk_opt_in( # noqa: PLR0913 self, account: str, asset_ids: list[int], signer: TransactionSigner | None = None, rekey_to: str | None = None, note: bytes | None = None, lease: bytes | None = None, static_fee: AlgoAmount | None = None, extra_fee: AlgoAmount | None = None, max_fee: AlgoAmount | None = None, validity_window: int | None = None, first_valid_round: int | None = None, last_valid_round: int | None = None, send_params: SendParams | None = None, ) -> list[BulkAssetOptInOutResult]: """Opt an account in to a list of Algorand Standard Assets. :param account: The account to opt-in :param asset_ids: The list of asset IDs to opt-in to :param signer: The signer to use for the transaction, defaults to None :param rekey_to: The address to rekey the account to, defaults to None :param note: The note to include in the transaction, defaults to None :param lease: The lease to include in the transaction, defaults to None :param static_fee: The static fee to include in the transaction, defaults to None :param extra_fee: The extra fee to include in the transaction, defaults to None :param max_fee: The maximum fee to include in the transaction, defaults to None :param validity_window: The validity window to include in the transaction, defaults to None :param first_valid_round: The first valid round to include in the transaction, defaults to None :param last_valid_round: The last valid round to include in the transaction, defaults to None :param send_params: The send parameters to use for the transaction, defaults to None :return: An array of records matching asset ID to transaction ID of the opt in """ results: list[BulkAssetOptInOutResult] = [] sender = self._get_address_from_sender(account) for asset_group in _chunk_array(asset_ids, algosdk.constants.TX_GROUP_LIMIT): composer = self._new_group() for asset_id in asset_group: params = AssetOptInParams( sender=sender, asset_id=asset_id, signer=signer, rekey_to=rekey_to, note=note, lease=lease, static_fee=static_fee, extra_fee=extra_fee, max_fee=max_fee, validity_window=validity_window, first_valid_round=first_valid_round, last_valid_round=last_valid_round, ) composer.add_asset_opt_in(params) result = composer.send(send_params) for i, asset_id in enumerate(asset_group): results.append(BulkAssetOptInOutResult(asset_id=asset_id, transaction_id=result.tx_ids[i])) return results def bulk_opt_out( # noqa: C901, PLR0913 self, *, account: str, asset_ids: list[int], ensure_zero_balance: bool = True, signer: TransactionSigner | None = None, rekey_to: str | None = None, note: bytes | None = None, lease: bytes | None = None, static_fee: AlgoAmount | None = None, extra_fee: AlgoAmount | None = None, max_fee: AlgoAmount | None = None, validity_window: int | None = None, first_valid_round: int | None = None, last_valid_round: int | None = None, send_params: SendParams | None = None, ) -> list[BulkAssetOptInOutResult]: """Opt an account out of a list of Algorand Standard Assets. :param account: The account to opt-out :param asset_ids: The list of asset IDs to opt-out of :param ensure_zero_balance: Whether to check if the account has a zero balance first, defaults to True :param signer: The signer to use for the transaction, defaults to None :param rekey_to: The address to rekey the account to, defaults to None :param note: The note to include in the transaction, defaults to None :param lease: The lease to include in the transaction, defaults to None :param static_fee: The static fee to include in the transaction, defaults to None :param extra_fee: The extra fee to include in the transaction, defaults to None :param max_fee: The maximum fee to include in the transaction, defaults to None :param validity_window: The validity window to include in the transaction, defaults to None :param first_valid_round: The first valid round to include in the transaction, defaults to None :param last_valid_round: The last valid round to include in the transaction, defaults to None :param send_params: The send parameters to use for the transaction, defaults to None :raises ValueError: If ensure_zero_balance is True and account has non-zero balance or is not opted in :return: An array of records matching asset ID to transaction ID of the opt out """ results: list[BulkAssetOptInOutResult] = [] sender = self._get_address_from_sender(account) for asset_group in _chunk_array(asset_ids, algosdk.constants.TX_GROUP_LIMIT): composer = self._new_group() not_opted_in_asset_ids: list[int] = [] non_zero_balance_asset_ids: list[int] = [] if ensure_zero_balance: for asset_id in asset_group: try: account_asset_info = self.get_account_information(sender, asset_id) if account_asset_info.balance != 0: non_zero_balance_asset_ids.append(asset_id) except Exception: not_opted_in_asset_ids.append(asset_id) if not_opted_in_asset_ids or non_zero_balance_asset_ids: error_message = f"Account {sender}" if not_opted_in_asset_ids: error_message += f" is not opted-in to Asset(s) {', '.join(map(str, not_opted_in_asset_ids))}" if non_zero_balance_asset_ids: error_message += ( f" has non-zero balance for Asset(s) {', '.join(map(str, non_zero_balance_asset_ids))}" ) error_message += "; can't opt-out." raise ValueError(error_message) for asset_id in asset_group: asset_info = self.get_by_id(asset_id) params = AssetOptOutParams( sender=sender, asset_id=asset_id, creator=asset_info.creator, signer=signer, rekey_to=rekey_to, note=note, lease=lease, static_fee=static_fee, extra_fee=extra_fee, max_fee=max_fee, validity_window=validity_window, first_valid_round=first_valid_round, last_valid_round=last_valid_round, ) composer.add_asset_opt_out(params) result = composer.send(send_params) for i, asset_id in enumerate(asset_group): results.append(BulkAssetOptInOutResult(asset_id=asset_id, transaction_id=result.tx_ids[i])) return results @staticmethod def _get_address_from_sender(sender: str | SigningAccount | TransactionSigner) -> str: if isinstance(sender, str): return sender if isinstance(sender, SigningAccount): return sender.address if isinstance(sender, AccountTransactionSigner): return str(algosdk.account.address_from_private_key(sender.private_key)) raise ValueError(f"Unsupported sender type: {type(sender)}") def _chunk_array(array: list, size: int) -> list[list]: return [array[i : i + size] for i in range(0, len(array), size)]
algorandfoundation/algokit-utils-py
src/algokit_utils/assets/asset_manager.py
Python
MIT
14,132
from typing import NoReturn def deprecated_import_error(old_path: str, new_path: str) -> NoReturn: """Helper to create consistent deprecation error messages""" raise ImportError( f"WARNING: The module '{old_path}' has been removed in algokit-utils v3. " f"Please update your imports to use '{new_path}' instead. " "See the migration guide for more details: " "https://github.com/algorandfoundation/algokit-utils-py/blob/main/docs/source/v3-migration-guide.md" ) def handle_getattr(name: str) -> NoReturn: param_mappings = { "ClientManager": "algokit_utils.ClientManager", "AlgorandClient": "algokit_utils.AlgorandClient", "AlgoSdkClients": "algokit_utils.AlgoSdkClients", "AccountManager": "algokit_utils.AccountManager", "PayParams": "algokit_utils.transactions.PaymentParams", "AlgokitComposer": "algokit_utils.TransactionComposer", "AssetCreateParams": "algokit_utils.transactions.AssetCreateParams", "AssetConfigParams": "algokit_utils.transactions.AssetConfigParams", "AssetFreezeParams": "algokit_utils.transactions.AssetFreezeParams", "AssetDestroyParams": "algokit_utils.transactions.AssetDestroyParams", "AssetTransferParams": "algokit_utils.transactions.AssetTransferParams", "AssetOptInParams": "algokit_utils.transactions.AssetOptInParams", "AppCallParams": "algokit_utils.transactions.AppCallParams", "MethodCallParams": "algokit_utils.transactions.MethodCallParams", "OnlineKeyRegParams": "algokit_utils.transactions.OnlineKeyRegistrationParams", } if name in param_mappings: deprecated_import_error(f"algokit_utils.beta.{name}", param_mappings[name]) raise AttributeError(f"module 'algokit_utils.beta' has no attribute '{name}'")
algorandfoundation/algokit-utils-py
src/algokit_utils/beta/_utils.py
Python
MIT
1,839
from typing import Any from algokit_utils.beta._utils import handle_getattr def __getattr__(name: str) -> Any: # noqa: ANN401 """Handle deprecated imports of parameter classes""" handle_getattr(name)
algorandfoundation/algokit-utils-py
src/algokit_utils/beta/account_manager.py
Python
MIT
213
from typing import Any from algokit_utils.beta._utils import handle_getattr def __getattr__(name: str) -> Any: # noqa: ANN401 """Handle deprecated imports of parameter classes""" handle_getattr(name)
algorandfoundation/algokit-utils-py
src/algokit_utils/beta/algorand_client.py
Python
MIT
213
from typing import Any from algokit_utils.beta._utils import handle_getattr def __getattr__(name: str) -> Any: # noqa: ANN401 """Handle deprecated imports of parameter classes""" handle_getattr(name)
algorandfoundation/algokit-utils-py
src/algokit_utils/beta/client_manager.py
Python
MIT
213
from typing import Any from algokit_utils.beta._utils import handle_getattr def __getattr__(name: str) -> Any: # noqa: ANN401 """Handle deprecated imports of parameter classes""" handle_getattr(name)
algorandfoundation/algokit-utils-py
src/algokit_utils/beta/composer.py
Python
MIT
213
from algokit_utils.clients.client_manager import * # noqa: F403 from algokit_utils.clients.dispenser_api_client import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/clients/__init__.py
Python
MIT
136
from __future__ import annotations import os from dataclasses import dataclass from typing import TYPE_CHECKING, Literal, TypeVar from urllib import parse import algosdk from algosdk.atomic_transaction_composer import TransactionSigner from algosdk.kmd import KMDClient from algosdk.source_map import SourceMap from algosdk.transaction import SuggestedParams from algosdk.v2client.algod import AlgodClient from algosdk.v2client.indexer import IndexerClient from algokit_utils._legacy_v2.application_specification import ApplicationSpecification from algokit_utils.applications.app_deployer import ApplicationLookup from algokit_utils.applications.app_spec.arc56 import Arc56Contract from algokit_utils.clients.dispenser_api_client import TestNetDispenserApiClient from algokit_utils.models.network import AlgoClientConfigs, AlgoClientNetworkConfig from algokit_utils.protocols.typed_clients import TypedAppClientProtocol, TypedAppFactoryProtocol if TYPE_CHECKING: from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.app_client import AppClient, AppClientCompilationParams from algokit_utils.applications.app_factory import AppFactory __all__ = [ "AlgoSdkClients", "ClientManager", "NetworkDetail", ] TypedFactoryT = TypeVar("TypedFactoryT", bound=TypedAppFactoryProtocol) TypedAppClientT = TypeVar("TypedAppClientT", bound=TypedAppClientProtocol) class AlgoSdkClients: """Container for Algorand SDK client instances. Holds references to Algod, Indexer and KMD clients. :param algod: Algod client instance :param indexer: Optional Indexer client instance :param kmd: Optional KMD client instance """ def __init__( self, algod: algosdk.v2client.algod.AlgodClient, indexer: IndexerClient | None = None, kmd: KMDClient | None = None, ): self.algod = algod self.indexer = indexer self.kmd = kmd @dataclass(kw_only=True, frozen=True) class NetworkDetail: """Details about an Algorand network. Contains network type flags and genesis information. """ is_testnet: bool is_mainnet: bool is_localnet: bool genesis_id: str genesis_hash: str def _get_config_from_environment(environment_prefix: str) -> AlgoClientNetworkConfig: server = os.getenv(f"{environment_prefix}_SERVER") if server is None: raise Exception(f"Server environment variable not set: {environment_prefix}_SERVER") port = os.getenv(f"{environment_prefix}_PORT") if port: parsed = parse.urlparse(server) server = parsed._replace(netloc=f"{parsed.hostname}:{port}").geturl() return AlgoClientNetworkConfig(server, os.getenv(f"{environment_prefix}_TOKEN", "")) class ClientManager: """Manager for Algorand SDK clients. Provides access to Algod, Indexer and KMD clients and helper methods for working with them. :param clients_or_configs: Either client instances or client configurations :param algorand_client: AlgorandClient instance """ def __init__(self, clients_or_configs: AlgoClientConfigs | AlgoSdkClients, algorand_client: AlgorandClient): if isinstance(clients_or_configs, AlgoSdkClients): _clients = clients_or_configs elif isinstance(clients_or_configs, AlgoClientConfigs): _clients = AlgoSdkClients( algod=ClientManager.get_algod_client(clients_or_configs.algod_config), indexer=ClientManager.get_indexer_client(clients_or_configs.indexer_config) if clients_or_configs.indexer_config else None, kmd=ClientManager.get_kmd_client(clients_or_configs.kmd_config) if clients_or_configs.kmd_config else None, ) self._algod = _clients.algod self._indexer = _clients.indexer self._kmd = _clients.kmd self._algorand = algorand_client self._suggested_params: SuggestedParams | None = None @property def algod(self) -> AlgodClient: """Returns an algosdk Algod API client. :return: Algod client instance """ return self._algod @property def indexer(self) -> IndexerClient: """Returns an algosdk Indexer API client. :raises ValueError: If no Indexer client is configured :return: Indexer client instance """ if not self._indexer: raise ValueError("Attempt to use Indexer client in AlgoKit instance with no Indexer configured") return self._indexer @property def indexer_if_present(self) -> IndexerClient | None: """Returns the Indexer client if configured, otherwise None. :return: Indexer client instance or None """ return self._indexer @property def kmd(self) -> KMDClient: """Returns an algosdk KMD API client. :raises ValueError: If no KMD client is configured :return: KMD client instance """ if not self._kmd: raise ValueError("Attempt to use Kmd client in AlgoKit instance with no Kmd configured") return self._kmd def network(self) -> NetworkDetail: """Get details about the connected Algorand network. :return: Network details including type and genesis information """ if self._suggested_params is None: self._suggested_params = self._algod.suggested_params() sp = self._suggested_params return NetworkDetail( is_testnet=sp.gen in ["testnet-v1.0", "testnet-v1", "testnet"], is_mainnet=sp.gen in ["mainnet-v1.0", "mainnet-v1", "mainnet"], is_localnet=ClientManager.genesis_id_is_localnet(str(sp.gen)), genesis_id=str(sp.gen), genesis_hash=sp.gh, ) def is_localnet(self) -> bool: """Check if connected to a local network. :return: True if connected to a local network """ return self.network().is_localnet def is_testnet(self) -> bool: """Check if connected to TestNet. :return: True if connected to TestNet """ return self.network().is_testnet def is_mainnet(self) -> bool: """Check if connected to MainNet. :return: True if connected to MainNet """ return self.network().is_mainnet def get_testnet_dispenser( self, auth_token: str | None = None, request_timeout: int | None = None ) -> TestNetDispenserApiClient: """Get a TestNet dispenser API client. :param auth_token: Optional authentication token :param request_timeout: Optional request timeout in seconds :return: TestNet dispenser client instance """ if request_timeout: return TestNetDispenserApiClient(auth_token=auth_token, request_timeout=request_timeout) return TestNetDispenserApiClient(auth_token=auth_token) def get_app_factory( self, app_spec: Arc56Contract | ApplicationSpecification | str, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, version: str | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> AppFactory: """Get an application factory for deploying smart contracts. :param app_spec: Application specification :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param version: Optional version string :param compilation_params: Optional compilation parameters :raises ValueError: If no Algorand client is configured :return: Application factory instance """ from algokit_utils.applications.app_factory import AppFactory, AppFactoryParams if not self._algorand: raise ValueError("Attempt to get app factory from a ClientManager without an Algorand client") return AppFactory( AppFactoryParams( algorand=self._algorand, app_spec=app_spec, app_name=app_name, default_sender=default_sender, default_signer=default_signer, version=version, compilation_params=compilation_params, ) ) def get_app_client_by_id( self, app_spec: (Arc56Contract | ApplicationSpecification | str), app_id: int, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: """Get an application client for an existing application by ID. :param app_spec: Application specification :param app_id: Application ID :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :raises ValueError: If no Algorand client is configured :return: Application client instance """ from algokit_utils.applications.app_client import AppClient, AppClientParams if not self._algorand: raise ValueError("Attempt to get app client from a ClientManager without an Algorand client") return AppClient( AppClientParams( app_spec=app_spec, algorand=self._algorand, app_id=app_id, app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, ) ) def get_app_client_by_network( self, app_spec: (Arc56Contract | ApplicationSpecification | str), app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: """Get an application client for an existing application by network. :param app_spec: Application specification :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :raises ValueError: If no Algorand client is configured :return: Application client instance """ from algokit_utils.applications.app_client import AppClient if not self._algorand: raise ValueError("Attempt to get app client from a ClientManager without an Algorand client") return AppClient.from_network( app_spec=app_spec, app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, algorand=self._algorand, ) def get_app_client_by_creator_and_name( self, creator_address: str, app_name: str, app_spec: Arc56Contract | ApplicationSpecification | str, default_sender: str | None = None, default_signer: TransactionSigner | None = None, ignore_cache: bool | None = None, app_lookup_cache: ApplicationLookup | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> AppClient: """Get an application client by creator address and name. :param creator_address: Creator address :param app_name: Application name :param app_spec: Application specification :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param ignore_cache: Optional flag to ignore cache :param app_lookup_cache: Optional app lookup cache :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :return: Application client instance """ from algokit_utils.applications.app_client import AppClient return AppClient.from_creator_and_name( creator_address=creator_address, app_name=app_name, default_sender=default_sender, default_signer=default_signer, ignore_cache=ignore_cache, app_lookup_cache=app_lookup_cache, app_spec=app_spec, approval_source_map=approval_source_map, clear_source_map=clear_source_map, algorand=self._algorand, ) @staticmethod def get_algod_client(config: AlgoClientNetworkConfig | None = None) -> AlgodClient: """Get an Algod client from config or environment. :param config: Optional client configuration :return: Algod client instance """ config = config or _get_config_from_environment("ALGOD") headers = {"X-Algo-API-Token": config.token or ""} return AlgodClient(algod_token=config.token or "", algod_address=config.server, headers=headers) @staticmethod def get_algod_client_from_environment() -> AlgodClient: """Get an Algod client from environment variables. :return: Algod client instance """ return ClientManager.get_algod_client(ClientManager.get_algod_config_from_environment()) @staticmethod def get_kmd_client(config: AlgoClientNetworkConfig | None = None) -> KMDClient: """Get a KMD client from config or environment. :param config: Optional client configuration :return: KMD client instance """ config = config or _get_config_from_environment("KMD") return KMDClient(config.token, config.server) @staticmethod def get_kmd_client_from_environment() -> KMDClient: """Get a KMD client from environment variables. :return: KMD client instance """ return ClientManager.get_kmd_client(ClientManager.get_kmd_config_from_environment()) @staticmethod def get_indexer_client(config: AlgoClientNetworkConfig | None = None) -> IndexerClient: """Get an Indexer client from config or environment. :param config: Optional client configuration :return: Indexer client instance """ config = config or _get_config_from_environment("INDEXER") headers = {"X-Indexer-API-Token": config.token} return IndexerClient(indexer_token=config.token, indexer_address=config.server, headers=headers) @staticmethod def get_indexer_client_from_environment() -> IndexerClient: """Get an Indexer client from environment variables. :return: Indexer client instance """ return ClientManager.get_indexer_client(ClientManager.get_indexer_config_from_environment()) @staticmethod def genesis_id_is_localnet(genesis_id: str | None) -> bool: """Check if a genesis ID indicates a local network. :param genesis_id: Genesis ID to check :return: True if genesis ID indicates a local network """ return genesis_id in ["devnet-v1", "sandnet-v1", "dockernet-v1"] def get_typed_app_client_by_creator_and_name( self, typed_client: type[TypedAppClientT], *, creator_address: str, app_name: str, default_sender: str | None = None, default_signer: TransactionSigner | None = None, ignore_cache: bool | None = None, app_lookup_cache: ApplicationLookup | None = None, ) -> TypedAppClientT: """Get a typed application client by creator address and name. :param typed_client: Typed client class :param creator_address: Creator address :param app_name: Application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param ignore_cache: Optional flag to ignore cache :param app_lookup_cache: Optional app lookup cache :raises ValueError: If no Algorand client is configured :return: Typed application client instance """ if not self._algorand: raise ValueError("Attempt to get app client from a ClientManager without an Algorand client") return typed_client.from_creator_and_name( creator_address=creator_address, app_name=app_name, default_sender=default_sender, default_signer=default_signer, ignore_cache=ignore_cache, app_lookup_cache=app_lookup_cache, algorand=self._algorand, ) def get_typed_app_client_by_id( self, typed_client: type[TypedAppClientT], *, app_id: int, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> TypedAppClientT: """Get a typed application client by ID. :param typed_client: Typed client class :param app_id: Application ID :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :raises ValueError: If no Algorand client is configured :return: Typed application client instance """ if not self._algorand: raise ValueError("Attempt to get app client from a ClientManager without an Algorand client") return typed_client( app_id=app_id, app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, algorand=self._algorand, ) def get_typed_app_client_by_network( self, typed_client: type[TypedAppClientT], *, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> TypedAppClientT: """Returns a new typed client, resolves the app ID for the current network. Uses pre-determined network-specific app IDs specified in the ARC-56 app spec. If no IDs are in the app spec or the network isn't recognised, an error is thrown. :param typed_client: The typed client class to instantiate :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param approval_source_map: Optional approval program source map :param clear_source_map: Optional clear program source map :raises ValueError: If no Algorand client is configured :return: The typed client instance """ if not self._algorand: raise ValueError("Attempt to get app client from a ClientManager without an Algorand client") return typed_client.from_network( app_name=app_name, default_sender=default_sender, default_signer=default_signer, approval_source_map=approval_source_map, clear_source_map=clear_source_map, algorand=self._algorand, ) def get_typed_app_factory( self, typed_factory: type[TypedFactoryT], *, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, version: str | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> TypedFactoryT: """Get a typed application factory. :param typed_factory: Typed factory class :param app_name: Optional application name :param default_sender: Optional default sender address :param default_signer: Optional default transaction signer :param version: Optional version string :param compilation_params: Optional compilation parameters :raises ValueError: If no Algorand client is configured :return: Typed application factory instance """ if not self._algorand: raise ValueError("Attempt to get app factory from a ClientManager without an Algorand client") return typed_factory( algorand=self._algorand, app_name=app_name, default_sender=default_sender, default_signer=default_signer, version=version, compilation_params=compilation_params, ) @staticmethod def get_config_from_environment_or_localnet() -> AlgoClientConfigs: """Retrieve client configuration from environment variables or fallback to localnet defaults. If ALGOD_SERVER is set in environment variables, it will use environment configuration, otherwise it will use default localnet configuration. :return: Configuration for algod, indexer, and optionally kmd """ algod_server = os.getenv("ALGOD_SERVER") if algod_server: # Use environment configuration algod_config = ClientManager.get_algod_config_from_environment() # Only include indexer if INDEXER_SERVER is set indexer_config = ( ClientManager.get_indexer_config_from_environment() if os.getenv("INDEXER_SERVER") else None ) # Include KMD config only for local networks (not mainnet/testnet) kmd_config = ( AlgoClientNetworkConfig( server=algod_config.server, token=algod_config.token, port=os.getenv("KMD_PORT", "4002") ) if not any(net in algod_server.lower() for net in ["mainnet", "testnet"]) else None ) else: # Use localnet defaults algod_config = ClientManager.get_default_localnet_config("algod") indexer_config = ClientManager.get_default_localnet_config("indexer") kmd_config = ClientManager.get_default_localnet_config("kmd") return AlgoClientConfigs( algod_config=algod_config, indexer_config=indexer_config, kmd_config=kmd_config, ) @staticmethod def get_default_localnet_config( config_or_port: Literal["algod", "indexer", "kmd"] | int, ) -> AlgoClientNetworkConfig: """Get default configuration for local network services. :param config_or_port: Service name or port number :return: Client configuration for local network """ port = ( config_or_port if isinstance(config_or_port, int) else {"algod": 4001, "indexer": 8980, "kmd": 4002}[config_or_port] ) return AlgoClientNetworkConfig(server=f"http://localhost:{port}", token="a" * 64) @staticmethod def get_algod_config_from_environment() -> AlgoClientNetworkConfig: """Retrieve the algod configuration from environment variables. Will raise an error if ALGOD_SERVER environment variable is not set :return: Algod client configuration """ return _get_config_from_environment("ALGOD") @staticmethod def get_indexer_config_from_environment() -> AlgoClientNetworkConfig: """Retrieve the indexer configuration from environment variables. Will raise an error if INDEXER_SERVER environment variable is not set :return: Indexer client configuration """ return _get_config_from_environment("INDEXER") @staticmethod def get_kmd_config_from_environment() -> AlgoClientNetworkConfig: """Retrieve the kmd configuration from environment variables. :return: KMD client configuration """ return _get_config_from_environment("KMD") @staticmethod def get_algonode_config( network: Literal["testnet", "mainnet"], config: Literal["algod", "indexer"] ) -> AlgoClientNetworkConfig: """Returns the Algorand configuration to point to the free tier of the AlgoNode service. :param network: Which network to connect to - TestNet or MainNet :param config: Which algod config to return - Algod or Indexer :return: Configuration for the specified network and service """ service_type = "api" if config == "algod" else "idx" return AlgoClientNetworkConfig( server=f"https://{network}-{service_type}.algonode.cloud", port=443, )
algorandfoundation/algokit-utils-py
src/algokit_utils/clients/client_manager.py
Python
MIT
25,683
import contextlib import enum import os from dataclasses import dataclass import httpx from algokit_utils.config import config __all__ = [ "DISPENSER_ACCESS_TOKEN_KEY", "DISPENSER_ASSETS", "DISPENSER_REQUEST_TIMEOUT", "DispenserApiConfig", "DispenserAsset", "DispenserAssetName", "DispenserFundResponse", "DispenserLimitResponse", "TestNetDispenserApiClient", ] logger = config.logger class DispenserApiConfig: BASE_URL = "https://api.dispenser.algorandfoundation.tools" class DispenserAssetName(enum.IntEnum): ALGO = 0 @dataclass class DispenserAsset: asset_id: int decimals: int description: str @dataclass class DispenserFundResponse: tx_id: str amount: int @dataclass class DispenserLimitResponse: amount: int DISPENSER_ASSETS = { DispenserAssetName.ALGO: DispenserAsset( asset_id=0, decimals=6, description="Algo", ), } DISPENSER_REQUEST_TIMEOUT = 15 DISPENSER_ACCESS_TOKEN_KEY = "ALGOKIT_DISPENSER_ACCESS_TOKEN" class TestNetDispenserApiClient: """ Client for interacting with the [AlgoKit TestNet Dispenser API](https://github.com/algorandfoundation/algokit/blob/main/docs/testnet_api.md). To get started create a new access token via `algokit dispenser login --ci` and pass it to the client constructor as `auth_token`. Alternatively set the access token as environment variable `ALGOKIT_DISPENSER_ACCESS_TOKEN`, and it will be auto loaded. If both are set, the constructor argument takes precedence. Default request timeout is 15 seconds. Modify by passing `request_timeout` to the constructor. """ # NOTE: ensures pytest does not think this is a test # https://docs.pytest.org/en/stable/example/pythoncollection.html#customizing-test-collection __test__ = False auth_token: str request_timeout = DISPENSER_REQUEST_TIMEOUT def __init__(self, auth_token: str | None = None, request_timeout: int = DISPENSER_REQUEST_TIMEOUT): auth_token_from_env = os.getenv(DISPENSER_ACCESS_TOKEN_KEY) if auth_token: self.auth_token = auth_token elif auth_token_from_env: self.auth_token = auth_token_from_env else: raise Exception( f"Can't init AlgoKit TestNet Dispenser API client " f"because neither environment variable {DISPENSER_ACCESS_TOKEN_KEY} or " "the auth_token were provided." ) self.request_timeout = request_timeout def _process_dispenser_request( self, *, auth_token: str, url_suffix: str, data: dict | None = None, method: str = "POST" ) -> httpx.Response: """ Generalized method to process http requests to dispenser API """ headers = {"Authorization": f"Bearer {(auth_token)}"} # Set request arguments request_args = { "url": f"{DispenserApiConfig.BASE_URL}/{url_suffix}", "headers": headers, "timeout": self.request_timeout, } if method.upper() != "GET" and data is not None: request_args["json"] = data try: response: httpx.Response = getattr(httpx, method.lower())(**request_args) response.raise_for_status() return response except httpx.HTTPStatusError as err: error_message = f"Error processing dispenser API request: {err.response.status_code}" error_response = None with contextlib.suppress(Exception): error_response = err.response.json() if error_response and error_response.get("code"): error_message = error_response.get("code") elif err.response.status_code == httpx.codes.BAD_REQUEST: error_message = err.response.json()["message"] raise Exception(error_message) from err except Exception as err: error_message = "Error processing dispenser API request" logger.debug(f"{error_message}: {err}", exc_info=True) raise err def fund(self, address: str, amount: int, asset_id: int) -> DispenserFundResponse: """ Fund an account with Algos from the dispenser API """ try: response = self._process_dispenser_request( auth_token=self.auth_token, url_suffix=f"fund/{asset_id}", data={"receiver": address, "amount": amount, "assetID": asset_id}, method="POST", ) content = response.json() return DispenserFundResponse(tx_id=content["txID"], amount=content["amount"]) except Exception as err: logger.exception(f"Error funding account {address}: {err}") raise err def refund(self, refund_txn_id: str) -> None: """ Register a refund for a transaction with the dispenser API """ try: self._process_dispenser_request( auth_token=self.auth_token, url_suffix="refund", data={"refundTransactionID": refund_txn_id}, method="POST", ) except Exception as err: logger.exception(f"Error issuing refund for txn_id {refund_txn_id}: {err}") raise err def get_limit( self, address: str, ) -> DispenserLimitResponse: """ Get current limit for an account with Algos from the dispenser API """ try: response = self._process_dispenser_request( auth_token=self.auth_token, url_suffix=f"fund/{DISPENSER_ASSETS[DispenserAssetName.ALGO].asset_id}/limit", method="GET", ) content = response.json() return DispenserLimitResponse(amount=content["amount"]) except Exception as err: logger.exception(f"Error setting limit for account {address}: {err}") raise err
algorandfoundation/algokit-utils-py
src/algokit_utils/clients/dispenser_api_client.py
Python
MIT
6,045
import warnings warnings.warn( "The legacy v2 common module is deprecated and will be removed in a future version. " "Refer to `CompiledTeal` class from `algokit_utils` instead.", DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.common import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/common.py
Python
MIT
300
import logging import os from collections.abc import Callable from pathlib import Path from typing import Any # Environment variable to override the project root ALGOKIT_PROJECT_ROOT = os.getenv("ALGOKIT_PROJECT_ROOT") ALGOKIT_CONFIG_FILENAME = ".algokit.toml" class AlgoKitLogger: def __init__(self) -> None: self._logger = logging.getLogger("algokit") self._setup_logger() def _setup_logger(self) -> None: formatter = logging.Formatter("%(levelname)s: %(message)s") handler = logging.StreamHandler() handler.setFormatter(formatter) self._logger.addHandler(handler) self._logger.setLevel(logging.INFO) def _get_logger(self, *, suppress_log: bool = False) -> logging.Logger: if suppress_log: null_logger = logging.getLogger("null") null_logger.addHandler(logging.NullHandler()) return null_logger return self._logger def error(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log an error message, optionally suppressing output""" self._get_logger(suppress_log=suppress_log).error(message, *args, **kwargs) def exception(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log an exception message, optionally suppressing output""" self._get_logger(suppress_log=suppress_log).exception(message, *args, **kwargs) def warning(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log a warning message, optionally suppressing output""" self._get_logger(suppress_log=suppress_log).warning(message, *args, **kwargs) def info(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log an info message, optionally suppressing output""" self._get_logger(suppress_log=suppress_log).info(message, *args, **kwargs) def debug(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log a debug message, optionally suppressing output""" self._get_logger(suppress_log=suppress_log).debug(message, *args, **kwargs) def verbose(self, message: str, *args: Any, suppress_log: bool = False, **kwargs: Any) -> None: """Log a verbose message (maps to debug), optionally suppressing output""" self._get_logger(suppress_log=suppress_log).debug(message, *args, **kwargs) class UpdatableConfig: """Class to manage and update configuration settings for the AlgoKit project. Attributes: debug (bool): Indicates whether debug mode is enabled. project_root (Path | None): The path to the project root directory. trace_all (bool): Indicates whether to trace all operations. trace_buffer_size_mb (int): The size of the trace buffer in megabytes. max_search_depth (int): The maximum depth to search for a specific file. populate_app_call_resources (bool): Indicates whether to populate app call resources. """ def __init__(self) -> None: self._logger = AlgoKitLogger() self._debug: bool = False self._project_root: Path | None = None self._trace_all: bool = False self._trace_buffer_size_mb: int | float = 256 # megabytes self._max_search_depth: int = 10 self._populate_app_call_resources: bool = False self._configure_project_root() def _configure_project_root(self) -> None: """Configures the project root by searching for a specific file within a depth limit.""" current_path = Path(__file__).resolve() for _ in range(self._max_search_depth): self.logger.debug(f"Searching in: {current_path}") if (current_path / ALGOKIT_CONFIG_FILENAME).exists(): self._project_root = current_path break current_path = current_path.parent @property def logger(self) -> AlgoKitLogger: return self._logger @property def debug(self) -> bool: """Returns the debug status.""" return self._debug @property def project_root(self) -> Path | None: """Returns the project root path.""" return self._project_root @property def trace_all(self) -> bool: """Indicates whether to store simulation traces for all operations.""" return self._trace_all @property def trace_buffer_size_mb(self) -> int | float: """Returns the size of the trace buffer in megabytes.""" return self._trace_buffer_size_mb @property def populate_app_call_resource(self) -> bool: return self._populate_app_call_resources def with_debug(self, func: Callable[[], str | None]) -> None: """Executes a function with debug mode temporarily enabled.""" original_debug = self._debug try: self._debug = True func() finally: self._debug = original_debug def configure( self, *, debug: bool | None = None, project_root: Path | None = None, trace_all: bool = False, trace_buffer_size_mb: float = 256, max_search_depth: int = 10, populate_app_call_resources: bool = False, ) -> None: """ Configures various settings for the application. Please note, when `project_root` is not specified, by default config will attempt to find the `algokit.toml` by scanning the parent directories according to the `max_search_depth` parameter. Alternatively value can also be set via the `ALGOKIT_PROJECT_ROOT` environment variable. If you are executing the config from an algokit compliant project, you can simply call `config.configure(debug=True)`. :param debug: Indicates whether debug mode is enabled. :param project_root: The path to the project root directory. Defaults to None. :param trace_all: Indicates whether to trace all operations. Defaults to False. Which implies that only the operations that are failed will be traced by default. :param trace_buffer_size_mb: The size of the trace buffer in megabytes. Defaults to 256 :param max_search_depth: The maximum depth to search for a specific file. Defaults to 10 :param populate_app_call_resources: Indicates whether to populate app call resources. Defaults to False """ if debug is not None: self._debug = debug if project_root is not None: self._project_root = project_root.resolve(strict=True) elif debug is not None and ALGOKIT_PROJECT_ROOT: self._project_root = Path(ALGOKIT_PROJECT_ROOT).resolve(strict=True) self._trace_all = trace_all self._trace_buffer_size_mb = trace_buffer_size_mb self._max_search_depth = max_search_depth self._populate_app_call_resources = populate_app_call_resources config = UpdatableConfig()
algorandfoundation/algokit-utils-py
src/algokit_utils/config.py
Python
MIT
7,029
import warnings warnings.warn( "The legacy v2 deploy module is deprecated and will be removed in a future version. " "Refer to `AppFactory` and `AppDeployer` abstractions from `algokit_utils` module instead.", DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.deploy import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/deploy.py
Python
MIT
330
import warnings warnings.warn( "The legacy v2 dispenser api module is deprecated and will be removed in a future version. " "Import from 'algokit_utils.clients.dispenser_api_client' instead.", DeprecationWarning, stacklevel=2, ) from algokit_utils.clients.dispenser_api_client import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/dispenser_api.py
Python
MIT
324
from algokit_utils.errors.logic_error import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/errors/__init__.py
Python
MIT
61
import base64 import re from collections.abc import Callable from copy import copy from typing import TYPE_CHECKING, TypedDict from algosdk.atomic_transaction_composer import ( SimulateAtomicTransactionResponse, ) from algokit_utils.models.simulate import SimulationTrace if TYPE_CHECKING: from algosdk.source_map import SourceMap as AlgoSourceMap __all__ = [ "LogicError", "LogicErrorData", "parse_logic_error", ] LOGIC_ERROR = ( ".*transaction (?P<transaction_id>[A-Z0-9]+): logic eval error: (?P<message>.*). Details: .*pc=(?P<pc>[0-9]+).*" ) class LogicErrorData(TypedDict): transaction_id: str message: str pc: int def parse_logic_error( error_str: str, ) -> LogicErrorData | None: match = re.match(LOGIC_ERROR, error_str) if match is None: return None return { "transaction_id": match.group("transaction_id"), "message": match.group("message"), "pc": int(match.group("pc")), } class LogicError(Exception): def __init__( self, *, logic_error_str: str, program: str, source_map: "AlgoSourceMap | None", transaction_id: str, message: str, pc: int, logic_error: Exception | None = None, traces: list[SimulationTrace] | None = None, get_line_for_pc: Callable[[int], int | None] | None = None, ): self.logic_error = logic_error self.logic_error_str = logic_error_str try: self.program = base64.b64decode(program).decode("utf-8") except Exception: self.program = program self.source_map = source_map self.lines = self.program.split("\n") self.transaction_id = transaction_id self.message = message self.pc = pc self.traces = traces self.line_no = ( self.source_map.get_line_for_pc(self.pc) if self.source_map else get_line_for_pc(self.pc) if get_line_for_pc else None ) def __str__(self) -> str: return ( f"Txn {self.transaction_id} had error '{self.message}' at PC {self.pc}" + (":" if self.line_no is None else f" and Source Line {self.line_no}:") + f"\n{self.trace()}" ) def trace(self, lines: int = 5) -> str: if self.line_no is None: return """ Could not determine TEAL source line for the error as no approval source map was provided, to receive a trace of the error please provide an approval SourceMap. Either by: 1.Providing template_values when creating the ApplicationClient, so a SourceMap can be obtained automatically OR 2.Set approval_source_map from a previously compiled approval program OR 3.Import a previously exported source map using import_source_map""" program_lines = copy(self.lines) program_lines[self.line_no] += "\t\t<-- Error" lines_before = max(0, self.line_no - lines) lines_after = min(len(program_lines), self.line_no + lines) return "\n\t" + "\n\t".join(program_lines[lines_before:lines_after]) def create_simulate_traces_for_logic_error(simulate: SimulateAtomicTransactionResponse) -> list[SimulationTrace]: traces = [] if hasattr(simulate, "simulate_response") and hasattr(simulate, "failed_at") and simulate.failed_at: for txn_group in simulate.simulate_response["txn-groups"]: app_budget_added = txn_group.get("app-budget-added", None) app_budget_consumed = txn_group.get("app-budget-consumed", None) failure_message = txn_group.get("failure-message", None) txn_result = txn_group.get("txn-results", [{}])[0] exec_trace = txn_result.get("exec-trace", {}) traces.append( SimulationTrace( app_budget_added=app_budget_added, app_budget_consumed=app_budget_consumed, failure_message=failure_message, exec_trace=exec_trace, ) ) return traces
algorandfoundation/algokit-utils-py
src/algokit_utils/errors/logic_error.py
Python
MIT
4,104
import warnings warnings.warn( "The legacy v2 logic error module is deprecated and will be removed in a future version. " "Use 'from algokit_utils.errors import LogicError' instead.", DeprecationWarning, stacklevel=2, ) from algokit_utils.errors.logic_error import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/logic_error.py
Python
MIT
305
from algokit_utils._legacy_v2.models import * # noqa: F403 from algokit_utils.models.account import * # noqa: F403 from algokit_utils.models.amount import * # noqa: F403 from algokit_utils.models.application import * # noqa: F403 from algokit_utils.models.network import * # noqa: F403 from algokit_utils.models.simulate import * # noqa: F403 from algokit_utils.models.state import * # noqa: F403 from algokit_utils.models.transaction import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/models/__init__.py
Python
MIT
465
import dataclasses import algosdk import algosdk.atomic_transaction_composer from algosdk.atomic_transaction_composer import AccountTransactionSigner, LogicSigTransactionSigner, TransactionSigner from algosdk.transaction import LogicSigAccount as AlgosdkLogicSigAccount from algosdk.transaction import Multisig, MultisigTransaction from typing_extensions import deprecated __all__ = [ "DISPENSER_ACCOUNT_NAME", "MultiSigAccount", "MultisigMetadata", "SigningAccount", "TransactionSignerAccount", ] DISPENSER_ACCOUNT_NAME = "DISPENSER" @dataclasses.dataclass(kw_only=True) class TransactionSignerAccount: """A basic transaction signer account.""" address: str signer: TransactionSigner def __post_init__(self) -> None: if not isinstance(self.address, str): raise TypeError("Address must be a string") if not isinstance(self.signer, TransactionSigner): raise TypeError("Signer must be a TransactionSigner instance") @dataclasses.dataclass(kw_only=True) class SigningAccount: """Holds the private key and address for an account. Provides access to the account's private key, address, public key and transaction signer. """ private_key: str """Base64 encoded private key""" address: str = dataclasses.field(default="") """Address for this account""" def __post_init__(self) -> None: if not self.address: self.address = str(algosdk.account.address_from_private_key(self.private_key)) @property def public_key(self) -> bytes: """The public key for this account. :return: The public key as bytes """ public_key = algosdk.encoding.decode_address(self.address) assert isinstance(public_key, bytes) return public_key @property def signer(self) -> AccountTransactionSigner: """Get an AccountTransactionSigner for this account. :return: A transaction signer for this account """ return AccountTransactionSigner(self.private_key) @deprecated( "Use `algorand.account.random()` or `SigningAccount(private_key=algosdk.account.generate_account()[0])` instead" ) @staticmethod def new_account() -> "SigningAccount": """Create a new random account. :return: A new Account instance """ private_key, address = algosdk.account.generate_account() return SigningAccount(private_key=private_key) @dataclasses.dataclass(kw_only=True) class MultisigMetadata: """Metadata for a multisig account. Contains the version, threshold and addresses for a multisig account. """ version: int threshold: int addresses: list[str] @dataclasses.dataclass(kw_only=True) class MultiSigAccount: """Account wrapper that supports partial or full multisig signing. Provides functionality to manage and sign transactions for a multisig account. :param multisig_params: The parameters for the multisig account :param signing_accounts: The list of accounts that can sign """ _params: MultisigMetadata _signing_accounts: list[SigningAccount] _addr: str _signer: TransactionSigner _multisig: Multisig def __init__(self, multisig_params: MultisigMetadata, signing_accounts: list[SigningAccount]) -> None: self._params = multisig_params self._signing_accounts = signing_accounts self._multisig = Multisig(multisig_params.version, multisig_params.threshold, multisig_params.addresses) self._addr = str(self._multisig.address()) self._signer = algosdk.atomic_transaction_composer.MultisigTransactionSigner( self._multisig, [account.private_key for account in signing_accounts], ) @property def params(self) -> MultisigMetadata: """Get the parameters for the multisig account. :return: The multisig account parameters """ return self._params @property def signing_accounts(self) -> list[SigningAccount]: """Get the list of accounts that are present to sign. :return: The list of signing accounts """ return self._signing_accounts @property def address(self) -> str: """Get the address of the multisig account. :return: The multisig account address """ return self._addr @property def signer(self) -> TransactionSigner: """Get the transaction signer for this multisig account. :return: The multisig transaction signer """ return self._signer def sign(self, transaction: algosdk.transaction.Transaction) -> MultisigTransaction: """Sign the given transaction with all present signers. :param transaction: Either a transaction object or a raw, partially signed transaction :return: The transaction signed by the present signers """ msig_txn = MultisigTransaction( transaction, self._multisig, ) for signer in self._signing_accounts: msig_txn.sign(signer.private_key) return msig_txn @dataclasses.dataclass(kw_only=True) class LogicSigAccount: """Account wrapper that supports logic sig signing. Provides functionality to manage and sign transactions for a logic sig account. """ _account: AlgosdkLogicSigAccount _signer: LogicSigTransactionSigner def __init__(self, account: AlgosdkLogicSigAccount) -> None: self._account = account self._signer = LogicSigTransactionSigner(account) @property def address(self) -> str: """Get the address of the multisig account. :return: The multisig account address """ return self._account.address() @property def signer(self) -> LogicSigTransactionSigner: """Get the transaction signer for this multisig account. :return: The multisig transaction signer """ return self._signer
algorandfoundation/algokit-utils-py
src/algokit_utils/models/account.py
Python
MIT
6,014
from __future__ import annotations from decimal import Decimal from typing import overload import algosdk from typing_extensions import Self __all__ = ["ALGORAND_MIN_TX_FEE", "AlgoAmount", "algo", "micro_algo", "transaction_fees"] class AlgoAmount: """Wrapper class to ensure safe, explicit conversion between µAlgo, Algo and numbers. :example: >>> amount = AlgoAmount(algos=1) >>> amount = AlgoAmount(algo=1) >>> amount = AlgoAmount.from_algos(1) >>> amount = AlgoAmount.from_algo(1) >>> amount = AlgoAmount(micro_algos=1_000_000) >>> amount = AlgoAmount(micro_algo=1_000_000) >>> amount = AlgoAmount.from_micro_algos(1_000_000) >>> amount = AlgoAmount.from_micro_algo(1_000_000) """ @overload def __init__(self, *, micro_algos: int) -> None: ... @overload def __init__(self, *, micro_algo: int) -> None: ... @overload def __init__(self, *, algos: int | Decimal) -> None: ... @overload def __init__(self, *, algo: int | Decimal) -> None: ... def __init__( self, *, micro_algos: int | None = None, micro_algo: int | None = None, algos: int | Decimal | None = None, algo: int | Decimal | None = None, ): if micro_algos is None and micro_algo is None and algos is None and algo is None: raise ValueError("No amount provided") if micro_algos is not None: self.amount_in_micro_algo = int(micro_algos) elif micro_algo is not None: self.amount_in_micro_algo = int(micro_algo) elif algos is not None: self.amount_in_micro_algo = int(algos * algosdk.constants.MICROALGOS_TO_ALGOS_RATIO) elif algo is not None: self.amount_in_micro_algo = int(algo * algosdk.constants.MICROALGOS_TO_ALGOS_RATIO) else: raise ValueError("Invalid amount provided") @property def micro_algos(self) -> int: """Return the amount as a number in µAlgo. :returns: The amount in µAlgo. """ return self.amount_in_micro_algo @property def micro_algo(self) -> int: """Return the amount as a number in µAlgo. :returns: The amount in µAlgo. """ return self.amount_in_micro_algo @property def algos(self) -> Decimal: """Return the amount as a number in Algo. :returns: The amount in Algo. """ return algosdk.util.microalgos_to_algos(self.amount_in_micro_algo) # type: ignore[no-any-return] @property def algo(self) -> Decimal: """Return the amount as a number in Algo. :returns: The amount in Algo. """ return algosdk.util.microalgos_to_algos(self.amount_in_micro_algo) # type: ignore[no-any-return] @staticmethod def from_algos(amount: int | Decimal) -> AlgoAmount: """Create an AlgoAmount object representing the given number of Algo. :param amount: The amount in Algo. :returns: An AlgoAmount instance. :example: >>> amount = AlgoAmount.from_algos(1) """ return AlgoAmount(algos=amount) @staticmethod def from_algo(amount: int | Decimal) -> AlgoAmount: """Create an AlgoAmount object representing the given number of Algo. :param amount: The amount in Algo. :returns: An AlgoAmount instance. :example: >>> amount = AlgoAmount.from_algo(1) """ return AlgoAmount(algo=amount) @staticmethod def from_micro_algos(amount: int) -> AlgoAmount: """Create an AlgoAmount object representing the given number of µAlgo. :param amount: The amount in µAlgo. :returns: An AlgoAmount instance. :example: >>> amount = AlgoAmount.from_micro_algos(1_000_000) """ return AlgoAmount(micro_algos=amount) @staticmethod def from_micro_algo(amount: int) -> AlgoAmount: """Create an AlgoAmount object representing the given number of µAlgo. :param amount: The amount in µAlgo. :returns: An AlgoAmount instance. :example: >>> amount = AlgoAmount.from_micro_algo(1_000_000) """ return AlgoAmount(micro_algo=amount) def __str__(self) -> str: return f"{self.micro_algo:,} µALGO" def __int__(self) -> int: return self.micro_algos def __add__(self, other: AlgoAmount) -> AlgoAmount: if isinstance(other, AlgoAmount): total_micro_algos = self.micro_algos + other.micro_algos else: raise TypeError(f"Unsupported operand type(s) for +: 'AlgoAmount' and '{type(other).__name__}'") return AlgoAmount.from_micro_algos(total_micro_algos) def __radd__(self, other: AlgoAmount) -> AlgoAmount: return self.__add__(other) def __iadd__(self, other: AlgoAmount) -> Self: if isinstance(other, AlgoAmount): self.amount_in_micro_algo += other.micro_algos else: raise TypeError(f"Unsupported operand type(s) for +: 'AlgoAmount' and '{type(other).__name__}'") return self def __eq__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo == other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo == int(other) raise TypeError(f"Unsupported operand type(s) for ==: 'AlgoAmount' and '{type(other).__name__}'") def __ne__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo != other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo != int(other) raise TypeError(f"Unsupported operand type(s) for !=: 'AlgoAmount' and '{type(other).__name__}'") def __lt__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo < other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo < int(other) raise TypeError(f"Unsupported operand type(s) for <: 'AlgoAmount' and '{type(other).__name__}'") def __le__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo <= other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo <= int(other) raise TypeError(f"Unsupported operand type(s) for <=: 'AlgoAmount' and '{type(other).__name__}'") def __gt__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo > other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo > int(other) raise TypeError(f"Unsupported operand type(s) for >: 'AlgoAmount' and '{type(other).__name__}'") def __ge__(self, other: object) -> bool: if isinstance(other, AlgoAmount): return self.amount_in_micro_algo >= other.amount_in_micro_algo elif isinstance(other, int): return self.amount_in_micro_algo >= int(other) raise TypeError(f"Unsupported operand type(s) for >=: 'AlgoAmount' and '{type(other).__name__}'") def __sub__(self, other: AlgoAmount) -> AlgoAmount: if isinstance(other, AlgoAmount): total_micro_algos = self.micro_algos - other.micro_algos else: raise TypeError(f"Unsupported operand type(s) for -: 'AlgoAmount' and '{type(other).__name__}'") return AlgoAmount.from_micro_algos(total_micro_algos) def __rsub__(self, other: int) -> AlgoAmount: if isinstance(other, (int)): total_micro_algos = int(other) - self.micro_algos return AlgoAmount.from_micro_algos(total_micro_algos) raise TypeError(f"Unsupported operand type(s) for -: '{type(other).__name__}' and 'AlgoAmount'") def __isub__(self, other: AlgoAmount) -> Self: if isinstance(other, AlgoAmount): self.amount_in_micro_algo -= other.micro_algos else: raise TypeError(f"Unsupported operand type(s) for -: 'AlgoAmount' and '{type(other).__name__}'") return self # Helper functions def algo(algos: int) -> AlgoAmount: """Create an AlgoAmount object representing the given number of Algo. :param algos: The number of Algo to create an AlgoAmount object for. :return: An AlgoAmount object representing the given number of Algo. """ return AlgoAmount.from_algos(algos) def micro_algo(microalgos: int) -> AlgoAmount: """Create an AlgoAmount object representing the given number of µAlgo. :param microalgos: The number of µAlgo to create an AlgoAmount object for. :return: An AlgoAmount object representing the given number of µAlgo. """ return AlgoAmount.from_micro_algos(microalgos) ALGORAND_MIN_TX_FEE = micro_algo(1_000) def transaction_fees(number_of_transactions: int) -> AlgoAmount: """Calculate the total transaction fees for a given number of transactions. :param number_of_transactions: The number of transactions to calculate the fees for. :return: The total transaction fees. """ total_micro_algos = number_of_transactions * ALGORAND_MIN_TX_FEE.micro_algos return micro_algo(total_micro_algos)
algorandfoundation/algokit-utils-py
src/algokit_utils/models/amount.py
Python
MIT
9,411
from dataclasses import dataclass from typing import TYPE_CHECKING import algosdk from algosdk.source_map import SourceMap if TYPE_CHECKING: pass __all__ = [ "AppCompilationResult", "AppInformation", "AppSourceMaps", "AppState", "CompiledTeal", ] @dataclass(kw_only=True, frozen=True) class AppState: key_raw: bytes key_base64: str value_raw: bytes | None value_base64: str | None value: str | int @dataclass(kw_only=True, frozen=True) class AppInformation: app_id: int app_address: str approval_program: bytes clear_state_program: bytes creator: str global_state: dict[str, AppState] local_ints: int local_byte_slices: int global_ints: int global_byte_slices: int extra_program_pages: int | None @dataclass(kw_only=True, frozen=True) class CompiledTeal: teal: str compiled: str compiled_hash: str compiled_base64_to_bytes: bytes source_map: algosdk.source_map.SourceMap | None @dataclass(kw_only=True, frozen=True) class AppCompilationResult: compiled_approval: CompiledTeal compiled_clear: CompiledTeal @dataclass(kw_only=True, frozen=True) class AppSourceMaps: approval_source_map: SourceMap | None = None clear_source_map: SourceMap | None = None
algorandfoundation/algokit-utils-py
src/algokit_utils/models/application.py
Python
MIT
1,288
import dataclasses __all__ = [ "AlgoClientConfigs", "AlgoClientNetworkConfig", ] @dataclasses.dataclass class AlgoClientNetworkConfig: """Connection details for connecting to an {py:class}`algosdk.v2client.algod.AlgodClient` or {py:class}`algosdk.v2client.indexer.IndexerClient`""" server: str """URL for the service e.g. `http://localhost:4001` or `https://testnet-api.algonode.cloud`""" token: str | None = None """API Token to authenticate with the service""" port: str | int | None = None @dataclasses.dataclass class AlgoClientConfigs: algod_config: AlgoClientNetworkConfig indexer_config: AlgoClientNetworkConfig | None kmd_config: AlgoClientNetworkConfig | None
algorandfoundation/algokit-utils-py
src/algokit_utils/models/network.py
Python
MIT
723
from dataclasses import dataclass __all__ = ["SimulationTrace"] @dataclass class SimulationTrace: app_budget_added: int | None app_budget_consumed: int | None failure_message: str | None exec_trace: dict[str, object]
algorandfoundation/algokit-utils-py
src/algokit_utils/models/simulate.py
Python
MIT
236
import base64 from collections.abc import Mapping from dataclasses import dataclass from enum import IntEnum from typing import TypeAlias from algosdk.atomic_transaction_composer import AccountTransactionSigner from algosdk.box_reference import BoxReference as AlgosdkBoxReference __all__ = [ "BoxIdentifier", "BoxName", "BoxReference", "BoxValue", "DataTypeFlag", "TealTemplateParams", ] @dataclass(kw_only=True, frozen=True) class BoxName: name: str name_raw: bytes name_base64: str @dataclass(kw_only=True, frozen=True) class BoxValue: name: BoxName value: bytes class DataTypeFlag(IntEnum): BYTES = 1 UINT = 2 TealTemplateParams: TypeAlias = Mapping[str, str | int | bytes] | dict[str, str | int | bytes] BoxIdentifier: TypeAlias = str | bytes | AccountTransactionSigner class BoxReference(AlgosdkBoxReference): def __init__(self, app_id: int, name: bytes | str): super().__init__(app_index=app_id, name=self._b64_decode(name)) def __eq__(self, other: object) -> bool: if isinstance(other, (BoxReference | AlgosdkBoxReference)): return self.app_index == other.app_index and self.name == other.name return False def _b64_decode(self, value: str | bytes) -> bytes: if isinstance(value, str): try: return base64.b64decode(value) except Exception: return value.encode("utf-8") return value
algorandfoundation/algokit-utils-py
src/algokit_utils/models/state.py
Python
MIT
1,478
from typing import Any, Literal, TypedDict, TypeVar import algosdk __all__ = [ "Arc2TransactionNote", "BaseArc2Note", "JsonFormatArc2Note", "SendParams", "StringFormatArc2Note", "TransactionNote", "TransactionNoteData", "TransactionWrapper", ] # Define specific types for different formats class BaseArc2Note(TypedDict): """Base ARC-0002 transaction note structure""" dapp_name: str class StringFormatArc2Note(BaseArc2Note): """ARC-0002 note for string-based formats (m/b/u)""" format: Literal["m", "b", "u"] data: str class JsonFormatArc2Note(BaseArc2Note): """ARC-0002 note for JSON format""" format: Literal["j"] data: str | dict[str, Any] | list[Any] | int | None # Combined type for all valid ARC-0002 notes # See: https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md Arc2TransactionNote = StringFormatArc2Note | JsonFormatArc2Note TransactionNoteData = str | None | int | list[Any] | dict[str, Any] TransactionNote = bytes | TransactionNoteData | Arc2TransactionNote TxnTypeT = TypeVar("TxnTypeT", bound=algosdk.transaction.Transaction) class TransactionWrapper(algosdk.transaction.Transaction): """Wrapper around algosdk.transaction.Transaction with optional property validators""" def __init__(self, transaction: algosdk.transaction.Transaction) -> None: self._raw = transaction @property def raw(self) -> algosdk.transaction.Transaction: return self._raw @property def payment(self) -> algosdk.transaction.PaymentTxn: return self._return_if_type( algosdk.transaction.PaymentTxn, ) @property def keyreg(self) -> algosdk.transaction.KeyregTxn: return self._return_if_type(algosdk.transaction.KeyregTxn) @property def asset_config(self) -> algosdk.transaction.AssetConfigTxn: return self._return_if_type(algosdk.transaction.AssetConfigTxn) @property def asset_transfer(self) -> algosdk.transaction.AssetTransferTxn: return self._return_if_type(algosdk.transaction.AssetTransferTxn) @property def asset_freeze(self) -> algosdk.transaction.AssetFreezeTxn: return self._return_if_type(algosdk.transaction.AssetFreezeTxn) @property def application_call(self) -> algosdk.transaction.ApplicationCallTxn: return self._return_if_type(algosdk.transaction.ApplicationCallTxn) @property def state_proof(self) -> algosdk.transaction.StateProofTxn: return self._return_if_type(algosdk.transaction.StateProofTxn) def _return_if_type(self, txn_type: type[TxnTypeT]) -> TxnTypeT: if isinstance(self._raw, txn_type): return self._raw raise ValueError(f"Transaction is not of type {txn_type.__name__}") class SendParams(TypedDict, total=False): """Parameters for sending a transaction""" max_rounds_to_wait: int | None suppress_log: bool | None populate_app_call_resources: bool | None cover_app_call_inner_transaction_fees: bool | None
algorandfoundation/algokit-utils-py
src/algokit_utils/models/transaction.py
Python
MIT
3,052
import warnings warnings.warn( "The legacy v2 network clients module is deprecated and will be removed in a future version.", DeprecationWarning, stacklevel=2, ) from algokit_utils._legacy_v2.network_clients import * # noqa: F403, E402
algorandfoundation/algokit-utils-py
src/algokit_utils/network_clients.py
Python
MIT
251
from algokit_utils.protocols.account import * # noqa: F403 from algokit_utils.protocols.typed_clients import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/protocols/__init__.py
Python
MIT
126
from typing import Protocol, runtime_checkable from algosdk.atomic_transaction_composer import TransactionSigner __all__ = ["TransactionSignerAccountProtocol"] @runtime_checkable class TransactionSignerAccountProtocol(Protocol): """An account that has a transaction signer. Implemented by SigningAccount, LogicSigAccount, MultiSigAccount and TransactionSignerAccount abstractions. """ @property def address(self) -> str: """The address of the account.""" ... @property def signer(self) -> TransactionSigner: """The transaction signer for the account.""" ...
algorandfoundation/algokit-utils-py
src/algokit_utils/protocols/account.py
Python
MIT
624
from __future__ import annotations from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar from algosdk.atomic_transaction_composer import TransactionSigner from algosdk.source_map import SourceMap from typing_extensions import Self from algokit_utils.models import SendParams if TYPE_CHECKING: from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.app_client import ( AppClientBareCallCreateParams, AppClientBareCallParams, AppClientCompilationParams, BaseAppClientMethodCallParams, ) from algokit_utils.applications.app_deployer import ( ApplicationLookup, OnSchemaBreak, OnUpdate, ) from algokit_utils.applications.app_factory import AppFactoryDeployResult __all__ = [ "TypedAppClientProtocol", "TypedAppFactoryProtocol", ] class TypedAppClientProtocol(Protocol): @classmethod def from_creator_and_name( cls, *, creator_address: str, app_name: str, default_sender: str | None = None, default_signer: TransactionSigner | None = None, ignore_cache: bool | None = None, app_lookup_cache: ApplicationLookup | None = None, algorand: AlgorandClient, ) -> Self: ... @classmethod def from_network( cls, *, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, algorand: AlgorandClient, ) -> Self: ... def __init__( self, *, app_id: int, app_name: str | None = None, default_sender: str | None = None, default_signer: TransactionSigner | None = None, algorand: AlgorandClient, approval_source_map: SourceMap | None = None, clear_source_map: SourceMap | None = None, ) -> None: ... CreateParamsT = TypeVar( # noqa: PLC0105 "CreateParamsT", bound="BaseAppClientMethodCallParams | AppClientBareCallCreateParams | None", contravariant=True, ) UpdateParamsT = TypeVar( # noqa: PLC0105 "UpdateParamsT", bound="BaseAppClientMethodCallParams | AppClientBareCallParams | None", contravariant=True, ) DeleteParamsT = TypeVar( # noqa: PLC0105 "DeleteParamsT", bound="BaseAppClientMethodCallParams | AppClientBareCallParams | None", contravariant=True, ) class TypedAppFactoryProtocol(Protocol, Generic[CreateParamsT, UpdateParamsT, DeleteParamsT]): def __init__( self, algorand: AlgorandClient, **kwargs: Any, ) -> None: ... def deploy( self, *, on_update: OnUpdate | None = None, on_schema_break: OnSchemaBreak | None = None, create_params: CreateParamsT | None = None, update_params: UpdateParamsT | None = None, delete_params: DeleteParamsT | None = None, existing_deployments: ApplicationLookup | None = None, ignore_cache: bool = False, app_name: str | None = None, send_params: SendParams | None = None, compilation_params: AppClientCompilationParams | None = None, ) -> tuple[TypedAppClientProtocol, AppFactoryDeployResult]: ...
algorandfoundation/algokit-utils-py
src/algokit_utils/protocols/typed_clients.py
Python
MIT
3,322
from algokit_utils.transactions.transaction_composer import * # noqa: F403 from algokit_utils.transactions.transaction_creator import * # noqa: F403 from algokit_utils.transactions.transaction_sender import * # noqa: F403
algorandfoundation/algokit-utils-py
src/algokit_utils/transactions/__init__.py
Python
MIT
225
from __future__ import annotations import base64 import json import re from copy import deepcopy from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypedDict, Union, cast import algosdk import algosdk.atomic_transaction_composer import algosdk.v2client.models from algosdk import logic, transaction from algosdk.atomic_transaction_composer import ( AtomicTransactionComposer, SimulateAtomicTransactionResponse, TransactionSigner, TransactionWithSigner, ) from algosdk.transaction import ApplicationCallTxn, OnComplete, SuggestedParams from algosdk.v2client.algod import AlgodClient from algosdk.v2client.models.simulate_request import SimulateRequest from typing_extensions import deprecated from algokit_utils.applications.abi import ABIReturn, ABIValue from algokit_utils.applications.app_manager import AppManager from algokit_utils.applications.app_spec.arc56 import Method as Arc56Method from algokit_utils.config import config from algokit_utils.models.state import BoxIdentifier, BoxReference from algokit_utils.models.transaction import SendParams, TransactionWrapper from algokit_utils.protocols.account import TransactionSignerAccountProtocol if TYPE_CHECKING: from collections.abc import Callable from algosdk.abi import Method from algosdk.v2client.algod import AlgodClient from algosdk.v2client.models import SimulateTraceConfig from algokit_utils.models.amount import AlgoAmount from algokit_utils.models.transaction import Arc2TransactionNote __all__ = [ "AppCallMethodCallParams", "AppCallParams", "AppCreateMethodCallParams", "AppCreateParams", "AppCreateSchema", "AppDeleteMethodCallParams", "AppDeleteParams", "AppMethodCallTransactionArgument", "AppUpdateMethodCallParams", "AppUpdateParams", "AssetConfigParams", "AssetCreateParams", "AssetDestroyParams", "AssetFreezeParams", "AssetOptInParams", "AssetOptOutParams", "AssetTransferParams", "BuiltTransactions", "MethodCallParams", "OfflineKeyRegistrationParams", "OnlineKeyRegistrationParams", "PaymentParams", "SendAtomicTransactionComposerResults", "TransactionComposer", "TransactionComposerBuildResult", "TxnParams", "send_atomic_transaction_composer", ] logger = config.logger MAX_TRANSACTION_GROUP_SIZE = 16 MAX_APP_CALL_FOREIGN_REFERENCES = 8 MAX_APP_CALL_ACCOUNT_REFERENCES = 4 @dataclass(kw_only=True, frozen=True) class _CommonTxnParams: sender: str signer: TransactionSigner | TransactionSignerAccountProtocol | None = None rekey_to: str | None = None note: bytes | None = None lease: bytes | None = None static_fee: AlgoAmount | None = None extra_fee: AlgoAmount | None = None max_fee: AlgoAmount | None = None validity_window: int | None = None first_valid_round: int | None = None last_valid_round: int | None = None @dataclass(kw_only=True, frozen=True) class AdditionalAtcContext: max_fees: dict[int, AlgoAmount] | None = None suggested_params: SuggestedParams | None = None @dataclass(kw_only=True, frozen=True) class PaymentParams(_CommonTxnParams): """Parameters for a payment transaction. :ivar receiver: The account that will receive the ALGO :ivar amount: Amount to send :ivar close_remainder_to: If given, close the sender account and send the remaining balance to this address, defaults to None """ receiver: str amount: AlgoAmount close_remainder_to: str | None = None @dataclass(kw_only=True, frozen=True) class AssetCreateParams(_CommonTxnParams): """Parameters for creating a new asset. :ivar total: The total amount of the smallest divisible unit to create :ivar decimals: The amount of decimal places the asset should have, defaults to None :ivar default_frozen: Whether the asset is frozen by default in the creator address, defaults to None :ivar manager: The address that can change the manager, reserve, clawback, and freeze addresses, defaults to None :ivar reserve: The address that holds the uncirculated supply, defaults to None :ivar freeze: The address that can freeze the asset in any account, defaults to None :ivar clawback: The address that can clawback the asset from any account, defaults to None :ivar unit_name: The short ticker name for the asset, defaults to None :ivar asset_name: The full name of the asset, defaults to None :ivar url: The metadata URL for the asset, defaults to None :ivar metadata_hash: Hash of the metadata contained in the metadata URL, defaults to None """ total: int asset_name: str | None = None unit_name: str | None = None url: str | None = None decimals: int | None = None default_frozen: bool | None = None manager: str | None = None reserve: str | None = None freeze: str | None = None clawback: str | None = None metadata_hash: bytes | None = None @dataclass(kw_only=True, frozen=True) class AssetConfigParams(_CommonTxnParams): """Parameters for configuring an existing asset. :ivar asset_id: ID of the asset :ivar manager: The address that can change the manager, reserve, clawback, and freeze addresses, defaults to None :ivar reserve: The address that holds the uncirculated supply, defaults to None :ivar freeze: The address that can freeze the asset in any account, defaults to None :ivar clawback: The address that can clawback the asset from any account, defaults to None """ asset_id: int manager: str | None = None reserve: str | None = None freeze: str | None = None clawback: str | None = None @dataclass(kw_only=True, frozen=True) class AssetFreezeParams(_CommonTxnParams): """Parameters for freezing an asset. :ivar asset_id: The ID of the asset :ivar account: The account to freeze or unfreeze :ivar frozen: Whether the assets in the account should be frozen """ asset_id: int account: str frozen: bool @dataclass(kw_only=True, frozen=True) class AssetDestroyParams(_CommonTxnParams): """Parameters for destroying an asset. :ivar asset_id: ID of the asset """ asset_id: int @dataclass(kw_only=True, frozen=True) class OnlineKeyRegistrationParams(_CommonTxnParams): """Parameters for online key registration. :ivar vote_key: The root participation public key :ivar selection_key: The VRF public key :ivar vote_first: The first round that the participation key is valid :ivar vote_last: The last round that the participation key is valid :ivar vote_key_dilution: The dilution for the 2-level participation key :ivar state_proof_key: The 64 byte state proof public key commitment, defaults to None """ vote_key: str selection_key: str vote_first: int vote_last: int vote_key_dilution: int state_proof_key: bytes | None = None @dataclass(kw_only=True, frozen=True) class OfflineKeyRegistrationParams(_CommonTxnParams): """Parameters for offline key registration. :ivar prevent_account_from_ever_participating_again: Whether to prevent the account from ever participating again """ prevent_account_from_ever_participating_again: bool @dataclass(kw_only=True, frozen=True) class AssetTransferParams(_CommonTxnParams): """Parameters for transferring an asset. :ivar asset_id: ID of the asset :ivar amount: Amount of the asset to transfer (smallest divisible unit) :ivar receiver: The account to send the asset to :ivar clawback_target: The account to take the asset from, defaults to None :ivar close_asset_to: The account to close the asset to, defaults to None """ asset_id: int amount: int receiver: str clawback_target: str | None = None close_asset_to: str | None = None @dataclass(kw_only=True, frozen=True) class AssetOptInParams(_CommonTxnParams): """Parameters for opting into an asset. :ivar asset_id: ID of the asset """ asset_id: int @dataclass(kw_only=True, frozen=True) class AssetOptOutParams(_CommonTxnParams): """Parameters for opting out of an asset. :ivar asset_id: ID of the asset :ivar creator: The creator address of the asset """ asset_id: int creator: str @dataclass(kw_only=True, frozen=True) class AppCallParams(_CommonTxnParams): """Parameters for calling an application. :ivar on_complete: The OnComplete action :ivar app_id: ID of the application, defaults to None :ivar approval_program: The program to execute for all OnCompletes other than ClearState, defaults to None :ivar clear_state_program: The program to execute for ClearState OnComplete, defaults to None :ivar schema: The state schema for the app. This is immutable, defaults to None :ivar args: Application arguments, defaults to None :ivar account_references: Account references, defaults to None :ivar app_references: App references, defaults to None :ivar asset_references: Asset references, defaults to None :ivar extra_pages: Number of extra pages required for the programs, defaults to None :ivar box_references: Box references, defaults to None """ on_complete: OnComplete app_id: int | None = None approval_program: str | bytes | None = None clear_state_program: str | bytes | None = None schema: dict[str, int] | None = None args: list[bytes] | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None extra_pages: int | None = None box_references: list[BoxReference | BoxIdentifier] | None = None class AppCreateSchema(TypedDict): global_ints: int global_byte_slices: int local_ints: int local_byte_slices: int @dataclass(kw_only=True, frozen=True) class AppCreateParams(_CommonTxnParams): """Parameters for creating an application. :ivar approval_program: The program to execute for all OnCompletes other than ClearState as raw teal (string) or compiled teal (bytes) :ivar clear_state_program: The program to execute for ClearState OnComplete as raw teal (string) or compiled teal (bytes) :ivar schema: The state schema for the app. This is immutable, defaults to None :ivar on_complete: The OnComplete action (cannot be ClearState), defaults to None :ivar args: Application arguments, defaults to None :ivar account_references: Account references, defaults to None :ivar app_references: App references, defaults to None :ivar asset_references: Asset references, defaults to None :ivar box_references: Box references, defaults to None :ivar extra_program_pages: Number of extra pages required for the programs, defaults to None """ approval_program: str | bytes clear_state_program: str | bytes schema: AppCreateSchema | None = None on_complete: OnComplete | None = None args: list[bytes] | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None extra_program_pages: int | None = None @dataclass(kw_only=True, frozen=True) class AppUpdateParams(_CommonTxnParams): """Parameters for updating an application. :ivar app_id: ID of the application :ivar approval_program: The program to execute for all OnCompletes other than ClearState as raw teal (string) or compiled teal (bytes) :ivar clear_state_program: The program to execute for ClearState OnComplete as raw teal (string) or compiled teal (bytes) :ivar args: Application arguments, defaults to None :ivar account_references: Account references, defaults to None :ivar app_references: App references, defaults to None :ivar asset_references: Asset references, defaults to None :ivar box_references: Box references, defaults to None :ivar on_complete: The OnComplete action, defaults to None """ app_id: int approval_program: str | bytes clear_state_program: str | bytes args: list[bytes] | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None on_complete: OnComplete | None = None @dataclass(kw_only=True, frozen=True) class AppDeleteParams(_CommonTxnParams): """Parameters for deleting an application. :ivar app_id: ID of the application :ivar args: Application arguments, defaults to None :ivar account_references: Account references, defaults to None :ivar app_references: App references, defaults to None :ivar asset_references: Asset references, defaults to None :ivar box_references: Box references, defaults to None :ivar on_complete: The OnComplete action, defaults to DeleteApplicationOC """ app_id: int args: list[bytes] | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None on_complete: OnComplete = OnComplete.DeleteApplicationOC @dataclass(kw_only=True, frozen=True) class _BaseAppMethodCall(_CommonTxnParams): app_id: int method: Method args: list | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None schema: AppCreateSchema | None = None @dataclass(kw_only=True, frozen=True) class AppMethodCallParams(_CommonTxnParams): """Parameters for calling an application method. :ivar app_id: ID of the application :ivar method: The ABI method to call :ivar args: Arguments to the ABI method, defaults to None :ivar on_complete: The OnComplete action (cannot be UpdateApplication or ClearState), defaults to None :ivar account_references: Account references, defaults to None :ivar app_references: App references, defaults to None :ivar asset_references: Asset references, defaults to None :ivar box_references: Box references, defaults to None """ app_id: int method: Method args: list[bytes] | None = None on_complete: OnComplete | None = None account_references: list[str] | None = None app_references: list[int] | None = None asset_references: list[int] | None = None box_references: list[BoxReference | BoxIdentifier] | None = None @dataclass(kw_only=True, frozen=True) class AppCallMethodCallParams(_BaseAppMethodCall): """Parameters for a regular ABI method call. :ivar app_id: ID of the application :ivar method: The ABI method to call :ivar args: Arguments to the ABI method, either an ABI value, transaction with explicit signer, transaction, another method call, or None :ivar on_complete: The OnComplete action (cannot be UpdateApplication or ClearState), defaults to None """ app_id: int on_complete: OnComplete | None = None @dataclass(kw_only=True, frozen=True) class AppCreateMethodCallParams(_BaseAppMethodCall): """Parameters for an ABI method call that creates an application. :ivar approval_program: The program to execute for all OnCompletes other than ClearState :ivar clear_state_program: The program to execute for ClearState OnComplete :ivar schema: The state schema for the app, defaults to None :ivar on_complete: The OnComplete action (cannot be ClearState), defaults to None :ivar extra_program_pages: Number of extra pages required for the programs, defaults to None """ approval_program: str | bytes clear_state_program: str | bytes schema: AppCreateSchema | None = None on_complete: OnComplete | None = None extra_program_pages: int | None = None @dataclass(kw_only=True, frozen=True) class AppUpdateMethodCallParams(_BaseAppMethodCall): """Parameters for an ABI method call that updates an application. :ivar app_id: ID of the application :ivar approval_program: The program to execute for all OnCompletes other than ClearState :ivar clear_state_program: The program to execute for ClearState OnComplete :ivar on_complete: The OnComplete action, defaults to UpdateApplicationOC """ app_id: int approval_program: str | bytes clear_state_program: str | bytes on_complete: OnComplete = OnComplete.UpdateApplicationOC @dataclass(kw_only=True, frozen=True) class AppDeleteMethodCallParams(_BaseAppMethodCall): """Parameters for an ABI method call that deletes an application. :ivar app_id: ID of the application :ivar on_complete: The OnComplete action, defaults to DeleteApplicationOC """ app_id: int on_complete: OnComplete = OnComplete.DeleteApplicationOC MethodCallParams = ( AppCallMethodCallParams | AppCreateMethodCallParams | AppUpdateMethodCallParams | AppDeleteMethodCallParams ) AppMethodCallTransactionArgument = ( TransactionWithSigner | algosdk.transaction.Transaction | AppCreateMethodCallParams | AppUpdateMethodCallParams | AppCallMethodCallParams ) TxnParams = Union[ # noqa: UP007 PaymentParams, AssetCreateParams, AssetConfigParams, AssetFreezeParams, AssetDestroyParams, OnlineKeyRegistrationParams, AssetTransferParams, AssetOptInParams, AssetOptOutParams, AppCallParams, AppCreateParams, AppUpdateParams, AppDeleteParams, MethodCallParams, OfflineKeyRegistrationParams, ] @dataclass(frozen=True, kw_only=True) class TransactionContext: """Contextual information for a transaction.""" max_fee: AlgoAmount | None = None abi_method: Method | None = None @staticmethod def empty() -> TransactionContext: return TransactionContext(max_fee=None, abi_method=None) class TransactionWithContext: """Combines Transaction with additional context.""" def __init__(self, txn: algosdk.transaction.Transaction, context: TransactionContext): self.txn = txn self.context = context class TransactionWithSignerAndContext(TransactionWithSigner): """Combines TransactionWithSigner with additional context.""" def __init__(self, txn: algosdk.transaction.Transaction, signer: TransactionSigner, context: TransactionContext): super().__init__(txn, signer) self.context = context @staticmethod def from_txn_with_context( txn_with_context: TransactionWithContext, signer: TransactionSigner ) -> TransactionWithSignerAndContext: return TransactionWithSignerAndContext( txn=txn_with_context.txn, signer=signer, context=txn_with_context.context ) @dataclass(frozen=True) class BuiltTransactions: """Set of transactions built by TransactionComposer. :ivar transactions: The built transactions :ivar method_calls: Any ABIMethod objects associated with any of the transactions in a map keyed by txn id :ivar signers: Any TransactionSigner objects associated with any of the transactions in a map keyed by txn id """ transactions: list[algosdk.transaction.Transaction] method_calls: dict[int, Method] signers: dict[int, TransactionSigner] @dataclass class TransactionComposerBuildResult: """Result of building transactions with TransactionComposer. :ivar atc: The AtomicTransactionComposer instance :ivar transactions: The list of transactions with signers :ivar method_calls: Map of transaction index to ABI method """ atc: AtomicTransactionComposer transactions: list[TransactionWithSigner] method_calls: dict[int, Method] @dataclass class SendAtomicTransactionComposerResults: """Results from sending an AtomicTransactionComposer transaction group. :ivar group_id: The group ID if this was a transaction group :ivar confirmations: The confirmation info for each transaction :ivar tx_ids: The transaction IDs that were sent :ivar transactions: The transactions that were sent :ivar returns: The ABI return values from any ABI method calls :ivar simulate_response: The simulation response if simulation was performed, defaults to None """ group_id: str confirmations: list[algosdk.v2client.algod.AlgodResponseType] tx_ids: list[str] transactions: list[TransactionWrapper] returns: list[ABIReturn] simulate_response: dict[str, Any] | None = None @dataclass class ExecutionInfoTxn: unnamed_resources_accessed: dict | None = None required_fee_delta: int = 0 @dataclass class ExecutionInfo: """Information about transaction execution from simulation.""" group_unnamed_resources_accessed: dict[str, Any] | None = None txns: list[ExecutionInfoTxn] | None = None @dataclass class _TransactionWithPriority: txn: algosdk.transaction.Transaction priority: int fee_delta: int index: int MAX_LEASE_LENGTH = 32 NULL_SIGNER: TransactionSigner = algosdk.atomic_transaction_composer.EmptySigner() def _encode_lease(lease: str | bytes | None) -> bytes | None: if lease is None: return None elif isinstance(lease, bytes): if not (1 <= len(lease) <= MAX_LEASE_LENGTH): raise ValueError( f"Received invalid lease; expected something with length between 1 and {MAX_LEASE_LENGTH}, " f"but received bytes with length {len(lease)}" ) if len(lease) == MAX_LEASE_LENGTH: return lease lease32 = bytearray(32) lease32[: len(lease)] = lease return bytes(lease32) elif isinstance(lease, str): encoded = lease.encode("utf-8") if not (1 <= len(encoded) <= MAX_LEASE_LENGTH): raise ValueError( f"Received invalid lease; expected something with length between 1 and {MAX_LEASE_LENGTH}, " f"but received '{lease}' with length {len(lease)}" ) lease32 = bytearray(MAX_LEASE_LENGTH) lease32[: len(encoded)] = encoded return bytes(lease32) else: raise TypeError(f"Unknown lease type received of {type(lease)}") def _get_group_execution_info( # noqa: C901, PLR0912 atc: AtomicTransactionComposer, algod: AlgodClient, populate_app_call_resources: bool | None = None, cover_app_call_inner_transaction_fees: bool | None = None, additional_atc_context: AdditionalAtcContext | None = None, ) -> ExecutionInfo: # Create simulation request suggested_params = additional_atc_context.suggested_params if additional_atc_context else None max_fees = additional_atc_context.max_fees if additional_atc_context else None simulate_request = SimulateRequest( txn_groups=[], allow_unnamed_resources=True, allow_empty_signatures=True, ) # Clone ATC with null signers empty_signer_atc = atc.clone() # Track app call indexes without max fees app_call_indexes_without_max_fees = [] # Copy transactions with null signers for i, txn in enumerate(empty_signer_atc.txn_list): txn_with_signer = TransactionWithSigner(txn=txn.txn, signer=NULL_SIGNER) if cover_app_call_inner_transaction_fees and isinstance(txn.txn, algosdk.transaction.ApplicationCallTxn): if not suggested_params: raise ValueError("suggested_params required when cover_app_call_inner_transaction_fees enabled") max_fee = max_fees.get(i).micro_algos if max_fees and i in max_fees else None # type: ignore[union-attr] if max_fee is None: app_call_indexes_without_max_fees.append(i) else: txn_with_signer.txn.fee = max_fee if cover_app_call_inner_transaction_fees and app_call_indexes_without_max_fees: raise ValueError( f"Please provide a `max_fee` for each app call transaction when `cover_app_call_inner_transaction_fees` is enabled. " # noqa: E501 f"Required for transactions: {', '.join(str(i) for i in app_call_indexes_without_max_fees)}" ) # Get fee parameters per_byte_txn_fee = suggested_params.fee if suggested_params else 0 min_txn_fee = int(suggested_params.min_fee) if suggested_params else 1000 # type: ignore[unused-ignore] # Simulate transactions result = empty_signer_atc.simulate(algod, simulate_request) group_response = result.simulate_response["txn-groups"][0] if group_response.get("failure-message"): msg = group_response["failure-message"] if cover_app_call_inner_transaction_fees and "fee too small" in msg: raise ValueError( "Fees were too small to resolve execution info via simulate. " "You may need to increase an app call transaction maxFee." ) failed_at = group_response.get("failed-at", [0])[0] raise ValueError( f"Error during resource population simulation in transaction {failed_at}: " f"{group_response['failure-message']}" ) # Build execution info txn_results = [] for i, txn_result_raw in enumerate(group_response["txn-results"]): txn_result = txn_result_raw.get("txn-result") if not txn_result: continue original_txn = atc.build_group()[i].txn required_fee_delta = 0 if cover_app_call_inner_transaction_fees: # Calculate parent transaction fee parent_per_byte_fee = per_byte_txn_fee * (original_txn.estimate_size() + 75) parent_min_fee = max(parent_per_byte_fee, min_txn_fee) parent_fee_delta = parent_min_fee - original_txn.fee if isinstance(original_txn, algosdk.transaction.ApplicationCallTxn): # Calculate inner transaction fees recursively def calculate_inner_fee_delta(inner_txns: list[dict], acc: int = 0) -> int: for inner_txn in reversed(inner_txns): current_fee_delta = ( calculate_inner_fee_delta(inner_txn["inner-txns"], acc) if inner_txn.get("inner-txns") else acc ) + (min_txn_fee - inner_txn["txn"]["txn"].get("fee", 0)) acc = max(0, current_fee_delta) return acc inner_fee_delta = calculate_inner_fee_delta(txn_result.get("inner-txns", [])) required_fee_delta = inner_fee_delta + parent_fee_delta else: required_fee_delta = parent_fee_delta txn_results.append( ExecutionInfoTxn( unnamed_resources_accessed=txn_result_raw.get("unnamed-resources-accessed") if populate_app_call_resources else None, required_fee_delta=required_fee_delta, ) ) return ExecutionInfo( group_unnamed_resources_accessed=group_response.get("unnamed-resources-accessed") if populate_app_call_resources else None, txns=txn_results, ) def _find_available_transaction_index( txns: list[TransactionWithSigner], reference_type: str, reference: str | dict[str, Any] | int ) -> int: """Find index of first transaction that can accommodate the new reference.""" def check_transaction(txn: TransactionWithSigner) -> bool: # Skip if not an application call transaction if txn.txn.type != "appl": return False # Get current counts (using get() with default 0 for Pythonic null handling) accounts = len(getattr(txn.txn, "accounts", []) or []) assets = len(getattr(txn.txn, "foreign_assets", []) or []) apps = len(getattr(txn.txn, "foreign_apps", []) or []) boxes = len(getattr(txn.txn, "boxes", []) or []) # For account references, only check account limit if reference_type == "account": return accounts < MAX_APP_CALL_ACCOUNT_REFERENCES # For asset holdings or local state, need space for both account and other reference if reference_type in ("asset_holding", "app_local"): return ( accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1 and accounts < MAX_APP_CALL_ACCOUNT_REFERENCES ) # For boxes with non-zero app ID, need space for box and app reference if reference_type == "box" and reference and int(getattr(reference, "app", 0)) != 0: return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1 # Default case - just check total references return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES # Return first matching index or -1 if none found return next((i for i, txn in enumerate(txns) if check_transaction(txn)), -1) def _num_extra_program_pages(approval: bytes | None, clear: bytes | None) -> int: """Calculate minimum number of extra_pages required for provided approval and clear programs""" total = len(approval or b"") + len(clear or b"") return max(0, (total - 1) // algosdk.constants.APP_PAGE_MAX_SIZE) def populate_app_call_resources(atc: AtomicTransactionComposer, algod: AlgodClient) -> AtomicTransactionComposer: """Populate application call resources based on simulation results. :param atc: The AtomicTransactionComposer containing transactions :param algod: Algod client for simulation :return: Modified AtomicTransactionComposer with populated resources """ return prepare_group_for_sending(atc, algod, populate_app_call_resources=True) def prepare_group_for_sending( # noqa: C901, PLR0912, PLR0915 atc: AtomicTransactionComposer, algod: AlgodClient, populate_app_call_resources: bool | None = None, cover_app_call_inner_transaction_fees: bool | None = None, additional_atc_context: AdditionalAtcContext | None = None, ) -> AtomicTransactionComposer: """Prepare a transaction group for sending by handling execution info and resources. :param atc: The AtomicTransactionComposer containing transactions :param algod: Algod client for simulation :param populate_app_call_resources: Whether to populate app call resources :param cover_app_call_inner_transaction_fees: Whether to cover inner txn fees :param additional_atc_context: Additional context for the AtomicTransactionComposer :return: Modified AtomicTransactionComposer ready for sending """ # Get execution info via simulation execution_info = _get_group_execution_info( atc, algod, populate_app_call_resources, cover_app_call_inner_transaction_fees, additional_atc_context ) max_fees = additional_atc_context.max_fees if additional_atc_context else None group = atc.build_group() # Handle transaction fees if needed if cover_app_call_inner_transaction_fees: # Sort transactions by fee priority txns_with_priority: list[_TransactionWithPriority] = [] for i, txn_info in enumerate(execution_info.txns or []): if not txn_info: continue txn = group[i].txn max_fee = max_fees.get(i).micro_algos if max_fees and i in max_fees else None # type: ignore[union-attr] immutable_fee = max_fee is not None and max_fee == txn.fee priority_multiplier = ( 1000 if ( txn_info.required_fee_delta > 0 and (immutable_fee or not isinstance(txn, algosdk.transaction.ApplicationCallTxn)) ) else 1 ) txns_with_priority.append( _TransactionWithPriority( txn=txn, index=i, fee_delta=txn_info.required_fee_delta, priority=txn_info.required_fee_delta * priority_multiplier if txn_info.required_fee_delta > 0 else -1, ) ) # Sort by priority descending txns_with_priority.sort(key=lambda x: x.priority, reverse=True) # Calculate surplus fees and additional fees needed surplus_fees = sum( txn_info.required_fee_delta * -1 for txn_info in execution_info.txns or [] if txn_info is not None and txn_info.required_fee_delta < 0 ) additional_fees = {} # Distribute surplus fees to cover deficits for txn_obj in txns_with_priority: if txn_obj.fee_delta > 0: if surplus_fees >= txn_obj.fee_delta: surplus_fees -= txn_obj.fee_delta else: additional_fees[txn_obj.index] = txn_obj.fee_delta - surplus_fees surplus_fees = 0 def populate_group_resource( # noqa: PLR0915, PLR0912, C901 txns: list[TransactionWithSigner], reference: str | dict[str, Any] | int, ref_type: str ) -> None: """Helper function to populate group-level resources.""" def is_appl_below_limit(t: TransactionWithSigner) -> bool: if not isinstance(t.txn, transaction.ApplicationCallTxn): return False accounts = len(getattr(t.txn, "accounts", []) or []) assets = len(getattr(t.txn, "foreign_assets", []) or []) apps = len(getattr(t.txn, "foreign_apps", []) or []) boxes = len(getattr(t.txn, "boxes", []) or []) return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES # Handle asset holding and app local references first if ref_type in ("assetHolding", "appLocal"): ref_dict = cast(dict[str, Any], reference) account = ref_dict["account"] # First try to find transaction with account already available txn_idx = next( ( i for i, t in enumerate(txns) if is_appl_below_limit(t) and isinstance(t.txn, transaction.ApplicationCallTxn) and ( account in (getattr(t.txn, "accounts", []) or []) or account in ( logic.get_application_address(app_id) for app_id in (getattr(t.txn, "foreign_apps", []) or []) ) or any(str(account) in str(v) for v in t.txn.__dict__.values()) ) ), -1, ) if txn_idx >= 0: app_txn = cast(transaction.ApplicationCallTxn, txns[txn_idx].txn) if ref_type == "assetHolding": asset_id = ref_dict["asset"] app_txn.foreign_assets = [*list(getattr(app_txn, "foreign_assets", []) or []), asset_id] else: app_id = ref_dict["app"] app_txn.foreign_apps = [*list(getattr(app_txn, "foreign_apps", []) or []), app_id] return # Try to find transaction that already has the app/asset available txn_idx = next( ( i for i, t in enumerate(txns) if is_appl_below_limit(t) and isinstance(t.txn, transaction.ApplicationCallTxn) and len(getattr(t.txn, "accounts", []) or []) < MAX_APP_CALL_ACCOUNT_REFERENCES and ( ( ref_type == "assetHolding" and ref_dict["asset"] in (getattr(t.txn, "foreign_assets", []) or []) ) or ( ref_type == "appLocal" and ( ref_dict["app"] in (getattr(t.txn, "foreign_apps", []) or []) or t.txn.index == ref_dict["app"] ) ) ) ), -1, ) if txn_idx >= 0: app_txn = cast(transaction.ApplicationCallTxn, txns[txn_idx].txn) accounts = list(getattr(app_txn, "accounts", []) or []) accounts.append(account) app_txn.accounts = accounts return # Handle box references if ref_type == "box": box_ref = (reference["app"], base64.b64decode(reference["name"])) # type: ignore[index] # Try to find transaction that already has the app available txn_idx = next( ( i for i, t in enumerate(txns) if is_appl_below_limit(t) and isinstance(t.txn, transaction.ApplicationCallTxn) and (box_ref[0] in (getattr(t.txn, "foreign_apps", []) or []) or t.txn.index == box_ref[0]) ), -1, ) if txn_idx >= 0: app_txn = cast(transaction.ApplicationCallTxn, txns[txn_idx].txn) boxes = list(getattr(app_txn, "boxes", []) or []) boxes.append(BoxReference.translate_box_reference(box_ref, app_txn.foreign_apps or [], app_txn.index)) # type: ignore[arg-type] app_txn.boxes = boxes return # Find available transaction for the resource txn_idx = _find_available_transaction_index(txns, ref_type, reference) if txn_idx == -1: raise ValueError("No more transactions below reference limit. Add another app call to the group.") app_txn = cast(transaction.ApplicationCallTxn, txns[txn_idx].txn) if ref_type == "account": accounts = list(getattr(app_txn, "accounts", []) or []) accounts.append(cast(str, reference)) app_txn.accounts = accounts elif ref_type == "app": app_id = int(cast(str | int, reference)) foreign_apps = list(getattr(app_txn, "foreign_apps", []) or []) foreign_apps.append(app_id) app_txn.foreign_apps = foreign_apps elif ref_type == "box": boxes = list(getattr(app_txn, "boxes", []) or []) boxes.append(BoxReference.translate_box_reference(box_ref, app_txn.foreign_apps or [], app_txn.index)) # type: ignore[arg-type] app_txn.boxes = boxes if box_ref[0] != 0: foreign_apps = list(getattr(app_txn, "foreign_apps", []) or []) foreign_apps.append(box_ref[0]) app_txn.foreign_apps = foreign_apps elif ref_type == "asset": asset_id = int(cast(str | int, reference)) foreign_assets = list(getattr(app_txn, "foreign_assets", []) or []) foreign_assets.append(asset_id) app_txn.foreign_assets = foreign_assets elif ref_type == "assetHolding": ref_dict = cast(dict[str, Any], reference) foreign_assets = list(getattr(app_txn, "foreign_assets", []) or []) foreign_assets.append(ref_dict["asset"]) app_txn.foreign_assets = foreign_assets accounts = list(getattr(app_txn, "accounts", []) or []) accounts.append(ref_dict["account"]) app_txn.accounts = accounts elif ref_type == "appLocal": ref_dict = cast(dict[str, Any], reference) foreign_apps = list(getattr(app_txn, "foreign_apps", []) or []) foreign_apps.append(ref_dict["app"]) app_txn.foreign_apps = foreign_apps accounts = list(getattr(app_txn, "accounts", []) or []) accounts.append(ref_dict["account"]) app_txn.accounts = accounts # Process transaction-level resources for i, txn_info in enumerate(execution_info.txns or []): if not txn_info: continue # Validate no unexpected resources is_app_txn = isinstance(group[i].txn, algosdk.transaction.ApplicationCallTxn) resources = txn_info.unnamed_resources_accessed if resources and is_app_txn: app_txn = group[i].txn if resources.get("boxes") or resources.get("extra-box-refs"): raise ValueError("Unexpected boxes at transaction level") if resources.get("appLocals"): raise ValueError("Unexpected app local at transaction level") if resources.get("assetHoldings"): raise ValueError("Unexpected asset holding at transaction level") # Update application call fields accounts = list(getattr(app_txn, "accounts", []) or []) foreign_apps = list(getattr(app_txn, "foreign_apps", []) or []) foreign_assets = list(getattr(app_txn, "foreign_assets", []) or []) boxes = list(getattr(app_txn, "boxes", []) or []) # Add new resources accounts.extend(resources.get("accounts", [])) foreign_apps.extend(resources.get("apps", [])) foreign_assets.extend(resources.get("assets", [])) boxes.extend(resources.get("boxes", [])) # Validate limits if len(accounts) > MAX_APP_CALL_ACCOUNT_REFERENCES: raise ValueError( f"Account reference limit of {MAX_APP_CALL_ACCOUNT_REFERENCES} exceeded in transaction {i}" ) total_refs = len(accounts) + len(foreign_assets) + len(foreign_apps) + len(boxes) if total_refs > MAX_APP_CALL_FOREIGN_REFERENCES: raise ValueError( f"Resource reference limit of {MAX_APP_CALL_FOREIGN_REFERENCES} exceeded in transaction {i}" ) # Update transaction app_txn.accounts = accounts # type: ignore[attr-defined] app_txn.foreign_apps = foreign_apps # type: ignore[attr-defined] app_txn.foreign_assets = foreign_assets # type: ignore[attr-defined] app_txn.boxes = boxes # type: ignore[attr-defined] # Update fees if needed if cover_app_call_inner_transaction_fees and i in additional_fees: cur_txn = group[i].txn additional_fee = additional_fees[i] if not isinstance(cur_txn, algosdk.transaction.ApplicationCallTxn): raise ValueError( f"An additional fee of {additional_fee} µALGO is required for non app call transaction {i}" ) transaction_fee = cur_txn.fee + additional_fee max_fee = max_fees.get(i).micro_algos if max_fees and i in max_fees else None # type: ignore[union-attr] if max_fee is None or transaction_fee > max_fee: raise ValueError( f"Calculated transaction fee {transaction_fee} µALGO is greater " f"than max of {max_fee or 'undefined'} " f"for transaction {i}" ) cur_txn.fee = transaction_fee # Process group-level resources group_resources = execution_info.group_unnamed_resources_accessed if group_resources: # Handle cross-reference resources first for app_local in group_resources.get("appLocals", []): populate_group_resource(group, app_local, "appLocal") # Remove processed resources if "accounts" in group_resources: group_resources["accounts"] = [ acc for acc in group_resources["accounts"] if acc != app_local["account"] ] if "apps" in group_resources: group_resources["apps"] = [app for app in group_resources["apps"] if int(app) != int(app_local["app"])] for asset_holding in group_resources.get("assetHoldings", []): populate_group_resource(group, asset_holding, "assetHolding") # Remove processed resources if "accounts" in group_resources: group_resources["accounts"] = [ acc for acc in group_resources["accounts"] if acc != asset_holding["account"] ] if "assets" in group_resources: group_resources["assets"] = [ asset for asset in group_resources["assets"] if int(asset) != int(asset_holding["asset"]) ] # Handle remaining resources for account in group_resources.get("accounts", []): populate_group_resource(group, account, "account") for box in group_resources.get("boxes", []): populate_group_resource(group, box, "box") if "apps" in group_resources: group_resources["apps"] = [app for app in group_resources["apps"] if int(app) != int(box["app"])] for asset in group_resources.get("assets", []): populate_group_resource(group, asset, "asset") for app in group_resources.get("apps", []): populate_group_resource(group, app, "app") # Handle extra box references extra_box_refs = group_resources.get("extra-box-refs", 0) for _ in range(extra_box_refs): populate_group_resource(group, {"app": 0, "name": ""}, "box") # Create new ATC with updated transactions new_atc = AtomicTransactionComposer() for txn_with_signer in group: txn_with_signer.txn.group = None new_atc.add_transaction(txn_with_signer) new_atc.method_dict = deepcopy(atc.method_dict) return new_atc def send_atomic_transaction_composer( # noqa: C901, PLR0912 atc: AtomicTransactionComposer, algod: AlgodClient, *, max_rounds_to_wait: int | None = 5, skip_waiting: bool = False, suppress_log: bool | None = None, populate_app_call_resources: bool | None = None, cover_app_call_inner_transaction_fees: bool | None = None, additional_atc_context: AdditionalAtcContext | None = None, ) -> SendAtomicTransactionComposerResults: """Send an AtomicTransactionComposer transaction group. Executes a group of transactions atomically using the AtomicTransactionComposer. :param atc: The AtomicTransactionComposer instance containing the transaction group to send :param algod: The Algod client to use for sending the transactions :param max_rounds_to_wait: Maximum number of rounds to wait for confirmation, defaults to 5 :param skip_waiting: If True, don't wait for transaction confirmation, defaults to False :param suppress_log: If True, suppress logging, defaults to None :param populate_app_call_resources: If True, populate app call resources, defaults to None :param cover_app_call_inner_transaction_fees: If True, cover app call inner transaction fees, defaults to None :param additional_atc_context: Additional context for the AtomicTransactionComposer :return: Results from sending the transaction group :raises Exception: If there is an error sending the transactions :raises error: If there is an error from the Algorand node """ from algokit_utils._debugging import simulate_and_persist_response, simulate_response try: # Build transactions transactions_with_signer = atc.build_group() populate_app_call_resources = ( populate_app_call_resources if populate_app_call_resources is not None else config.populate_app_call_resource ) if (populate_app_call_resources or cover_app_call_inner_transaction_fees) and any( isinstance(t.txn, algosdk.transaction.ApplicationCallTxn) for t in transactions_with_signer ): atc = prepare_group_for_sending( atc, algod, populate_app_call_resources, cover_app_call_inner_transaction_fees, additional_atc_context, ) transactions_to_send = [t.txn for t in transactions_with_signer] # Get group ID if multiple transactions group_id = None if len(transactions_to_send) > 1: group_id = ( base64.b64encode(transactions_to_send[0].group).decode("utf-8") if transactions_to_send[0].group else "" ) if not suppress_log: logger.info( f"Sending group of {len(transactions_to_send)} transactions ({group_id})", suppress_log=suppress_log or False, ) logger.debug( f"Transaction IDs ({group_id}): {[t.get_txid() for t in transactions_to_send]}", suppress_log=suppress_log or False, ) # Simulate if debug enabled if config.debug and config.trace_all and config.project_root: simulate_and_persist_response( atc, config.project_root, algod, config.trace_buffer_size_mb, ) # Execute transactions result = atc.execute(algod, wait_rounds=max_rounds_to_wait or 5) # Log results if not suppress_log: if len(transactions_to_send) > 1: logger.info( f"Group transaction ({group_id}) sent with {len(transactions_to_send)} transactions", suppress_log=suppress_log or False, ) else: logger.info( f"Sent transaction ID {transactions_to_send[0].get_txid()}", suppress_log=suppress_log or False, ) # Get confirmations if not skipping confirmations = None if not skip_waiting: confirmations = [algod.pending_transaction_info(t.get_txid()) for t in transactions_to_send] # Return results return SendAtomicTransactionComposerResults( group_id=group_id or "", confirmations=confirmations or [], tx_ids=[t.get_txid() for t in transactions_to_send], transactions=[TransactionWrapper(t) for t in transactions_to_send], returns=[ABIReturn(r) for r in result.abi_results], ) except Exception as e: # Handle error with debug info if enabled if config.debug: logger.error( "Received error executing Atomic Transaction Composer and debug flag enabled; " "attempting simulation to get more information", suppress_log=suppress_log or False, ) simulate = None if config.project_root and not config.trace_all: # Only simulate if trace_all is disabled and project_root is set simulate = simulate_and_persist_response(atc, config.project_root, algod, config.trace_buffer_size_mb) else: simulate = simulate_response(atc, algod) traces = [] if simulate and simulate.failed_at: for txn_group in simulate.simulate_response["txn-groups"]: app_budget = txn_group.get("app-budget-added") app_budget_consumed = txn_group.get("app-budget-consumed") failure_message = txn_group.get("failure-message") txn_result = txn_group.get("txn-results", [{}])[0] exec_trace = txn_result.get("exec-trace", {}) traces.append( { "trace": exec_trace, "app_budget": app_budget, "app_budget_consumed": app_budget_consumed, "failure_message": failure_message, } ) error = Exception(f"Transaction failed: {e}") error.traces = traces # type: ignore[attr-defined] raise error from e logger.error( "Received error executing Atomic Transaction Composer, for more information enable the debug flag", suppress_log=suppress_log or False, ) raise e class TransactionComposer: """A class for composing and managing Algorand transactions. Provides a high-level interface for building and executing transaction groups using the Algosdk library. Supports various transaction types including payments, asset operations, application calls, and key registrations. :param algod: An instance of AlgodClient used to get suggested params and send transactions :param get_signer: A function that takes an address and returns a TransactionSigner for that address :param get_suggested_params: Optional function to get suggested transaction parameters, defaults to using algod.suggested_params() :param default_validity_window: Optional default validity window for transactions in rounds, defaults to 10 :param app_manager: Optional AppManager instance for compiling TEAL programs, defaults to None """ def __init__( self, algod: AlgodClient, get_signer: Callable[[str], TransactionSigner], get_suggested_params: Callable[[], algosdk.transaction.SuggestedParams] | None = None, default_validity_window: int | None = None, app_manager: AppManager | None = None, ): # Map of transaction index in the atc to a max logical fee. # This is set using the value of either maxFee or staticFee. self._txn_max_fees: dict[int, AlgoAmount] = {} self._txns: list[TransactionWithSigner | TxnParams | AtomicTransactionComposer] = [] self._atc: AtomicTransactionComposer = AtomicTransactionComposer() self._algod: AlgodClient = algod self._default_get_send_params = lambda: self._algod.suggested_params() self._get_suggested_params = get_suggested_params or self._default_get_send_params self._get_signer: Callable[[str], TransactionSigner] = get_signer self._default_validity_window: int = default_validity_window or 10 self._default_validity_window_is_explicit: bool = default_validity_window is not None self._app_manager = app_manager or AppManager(algod) def add_transaction( self, transaction: algosdk.transaction.Transaction, signer: TransactionSigner | None = None ) -> TransactionComposer: """Add a raw transaction to the composer. :param transaction: The transaction to add :param signer: Optional transaction signer, defaults to getting signer from transaction sender :return: The transaction composer instance for chaining """ self._txns.append(TransactionWithSigner(txn=transaction, signer=signer or self._get_signer(transaction.sender))) return self def add_payment(self, params: PaymentParams) -> TransactionComposer: """Add a payment transaction. :param params: The payment transaction parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_create(self, params: AssetCreateParams) -> TransactionComposer: """Add an asset creation transaction. :param params: The asset creation parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_config(self, params: AssetConfigParams) -> TransactionComposer: """Add an asset configuration transaction. :param params: The asset configuration parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_freeze(self, params: AssetFreezeParams) -> TransactionComposer: """Add an asset freeze transaction. :param params: The asset freeze parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_destroy(self, params: AssetDestroyParams) -> TransactionComposer: """Add an asset destruction transaction. :param params: The asset destruction parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_transfer(self, params: AssetTransferParams) -> TransactionComposer: """Add an asset transfer transaction. :param params: The asset transfer parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_opt_in(self, params: AssetOptInParams) -> TransactionComposer: """Add an asset opt-in transaction. :param params: The asset opt-in parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_asset_opt_out(self, params: AssetOptOutParams) -> TransactionComposer: """Add an asset opt-out transaction. :param params: The asset opt-out parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_create(self, params: AppCreateParams) -> TransactionComposer: """Add an application creation transaction. :param params: The application creation parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_update(self, params: AppUpdateParams) -> TransactionComposer: """Add an application update transaction. :param params: The application update parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_delete(self, params: AppDeleteParams) -> TransactionComposer: """Add an application deletion transaction. :param params: The application deletion parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_call(self, params: AppCallParams) -> TransactionComposer: """Add an application call transaction. :param params: The application call parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_create_method_call(self, params: AppCreateMethodCallParams) -> TransactionComposer: """Add an application creation method call transaction. :param params: The application creation method call parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_update_method_call(self, params: AppUpdateMethodCallParams) -> TransactionComposer: """Add an application update method call transaction. :param params: The application update method call parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_delete_method_call(self, params: AppDeleteMethodCallParams) -> TransactionComposer: """Add an application deletion method call transaction. :param params: The application deletion method call parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_app_call_method_call(self, params: AppCallMethodCallParams) -> TransactionComposer: """Add an application call method call transaction. :param params: The application call method call parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_online_key_registration(self, params: OnlineKeyRegistrationParams) -> TransactionComposer: """Add an online key registration transaction. :param params: The online key registration parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_offline_key_registration(self, params: OfflineKeyRegistrationParams) -> TransactionComposer: """Add an offline key registration transaction. :param params: The offline key registration parameters :return: The transaction composer instance for chaining """ self._txns.append(params) return self def add_atc(self, atc: AtomicTransactionComposer) -> TransactionComposer: """Add an existing AtomicTransactionComposer's transactions. :param atc: The AtomicTransactionComposer to add :return: The transaction composer instance for chaining """ self._txns.append(atc) return self def count(self) -> int: """Get the total number of transactions. :return: The number of transactions """ return len(self.build_transactions().transactions) def build(self) -> TransactionComposerBuildResult: """Build the transaction group. :return: The built transaction group result """ if self._atc.get_status() == algosdk.atomic_transaction_composer.AtomicTransactionComposerStatus.BUILDING: suggested_params = self._get_suggested_params() txn_with_signers: list[TransactionWithSignerAndContext] = [] for txn in self._txns: txn_with_signers.extend(self._build_txn(txn, suggested_params)) for ts in txn_with_signers: self._atc.add_transaction(ts) if ts.context.abi_method: self._atc.method_dict[len(self._atc.txn_list) - 1] = ts.context.abi_method if ts.context.max_fee: self._txn_max_fees[len(self._atc.txn_list) - 1] = ts.context.max_fee return TransactionComposerBuildResult( atc=self._atc, transactions=self._atc.build_group(), method_calls=self._atc.method_dict, ) def rebuild(self) -> TransactionComposerBuildResult: """Rebuild the transaction group from scratch. :return: The rebuilt transaction group result """ self._atc = AtomicTransactionComposer() return self.build() def build_transactions(self) -> BuiltTransactions: """Build and return the transactions without executing them. :return: The built transactions result """ suggested_params = self._get_suggested_params() transactions: list[algosdk.transaction.Transaction] = [] method_calls: dict[int, Method] = {} signers: dict[int, TransactionSigner] = {} idx = 0 for txn in self._txns: txn_with_signers: list[TransactionWithSigner] = [] if isinstance(txn, MethodCallParams): txn_with_signers.extend(self._build_method_call(txn, suggested_params)) else: txn_with_signers.extend(self._build_txn(txn, suggested_params)) for ts in txn_with_signers: transactions.append(ts.txn) if ts.signer and ts.signer != NULL_SIGNER: signers[idx] = ts.signer if isinstance(ts, TransactionWithSignerAndContext) and ts.context.abi_method: method_calls[idx] = ts.context.abi_method idx += 1 return BuiltTransactions(transactions=transactions, method_calls=method_calls, signers=signers) @deprecated("Use send() instead") def execute( self, *, max_rounds_to_wait: int | None = None, ) -> SendAtomicTransactionComposerResults: return self.send(SendParams(max_rounds_to_wait=max_rounds_to_wait)) def send( self, params: SendParams | None = None, ) -> SendAtomicTransactionComposerResults: """Send the transaction group to the network. :param params: Parameters for the send operation :return: The transaction send results :raises Exception: If the transaction fails """ group = self.build().transactions if not params: has_app_call = any(isinstance(txn.txn, ApplicationCallTxn) for txn in group) params = SendParams() if has_app_call else SendParams() cover_app_call_inner_transaction_fees = params.get("cover_app_call_inner_transaction_fees") populate_app_call_resources = params.get("populate_app_call_resources") wait_rounds = params.get("max_rounds_to_wait") sp = self._get_suggested_params() if not wait_rounds or cover_app_call_inner_transaction_fees else None if wait_rounds is None: last_round = max(txn.txn.last_valid_round for txn in group) assert sp is not None first_round = sp.first wait_rounds = last_round - first_round + 1 try: return send_atomic_transaction_composer( self._atc, self._algod, max_rounds_to_wait=wait_rounds, suppress_log=params.get("suppress_log"), populate_app_call_resources=populate_app_call_resources, cover_app_call_inner_transaction_fees=cover_app_call_inner_transaction_fees, additional_atc_context=AdditionalAtcContext( suggested_params=sp, max_fees=self._txn_max_fees, ), ) except algosdk.error.AlgodHTTPError as e: raise Exception(f"Transaction failed: {e}") from e def _handle_simulate_error(self, simulate_response: SimulateAtomicTransactionResponse) -> None: # const failedGroup = simulateResponse?.txnGroups[0] failed_group = simulate_response.simulate_response.get("txn-groups", [{}])[0] failure_message = failed_group.get("failure-message") failed_at = [str(x) for x in failed_group.get("failed-at", [])] if failure_message: error_message = ( f"Transaction failed at transaction(s) {', '.join(failed_at) if failed_at else 'N/A'} in the group. " f"{failure_message}" ) raise Exception(error_message) def simulate( self, allow_more_logs: bool | None = None, allow_empty_signatures: bool | None = None, allow_unnamed_resources: bool | None = None, extra_opcode_budget: int | None = None, exec_trace_config: SimulateTraceConfig | None = None, simulation_round: int | None = None, skip_signatures: bool | None = None, ) -> SendAtomicTransactionComposerResults: """Simulate transaction group execution with configurable validation rules. :param allow_more_logs: Whether to allow more logs than the standard limit :param allow_empty_signatures: Whether to allow transactions with empty signatures :param allow_unnamed_resources: Whether to allow unnamed resources :param extra_opcode_budget: Additional opcode budget to allocate :param exec_trace_config: Configuration for execution tracing :param simulation_round: Round number to simulate at :param skip_signatures: Whether to skip signature validation :return: The simulation results """ from algokit_utils._debugging import simulate_and_persist_response, simulate_response atc = AtomicTransactionComposer() if skip_signatures else self._atc if skip_signatures: allow_empty_signatures = True transactions = self.build_transactions() for txn in transactions.transactions: atc.add_transaction(TransactionWithSigner(txn=txn, signer=NULL_SIGNER)) atc.method_dict = transactions.method_calls else: self.build() if config.debug and config.project_root and config.trace_all: response = simulate_and_persist_response( atc, config.project_root, self._algod, config.trace_buffer_size_mb, allow_more_logs, allow_empty_signatures, allow_unnamed_resources, extra_opcode_budget, exec_trace_config, simulation_round, ) self._handle_simulate_error(response) return SendAtomicTransactionComposerResults( confirmations=response.simulate_response.get("txn-groups", [{"txn-results": [{"txn-result": {}}]}])[0][ "txn-results" ], transactions=[TransactionWrapper(txn.txn) for txn in atc.txn_list], tx_ids=response.tx_ids, group_id=atc.txn_list[-1].txn.group or "", simulate_response=response.simulate_response, returns=[ABIReturn(r) for r in response.abi_results], ) response = simulate_response( atc, self._algod, allow_more_logs, allow_empty_signatures, allow_unnamed_resources, extra_opcode_budget, exec_trace_config, simulation_round, ) self._handle_simulate_error(response) confirmation_results = response.simulate_response.get("txn-groups", [{"txn-results": [{"txn-result": {}}]}])[0][ "txn-results" ] return SendAtomicTransactionComposerResults( confirmations=[txn["txn-result"] for txn in confirmation_results], transactions=[TransactionWrapper(txn.txn) for txn in atc.txn_list], tx_ids=response.tx_ids, group_id=atc.txn_list[-1].txn.group or "", simulate_response=response.simulate_response, returns=[ABIReturn(r) for r in response.abi_results], ) @staticmethod def arc2_note(note: Arc2TransactionNote) -> bytes: """Create an encoded transaction note that follows the ARC-2 spec. https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md :param note: The ARC-2 note to encode :return: The encoded note bytes :raises ValueError: If the dapp_name is invalid """ pattern = r"^[a-zA-Z0-9][a-zA-Z0-9_/@.-]{4,31}$" if not re.match(pattern, note["dapp_name"]): raise ValueError( "dapp_name must be 5-32 chars, start with alphanumeric, " "and contain only alphanumeric, _, /, @, ., or -" ) data = note["data"] if note["format"] == "j" and isinstance(data, (dict | list)): # Ensure JSON data uses double quotes data = json.dumps(data) arc2_payload = f"{note['dapp_name']}:{note['format']}{data}" return arc2_payload.encode("utf-8") def _build_atc(self, atc: AtomicTransactionComposer) -> list[TransactionWithSignerAndContext]: group = atc.build_group() txn_with_signers = [] for idx, ts in enumerate(group): ts.txn.group = None if atc.method_dict.get(idx): txn_with_signers.append( TransactionWithSignerAndContext( txn=ts.txn, signer=ts.signer, context=TransactionContext(abi_method=atc.method_dict.get(idx)), ) ) else: txn_with_signers.append( TransactionWithSignerAndContext( txn=ts.txn, signer=ts.signer, context=TransactionContext(abi_method=None), ) ) return txn_with_signers def _common_txn_build_step( # noqa: C901 self, build_txn: Callable[[dict], algosdk.transaction.Transaction], params: _CommonTxnParams, txn_params: dict, ) -> TransactionWithContext: # Clone suggested params txn_params["sp"] = ( algosdk.transaction.SuggestedParams(**txn_params["sp"].__dict__) if "sp" in txn_params else None ) if params.lease: txn_params["lease"] = _encode_lease(params.lease) if params.rekey_to: txn_params["rekey_to"] = params.rekey_to if params.note: txn_params["note"] = params.note if txn_params["sp"]: if params.first_valid_round: txn_params["sp"].first = params.first_valid_round if params.last_valid_round: txn_params["sp"].last = params.last_valid_round else: # If the validity window isn't set in this transaction or by default and we are pointing at # LocalNet set a bigger window to avoid dead transactions from algokit_utils.clients import ClientManager is_localnet = ClientManager.genesis_id_is_localnet(txn_params["sp"].gen) window = params.validity_window or ( 1000 if is_localnet and not self._default_validity_window_is_explicit else self._default_validity_window ) txn_params["sp"].last = txn_params["sp"].first + window if params.static_fee is not None and txn_params["sp"]: txn_params["sp"].fee = params.static_fee.micro_algos txn_params["sp"].flat_fee = True if isinstance(txn_params.get("method"), Arc56Method): txn_params["method"] = txn_params["method"].to_abi_method() txn = build_txn(txn_params) if params.extra_fee: txn.fee += params.extra_fee.micro_algos if params.max_fee and txn.fee > params.max_fee.micro_algos: raise ValueError(f"Transaction fee {txn.fee} is greater than max_fee {params.max_fee}") use_max_fee = params.max_fee and params.max_fee.micro_algo > ( params.static_fee.micro_algo if params.static_fee else 0 ) logical_max_fee = params.max_fee if use_max_fee else params.static_fee return TransactionWithContext( txn=txn, context=TransactionContext(max_fee=logical_max_fee), ) def _build_method_call( # noqa: C901, PLR0912, PLR0915 self, params: MethodCallParams, suggested_params: algosdk.transaction.SuggestedParams ) -> list[TransactionWithSignerAndContext]: method_args: list[ABIValue | TransactionWithSigner] = [] txns_for_group: list[TransactionWithSignerAndContext] = [] if params.args: for arg in reversed(params.args): if arg is None and len(txns_for_group) > 0: # Pull last transaction from group as placeholder placeholder_transaction = txns_for_group.pop() method_args.append(placeholder_transaction) continue if self._is_abi_value(arg): method_args.append(arg) continue if isinstance(arg, TransactionWithSigner): method_args.append(arg) continue if isinstance(arg, algosdk.transaction.Transaction): # Wrap in TransactionWithSigner signer = ( params.signer.signer if isinstance(params.signer, TransactionSignerAccountProtocol) else params.signer ) method_args.append( TransactionWithSignerAndContext( txn=arg, signer=signer if signer is not None else self._get_signer(params.sender), context=TransactionContext(abi_method=None), ) ) continue match arg: case ( AppCreateMethodCallParams() | AppCallMethodCallParams() | AppUpdateMethodCallParams() | AppDeleteMethodCallParams() ): temp_txn_with_signers = self._build_method_call(arg, suggested_params) # Add all transactions except the last one in reverse order txns_for_group.extend(temp_txn_with_signers[:-1]) # Add the last transaction to method_args method_args.append(temp_txn_with_signers[-1]) continue case AppCallParams(): txn = self._build_app_call(arg, suggested_params) case PaymentParams(): txn = self._build_payment(arg, suggested_params) case AssetOptInParams(): txn = self._build_asset_transfer( AssetTransferParams(**arg.__dict__, receiver=arg.sender, amount=0), suggested_params ) case AssetCreateParams(): txn = self._build_asset_create(arg, suggested_params) case AssetConfigParams(): txn = self._build_asset_config(arg, suggested_params) case AssetDestroyParams(): txn = self._build_asset_destroy(arg, suggested_params) case AssetFreezeParams(): txn = self._build_asset_freeze(arg, suggested_params) case AssetTransferParams(): txn = self._build_asset_transfer(arg, suggested_params) case OnlineKeyRegistrationParams() | OfflineKeyRegistrationParams(): txn = self._build_key_reg(arg, suggested_params) case _: raise ValueError(f"Unsupported method arg transaction type: {arg!s}") signer = ( params.signer.signer if isinstance(params.signer, TransactionSignerAccountProtocol) else params.signer ) method_args.append( TransactionWithSignerAndContext( txn=txn.txn, signer=signer or self._get_signer(params.sender), context=TransactionContext(abi_method=params.method), ) ) continue method_atc = AtomicTransactionComposer() max_fees: dict[int, AlgoAmount] = {} # Process in reverse order for arg in reversed(txns_for_group): atc_index = method_atc.get_tx_count() - 1 if isinstance(arg, TransactionWithSignerAndContext) and arg.context: if arg.context.abi_method: method_atc.method_dict[atc_index] = arg.context.abi_method if arg.context.max_fee is not None: max_fees[atc_index] = arg.context.max_fee # Process method args that are transactions with ABI method info for i, arg in enumerate(reversed([a for a in method_args if isinstance(a, TransactionWithSignerAndContext)])): atc_index = method_atc.get_tx_count() + i if arg.context: if arg.context.abi_method: method_atc.method_dict[atc_index] = arg.context.abi_method if arg.context.max_fee is not None: max_fees[atc_index] = arg.context.max_fee app_id = params.app_id or 0 approval_program = getattr(params, "approval_program", None) clear_program = getattr(params, "clear_state_program", None) extra_pages = None if app_id == 0: extra_pages = getattr(params, "extra_program_pages", None) if extra_pages is None and approval_program is not None: extra_pages = _num_extra_program_pages(approval_program, clear_program) txn_params = { "app_id": app_id, "method": params.method, "sender": params.sender, "sp": suggested_params, "signer": params.signer if params.signer is not None else self._get_signer(params.sender) or algosdk.atomic_transaction_composer.EmptySigner(), "method_args": list(reversed(method_args)), "on_complete": params.on_complete or algosdk.transaction.OnComplete.NoOpOC, "boxes": [AppManager.get_box_reference(ref) for ref in params.box_references] if params.box_references else None, "foreign_apps": params.app_references, "foreign_assets": params.asset_references, "accounts": params.account_references, "global_schema": algosdk.transaction.StateSchema( num_uints=params.schema.get("global_ints", 0), num_byte_slices=params.schema.get("global_byte_slices", 0), ) if params.schema else None, "local_schema": algosdk.transaction.StateSchema( num_uints=params.schema.get("local_ints", 0), num_byte_slices=params.schema.get("local_byte_slices", 0), ) if params.schema else None, "approval_program": approval_program, "clear_program": clear_program, "extra_pages": extra_pages, } def _add_method_call_and_return_txn(x: dict) -> algosdk.transaction.Transaction: method_atc.add_method_call(**x) return method_atc.build_group()[-1].txn result = self._common_txn_build_step(lambda x: _add_method_call_and_return_txn(x), params, txn_params) build_atc_resp = self._build_atc(method_atc) response = [] for i, v in enumerate(build_atc_resp): max_fee = result.context.max_fee if i == method_atc.get_tx_count() - 1 else max_fees.get(i) context = TransactionContext(abi_method=v.context.abi_method, max_fee=max_fee) response.append(TransactionWithSignerAndContext(txn=v.txn, signer=v.signer, context=context)) return response def _build_payment( self, params: PaymentParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "receiver": params.receiver, "amt": params.amount.micro_algos, "close_remainder_to": params.close_remainder_to, } return self._common_txn_build_step(lambda x: algosdk.transaction.PaymentTxn(**x), params, txn_params) def _build_asset_create( self, params: AssetCreateParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "total": params.total, "default_frozen": params.default_frozen or False, "unit_name": params.unit_name or "", "asset_name": params.asset_name or "", "manager": params.manager, "reserve": params.reserve, "freeze": params.freeze, "clawback": params.clawback, "url": params.url or "", "metadata_hash": params.metadata_hash, "decimals": params.decimals or 0, } return self._common_txn_build_step(lambda x: algosdk.transaction.AssetCreateTxn(**x), params, txn_params) def _build_app_call( self, params: AppCallParams | AppUpdateParams | AppCreateParams | AppDeleteParams, suggested_params: algosdk.transaction.SuggestedParams, ) -> TransactionWithContext: app_id = getattr(params, "app_id", 0) approval_program = None clear_program = None if isinstance(params, AppUpdateParams | AppCreateParams): if isinstance(params.approval_program, str): approval_program = self._app_manager.compile_teal(params.approval_program).compiled_base64_to_bytes elif isinstance(params.approval_program, bytes): approval_program = params.approval_program if isinstance(params.clear_state_program, str): clear_program = self._app_manager.compile_teal(params.clear_state_program).compiled_base64_to_bytes elif isinstance(params.clear_state_program, bytes): clear_program = params.clear_state_program sdk_params = { "sender": params.sender, "sp": suggested_params, "app_args": params.args, "on_complete": params.on_complete or algosdk.transaction.OnComplete.NoOpOC, "accounts": params.account_references, "foreign_apps": params.app_references, "foreign_assets": params.asset_references, "boxes": params.box_references, "approval_program": approval_program, "clear_program": clear_program, } txn_params = {**sdk_params, "index": app_id} if not app_id and isinstance(params, AppCreateParams): if not sdk_params["approval_program"] or not sdk_params["clear_program"]: raise ValueError("approval_program and clear_program are required for application creation") if not params.schema: raise ValueError("schema is required for application creation") txn_params = { **txn_params, "global_schema": algosdk.transaction.StateSchema( num_uints=params.schema.get("global_ints", 0), num_byte_slices=params.schema.get("global_byte_slices", 0), ), "local_schema": algosdk.transaction.StateSchema( num_uints=params.schema.get("local_ints", 0), num_byte_slices=params.schema.get("local_byte_slices", 0), ), "extra_pages": params.extra_program_pages or _num_extra_program_pages(approval_program, clear_program), } return self._common_txn_build_step(lambda x: algosdk.transaction.ApplicationCallTxn(**x), params, txn_params) def _build_asset_config( self, params: AssetConfigParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "index": params.asset_id, "manager": params.manager, "reserve": params.reserve, "freeze": params.freeze, "clawback": params.clawback, "strict_empty_address_check": False, } return self._common_txn_build_step(lambda x: algosdk.transaction.AssetConfigTxn(**x), params, txn_params) def _build_asset_destroy( self, params: AssetDestroyParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "index": params.asset_id, } return self._common_txn_build_step(lambda x: algosdk.transaction.AssetDestroyTxn(**x), params, txn_params) def _build_asset_freeze( self, params: AssetFreezeParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "index": params.asset_id, "target": params.account, "new_freeze_state": params.frozen, } return self._common_txn_build_step(lambda x: algosdk.transaction.AssetFreezeTxn(**x), params, txn_params) def _build_asset_transfer( self, params: AssetTransferParams, suggested_params: algosdk.transaction.SuggestedParams ) -> TransactionWithContext: txn_params = { "sender": params.sender, "sp": suggested_params, "receiver": params.receiver, "amt": params.amount, "index": params.asset_id, "close_assets_to": params.close_asset_to, "revocation_target": params.clawback_target, } return self._common_txn_build_step(lambda x: algosdk.transaction.AssetTransferTxn(**x), params, txn_params) def _build_key_reg( self, params: OnlineKeyRegistrationParams | OfflineKeyRegistrationParams, suggested_params: algosdk.transaction.SuggestedParams, ) -> TransactionWithContext: if isinstance(params, OnlineKeyRegistrationParams): txn_params = { "sender": params.sender, "sp": suggested_params, "votekey": params.vote_key, "selkey": params.selection_key, "votefst": params.vote_first, "votelst": params.vote_last, "votekd": params.vote_key_dilution, "rekey_to": params.rekey_to, "nonpart": False, "sprfkey": params.state_proof_key, } return self._common_txn_build_step(lambda x: algosdk.transaction.KeyregTxn(**x), params, txn_params) return self._common_txn_build_step( lambda x: algosdk.transaction.KeyregTxn(**x), params, { "sender": params.sender, "sp": suggested_params, "nonpart": params.prevent_account_from_ever_participating_again, "votekey": None, "selkey": None, "votefst": None, "votelst": None, "votekd": None, }, ) def _is_abi_value(self, x: bool | float | str | bytes | list | TxnParams) -> bool: if isinstance(x, list | tuple): return len(x) == 0 or all(self._is_abi_value(item) for item in x) return isinstance(x, bool | int | float | str | bytes) def _build_txn( # noqa: C901, PLR0912, PLR0911 self, txn: TransactionWithSigner | TxnParams | AtomicTransactionComposer, suggested_params: algosdk.transaction.SuggestedParams, ) -> list[TransactionWithSignerAndContext]: match txn: case TransactionWithSigner(): return [ TransactionWithSignerAndContext(txn=txn.txn, signer=txn.signer, context=TransactionContext.empty()) ] case AtomicTransactionComposer(): return self._build_atc(txn) case algosdk.transaction.Transaction(): signer = self._get_signer(txn.sender) return [TransactionWithSignerAndContext(txn=txn, signer=signer, context=TransactionContext.empty())] case ( AppCreateMethodCallParams() | AppCallMethodCallParams() | AppUpdateMethodCallParams() | AppDeleteMethodCallParams() ): return self._build_method_call(txn, suggested_params) signer = txn.signer.signer if isinstance(txn.signer, TransactionSignerAccountProtocol) else txn.signer # type: ignore[assignment] signer = signer or self._get_signer(txn.sender) match txn: case PaymentParams(): payment = self._build_payment(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(payment, signer)] case AssetCreateParams(): asset_create = self._build_asset_create(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(asset_create, signer)] case AppCallParams() | AppUpdateParams() | AppCreateParams() | AppDeleteParams(): app_call = self._build_app_call(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(app_call, signer)] case AssetConfigParams(): asset_config = self._build_asset_config(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(asset_config, signer)] case AssetDestroyParams(): asset_destroy = self._build_asset_destroy(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(asset_destroy, signer)] case AssetFreezeParams(): asset_freeze = self._build_asset_freeze(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(asset_freeze, signer)] case AssetTransferParams(): asset_transfer = self._build_asset_transfer(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(asset_transfer, signer)] case AssetOptInParams(): asset_transfer = self._build_asset_transfer( AssetTransferParams(**txn.__dict__, receiver=txn.sender, amount=0), suggested_params ) return [TransactionWithSignerAndContext.from_txn_with_context(asset_transfer, signer)] case AssetOptOutParams(): txn_dict = txn.__dict__ creator = txn_dict.pop("creator") asset_transfer = self._build_asset_transfer( AssetTransferParams(**txn_dict, receiver=txn.sender, amount=0, close_asset_to=creator), suggested_params, ) return [TransactionWithSignerAndContext.from_txn_with_context(asset_transfer, signer)] case OnlineKeyRegistrationParams() | OfflineKeyRegistrationParams(): key_reg = self._build_key_reg(txn, suggested_params) return [TransactionWithSignerAndContext.from_txn_with_context(key_reg, signer)] case _: raise ValueError(f"Unsupported txn: {txn}")
algorandfoundation/algokit-utils-py
src/algokit_utils/transactions/transaction_composer.py
Python
MIT
94,794
from collections.abc import Callable from typing import TypeVar from algosdk.transaction import Transaction from algokit_utils.transactions.transaction_composer import ( AppCallMethodCallParams, AppCallParams, AppCreateMethodCallParams, AppCreateParams, AppDeleteMethodCallParams, AppDeleteParams, AppUpdateMethodCallParams, AppUpdateParams, AssetConfigParams, AssetCreateParams, AssetDestroyParams, AssetFreezeParams, AssetOptInParams, AssetOptOutParams, AssetTransferParams, BuiltTransactions, OfflineKeyRegistrationParams, OnlineKeyRegistrationParams, PaymentParams, TransactionComposer, ) __all__ = [ "AlgorandClientTransactionCreator", ] TxnParam = TypeVar("TxnParam") TxnResult = TypeVar("TxnResult") class AlgorandClientTransactionCreator: """A creator for Algorand transactions. Provides methods to create various types of Algorand transactions including payments, asset operations, application calls and key registrations. :param new_group: A lambda that starts a new TransactionComposer transaction group """ def __init__(self, new_group: Callable[[], TransactionComposer]) -> None: self._new_group = new_group def _transaction( self, c: Callable[[TransactionComposer], Callable[[TxnParam], TransactionComposer]] ) -> Callable[[TxnParam], Transaction]: def create_transaction(params: TxnParam) -> Transaction: composer = self._new_group() result = c(composer)(params).build_transactions() return result.transactions[-1] return create_transaction def _transactions( self, c: Callable[[TransactionComposer], Callable[[TxnParam], TransactionComposer]] ) -> Callable[[TxnParam], BuiltTransactions]: def create_transactions(params: TxnParam) -> BuiltTransactions: composer = self._new_group() return c(composer)(params).build_transactions() return create_transactions @property def payment(self) -> Callable[[PaymentParams], Transaction]: """Create a payment transaction to transfer Algo between accounts.""" return self._transaction(lambda c: c.add_payment) @property def asset_create(self) -> Callable[[AssetCreateParams], Transaction]: """Create a create Algorand Standard Asset transaction.""" return self._transaction(lambda c: c.add_asset_create) @property def asset_config(self) -> Callable[[AssetConfigParams], Transaction]: """Create an asset config transaction to reconfigure an existing Algorand Standard Asset.""" return self._transaction(lambda c: c.add_asset_config) @property def asset_freeze(self) -> Callable[[AssetFreezeParams], Transaction]: """Create an Algorand Standard Asset freeze transaction.""" return self._transaction(lambda c: c.add_asset_freeze) @property def asset_destroy(self) -> Callable[[AssetDestroyParams], Transaction]: """Create an Algorand Standard Asset destroy transaction.""" return self._transaction(lambda c: c.add_asset_destroy) @property def asset_transfer(self) -> Callable[[AssetTransferParams], Transaction]: """Create an Algorand Standard Asset transfer transaction.""" return self._transaction(lambda c: c.add_asset_transfer) @property def asset_opt_in(self) -> Callable[[AssetOptInParams], Transaction]: """Create an Algorand Standard Asset opt-in transaction.""" return self._transaction(lambda c: c.add_asset_opt_in) @property def asset_opt_out(self) -> Callable[[AssetOptOutParams], Transaction]: """Create an asset opt-out transaction.""" return self._transaction(lambda c: c.add_asset_opt_out) @property def app_create(self) -> Callable[[AppCreateParams], Transaction]: """Create an application create transaction.""" return self._transaction(lambda c: c.add_app_create) @property def app_update(self) -> Callable[[AppUpdateParams], Transaction]: """Create an application update transaction.""" return self._transaction(lambda c: c.add_app_update) @property def app_delete(self) -> Callable[[AppDeleteParams], Transaction]: """Create an application delete transaction.""" return self._transaction(lambda c: c.add_app_delete) @property def app_call(self) -> Callable[[AppCallParams], Transaction]: """Create an application call transaction.""" return self._transaction(lambda c: c.add_app_call) @property def app_create_method_call(self) -> Callable[[AppCreateMethodCallParams], BuiltTransactions]: """Create an application create call with ABI method call transaction.""" return self._transactions(lambda c: c.add_app_create_method_call) @property def app_update_method_call(self) -> Callable[[AppUpdateMethodCallParams], BuiltTransactions]: """Create an application update call with ABI method call transaction.""" return self._transactions(lambda c: c.add_app_update_method_call) @property def app_delete_method_call(self) -> Callable[[AppDeleteMethodCallParams], BuiltTransactions]: """Create an application delete call with ABI method call transaction.""" return self._transactions(lambda c: c.add_app_delete_method_call) @property def app_call_method_call(self) -> Callable[[AppCallMethodCallParams], BuiltTransactions]: """Create an application call with ABI method call transaction.""" return self._transactions(lambda c: c.add_app_call_method_call) @property def online_key_registration(self) -> Callable[[OnlineKeyRegistrationParams], Transaction]: """Create an online key registration transaction.""" return self._transaction(lambda c: c.add_online_key_registration) @property def offline_key_registration(self) -> Callable[[OfflineKeyRegistrationParams], Transaction]: """Create an offline key registration transaction.""" return self._transaction(lambda c: c.add_offline_key_registration)
algorandfoundation/algokit-utils-py
src/algokit_utils/transactions/transaction_creator.py
Python
MIT
6,167
from collections.abc import Callable from dataclasses import dataclass from typing import Any, Generic, TypeVar import algosdk import algosdk.atomic_transaction_composer from algosdk.transaction import Transaction from typing_extensions import Self from algokit_utils.applications.abi import ABIReturn from algokit_utils.applications.app_manager import AppManager from algokit_utils.assets.asset_manager import AssetManager from algokit_utils.config import config from algokit_utils.models.transaction import SendParams, TransactionWrapper from algokit_utils.transactions.transaction_composer import ( AppCallMethodCallParams, AppCallParams, AppCreateMethodCallParams, AppCreateParams, AppDeleteMethodCallParams, AppDeleteParams, AppUpdateMethodCallParams, AppUpdateParams, AssetConfigParams, AssetCreateParams, AssetDestroyParams, AssetFreezeParams, AssetOptInParams, AssetOptOutParams, AssetTransferParams, OfflineKeyRegistrationParams, OnlineKeyRegistrationParams, PaymentParams, SendAtomicTransactionComposerResults, TransactionComposer, TxnParams, ) __all__ = [ "AlgorandClientTransactionSender", "SendAppCreateTransactionResult", "SendAppTransactionResult", "SendAppUpdateTransactionResult", "SendSingleAssetCreateTransactionResult", "SendSingleTransactionResult", ] logger = config.logger TxnParamsT = TypeVar("TxnParamsT", bound=TxnParams) @dataclass(frozen=True, kw_only=True) class SendSingleTransactionResult: """Base class for transaction results. Represents the result of sending a single transaction. """ transaction: TransactionWrapper # Last transaction confirmation: algosdk.v2client.algod.AlgodResponseType # Last confirmation # Fields from SendAtomicTransactionComposerResults group_id: str tx_id: str | None = None tx_ids: list[str] # Full array of transaction IDs transactions: list[TransactionWrapper] confirmations: list[algosdk.v2client.algod.AlgodResponseType] returns: list[ABIReturn] | None = None @classmethod def from_composer_result(cls, result: SendAtomicTransactionComposerResults, index: int = -1) -> Self: # Get base parameters base_params = { "transaction": result.transactions[index], "confirmation": result.confirmations[index], "group_id": result.group_id, "tx_id": result.tx_ids[index], "tx_ids": result.tx_ids, "transactions": [result.transactions[index]], "confirmations": result.confirmations, "returns": result.returns, } # For asset creation, extract asset_id from confirmation if cls is SendSingleAssetCreateTransactionResult: base_params["asset_id"] = result.confirmations[index]["asset-index"] # type: ignore[call-overload] # For app creation, extract app_id and calculate app_address elif cls is SendAppCreateTransactionResult: app_id = result.confirmations[index]["application-index"] # type: ignore[call-overload] base_params.update( { "app_id": app_id, "app_address": algosdk.logic.get_application_address(app_id), "abi_return": result.returns[index] if result.returns else None, # type: ignore[dict-item] } ) # For regular app transactions, just add abi_return elif cls is SendAppTransactionResult: base_params["abi_return"] = result.returns[index] if result.returns else None # type: ignore[assignment] return cls(**base_params) # type: ignore[arg-type] @dataclass(frozen=True, kw_only=True) class SendSingleAssetCreateTransactionResult(SendSingleTransactionResult): """Result of creating a new ASA (Algorand Standard Asset). Contains the asset ID of the newly created asset. """ asset_id: int ABIReturnT = TypeVar("ABIReturnT") @dataclass(frozen=True) class SendAppTransactionResult(SendSingleTransactionResult, Generic[ABIReturnT]): """Result of an application transaction. Contains the ABI return value if applicable. """ abi_return: ABIReturnT | None = None @dataclass(frozen=True) class SendAppUpdateTransactionResult(SendAppTransactionResult[ABIReturnT]): """Result of updating an application. Contains the compiled approval and clear programs. """ compiled_approval: Any | None = None compiled_clear: Any | None = None @dataclass(frozen=True, kw_only=True) class SendAppCreateTransactionResult(SendAppUpdateTransactionResult[ABIReturnT]): """Result of creating a new application. Contains the app ID and address of the newly created application. """ app_id: int app_address: str class AlgorandClientTransactionSender: """Orchestrates sending transactions for AlgorandClient. Provides methods to send various types of transactions including payments, asset operations, and application calls. """ def __init__( self, new_group: Callable[[], TransactionComposer], asset_manager: AssetManager, app_manager: AppManager, algod_client: algosdk.v2client.algod.AlgodClient, ) -> None: self._new_group = new_group self._asset_manager = asset_manager self._app_manager = app_manager self._algod = algod_client def new_group(self) -> TransactionComposer: """Create a new transaction group. :return: A new TransactionComposer instance """ return self._new_group() def _send( self, c: Callable[[TransactionComposer], Callable[[TxnParamsT], TransactionComposer]], pre_log: Callable[[TxnParamsT, Transaction], str] | None = None, post_log: Callable[[TxnParamsT, SendSingleTransactionResult], str] | None = None, ) -> Callable[[TxnParamsT, SendParams | None], SendSingleTransactionResult]: def send_transaction(params: TxnParamsT, send_params: SendParams | None = None) -> SendSingleTransactionResult: composer = self.new_group() c(composer)(params) if pre_log: transaction = composer.build().transactions[-1].txn logger.debug(pre_log(params, transaction)) raw_result = composer.send( send_params, ) raw_result_dict = raw_result.__dict__.copy() raw_result_dict["transactions"] = raw_result.transactions del raw_result_dict["simulate_response"] result = SendSingleTransactionResult( **raw_result_dict, confirmation=raw_result.confirmations[-1], transaction=raw_result_dict["transactions"][-1], tx_id=raw_result.tx_ids[-1], ) if post_log: logger.debug(post_log(params, result)) return result return send_transaction def _send_app_call( self, c: Callable[[TransactionComposer], Callable[[TxnParamsT], TransactionComposer]], pre_log: Callable[[TxnParamsT, Transaction], str] | None = None, post_log: Callable[[TxnParamsT, SendSingleTransactionResult], str] | None = None, ) -> Callable[[TxnParamsT, SendParams | None], SendAppTransactionResult[ABIReturn]]: def send_app_call( params: TxnParamsT, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: result = self._send(c, pre_log, post_log)(params, send_params) return SendAppTransactionResult[ABIReturn]( **result.__dict__, abi_return=AppManager.get_abi_return(result.confirmation, getattr(params, "method", None)), ) return send_app_call def _send_app_update_call( self, c: Callable[[TransactionComposer], Callable[[TxnParamsT], TransactionComposer]], pre_log: Callable[[TxnParamsT, Transaction], str] | None = None, post_log: Callable[[TxnParamsT, SendSingleTransactionResult], str] | None = None, ) -> Callable[[TxnParamsT, SendParams | None], SendAppUpdateTransactionResult[ABIReturn]]: def send_app_update_call( params: TxnParamsT, send_params: SendParams | None = None ) -> SendAppUpdateTransactionResult[ABIReturn]: result = self._send_app_call(c, pre_log, post_log)(params, send_params) if not isinstance( params, AppCreateParams | AppUpdateParams | AppCreateMethodCallParams | AppUpdateMethodCallParams ): raise TypeError("Invalid parameter type") compiled_approval = ( self._app_manager.get_compilation_result(params.approval_program) if isinstance(params.approval_program, str) else params.approval_program ) compiled_clear = ( self._app_manager.get_compilation_result(params.clear_state_program) if isinstance(params.clear_state_program, str) else params.clear_state_program ) return SendAppUpdateTransactionResult[ABIReturn]( **result.__dict__, compiled_approval=compiled_approval, compiled_clear=compiled_clear, ) return send_app_update_call def _send_app_create_call( self, c: Callable[[TransactionComposer], Callable[[TxnParamsT], TransactionComposer]], pre_log: Callable[[TxnParamsT, Transaction], str] | None = None, post_log: Callable[[TxnParamsT, SendSingleTransactionResult], str] | None = None, ) -> Callable[[TxnParamsT, SendParams | None], SendAppCreateTransactionResult[ABIReturn]]: def send_app_create_call( params: TxnParamsT, send_params: SendParams | None = None ) -> SendAppCreateTransactionResult[ABIReturn]: result = self._send_app_update_call(c, pre_log, post_log)(params, send_params) app_id = int(result.confirmation["application-index"]) # type: ignore[call-overload] return SendAppCreateTransactionResult[ABIReturn]( **result.__dict__, app_id=app_id, app_address=algosdk.logic.get_application_address(app_id), ) return send_app_create_call def _get_method_call_for_log(self, method: algosdk.abi.Method, args: list[Any]) -> str: """Helper function to format method call logs similar to TypeScript version""" args_str = str([str(a) if not isinstance(a, bytes | bytearray) else a.hex() for a in args]) return f"{method.name}({args_str})" def payment(self, params: PaymentParams, send_params: SendParams | None = None) -> SendSingleTransactionResult: """Send a payment transaction to transfer Algo between accounts. :param params: Payment transaction parameters :param send_params: Send parameters :return: Result of the payment transaction """ return self._send( lambda c: c.add_payment, pre_log=lambda params, transaction: ( f"Sending {params.amount} from {params.sender} to {params.receiver} " f"via transaction {transaction.get_txid()}" ), )(params, send_params) def asset_create( self, params: AssetCreateParams, send_params: SendParams | None = None ) -> SendSingleAssetCreateTransactionResult: """Create a new Algorand Standard Asset. :param params: Asset creation parameters :param send_params: Send parameters :return: Result containing the new asset ID """ result = self._send( lambda c: c.add_asset_create, post_log=lambda params, result: ( f"Created asset{f' {params.asset_name}' if hasattr(params, 'asset_name') else ''}" f"{f' ({params.unit_name})' if hasattr(params, 'unit_name') else ''} with " f"{params.total} units and {getattr(params, 'decimals', 0)} decimals created by " f"{params.sender} with ID {result.confirmation['asset-index']} via transaction " # type: ignore[call-overload] f"{result.tx_ids[-1]}" ), )(params, send_params) return SendSingleAssetCreateTransactionResult( **result.__dict__, asset_id=int(result.confirmation["asset-index"]), # type: ignore[call-overload] ) def asset_config( self, params: AssetConfigParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Configure an existing Algorand Standard Asset. :param params: Asset configuration parameters :param send_params: Send parameters :return: Result of the configuration transaction """ return self._send( lambda c: c.add_asset_config, pre_log=lambda params, transaction: ( f"Configuring asset with ID {params.asset_id} via transaction {transaction.get_txid()}" ), )(params, send_params) def asset_freeze( self, params: AssetFreezeParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Freeze or unfreeze an Algorand Standard Asset for an account. :param params: Asset freeze parameters :param send_params: Send parameters :return: Result of the freeze transaction """ return self._send( lambda c: c.add_asset_freeze, pre_log=lambda params, transaction: ( f"Freezing asset with ID {params.asset_id} via transaction {transaction.get_txid()}" ), )(params, send_params) def asset_destroy( self, params: AssetDestroyParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Destroys an Algorand Standard Asset. :param params: Asset destruction parameters :param send_params: Send parameters :return: Result of the destroy transaction """ return self._send( lambda c: c.add_asset_destroy, pre_log=lambda params, transaction: ( f"Destroying asset with ID {params.asset_id} via transaction {transaction.get_txid()}" ), )(params, send_params) def asset_transfer( self, params: AssetTransferParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Transfer an Algorand Standard Asset. :param params: Asset transfer parameters :param send_params: Send parameters :return: Result of the transfer transaction """ return self._send( lambda c: c.add_asset_transfer, pre_log=lambda params, transaction: ( f"Transferring {params.amount} units of asset with ID {params.asset_id} from " f"{params.sender} to {params.receiver} via transaction {transaction.get_txid()}" ), )(params, send_params) def asset_opt_in( self, params: AssetOptInParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Opt an account into an Algorand Standard Asset. :param params: Asset opt-in parameters :param send_params: Send parameters :return: Result of the opt-in transaction """ return self._send( lambda c: c.add_asset_opt_in, pre_log=lambda params, transaction: ( f"Opting in {params.sender} to asset with ID {params.asset_id} via transaction " f"{transaction.get_txid()}" ), )(params, send_params) def asset_opt_out( self, *, params: AssetOptOutParams, send_params: SendParams | None = None, ensure_zero_balance: bool = True, ) -> SendSingleTransactionResult: """Opt an account out of an Algorand Standard Asset. :param params: Asset opt-out parameters :param send_params: Send parameters :param ensure_zero_balance: Check if account has zero balance before opt-out, defaults to True :raises ValueError: If account has non-zero balance or is not opted in :return: Result of the opt-out transaction """ if ensure_zero_balance: try: account_asset_info = self._asset_manager.get_account_information(params.sender, params.asset_id) balance = account_asset_info.balance if balance != 0: raise ValueError( f"Account {params.sender} does not have a zero balance for Asset " f"{params.asset_id}; can't opt-out." ) except Exception as e: raise ValueError( f"Account {params.sender} is not opted-in to Asset {params.asset_id}; " "can't opt-out." ) from e if not hasattr(params, "creator"): asset_info = self._asset_manager.get_by_id(params.asset_id) params = AssetOptOutParams( **params.__dict__, creator=asset_info.creator, ) creator = params.__dict__.get("creator") return self._send( lambda c: c.add_asset_opt_out, pre_log=lambda params, transaction: ( f"Opting {params.sender} out of asset with ID {params.asset_id} to creator " f"{creator} via transaction {transaction.get_txid()}" ), )(params, send_params) def app_create( self, params: AppCreateParams, send_params: SendParams | None = None ) -> SendAppCreateTransactionResult[ABIReturn]: """Create a new application. :param params: Application creation parameters :param send_params: Send parameters :return: Result containing the new application ID and address """ return self._send_app_create_call(lambda c: c.add_app_create)(params, send_params) def app_update( self, params: AppUpdateParams, send_params: SendParams | None = None ) -> SendAppUpdateTransactionResult[ABIReturn]: """Update an application. :param params: Application update parameters :param send_params: Send parameters :return: Result containing the compiled programs """ return self._send_app_update_call(lambda c: c.add_app_update)(params, send_params) def app_delete( self, params: AppDeleteParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Delete an application. :param params: Application deletion parameters :param send_params: Send parameters :return: Result of the deletion transaction """ return self._send_app_call(lambda c: c.add_app_delete)(params, send_params) def app_call( self, params: AppCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Call an application. :param params: Application call parameters :param send_params: Send parameters :return: Result containing any ABI return value """ return self._send_app_call(lambda c: c.add_app_call)(params, send_params) def app_create_method_call( self, params: AppCreateMethodCallParams, send_params: SendParams | None = None ) -> SendAppCreateTransactionResult[ABIReturn]: """Call an application's create method. :param params: Method call parameters for application creation :param send_params: Send parameters :return: Result containing the new application ID and address """ return self._send_app_create_call(lambda c: c.add_app_create_method_call)(params, send_params) def app_update_method_call( self, params: AppUpdateMethodCallParams, send_params: SendParams | None = None ) -> SendAppUpdateTransactionResult[ABIReturn]: """Call an application's update method. :param params: Method call parameters for application update :param send_params: Send parameters :return: Result containing the compiled programs """ return self._send_app_update_call(lambda c: c.add_app_update_method_call)(params, send_params) def app_delete_method_call( self, params: AppDeleteMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Call an application's delete method. :param params: Method call parameters for application deletion :param send_params: Send parameters :return: Result of the deletion transaction """ return self._send_app_call(lambda c: c.add_app_delete_method_call)(params, send_params) def app_call_method_call( self, params: AppCallMethodCallParams, send_params: SendParams | None = None ) -> SendAppTransactionResult[ABIReturn]: """Call an application's call method. :param params: Method call parameters :param send_params: Send parameters :return: Result containing any ABI return value """ return self._send_app_call(lambda c: c.add_app_call_method_call)(params, send_params) def online_key_registration( self, params: OnlineKeyRegistrationParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Register an online key. :param params: Key registration parameters :param send_params: Send parameters :return: Result of the registration transaction """ return self._send( lambda c: c.add_online_key_registration, pre_log=lambda params, transaction: ( f"Registering online key for {params.sender} via transaction {transaction.get_txid()}" ), )(params, send_params) def offline_key_registration( self, params: OfflineKeyRegistrationParams, send_params: SendParams | None = None ) -> SendSingleTransactionResult: """Register an offline key. :param params: Key registration parameters :param send_params: Send parameters :return: Result of the registration transaction """ return self._send( lambda c: c.add_offline_key_registration, pre_log=lambda params, transaction: ( f"Registering offline key for {params.sender} via transaction {transaction.get_txid()}" ), )(params, send_params)
algorandfoundation/algokit-utils-py
src/algokit_utils/transactions/transaction_sender.py
Python
MIT
22,769
algorandfoundation/algokit-utils-py
tests/__init__.py
Python
MIT
0
algorandfoundation/algokit-utils-py
tests/accounts/__init__.py
Python
MIT
0
import algosdk import pytest from algokit_utils import SigningAccount from algokit_utils.algorand import AlgorandClient from algokit_utils.models.amount import AlgoAmount from tests.conftest import get_unique_name @pytest.fixture def algorand() -> AlgorandClient: return AlgorandClient.default_localnet() @pytest.fixture def funded_account(algorand: AlgorandClient) -> SigningAccount: new_account = algorand.account.random() dispenser = algorand.account.localnet_dispenser() algorand.account.ensure_funded( new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1) ) algorand.set_signer(sender=new_account.address, signer=new_account.signer) return new_account def test_new_account_is_retrieved_and_funded(algorand: AlgorandClient) -> None: # Act account_name = get_unique_name() account = algorand.account.from_environment(account_name) # Assert account_info = algorand.account.get_information(account.address) assert account_info.amount > 0 def test_same_account_is_subsequently_retrieved(algorand: AlgorandClient) -> None: # Arrange account_name = get_unique_name() # Act account1 = algorand.account.from_environment(account_name) account2 = algorand.account.from_environment(account_name) # Assert - accounts should be different objects but with same underlying keys assert account1 is not account2 assert account1.address == account2.address assert account1.private_key == account2.private_key def test_environment_is_used_in_preference_to_kmd(algorand: AlgorandClient, monkeypatch: pytest.MonkeyPatch) -> None: # Arrange account_name = get_unique_name() account1 = algorand.account.from_environment(account_name) # Set up environment variable for second account env_account_name = "TEST_ACCOUNT" monkeypatch.setenv(f"{env_account_name}_MNEMONIC", algosdk.mnemonic.from_private_key(account1.private_key)) # Act account2 = algorand.account.from_environment(env_account_name) # Assert - accounts should be different objects but with same underlying keys assert account1 is not account2 assert account1.address == account2.address assert account1.private_key == account2.private_key def test_random_account_creation(algorand: AlgorandClient) -> None: # Act account = algorand.account.random() # Assert assert account.address assert account.private_key assert len(account.public_key) == 32 def test_ensure_funded_from_environment(algorand: AlgorandClient) -> None: # Arrange account = algorand.account.random() min_balance = AlgoAmount.from_algos(1) # Act result = algorand.account.ensure_funded_from_environment( account_to_fund=account.address, min_spending_balance=min_balance, ) # Assert assert result is not None assert result.amount_funded is not None account_info = algorand.account.get_information(account.address) assert account_info.amount_without_pending_rewards >= min_balance.micro_algos def test_get_account_information(algorand: AlgorandClient) -> None: # Arrange account = algorand.account.random() # Act info = algorand.account.get_information(account.address) # Assert assert info.amount is not None assert info.min_balance is not None assert info.address is not None assert info.address == account.address
algorandfoundation/algokit-utils-py
tests/accounts/test_account_manager.py
Python
MIT
3,459
algorandfoundation/algokit-utils-py
tests/applications/__init__.py
Python
MIT
0
import base64 import json import random from pathlib import Path from typing import Any import algosdk import pytest from algosdk.atomic_transaction_composer import TransactionSigner, TransactionWithSigner from algokit_utils._legacy_v2.application_specification import ApplicationSpecification from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.abi import ABIType from algokit_utils.applications.app_client import ( AppClient, AppClientMethodCallParams, AppClientParams, FundAppAccountParams, ) from algokit_utils.applications.app_manager import AppManager from algokit_utils.applications.app_spec.arc56 import Arc56Contract, Network from algokit_utils.errors.logic_error import LogicError from algokit_utils.models.account import SigningAccount from algokit_utils.models.amount import AlgoAmount from algokit_utils.models.state import BoxReference from algokit_utils.transactions.transaction_composer import AppCreateParams, PaymentParams @pytest.fixture def algorand() -> AlgorandClient: return AlgorandClient.default_localnet() @pytest.fixture def funded_account(algorand: AlgorandClient) -> SigningAccount: new_account = algorand.account.random() dispenser = algorand.account.localnet_dispenser() algorand.account.ensure_funded( new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1) ) algorand.set_signer(sender=new_account.address, signer=new_account.signer) return new_account @pytest.fixture def raw_hello_world_arc32_app_spec() -> str: raw_json_spec = Path(__file__).parent.parent / "artifacts" / "hello_world" / "app_spec.arc32.json" return raw_json_spec.read_text() @pytest.fixture def hello_world_arc32_app_spec() -> ApplicationSpecification: raw_json_spec = Path(__file__).parent.parent / "artifacts" / "hello_world" / "app_spec.arc32.json" return ApplicationSpecification.from_json(raw_json_spec.read_text()) @pytest.fixture def hello_world_arc32_app_id( algorand: AlgorandClient, funded_account: SigningAccount, hello_world_arc32_app_spec: ApplicationSpecification ) -> int: global_schema = hello_world_arc32_app_spec.global_state_schema local_schema = hello_world_arc32_app_spec.local_state_schema response = algorand.send.app_create( AppCreateParams( sender=funded_account.address, approval_program=hello_world_arc32_app_spec.approval_program, clear_state_program=hello_world_arc32_app_spec.clear_program, schema={ "global_ints": int(global_schema.num_uints) if global_schema.num_uints else 0, "global_byte_slices": int(global_schema.num_byte_slices) if global_schema.num_byte_slices else 0, "local_ints": int(local_schema.num_uints) if local_schema.num_uints else 0, "local_byte_slices": int(local_schema.num_byte_slices) if local_schema.num_byte_slices else 0, }, ) ) return response.app_id @pytest.fixture def raw_testing_app_arc32_app_spec() -> str: raw_json_spec = Path(__file__).parent.parent / "artifacts" / "testing_app" / "app_spec.arc32.json" return raw_json_spec.read_text() @pytest.fixture def testing_app_arc32_app_spec() -> ApplicationSpecification: raw_json_spec = Path(__file__).parent.parent / "artifacts" / "testing_app" / "app_spec.arc32.json" return ApplicationSpecification.from_json(raw_json_spec.read_text()) @pytest.fixture def testing_app_arc32_app_id( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_arc32_app_spec: ApplicationSpecification ) -> int: global_schema = testing_app_arc32_app_spec.global_state_schema local_schema = testing_app_arc32_app_spec.local_state_schema approval = AppManager.replace_template_variables( testing_app_arc32_app_spec.approval_program, { "VALUE": 1, "UPDATABLE": 0, "DELETABLE": 0, }, ) response = algorand.send.app_create( AppCreateParams( sender=funded_account.address, approval_program=approval, clear_state_program=testing_app_arc32_app_spec.clear_program, schema={ "global_byte_slices": int(global_schema.num_byte_slices) if global_schema.num_byte_slices else 0, "global_ints": int(global_schema.num_uints) if global_schema.num_uints else 0, "local_byte_slices": int(local_schema.num_byte_slices) if local_schema.num_byte_slices else 0, "local_ints": int(local_schema.num_uints) if local_schema.num_uints else 0, }, ) ) return response.app_id @pytest.fixture def test_app_client( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_arc32_app_spec: ApplicationSpecification, testing_app_arc32_app_id: int, ) -> AppClient: return AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=testing_app_arc32_app_id, algorand=algorand, app_spec=testing_app_arc32_app_spec, ) ) @pytest.fixture def test_app_client_with_sourcemaps( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_arc32_app_spec: ApplicationSpecification, testing_app_arc32_app_id: int, ) -> AppClient: sourcemaps = json.loads( (Path(__file__).parent.parent / "artifacts" / "testing_app" / "sources.teal.map.json").read_text() ) return AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=testing_app_arc32_app_id, algorand=algorand, approval_source_map=algosdk.source_map.SourceMap(sourcemaps["approvalSourceMap"]), clear_source_map=algosdk.source_map.SourceMap(sourcemaps["clearSourceMap"]), app_spec=testing_app_arc32_app_spec, ) ) @pytest.fixture def testing_app_puya_arc32_app_spec() -> ApplicationSpecification: raw_json_spec = Path(__file__).parent.parent / "artifacts" / "testing_app_puya" / "app_spec.arc32.json" return ApplicationSpecification.from_json(raw_json_spec.read_text()) @pytest.fixture def testing_app_puya_arc32_app_id( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_puya_arc32_app_spec: ApplicationSpecification ) -> int: global_schema = testing_app_puya_arc32_app_spec.global_state_schema local_schema = testing_app_puya_arc32_app_spec.local_state_schema response = algorand.send.app_create( AppCreateParams( sender=funded_account.address, approval_program=testing_app_puya_arc32_app_spec.approval_program, clear_state_program=testing_app_puya_arc32_app_spec.clear_program, schema={ "global_byte_slices": int(global_schema.num_byte_slices) if global_schema.num_byte_slices else 0, "global_ints": int(global_schema.num_uints) if global_schema.num_uints else 0, "local_byte_slices": int(local_schema.num_byte_slices) if local_schema.num_byte_slices else 0, "local_ints": int(local_schema.num_uints) if local_schema.num_uints else 0, }, ) ) return response.app_id @pytest.fixture def test_app_client_puya( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_puya_arc32_app_spec: ApplicationSpecification, testing_app_puya_arc32_app_id: int, ) -> AppClient: return AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=testing_app_puya_arc32_app_id, algorand=algorand, app_spec=testing_app_puya_arc32_app_spec, ) ) def test_clone_overriding_default_sender_and_inheriting_app_name( algorand: AlgorandClient, funded_account: SigningAccount, hello_world_arc32_app_spec: ApplicationSpecification, hello_world_arc32_app_id: int, ) -> None: app_client = AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=hello_world_arc32_app_id, algorand=algorand, app_spec=hello_world_arc32_app_spec, ) ) cloned_default_sender = "ABC" * 55 cloned_app_client = app_client.clone(default_sender=cloned_default_sender) assert app_client.app_name == "HelloWorld" assert cloned_app_client.app_id == app_client.app_id assert cloned_app_client.app_name == app_client.app_name assert cloned_app_client._default_sender == cloned_default_sender # noqa: SLF001 assert app_client._default_sender == funded_account.address # noqa: SLF001 def test_clone_overriding_app_name( algorand: AlgorandClient, funded_account: SigningAccount, hello_world_arc32_app_spec: ApplicationSpecification, hello_world_arc32_app_id: int, ) -> None: app_client = AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=hello_world_arc32_app_id, algorand=algorand, app_spec=hello_world_arc32_app_spec, ) ) cloned_app_name = "George CLONEy" cloned_app_client = app_client.clone(app_name=cloned_app_name) assert app_client.app_name == hello_world_arc32_app_spec.contract.name == "HelloWorld" assert cloned_app_client.app_name == cloned_app_name # Test for explicit None when closning cloned_app_client = app_client.clone(app_name=None) assert cloned_app_client.app_name == app_client.app_name def test_clone_inheriting_app_name_based_on_default_handling( algorand: AlgorandClient, funded_account: SigningAccount, hello_world_arc32_app_spec: ApplicationSpecification, hello_world_arc32_app_id: int, ) -> None: app_client = AppClient( AppClientParams( default_sender=funded_account.address, default_signer=funded_account.signer, app_id=hello_world_arc32_app_id, algorand=algorand, app_spec=hello_world_arc32_app_spec, ) ) cloned_app_name = None cloned_app_client = app_client.clone(app_name=cloned_app_name) assert cloned_app_client.app_name == hello_world_arc32_app_spec.contract.name == app_client.app_name def test_normalise_app_spec( raw_hello_world_arc32_app_spec: str, hello_world_arc32_app_spec: ApplicationSpecification, ) -> None: normalized_app_spec_from_arc32 = AppClient.normalise_app_spec(hello_world_arc32_app_spec) assert isinstance(normalized_app_spec_from_arc32, Arc56Contract) normalize_app_spec_from_raw_arc32 = AppClient.normalise_app_spec(raw_hello_world_arc32_app_spec) assert isinstance(normalize_app_spec_from_raw_arc32, Arc56Contract) def test_resolve_from_network( algorand: AlgorandClient, hello_world_arc32_app_id: int, hello_world_arc32_app_spec: ApplicationSpecification, ) -> None: arc56_app_spec = Arc56Contract.from_arc32(hello_world_arc32_app_spec) arc56_app_spec.networks = {"localnet": Network(app_id=hello_world_arc32_app_id)} app_client = AppClient.from_network( algorand=algorand, app_spec=arc56_app_spec, ) assert app_client def test_construct_transaction_with_boxes(test_app_client: AppClient) -> None: call = test_app_client.create_transaction.call( AppClientMethodCallParams( method="call_abi", args=["test"], box_references=[BoxReference(app_id=0, name=b"1")], ) ) assert isinstance(call.transactions[0], algosdk.transaction.ApplicationCallTxn) assert call.transactions[0].boxes == [BoxReference(app_id=0, name=b"1")] # Test with string box reference call2 = test_app_client.create_transaction.call( AppClientMethodCallParams( method="call_abi", args=["test"], box_references=["1"], ) ) assert isinstance(call2.transactions[0], algosdk.transaction.ApplicationCallTxn) assert call2.transactions[0].boxes == [BoxReference(app_id=0, name=b"1")] def test_construct_transaction_with_abi_encoding_including_transaction( algorand: AlgorandClient, funded_account: SigningAccount, test_app_client: AppClient ) -> None: # Create a payment transaction with random amount amount = AlgoAmount.from_micro_algos(random.randint(1, 10000)) payment_txn = algorand.create_transaction.payment( PaymentParams( sender=funded_account.address, receiver=funded_account.address, amount=amount, ) ) # Call the ABI method with the payment transaction result = test_app_client.send.call( AppClientMethodCallParams( method="call_abi_txn", args=[payment_txn, "test"], ) ) assert result.confirmation assert len(result.transactions) == 2 response = AppManager.get_abi_return( result.confirmation, test_app_client.app_spec.get_arc56_method("call_abi_txn").to_abi_method() ) expected_return = f"Sent {amount.micro_algos}. test" assert result.abi_return == expected_return assert response assert response.value == result.abi_return def test_sign_all_transactions_in_group_with_abi_call_with_transaction_arg( algorand: AlgorandClient, test_app_client: AppClient, funded_account: SigningAccount ) -> None: # Create a payment transaction with a random amount amount = AlgoAmount.from_micro_algos(random.randint(1, 10000)) txn = algorand.create_transaction.payment( PaymentParams( sender=funded_account.address, receiver=funded_account.address, amount=amount, ) ) called_indexes = [] original_signer = algorand.account.get_signer(funded_account.address) class IndexCapturingSigner(TransactionSigner): def sign_transactions( self, txn_group: list[algosdk.transaction.Transaction], indexes: list[int] ) -> list[algosdk.transaction.GenericSignedTransaction]: called_indexes.extend(indexes) return original_signer.sign_transactions(txn_group, indexes) test_app_client.send.call( AppClientMethodCallParams( method="call_abi_txn", args=[txn, "test"], sender=funded_account.address, signer=IndexCapturingSigner(), ) ) assert called_indexes == [0, 1] def test_sign_transaction_in_group_with_different_signer_if_provided( algorand: AlgorandClient, test_app_client: AppClient, funded_account: SigningAccount ) -> None: # Generate a new account test_account = algorand.account.random() algorand.account.ensure_funded( account_to_fund=test_account, dispenser_account=funded_account, min_spending_balance=AlgoAmount.from_algos(10), min_funding_increment=AlgoAmount.from_algos(1), ) # Fund the account with 1 Algo txn = algorand.create_transaction.payment( PaymentParams( sender=test_account.address, receiver=test_account.address, amount=AlgoAmount.from_algos(random.randint(1, 5)), ) ) # Call method with transaction and signer test_app_client.send.call( AppClientMethodCallParams( method="call_abi_txn", args=[TransactionWithSigner(txn=txn, signer=test_account.signer), "test"], ) ) def test_construct_transaction_with_abi_encoding_including_foreign_references_not_in_signature( algorand: AlgorandClient, test_app_client: AppClient, funded_account: SigningAccount ) -> None: test_account = algorand.account.random() algorand.account.ensure_funded( account_to_fund=test_account, dispenser_account=funded_account, min_spending_balance=AlgoAmount.from_algos(10), min_funding_increment=AlgoAmount.from_algos(1), ) result = test_app_client.send.call( AppClientMethodCallParams( method="call_abi_foreign_refs", app_references=[345], account_references=[test_account.address], asset_references=[567], ) ) # Assuming the method returns a string matching the format below expected_return = AppManager.get_abi_return( result.confirmations[0], test_app_client.app_spec.get_arc56_method("call_abi_foreign_refs").to_abi_method(), ) assert result.abi_return assert str(result.abi_return).startswith("App: 345, Asset: 567, Account: ") assert expected_return assert expected_return.value == result.abi_return def test_retrieve_state(test_app_client: AppClient, funded_account: SigningAccount) -> None: # Test global state test_app_client.send.call(AppClientMethodCallParams(method="set_global", args=[1, 2, "asdf", bytes([1, 2, 3, 4])])) global_state = test_app_client.get_global_state() assert "int1" in global_state assert "int2" in global_state assert "bytes1" in global_state assert "bytes2" in global_state assert hasattr(global_state["bytes2"], "value_raw") assert sorted(global_state.keys()) == ["bytes1", "bytes2", "int1", "int2", "value"] assert global_state["int1"].value == 1 assert global_state["int2"].value == 2 assert global_state["bytes1"].value == "asdf" assert global_state["bytes2"].value_raw == bytes([1, 2, 3, 4]) # Test local state test_app_client.send.opt_in(AppClientMethodCallParams(method="opt_in")) test_app_client.send.call(AppClientMethodCallParams(method="set_local", args=[1, 2, "asdf", bytes([1, 2, 3, 4])])) local_state = test_app_client.get_local_state(funded_account.address) assert "local_int1" in local_state assert "local_int2" in local_state assert "local_bytes1" in local_state assert "local_bytes2" in local_state assert sorted(local_state.keys()) == ["local_bytes1", "local_bytes2", "local_int1", "local_int2"] assert local_state["local_int1"].value == 1 assert local_state["local_int2"].value == 2 assert local_state["local_bytes1"].value == "asdf" assert local_state["local_bytes2"].value_raw == bytes([1, 2, 3, 4]) # Test box storage box_name1 = bytes([0, 0, 0, 1]) box_name1_base64 = base64.b64encode(box_name1).decode() box_name2 = bytes([0, 0, 0, 2]) box_name2_base64 = base64.b64encode(box_name2).decode() test_app_client.fund_app_account(params=FundAppAccountParams(amount=AlgoAmount.from_algos(1))) test_app_client.send.call( AppClientMethodCallParams( method="set_box", args=[box_name1, "value1"], box_references=[box_name1], ) ) test_app_client.send.call( AppClientMethodCallParams( method="set_box", args=[box_name2, "value2"], box_references=[box_name2], ) ) box_values = test_app_client.get_box_values() box1_value = test_app_client.get_box_value(box_name1) assert sorted(b.name.name_base64 for b in box_values) == sorted([box_name1_base64, box_name2_base64]) box1 = next(b for b in box_values if b.name.name_base64 == box_name1_base64) assert box1.value == b"value1" assert box1_value == box1.value box2 = next(b for b in box_values if b.name.name_base64 == box_name2_base64) assert box2.value == b"value2" # Legacy contract strips ABI prefix; manually encoded ABI string after # passing algosdk's atc results in \x00\n\x00\n1234524352. expected_value_decoded = "1234524352" expected_value = "\x00\n" + expected_value_decoded test_app_client.send.call( AppClientMethodCallParams( method="set_box", args=[box_name1, expected_value], box_references=[box_name1], ) ) boxes = test_app_client.get_box_values_from_abi_type( ABIType.from_string("string"), lambda n: n.name_base64 == box_name1_base64, ) box1_abi_value = test_app_client.get_box_value_from_abi_type(box_name1, ABIType.from_string("string")) assert len(boxes) == 1 assert boxes[0].value == expected_value_decoded assert box1_abi_value == expected_value_decoded @pytest.mark.parametrize( ("box_name", "box_value", "value_type", "expected_value"), [ ( "name1", b"test_bytes", # Updated to match Bytes type "byte[]", [116, 101, 115, 116, 95, 98, 121, 116, 101, 115], ), ( "name2", "test_string", "string", "test_string", ), ( "name3", # Updated to use string key 123, "uint32", 123, ), ( "name4", # Updated to use string key 2**256, # Large number within uint512 range "uint512", 2**256, ), ( "name5", # Updated to use string key [1, 2, 3, 4], "byte[4]", [1, 2, 3, 4], ), ], ) def test_box_methods_with_manually_encoded_abi_args( test_app_client_puya: AppClient, box_name: Any, # noqa: ANN401 box_value: Any, # noqa: ANN401 value_type: str, expected_value: Any, # noqa: ANN401 ) -> None: # Fund the app account box_prefix = b"box_bytes" test_app_client_puya.fund_app_account(params=FundAppAccountParams(amount=AlgoAmount.from_algos(1))) # Encode the box reference box_identifier = box_prefix + ABIType.from_string("string").encode(box_name) # Call the method to set the box value test_app_client_puya.send.call( AppClientMethodCallParams( method="set_box_bytes", args=[box_name, ABIType.from_string(value_type).encode(box_value)], box_references=[box_identifier], ) ) # Get and verify the box value box_abi_value = test_app_client_puya.get_box_value_from_abi_type(box_identifier, ABIType.from_string(value_type)) # Convert the retrieved value to match expected type if needed assert box_abi_value == expected_value @pytest.mark.parametrize( ("box_prefix_str", "method", "arg_value", "value_type"), [ ("box_str", "set_box_str", "string", "string"), ("box_int", "set_box_int", 123, "uint32"), ("box_int512", "set_box_int512", 2**256, "uint512"), ("box_static", "set_box_static", [1, 2, 3, 4], "byte[4]"), ("", "set_struct", ("box1", 123), "(string,uint64)"), ], ) def test_box_methods_with_arc4_returns_parametrized( test_app_client_puya: AppClient, box_prefix_str: str, method: str, arg_value: Any, # noqa: ANN401 value_type: str, ) -> None: # Encode the box prefix box_prefix = box_prefix_str.encode() # Fund the app account with 1 Algo test_app_client_puya.fund_app_account(params=FundAppAccountParams(amount=AlgoAmount.from_algos(1))) # Encode the box name "box1" using ABIType "string" box_name_encoded = ABIType.from_string("string").encode("box1") box_reference = box_prefix + box_name_encoded # Send the transaction to set the box value test_app_client_puya.send.call( AppClientMethodCallParams( method=method, args=["box1", arg_value], box_references=[box_reference], ) ) # Encode the expected value using the specified ABI type expected_value = ABIType.from_string(value_type).encode(arg_value) # Retrieve the actual box value actual_box_value = test_app_client_puya.get_box_value(box_reference) # Assert that the actual box value matches the expected value assert actual_box_value == expected_value if method == "set_struct": abi_decoded_boxes = test_app_client_puya.get_box_values_from_abi_type( ABIType.from_string("(string,uint64)"), lambda n: n.name_base64 == base64.b64encode(box_prefix + box_name_encoded).decode(), ) assert len(abi_decoded_boxes) == 1 assert abi_decoded_boxes[0].value == arg_value def test_abi_with_default_arg_method( algorand: AlgorandClient, funded_account: SigningAccount, testing_app_arc32_app_id: int, testing_app_arc32_app_spec: ApplicationSpecification, ) -> None: arc56_app_spec = Arc56Contract.from_arc32(testing_app_arc32_app_spec) arc56_app_spec.networks = {"localnet": Network(app_id=testing_app_arc32_app_id)} app_client = AppClient.from_network( algorand=algorand, app_spec=arc56_app_spec, default_sender=funded_account.address, default_signer=funded_account.signer, ) # app_client.send. app_client.send.opt_in(AppClientMethodCallParams(method="opt_in")) app_client.send.call( AppClientMethodCallParams( method="set_local", args=[1, 2, "banana", [1, 2, 3, 4]], ) ) method_signature = "default_value_from_local_state(string)string" defined_value = "defined value" # Test with defined value defined_value_result = app_client.send.call( AppClientMethodCallParams(method=method_signature, args=[defined_value]) ) assert defined_value_result.abi_return == "Local state, defined value" # Test with default value default_value_result = app_client.send.call(AppClientMethodCallParams(method=method_signature, args=[None])) assert default_value_result assert default_value_result.abi_return == "Local state, banana" def test_exposing_logic_error(test_app_client_with_sourcemaps: AppClient) -> None: with pytest.raises(LogicError) as exc_info: test_app_client_with_sourcemaps.send.call(AppClientMethodCallParams(method="error")) error = exc_info.value assert error.pc == 885 assert "assert failed pc=885" in str(error) assert len(error.transaction_id) == 52 assert error.line_no == 469
algorandfoundation/algokit-utils-py
tests/applications/test_app_client.py
Python
MIT
26,174
from pathlib import Path import algosdk import pytest from algosdk.logic import get_application_address from algosdk.transaction import OnComplete from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.app_client import ( AppClient, AppClientMethodCallCreateParams, AppClientMethodCallParams, AppClientParams, ) from algokit_utils.applications.app_deployer import OnSchemaBreak, OnUpdate, OperationPerformed from algokit_utils.applications.app_factory import ( AppFactory, AppFactoryCreateMethodCallParams, AppFactoryCreateParams, ) from algokit_utils.errors import LogicError from algokit_utils.models.account import SigningAccount from algokit_utils.models.amount import AlgoAmount from algokit_utils.transactions.transaction_composer import PaymentParams @pytest.fixture def algorand() -> AlgorandClient: return AlgorandClient.default_localnet() @pytest.fixture def funded_account(algorand: AlgorandClient) -> SigningAccount: new_account = algorand.account.random() dispenser = algorand.account.localnet_dispenser() algorand.account.ensure_funded( new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1) ) algorand.set_signer(sender=new_account.address, signer=new_account.signer) return new_account @pytest.fixture def app_spec() -> str: return (Path(__file__).parent.parent / "artifacts" / "testing_app" / "app_spec.arc32.json").read_text() @pytest.fixture def factory(algorand: AlgorandClient, funded_account: SigningAccount, app_spec: str) -> AppFactory: """Create AppFactory fixture""" return algorand.client.get_app_factory(app_spec=app_spec, default_sender=funded_account.address) @pytest.fixture def arc56_factory( algorand: AlgorandClient, funded_account: SigningAccount, ) -> AppFactory: """Create AppFactory fixture""" arc56_raw_spec = ( Path(__file__).parent.parent / "artifacts" / "testing_app_arc56" / "app_spec.arc56.json" ).read_text() return algorand.client.get_app_factory(app_spec=arc56_raw_spec, default_sender=funded_account.address) def test_create_app(factory: AppFactory) -> None: """Test creating an app using the factory""" app_client, result = factory.send.bare.create( params=AppFactoryCreateParams(), compilation_params={ "deploy_time_params": { # It should strip off the TMPL_ "TMPL_UPDATABLE": 0, "DELETABLE": 0, "VALUE": 1, } }, ) assert app_client.app_id > 0 assert app_client.app_address == get_application_address(app_client.app_id) assert isinstance(result.confirmation, dict) assert result.confirmation.get("application-index", 0) == app_client.app_id assert result.compiled_approval is not None assert result.compiled_clear is not None def test_create_app_with_constructor_deploy_time_params(algorand: AlgorandClient, app_spec: str) -> None: """Test creating an app using the factory with constructor deploy time params""" random_account = algorand.account.random() dispenser_account = algorand.account.localnet_dispenser() algorand.account.ensure_funded( account_to_fund=random_account, dispenser_account=dispenser_account.address, min_spending_balance=AlgoAmount.from_algo(10), min_funding_increment=AlgoAmount.from_algo(1), ) factory = algorand.client.get_app_factory( app_spec=app_spec, default_sender=random_account.address, compilation_params={ "deploy_time_params": { # It should strip off the TMPL_ "TMPL_UPDATABLE": 0, "DELETABLE": 0, "VALUE": 1, } }, ) app_client, result = factory.send.bare.create() assert result.app_id > 0 assert app_client.app_id == result.app_id def test_create_app_with_oncomplete_overload(factory: AppFactory) -> None: app_client, result = factory.send.bare.create( params=AppFactoryCreateParams( on_complete=OnComplete.OptInOC, ), compilation_params={ "updatable": True, "deletable": True, "deploy_time_params": { "VALUE": 1, }, }, ) assert result.transaction.application_call assert result.transaction.application_call.on_complete == OnComplete.OptInOC assert app_client.app_id > 0 assert app_client.app_address == get_application_address(app_client.app_id) assert isinstance(result.confirmation, dict) assert result.confirmation.get("application-index", 0) == app_client.app_id def test_deploy_when_immutable_and_permanent(factory: AppFactory) -> None: factory.deploy( on_schema_break=OnSchemaBreak.Fail, on_update=OnUpdate.Fail, compilation_params={ "deletable": False, "updatable": False, "deploy_time_params": { "VALUE": 1, }, }, ) def test_deploy_app_create(factory: AppFactory) -> None: app_client, deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, }, ) assert deploy_result.operation_performed == OperationPerformed.Create assert deploy_result.create_result assert deploy_result.create_result.app_id > 0 assert app_client.app_id == deploy_result.create_result.app_id assert app_client.app_address == get_application_address(app_client.app_id) def test_deploy_app_create_abi(factory: AppFactory) -> None: app_client, deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, }, create_params=AppClientMethodCallCreateParams(method="create_abi", args=["arg_io"]), ) assert deploy_result.operation_performed == OperationPerformed.Create create_result = deploy_result.create_result assert create_result is not None assert deploy_result.app.app_id > 0 app_index = create_result.confirmation["application-index"] # type: ignore[call-overload] assert app_client.app_id == deploy_result.app.app_id == app_index assert app_client.app_address == get_application_address(app_client.app_id) def test_deploy_app_update(factory: AppFactory) -> None: app_client, create_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, "updatable": True, }, ) assert create_deploy_result.operation_performed == OperationPerformed.Create assert create_deploy_result.create_result updated_app_client, update_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 2, }, }, on_update=OnUpdate.UpdateApp, ) assert update_deploy_result.operation_performed == OperationPerformed.Update assert update_deploy_result.update_result assert create_deploy_result.app.app_id == update_deploy_result.app.app_id assert create_deploy_result.app.app_address == update_deploy_result.app.app_address assert create_deploy_result.create_result.confirmation assert create_deploy_result.app.updatable assert create_deploy_result.app.updatable == update_deploy_result.app.updatable assert create_deploy_result.app.updated_round != update_deploy_result.app.updated_round assert create_deploy_result.app.created_round == update_deploy_result.app.created_round assert update_deploy_result.update_result.confirmation confirmed_round = update_deploy_result.update_result.confirmation["confirmed-round"] # type: ignore[call-overload] assert update_deploy_result.app.updated_round == confirmed_round def test_deploy_app_update_abi(factory: AppFactory) -> None: _, create_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, "updatable": True, }, ) assert create_deploy_result.operation_performed == OperationPerformed.Create assert create_deploy_result.create_result created_app = create_deploy_result.create_result _, update_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 2, }, }, on_update=OnUpdate.UpdateApp, update_params=AppClientMethodCallParams(method="update_abi", args=["args_io"]), ) assert update_deploy_result.operation_performed == OperationPerformed.Update assert update_deploy_result.update_result assert update_deploy_result.app.app_id == created_app.app_id assert update_deploy_result.app.app_address == created_app.app_address assert update_deploy_result.update_result.confirmation is not None assert update_deploy_result.app.created_round == create_deploy_result.app.created_round assert update_deploy_result.app.updated_round != update_deploy_result.app.created_round assert ( update_deploy_result.app.updated_round == update_deploy_result.update_result.confirmation["confirmed-round"] # type: ignore[call-overload] ) assert update_deploy_result.update_result.transaction.application_call assert update_deploy_result.update_result.transaction.application_call.on_complete == OnComplete.UpdateApplicationOC assert update_deploy_result.update_result.abi_return == "args_io" def test_deploy_app_replace(factory: AppFactory) -> None: _, create_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, "deletable": True, }, ) assert create_deploy_result.operation_performed == OperationPerformed.Create assert create_deploy_result.create_result _, replace_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 2, }, }, on_update=OnUpdate.ReplaceApp, ) assert replace_deploy_result.operation_performed == OperationPerformed.Replace assert replace_deploy_result.app.app_id > create_deploy_result.app.app_id assert replace_deploy_result.app.app_address == algosdk.logic.get_application_address( replace_deploy_result.app.app_id ) assert replace_deploy_result.create_result is not None assert replace_deploy_result.delete_result is not None assert replace_deploy_result.delete_result.confirmation is not None assert ( len(replace_deploy_result.create_result.transactions) + len(replace_deploy_result.delete_result.transactions) == 2 ) assert replace_deploy_result.delete_result.transaction.application_call assert replace_deploy_result.delete_result.transaction.application_call.index == create_deploy_result.app.app_id assert ( replace_deploy_result.delete_result.transaction.application_call.on_complete == OnComplete.DeleteApplicationOC ) def test_deploy_app_replace_abi(factory: AppFactory) -> None: _, create_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 1, }, "deletable": True, }, send_params={ "populate_app_call_resources": False, }, ) replaced_app_client, replace_deploy_result = factory.deploy( compilation_params={ "deploy_time_params": { "VALUE": 2, }, "deletable": True, }, on_update=OnUpdate.ReplaceApp, create_params=AppClientMethodCallCreateParams(method="create_abi", args=["arg_io"]), delete_params=AppClientMethodCallParams(method="delete_abi", args=["arg2_io"]), ) assert replace_deploy_result.operation_performed == OperationPerformed.Replace assert replace_deploy_result.app.app_id > create_deploy_result.app.app_id assert replace_deploy_result.app.app_address == algosdk.logic.get_application_address(replaced_app_client.app_id) assert replace_deploy_result.create_result is not None assert replace_deploy_result.delete_result is not None assert replace_deploy_result.delete_result.confirmation is not None assert ( len(replace_deploy_result.create_result.transactions) + len(replace_deploy_result.delete_result.transactions) == 2 ) assert replace_deploy_result.delete_result.transaction.application_call assert replace_deploy_result.delete_result.transaction.application_call.index == create_deploy_result.app.app_id assert ( replace_deploy_result.delete_result.transaction.application_call.on_complete == OnComplete.DeleteApplicationOC ) assert replace_deploy_result.create_result.abi_return == "arg_io" assert replace_deploy_result.delete_result.abi_return == "arg2_io" def test_create_then_call_app(factory: AppFactory) -> None: app_client, _ = factory.send.bare.create( compilation_params={ "updatable": True, "deletable": True, "deploy_time_params": { "VALUE": 1, }, }, ) call = app_client.send.call(AppClientMethodCallParams(method="call_abi", args=["test"])) assert call.abi_return == "Hello, test" def test_call_app_with_rekey(funded_account: SigningAccount, algorand: AlgorandClient, factory: AppFactory) -> None: rekey_to = algorand.account.random() app_client, _ = factory.send.bare.create( compilation_params={ "updatable": True, "deletable": True, "deploy_time_params": { "VALUE": 1, }, }, ) app_client.send.opt_in(AppClientMethodCallParams(method="opt_in", rekey_to=rekey_to.address)) # If the rekey didn't work this will throw rekeyed_account = algorand.account.rekeyed(sender=funded_account.address, account=rekey_to) algorand.send.payment( PaymentParams(amount=AlgoAmount.from_algo(0), sender=rekeyed_account.address, receiver=funded_account.address) ) def test_create_app_with_abi(factory: AppFactory) -> None: _, call_return = factory.send.create( AppFactoryCreateMethodCallParams( method="create_abi", args=["string_io"], ), compilation_params={ "deploy_time_params": { "UPDATABLE": 0, "DELETABLE": 0, "VALUE": 1, }, }, ) assert call_return.abi_return assert call_return.abi_return == "string_io" def test_update_app_with_abi(factory: AppFactory) -> None: deploy_time_params = { "UPDATABLE": 1, "DELETABLE": 0, "VALUE": 1, } app_client, _ = factory.send.bare.create( compilation_params={ "deploy_time_params": deploy_time_params, }, ) call_return = app_client.send.update( AppClientMethodCallParams( method="update_abi", args=["string_io"], ), compilation_params={ "deploy_time_params": deploy_time_params, }, ) assert call_return.abi_return == "string_io" # assert call_return.compiled_approval is not None # TODO: centralize approval/clear compilation def test_delete_app_with_abi(factory: AppFactory) -> None: app_client, _ = factory.send.bare.create( compilation_params={ "deploy_time_params": { "UPDATABLE": 0, "DELETABLE": 1, "VALUE": 1, }, }, ) call_return = app_client.send.delete( AppClientMethodCallParams( method="delete_abi", args=["string_io"], ) ) assert call_return.abi_return == "string_io" def test_export_import_sourcemaps( factory: AppFactory, algorand: AlgorandClient, funded_account: SigningAccount, ) -> None: # Export source maps from original client app_client, _ = factory.deploy(compilation_params={"deploy_time_params": {"VALUE": 1}}) old_sourcemaps = app_client.export_source_maps() # Create new client instance new_client = AppClient( AppClientParams( app_id=app_client.app_id, default_sender=funded_account.address, default_signer=funded_account.signer, algorand=algorand, app_spec=app_client.app_spec, ) ) # Test error handling before importing source maps with pytest.raises(LogicError) as exc_info: new_client.send.call(AppClientMethodCallParams(method="error")) assert "assert failed" in exc_info.value.message # Import source maps into new client new_client.import_source_maps(old_sourcemaps) # Test error handling after importing source maps with pytest.raises(LogicError) as exc_info: new_client.send.call(AppClientMethodCallParams(method="error")) error = exc_info.value assert ( error.trace().strip() == "// error\n\terror_7:\n\tproto 0 0\n\tintc_0 // 0\n\t// Deliberate error\n\tassert\t\t<-- Error\n\tretsub\n\t\n\t// create\n\tcreate_8:" # noqa: E501 ) assert error.pc == 885 assert error.message == "assert failed pc=885" assert len(error.transaction_id) == 52 def test_arc56_error_messages_with_dynamic_template_vars_cblock_offset( arc56_factory: AppFactory, ) -> None: app_client, _ = arc56_factory.deploy( create_params=AppClientMethodCallCreateParams(method="createApplication"), compilation_params={ "deploy_time_params": { "bytes64TmplVar": "0" * 64, "uint64TmplVar": 123, "bytes32TmplVar": "0" * 32, "bytesTmplVar": "foo", }, }, ) with pytest.raises(Exception, match="this is an error"): app_client.send.call(AppClientMethodCallParams(method="throwError")) def test_arc56_undefined_error_message_with_dynamic_template_vars_cblock_offset( arc56_factory: AppFactory, algorand: AlgorandClient, funded_account: SigningAccount, ) -> None: # Deploy app with template parameters app_client, _ = arc56_factory.deploy( create_params=AppClientMethodCallCreateParams(method="createApplication"), compilation_params={ "deploy_time_params": { "bytes64TmplVar": "0" * 64, "uint64TmplVar": 0, "bytes32TmplVar": "0" * 32, "bytesTmplVar": "foo", }, }, ) app_id = app_client.app_id # Create new client without source map from compilation app_client = AppClient( AppClientParams( app_id=app_id, default_sender=funded_account.address, default_signer=funded_account.signer, algorand=algorand, app_spec=app_client.app_spec, ) ) # Test error handling with pytest.raises(LogicError) as exc_info: app_client.send.call(AppClientMethodCallParams(method="tmpl")) assert ( exc_info.value.trace().strip() == "// tests/example-contracts/arc56_templates/templates.algo.ts:14\n\t\t// assert(this.uint64TmplVar)\n\t\tintc 1 // TMPL_uint64TmplVar\n\t\tassert\n\t\tretsub\t\t<-- Error\n\t\n\t// specificLengthTemplateVar()void\n\t*abi_route_specificLengthTemplateVar:\n\t\t// execute specificLengthTemplateVar()void" # noqa: E501 )
algorandfoundation/algokit-utils-py
tests/applications/test_app_factory.py
Python
MIT
19,701
import pytest from algokit_utils.algorand import AlgorandClient from algokit_utils.applications.app_manager import AppManager from algokit_utils.models.account import SigningAccount from algokit_utils.models.amount import AlgoAmount from tests.conftest import check_output_stability @pytest.fixture def algorand() -> AlgorandClient: return AlgorandClient.default_localnet() @pytest.fixture def funded_account(algorand: AlgorandClient) -> SigningAccount: new_account = algorand.account.random() dispenser = algorand.account.localnet_dispenser() algorand.account.ensure_funded( new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1) ) algorand.set_signer(sender=new_account.address, signer=new_account.signer) return new_account def test_template_substitution() -> None: program = """ test TMPL_INT // TMPL_INT test TMPL_INT no change test TMPL_STR // TMPL_STR TMPL_STR TMPL_STR // TMPL_INT TMPL_STR // foo // TMPL_STR // bar test "TMPL_STR" // not replaced test "TMPL_STRING" // not replaced test TMPL_STRING // not replaced test TMPL_STRI // not replaced test TMPL_STR TMPL_INT TMPL_INT TMPL_STR // TMPL_STR TMPL_INT TMPL_INT TMPL_STR test TMPL_INT TMPL_STR TMPL_STRING "TMPL_INT TMPL_STR TMPL_STRING" //TMPL_INT TMPL_STR TMPL_STRING test TMPL_INT TMPL_INT TMPL_STRING TMPL_STRING TMPL_STRING TMPL_INT TMPL_STRING //keep TMPL_STR TMPL_STR TMPL_STR TMPL_STRING test NOTTMPL_STR // not replaced NOTTMPL_STR // not replaced TMPL_STR // replaced """ result = AppManager.replace_template_variables(program, {"INT": 123, "STR": "ABC"}) check_output_stability(result) def test_comment_stripping() -> None: program = r""" //comment op arg //comment op "arg" //comment op "//" //comment op " //comment " //comment op "\" //" //comment op "// \" //" //comment op "" //comment // op 123 op 123 // something op "" // more comments op "//" //op "//" op "//" pushbytes base64(//8=) pushbytes b64(//8=) pushbytes base64(//8=) // pushbytes base64(//8=) pushbytes b64(//8=) // pushbytes b64(//8=) pushbytes "base64(//8=)" // pushbytes "base64(//8=)" pushbytes "b64(//8=)" // pushbytes "b64(//8=)" pushbytes base64 //8= pushbytes b64 //8= pushbytes base64 //8= // pushbytes base64 //8= pushbytes b64 //8= // pushbytes b64 //8= pushbytes "base64 //8=" // pushbytes "base64 //8=" pushbytes "b64 //8=" // pushbytes "b64 //8=" """ result = AppManager.strip_teal_comments(program) check_output_stability(result)
algorandfoundation/algokit-utils-py
tests/applications/test_app_manager.py
Python
MIT
2,528
import json from pathlib import Path from algokit_utils.applications.app_spec.arc56 import Arc56Contract from tests.conftest import check_output_stability from tests.utils import load_app_spec TEST_ARC32_SPEC_FILE_PATH = Path(__file__).parent.parent / "artifacts" / "hello_world" / "app_spec.arc32.json" TEST_ARC56_SPEC_FILE_PATH = Path(__file__).parent.parent / "artifacts" / "amm_arc56_example" / "amm.arc56.json" def test_arc56_from_arc32_json() -> None: arc56_app_spec = Arc56Contract.from_arc32(TEST_ARC32_SPEC_FILE_PATH.read_text()) assert arc56_app_spec check_output_stability(arc56_app_spec.to_json(indent=4)) def test_arc56_from_arc32_instance() -> None: arc32_app_spec = load_app_spec( TEST_ARC32_SPEC_FILE_PATH, arc=32, deletable=True, updatable=True, template_values={"VERSION": 1} ) arc56_app_spec = Arc56Contract.from_arc32(arc32_app_spec) assert arc56_app_spec check_output_stability(arc56_app_spec.to_json(indent=4)) def test_arc56_from_json() -> None: arc56_app_spec = Arc56Contract.from_json(TEST_ARC56_SPEC_FILE_PATH.read_text()) assert arc56_app_spec check_output_stability(arc56_app_spec.to_json(indent=4)) def test_arc56_from_dict() -> None: arc56_app_spec = Arc56Contract.from_dict(json.loads(TEST_ARC56_SPEC_FILE_PATH.read_text())) assert arc56_app_spec check_output_stability(arc56_app_spec.to_json(indent=4))
algorandfoundation/algokit-utils-py
tests/applications/test_arc56.py
Python
MIT
1,418