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 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 74