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
|
---|---|---|---|---|---|
from algopy import (
ARC4Contract,
BigUInt,
Global,
UInt64,
arc4,
ensure_budget,
itxn,
op,
urange,
)
class InnerFeeContract(ARC4Contract):
@arc4.abimethod
def burn_ops(self, op_budget: UInt64) -> None:
# Uses approx 60 op budget per iteration
count = op_budget // 60
ensure_budget(op_budget)
for i in urange(count):
sqrt = op.bsqrt(BigUInt(i))
assert sqrt >= 0 # Prevent optimiser removing the sqrt
@arc4.abimethod
def no_op(self) -> None:
pass
@arc4.abimethod
def send_x_inners_with_fees(self, app_id: UInt64, fees: arc4.DynamicArray[arc4.UInt64]) -> None:
for fee in fees:
arc4.abi_call("no_op", app_id=app_id, fee=fee.native)
@arc4.abimethod
def send_inners_with_fees(
self,
app_id_1: UInt64,
app_id_2: UInt64,
fees: arc4.Tuple[arc4.UInt64, arc4.UInt64, arc4.UInt64, arc4.UInt64, arc4.DynamicArray[arc4.UInt64]],
) -> None:
arc4.abi_call("no_op", app_id=app_id_1, fee=fees[0].native)
arc4.abi_call("no_op", app_id=app_id_1, fee=fees[1].native)
itxn.Payment(amount=0, receiver=Global.current_application_address, fee=fees[2].native).submit()
arc4.abi_call("send_x_inners_with_fees", app_id_2, fees[4], app_id=app_id_1, fee=fees[3].native)
@arc4.abimethod
def send_inners_with_fees_2(
self,
app_id_1: UInt64,
app_id_2: UInt64,
fees: arc4.Tuple[
arc4.UInt64,
arc4.UInt64,
arc4.DynamicArray[arc4.UInt64],
arc4.UInt64,
arc4.UInt64,
arc4.DynamicArray[arc4.UInt64],
],
) -> None:
arc4.abi_call("no_op", app_id=app_id_1, fee=fees[0].native)
arc4.abi_call("send_x_inners_with_fees", app_id_2, fees[2], app_id=app_id_1, fee=fees[1].native)
arc4.abi_call("no_op", app_id=app_id_1, fee=fees[3].native)
arc4.abi_call("send_x_inners_with_fees", app_id_2, fees[5], app_id=app_id_1, fee=fees[4].native)
| algorandfoundation/algokit-utils-py | tests/artifacts/inner-fee/contract.py | Python | MIT | 2,073 |
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 | tests/artifacts/legacy_app_client_test/app_client_test.py | Python | MIT | 5,773 |
from typing import Literal
import beaker
import pyteal as pt
from beaker.lib.storage import BoxMapping
from pyteal.ast import CallConfig, MethodConfig
UPDATABLE_TEMPLATE_NAME = "TMPL_UPDATABLE"
DELETABLE_TEMPLATE_NAME = "TMPL_DELETABLE"
class BareCallAppState:
value = beaker.GlobalStateValue(stack_type=pt.TealType.uint64)
bytes1 = beaker.GlobalStateValue(stack_type=pt.TealType.bytes)
bytes2 = beaker.GlobalStateValue(stack_type=pt.TealType.bytes)
int1 = beaker.GlobalStateValue(stack_type=pt.TealType.uint64)
int2 = beaker.GlobalStateValue(stack_type=pt.TealType.uint64)
local_bytes1 = beaker.LocalStateValue(stack_type=pt.TealType.bytes)
local_bytes2 = beaker.LocalStateValue(stack_type=pt.TealType.bytes)
local_int1 = beaker.LocalStateValue(stack_type=pt.TealType.uint64)
local_int2 = beaker.LocalStateValue(stack_type=pt.TealType.uint64)
box = BoxMapping(pt.abi.StaticBytes[Literal[4]], pt.abi.String)
app = beaker.Application("TestingApp", state=BareCallAppState)
@app.external(read_only=True)
def call_abi(value: pt.abi.String, *, output: pt.abi.String) -> pt.Expr:
return output.set(pt.Concat(pt.Bytes("Hello, "), value.get()))
# https://github.com/algorand/pyteal-utils/blob/main/pytealutils/strings/string.py#L63
@pt.Subroutine(pt.TealType.bytes)
def itoa(i: pt.Expr) -> pt.Expr:
"""itoa converts an integer to the ascii byte string it represents"""
return pt.If(
i == pt.Int(0),
pt.Bytes("0"),
pt.Concat(
pt.If(i / pt.Int(10) > pt.Int(0), itoa(i / pt.Int(10)), pt.Bytes("")),
pt.Extract(pt.Bytes("0123456789"), i % pt.Int(10), pt.Int(1)),
),
)
@app.external()
def call_abi_txn(txn: pt.abi.PaymentTransaction, value: pt.abi.String, *, output: pt.abi.String) -> pt.Expr:
return output.set(
pt.Concat(
pt.Bytes("Sent "),
itoa(txn.get().amount()),
pt.Bytes(". "),
value.get(),
)
)
@app.external(read_only=True)
def call_abi_foreign_refs(*, output: pt.abi.String) -> pt.Expr:
return output.set(
pt.Concat(
pt.Bytes("App: "),
itoa(pt.Txn.applications[1]),
pt.Bytes(", Asset: "),
itoa(pt.Txn.assets[0]),
pt.Bytes(", Account: "),
itoa(pt.GetByte(pt.Txn.accounts[0], pt.Int(0))),
pt.Bytes(":"),
itoa(pt.GetByte(pt.Txn.accounts[0], pt.Int(1))),
)
)
@app.external()
def set_global(
int1: pt.abi.Uint64, int2: pt.abi.Uint64, bytes1: pt.abi.String, bytes2: pt.abi.StaticBytes[Literal[4]]
) -> pt.Expr:
return pt.Seq(
app.state.int1.set(int1.get()),
app.state.int2.set(int2.get()),
app.state.bytes1.set(bytes1.get()),
app.state.bytes2.set(bytes2.get()),
)
@app.external()
def set_local(
int1: pt.abi.Uint64, int2: pt.abi.Uint64, bytes1: pt.abi.String, bytes2: pt.abi.StaticBytes[Literal[4]]
) -> pt.Expr:
return pt.Seq(
app.state.local_int1.set(int1.get()),
app.state.local_int2.set(int2.get()),
app.state.local_bytes1.set(bytes1.get()),
app.state.local_bytes2.set(bytes2.get()),
)
@app.external()
def set_box(name: pt.abi.StaticBytes[Literal[4]], value: pt.abi.String) -> pt.Expr:
return app.state.box[name.get()].set(value.get())
@app.external()
def error() -> pt.Expr:
return pt.Assert(pt.Int(0), comment="Deliberate error")
@app.external(
authorize=beaker.Authorize.only_creator(),
bare=True,
method_config=MethodConfig(no_op=CallConfig.CREATE, opt_in=CallConfig.CREATE),
)
def create() -> pt.Expr:
return app.state.value.set(pt.Tmpl.Int("TMPL_VALUE"))
@app.create(authorize=beaker.Authorize.only_creator())
def create_abi(input: pt.abi.String, *, output: pt.abi.String) -> pt.Expr:
return output.set(input.get())
@app.update(authorize=beaker.Authorize.only_creator(), bare=True)
def update() -> pt.Expr:
return pt.Assert(pt.Tmpl.Int(UPDATABLE_TEMPLATE_NAME), comment="Check app is updatable")
@app.update(authorize=beaker.Authorize.only_creator())
def update_abi(input: pt.abi.String, *, output: pt.abi.String) -> pt.Expr:
return pt.Seq(
pt.Assert(pt.Tmpl.Int(UPDATABLE_TEMPLATE_NAME), comment="Check app is updatable"), output.set(input.get())
)
@app.delete(authorize=beaker.Authorize.only_creator(), bare=True)
def delete() -> pt.Expr:
return pt.Assert(pt.Tmpl.Int(DELETABLE_TEMPLATE_NAME), comment="Check app is deletable")
@app.delete(authorize=beaker.Authorize.only_creator())
def delete_abi(input: pt.abi.String, *, output: pt.abi.String) -> pt.Expr:
return pt.Seq(
pt.Assert(pt.Tmpl.Int(DELETABLE_TEMPLATE_NAME), comment="Check app is deletable"), output.set(input.get())
)
@app.opt_in
def opt_in() -> pt.Expr:
return pt.Approve()
@app.external(read_only=True)
def default_value(
arg_with_default: pt.abi.String = "default value",
*,
output: pt.abi.String, # type: ignore[assignment]
) -> pt.Expr:
return output.set(arg_with_default.get())
@app.external(read_only=True)
def default_value_from_abi(
arg_with_default: pt.abi.String = default_value,
*,
output: pt.abi.String, # type: ignore[assignment]
) -> pt.Expr:
return output.set(pt.Concat(pt.Bytes("ABI, "), arg_with_default.get()))
@app.external(read_only=True)
def default_value_from_global_state(
arg_with_default: pt.abi.Uint64 = BareCallAppState.int1,
*,
output: pt.abi.Uint64, # type: ignore[assignment]
) -> pt.Expr:
return output.set(arg_with_default.get())
@app.external(read_only=True)
def default_value_from_local_state(
arg_with_default: pt.abi.String = BareCallAppState.local_bytes1,
*,
output: pt.abi.String, # type: ignore[assignment]
) -> pt.Expr:
return output.set(pt.Concat(pt.Bytes("Local state, "), arg_with_default.get()))
| algorandfoundation/algokit-utils-py | tests/artifacts/testing_app/contract.py | Python | MIT | 5,883 |
from typing import Literal
from algopy import ARC4Contract, BoxMap, Bytes, arc4, op
class DummyStruct(arc4.Struct):
name: arc4.String
id: arc4.UInt64
class TestPuyaBoxes(ARC4Contract):
def __init__(self) -> None:
self.box_bytes = BoxMap(arc4.String, Bytes)
self.box_bytes2 = BoxMap(Bytes, Bytes)
self.box_str = BoxMap(arc4.String, arc4.String)
self.box_int = BoxMap(arc4.String, arc4.UInt32)
self.box_int512 = BoxMap(arc4.String, arc4.UInt512)
self.box_static = BoxMap(arc4.String, arc4.StaticArray[arc4.Byte, Literal[4]])
@arc4.abimethod
def set_box_bytes(self, name: arc4.String, value: Bytes) -> None:
self.box_bytes[name] = value
@arc4.abimethod
def set_box_str(self, name: arc4.String, value: arc4.String) -> None:
self.box_str[name] = value
@arc4.abimethod
def set_box_int(self, name: arc4.String, value: arc4.UInt32) -> None:
self.box_int[name] = value
@arc4.abimethod
def set_box_int512(self, name: arc4.String, value: arc4.UInt512) -> None:
self.box_int512[name] = value
@arc4.abimethod
def set_box_static(self, name: arc4.String, value: arc4.StaticArray[arc4.Byte, Literal[4]]) -> None:
self.box_static[name] = value.copy()
@arc4.abimethod()
def set_struct(self, name: arc4.String, value: DummyStruct) -> None:
assert name.bytes == value.name.bytes, "Name must match id of struct"
op.Box.put(name.bytes, value.bytes)
| algorandfoundation/algokit-utils-py | tests/artifacts/testing_app_puya/contract.py | Python | MIT | 1,502 |
algorandfoundation/algokit-utils-py | tests/assets/__init__.py | Python | MIT | 0 |
|
import pytest
from algosdk.atomic_transaction_composer import AccountTransactionSigner
from algokit_utils import SigningAccount
from algokit_utils.algorand import AlgorandClient
from algokit_utils.assets.asset_manager import (
AccountAssetInformation,
AssetInformation,
BulkAssetOptInOutResult,
)
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AssetCreateParams,
PaymentParams,
)
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def sender(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
@pytest.fixture
def receiver(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
return new_account
def test_get_by_id(algorand: AlgorandClient, sender: SigningAccount) -> None:
# First create an asset
total = 1000
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then get its info
asset_info = algorand.asset.get_by_id(asset_id)
assert isinstance(asset_info, AssetInformation)
assert asset_info.asset_id == asset_id
assert asset_info.total == total
assert asset_info.decimals == 0
assert asset_info.default_frozen is False
assert asset_info.unit_name == "TEST"
assert asset_info.asset_name == "Test Asset"
assert asset_info.url == "https://example.com"
assert asset_info.creator == sender.address
def test_get_account_information_with_address(algorand: AlgorandClient, sender: SigningAccount) -> None:
# First create an asset
total = 1000
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then get account info
account_info = algorand.asset.get_account_information(sender.address, asset_id)
assert isinstance(account_info, AccountAssetInformation)
assert account_info.asset_id == asset_id
assert account_info.balance == total
assert account_info.frozen is False
def test_get_account_information_with_account(algorand: AlgorandClient, sender: SigningAccount) -> None:
# First create an asset
total = 1000
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then get account info
account_info = algorand.asset.get_account_information(sender, asset_id)
assert isinstance(account_info, AccountAssetInformation)
assert account_info.asset_id == asset_id
assert account_info.balance == total
assert account_info.frozen is False
def test_get_account_information_with_transaction_signer(algorand: AlgorandClient, sender: SigningAccount) -> None:
# First create an asset
total = 1000
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then get account info using transaction signer
signer = AccountTransactionSigner(sender.private_key)
account_info = algorand.asset.get_account_information(signer, asset_id)
assert isinstance(account_info, AccountAssetInformation)
assert account_info.asset_id == asset_id
assert account_info.balance == total
assert account_info.frozen is False
def test_bulk_opt_in_with_address(algorand: AlgorandClient, sender: SigningAccount, receiver: SigningAccount) -> None:
# First create some assets
asset_ids = []
for i in range(3):
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
unit_name=f"TST{i}",
asset_name=f"Test Asset {i}",
url="https://example.com",
signer=sender.signer,
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
asset_ids.append(asset_id)
# Fund receiver
algorand.send.payment(
PaymentParams(
sender=sender.address,
receiver=receiver.address,
amount=AlgoAmount.from_algos(1),
)
)
# Then bulk opt-in
results = algorand.asset.bulk_opt_in(receiver.address, asset_ids, signer=receiver.signer)
assert len(results) == len(asset_ids)
for result in results:
assert isinstance(result, BulkAssetOptInOutResult)
assert result.asset_id in asset_ids
assert result.transaction_id
def test_bulk_opt_out_not_opted_in_fails(
algorand: AlgorandClient, sender: SigningAccount, receiver: SigningAccount
) -> None:
# First create an asset
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Fund receiver but don't opt-in
algorand.send.payment(
PaymentParams(
sender=sender.address,
receiver=receiver.address,
amount=AlgoAmount.from_algos(1),
)
)
# Then attempt to opt-out
with pytest.raises(ValueError, match="is not opted-in"):
algorand.asset.bulk_opt_out(account=receiver.address, asset_ids=[asset_id])
| algorandfoundation/algokit-utils-py | tests/assets/test_asset_manager.py | Python | MIT | 7,241 |
algorandfoundation/algokit-utils-py | tests/clients/__init__.py | Python | MIT | 0 |
|
algorandfoundation/algokit-utils-py | tests/clients/algorand_client/__init__.py | Python | MIT | 0 |
|
import httpx
import pytest
from pytest_httpx._httpx_mock import HTTPXMock
from algokit_utils.algorand import AlgorandClient
from algokit_utils.clients.dispenser_api_client import DispenserApiConfig, TestNetDispenserApiClient
from algokit_utils.models.account import SigningAccount
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AssetOptInParams,
AssetTransferParams,
PaymentParams,
)
from tests.conftest import generate_test_asset
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
def test_transfer_algo_is_sent_and_waited_for(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
second_account = algorand.account.random()
result = algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=second_account.address,
amount=AlgoAmount.from_algos(5),
note=b"Transfer 5 Algos",
)
)
account_info = algorand.account.get_information(second_account)
assert result.transaction.payment
assert result.transaction.payment.amt == 5_000_000
assert result.transaction.payment.sender == funded_account.address == result.confirmation["txn"]["txn"]["snd"] # type: ignore # noqa: PGH003
assert account_info.amount == 5_000_000
def test_transfer_algo_respects_string_lease(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
second_account = algorand.account.random()
algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=second_account.address,
amount=AlgoAmount.from_algos(1),
lease=b"test",
)
)
with pytest.raises(Exception, match="overlapping lease"):
algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=second_account.address,
amount=AlgoAmount.from_algos(2),
lease=b"test",
)
)
def test_transfer_algo_respects_byte_array_lease(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
second_account = algorand.account.random()
algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=second_account.address,
amount=AlgoAmount.from_algos(1),
lease=b"\x01\x02\x03\x04",
)
)
with pytest.raises(Exception, match="overlapping lease"):
algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=second_account.address,
amount=AlgoAmount.from_algos(2),
lease=b"\x01\x02\x03\x04",
)
)
def test_transfer_asa_respects_lease(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
test_asset_id = generate_test_asset(algorand, funded_account, 100)
second_account = algorand.account.random()
algorand.account.ensure_funded(
account_to_fund=second_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
algorand.send.asset_opt_in(
AssetOptInParams(
sender=second_account.address,
asset_id=test_asset_id,
)
)
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=test_asset_id,
amount=1,
lease=b"test",
)
)
with pytest.raises(Exception, match="overlapping lease"):
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=test_asset_id,
amount=2,
lease=b"test",
)
)
def test_transfer_asa_receiver_not_opted_in(
algorand: AlgorandClient,
funded_account: SigningAccount,
) -> None:
test_asset_id = generate_test_asset(algorand, funded_account, 100)
second_account = algorand.account.random()
with pytest.raises(Exception, match="receiver error: must optin"):
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=test_asset_id,
amount=1,
note=b"Transfer 5 assets with id %d" % test_asset_id,
)
)
def test_transfer_asa_sender_not_opted_in(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
test_asset_id = generate_test_asset(algorand, funded_account, 100)
second_account = algorand.account.random()
algorand.account.ensure_funded(
account_to_fund=second_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
with pytest.raises(Exception, match=f"asset {test_asset_id} missing from {second_account.address}"):
algorand.send.asset_transfer(
AssetTransferParams(
sender=second_account.address,
receiver=funded_account.address,
asset_id=test_asset_id,
amount=1,
note=b"Transfer 5 assets with id %d" % test_asset_id,
)
)
def test_transfer_asa_asset_doesnt_exist(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
second_account = algorand.account.random()
algorand.account.ensure_funded(
account_to_fund=second_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
with pytest.raises(Exception, match=f"asset 123123 missing from {funded_account.address}"):
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=123123,
amount=5,
note=b"Transfer asset with wrong id",
)
)
def test_transfer_asa_to_another_account(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
test_asset_id = generate_test_asset(algorand, funded_account, 100)
second_account = algorand.account.random()
algorand.account.ensure_funded(
account_to_fund=second_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
with pytest.raises(Exception, match="account asset info not found"):
algorand.asset.get_account_information(second_account, test_asset_id)
algorand.send.asset_opt_in(
AssetOptInParams(
sender=second_account.address,
asset_id=test_asset_id,
)
)
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=test_asset_id,
amount=5,
note=b"Transfer 5 assets with id %d" % test_asset_id,
)
)
second_account_info = algorand.asset.get_account_information(second_account, test_asset_id)
assert second_account_info.balance == 5
test_account_info = algorand.asset.get_account_information(funded_account, test_asset_id)
assert test_account_info.balance == 95
def test_transfer_asa_from_revocation_target(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
test_asset_id = generate_test_asset(algorand, funded_account, 100)
second_account = algorand.account.random()
clawback_account = algorand.account.random()
algorand.account.ensure_funded(
account_to_fund=second_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
algorand.account.ensure_funded(
account_to_fund=clawback_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
algorand.send.asset_opt_in(
AssetOptInParams(
sender=second_account.address,
asset_id=test_asset_id,
)
)
algorand.send.asset_opt_in(
AssetOptInParams(
sender=clawback_account.address,
asset_id=test_asset_id,
)
)
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=clawback_account.address,
asset_id=test_asset_id,
amount=5,
note=b"Transfer 5 assets with id %d" % test_asset_id,
)
)
clawback_from_info = algorand.asset.get_account_information(clawback_account, test_asset_id)
assert clawback_from_info.balance == 5
algorand.send.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=second_account.address,
asset_id=test_asset_id,
amount=5,
note=b"Transfer 5 assets with id %d" % test_asset_id,
clawback_target=clawback_account.address,
)
)
second_account_info = algorand.asset.get_account_information(second_account, test_asset_id)
assert second_account_info.balance == 5
clawback_account_info = algorand.asset.get_account_information(clawback_account, test_asset_id)
assert clawback_account_info.balance == 0
test_account_info = algorand.asset.get_account_information(funded_account, test_asset_id)
assert test_account_info.balance == 95
MINIMUM_BALANCE = AlgoAmount.from_micro_algos(
100_000
) # see https://developer.algorand.org/docs/get-details/accounts/#minimum-balance
def test_ensure_funded(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
test_account = algorand.account.random()
response = algorand.account.ensure_funded(
account_to_fund=test_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_algos(1),
)
assert response is not None
to_account_info = algorand.account.get_information(test_account)
assert to_account_info.amount == MINIMUM_BALANCE + AlgoAmount.from_algos(1)
def test_ensure_funded_uses_dispenser_by_default(
algorand: AlgorandClient,
) -> None:
second_account = algorand.account.random()
dispenser = algorand.account.dispenser_from_environment()
result = algorand.account.ensure_funded_from_environment(
account_to_fund=second_account,
min_spending_balance=AlgoAmount.from_algos(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
assert result is not None
assert result.transaction.payment is not None
assert result.transaction.payment.sender == dispenser.address
account_info = algorand.account.get_information(second_account)
assert account_info.amount == MINIMUM_BALANCE + AlgoAmount.from_algos(1)
def test_ensure_funded_respects_minimum_funding_increment(
algorand: AlgorandClient, funded_account: SigningAccount
) -> None:
test_account = algorand.account.random()
response = algorand.account.ensure_funded(
account_to_fund=test_account,
dispenser_account=funded_account,
min_spending_balance=AlgoAmount.from_micro_algo(1),
min_funding_increment=AlgoAmount.from_algos(1),
)
assert response is not None
to_account_info = algorand.account.get_information(test_account)
assert to_account_info.amount == AlgoAmount.from_algos(1)
def test_ensure_funded_testnet_api_success(monkeypatch: pytest.MonkeyPatch, httpx_mock: HTTPXMock) -> None:
algorand = AlgorandClient.testnet()
account_to_fund = algorand.account.random()
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"},
)
result = algorand.account.ensure_funded_from_testnet_dispenser_api(
account_to_fund=account_to_fund,
dispenser_client=TestNetDispenserApiClient(),
min_spending_balance=AlgoAmount.from_micro_algo(1),
)
assert result is not None
assert result.transaction_id == "dummy_tx_id"
assert result.amount_funded == AlgoAmount.from_micro_algo(1)
def test_ensure_funded_testnet_api_bad_response(monkeypatch: pytest.MonkeyPatch, httpx_mock: HTTPXMock) -> None:
algorand = AlgorandClient.testnet()
account_to_fund = algorand.account.random()
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",
)
with pytest.raises(Exception, match="fund_limit_exceeded"):
algorand.account.ensure_funded_from_testnet_dispenser_api(
account_to_fund=account_to_fund,
dispenser_client=TestNetDispenserApiClient(),
min_spending_balance=AlgoAmount.from_micro_algo(1),
)
def test_rekey_works(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
second_account = algorand.account.random()
algorand.account.rekey_account(funded_account.address, second_account, note=b"rekey")
# This will throw if the rekey wasn't successful
algorand.send.payment(
PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(1),
signer=second_account.signer,
)
)
| algorandfoundation/algokit-utils-py | tests/clients/algorand_client/test_transfer.py | Python | MIT | 14,942 |
import inspect
import math
import random
import subprocess
from pathlib import Path
from typing import TYPE_CHECKING
from uuid import uuid4
import pytest
from dotenv import load_dotenv
from algokit_utils import (
ApplicationClient,
ApplicationSpecification,
SigningAccount,
replace_template_variables,
)
from algokit_utils.algorand import AlgorandClient
from algokit_utils.applications.app_manager import DELETABLE_TEMPLATE_NAME, UPDATABLE_TEMPLATE_NAME
from algokit_utils.transactions.transaction_composer import AssetCreateParams
if TYPE_CHECKING:
pass
@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 / "_snapshots" / 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)
def generate_test_asset(algorand: AlgorandClient, sender: SigningAccount, 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}"
create_result = algorand.send.asset_create(
AssetCreateParams(
sender=sender.address,
total=total,
decimals=decimals,
default_frozen=False,
unit_name="CFG",
asset_name=asset_name,
url="https://example.com",
manager=sender.address,
reserve=sender.address,
freeze=sender.address,
clawback=sender.address,
)
)
return int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
| algorandfoundation/algokit-utils-py | tests/conftest.py | Python | MIT | 4,824 |
from decimal import Decimal
import pytest
from algokit_utils.models.amount import ALGORAND_MIN_TX_FEE, AlgoAmount, algo, micro_algo, transaction_fees
def test_initialization() -> None:
# Test valid initialization formats
assert AlgoAmount(micro_algos=1_000_000).micro_algos == 1_000_000
assert AlgoAmount(micro_algo=500_000).micro_algos == 500_000
assert AlgoAmount(algos=1).micro_algos == 1_000_000
assert AlgoAmount(algo=Decimal("0.5")).micro_algos == 500_000
# Test decimal precision
assert AlgoAmount(algos=Decimal("0.000001")).micro_algos == 1
assert AlgoAmount(algo=Decimal("123.456789")).micro_algos == 123_456_789
def test_from_methods() -> None:
assert AlgoAmount.from_micro_algos(500_000).micro_algos == 500_000
assert AlgoAmount.from_micro_algo(250_000).micro_algos == 250_000
assert AlgoAmount.from_algos(2).micro_algos == 2_000_000
assert AlgoAmount.from_algo(Decimal("0.75")).micro_algos == 750_000
def test_properties() -> None:
amount = AlgoAmount.from_micro_algos(1_234_567)
assert amount.micro_algos == 1_234_567
assert amount.micro_algo == 1_234_567
assert amount.algos == Decimal("1.234567")
assert amount.algo == Decimal("1.234567")
def test_arithmetic_operations() -> None:
a = AlgoAmount.from_algos(5)
b = AlgoAmount.from_algos(3)
# Addition
assert (a + b).micro_algos == 8_000_000
a += b
assert a.micro_algos == 8_000_000
# Subtraction
assert (a - b).micro_algos == 5_000_000
a -= b
assert a.micro_algos == 5_000_000
# Right operations
assert (AlgoAmount.from_micro_algo(1000) + a).micro_algos == 5_001_000
assert (AlgoAmount.from_algos(10) - a).micro_algos == 5_000_000
def test_comparison_operators() -> None:
base = AlgoAmount.from_algos(5)
same = AlgoAmount.from_algos(5)
larger = AlgoAmount.from_algos(10)
assert base == same
assert base != larger
assert base < larger
assert larger > base
assert base <= same
assert larger >= base
# Test int comparison
assert base == 5_000_000
assert base < 6_000_000
assert base > 4_000_000
def test_edge_cases() -> None:
# Zero value
zero = AlgoAmount.from_micro_algos(0)
assert zero.micro_algos == 0
assert zero.algos == 0
# Very large values
large = AlgoAmount.from_algos(Decimal("1e9"))
assert large.micro_algos == 1e9 * 1e6
# Decimal precision limits
precise = AlgoAmount(algos=Decimal("0.123456789"))
assert precise.micro_algos == 123_456
def test_string_representation() -> None:
assert str(AlgoAmount.from_micro_algos(1_000_000)) == "1,000,000 µALGO"
assert str(AlgoAmount.from_algos(Decimal("2.5"))) == "2,500,000 µALGO"
def test_type_safety() -> None:
with pytest.raises(TypeError, match="Unsupported operand type"):
# int is not AlgoAmount
AlgoAmount.from_algos(5) + 1000 # type: ignore # noqa: PGH003
with pytest.raises(TypeError, match="Unsupported operand type"):
AlgoAmount.from_algos(5) - "invalid" # type: ignore # noqa: PGH003
def test_helper_functions() -> None:
assert algo(1).micro_algos == 1_000_000
assert micro_algo(1_000_000).micro_algos == 1_000_000
assert ALGORAND_MIN_TX_FEE.micro_algos == 1_000
assert transaction_fees(1).micro_algos == 1_000
| algorandfoundation/algokit-utils-py | tests/models/test_algo_amount.py | Python | MIT | 3,340 |
import json
import os
from collections.abc import Generator
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from algosdk.abi.method import Method
from algosdk.atomic_transaction_composer import (
AccountTransactionSigner,
AtomicTransactionComposer,
TransactionWithSigner,
)
from algosdk.transaction import PaymentTxn
from algokit_utils._debugging import (
PersistSourceMapInput,
cleanup_old_trace_files,
persist_sourcemaps,
simulate_and_persist_response,
)
from algokit_utils.algorand import AlgorandClient
from algokit_utils.applications import AppFactoryCreateMethodCallParams
from algokit_utils.applications.app_client import AppClient, AppClientMethodCallParams
from algokit_utils.common import Program
from algokit_utils.models import SigningAccount
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AppCallMethodCallParams,
AssetCreateParams,
AssetTransferParams,
PaymentParams,
)
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account,
dispenser,
min_spending_balance=AlgoAmount.from_algo(100),
min_funding_increment=AlgoAmount.from_algo(100),
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
@pytest.fixture
def client_fixture(algorand: AlgorandClient, funded_account: SigningAccount) -> AppClient:
app_spec = (Path(__file__).parent / "artifacts" / "legacy_app_client_test" / "app_client_test.json").read_text()
app_factory = algorand.client.get_app_factory(
app_spec=app_spec, default_sender=funded_account.address, default_signer=funded_account.signer
)
app_client, _ = app_factory.send.create(
AppFactoryCreateMethodCallParams(method="create"),
compilation_params={
"deletable": True,
"updatable": True,
"deploy_time_params": {"VERSION": 1},
},
)
return app_client
@pytest.fixture
def mock_config() -> Generator[Mock, None, None]:
with patch("algokit_utils.transactions.transaction_composer.config", new_callable=Mock) as mock_config:
mock_config.debug = True
mock_config.project_root = None
yield mock_config
def test_build_teal_sourcemaps(algorand: AlgorandClient, 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=algorand.client.algod)
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_build_teal_sourcemaps_without_sources(
algorand: AlgorandClient, 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, algorand.client.algod)
compiled_clear = Program(clear, algorand.client.algod)
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=algorand.client.algod, 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_simulate_and_persist_response_via_app_call(
tmp_path_factory: pytest.TempPathFactory,
client_fixture: AppClient,
mock_config: Mock,
) -> None:
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.send.call(AppClientMethodCallParams(method="hello", args=["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_simulate_and_persist_response(
tmp_path_factory: pytest.TempPathFactory,
algorand: AlgorandClient,
mock_config: Mock,
funded_account: SigningAccount,
) -> None:
mock_config.debug = True
mock_config.trace_all = True
cwd = tmp_path_factory.mktemp("cwd")
mock_config.project_root = cwd
algod = algorand.client.algod
payment = PaymentTxn(
sender=funded_account.address,
receiver=funded_account.address,
amt=1_000_000,
note=b"Payment",
sp=algod.suggested_params(),
)
txn_with_signer = TransactionWithSigner(payment, AccountTransactionSigner(funded_account.private_key))
atc = AtomicTransactionComposer()
atc.add_transaction(txn_with_signer)
simulate_and_persist_response(atc, cwd, algod)
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, algod, buffer_size_mb=0.003)
@pytest.mark.parametrize(
("transactions", "expected_filename_part"),
[
# Single transaction types
({"pay": 1}, "1pay"),
({"axfer": 1}, "1axfer"),
({"appl": 1}, "1appl"),
# Multiple of same type
({"pay": 3}, "3pay"),
({"axfer": 2}, "2axfer"),
({"appl": 4}, "4appl"),
# Mixed combinations
({"pay": 2, "axfer": 1, "appl": 3}, "2pay_1axfer_3appl"),
({"pay": 1, "axfer": 1, "appl": 1}, "1pay_1axfer_1appl"),
],
)
def test_simulate_response_filename_generation(
transactions: dict[str, int],
expected_filename_part: str,
tmp_path_factory: pytest.TempPathFactory,
client_fixture: AppClient,
funded_account: SigningAccount,
monkeypatch: pytest.MonkeyPatch,
mock_config: Mock,
) -> None:
asset_id = 1
if "axfer" in transactions:
asset_id = client_fixture.algorand.send.asset_create(
AssetCreateParams(
sender=funded_account.address,
total=100_000_000,
decimals=0,
unit_name="TEST",
asset_name="Test Asset",
)
).asset_id
cwd = tmp_path_factory.mktemp("cwd")
mock_config.debug = True
mock_config.trace_all = True
mock_config.trace_buffer_size_mb = 256
mock_config.project_root = cwd
atc = client_fixture.algorand.new_group()
# Add payment transactions
for i in range(transactions.get("pay", 0)):
atc.add_payment(
PaymentParams(
sender=funded_account.address,
receiver=client_fixture.app_address,
amount=AlgoAmount.from_micro_algos(1_000_000 * (i + 1)),
note=f"Payment{i+1}".encode(),
)
)
# Add asset transfer transactions
for i in range(transactions.get("axfer", 0)):
atc.add_asset_transfer(
AssetTransferParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=1_000 * (i + 1),
asset_id=asset_id,
)
)
# Add app calls
for i in range(transactions.get("appl", 0)):
atc.add_app_call_method_call(
AppCallMethodCallParams(
method=Method.from_signature("hello(string)string"),
args=[f"test{i+1}"],
sender=funded_account.address,
app_id=client_fixture.app_id,
)
)
# Mock datetime
mock_datetime = datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
class MockDateTime:
@classmethod
def now(cls, tz: timezone | None = None) -> datetime: # noqa: ARG003
return mock_datetime
monkeypatch.setattr("algokit_utils._debugging.datetime", MockDateTime)
response = atc.simulate()
assert response.simulate_response
last_round = response.simulate_response["last-round"]
expected_filename = f"20230101_120000_lr{last_round}_{expected_filename_part}.trace.avm.json"
# Verify file exists with expected name
output_path = cwd / "debug_traces"
files = list(output_path.iterdir())
assert len(files) == 1
assert files[0].name == expected_filename
# Verify transaction count
trace_file_content = json.loads(files[0].read_text())
txn_results = trace_file_content["txn-groups"][0]["txn-results"]
expected_total_txns = sum(transactions.values())
assert len(txn_results) == expected_total_txns
@dataclass
class TestFile:
__test__ = False
name: str
content: bytes
mtime: datetime
def test_removes_oldest_files_when_buffer_size_exceeded(
tmp_path_factory: pytest.TempPathFactory, mock_config: Mock
) -> None:
cwd = tmp_path_factory.mktemp("cwd")
trace_dir = cwd / "debug_traces"
trace_dir.mkdir(exist_ok=True)
mock_config.debug = True
mock_config.trace_all = True
mock_config.trace_buffer_size_mb = 256
mock_config.project_root = cwd
# Create test files with different timestamps and sizes
test_files: list[TestFile] = [
TestFile(name="old.json", content=b"a" * (1024 * 1024), mtime=datetime(2023, 1, 1, tzinfo=timezone.utc)),
TestFile(name="newer.json", content=b"b" * (1024 * 1024), mtime=datetime(2023, 1, 2, tzinfo=timezone.utc)),
TestFile(name="newest.json", content=b"c" * (1024 * 1024), mtime=datetime(2023, 1, 3, tzinfo=timezone.utc)),
]
# Create files with specific timestamps
for file in test_files:
file_path = trace_dir / file.name
file_path.write_bytes(file.content)
os.utime(file_path, (file.mtime.timestamp(), file.mtime.timestamp()))
# Set buffer size to 2MB (should remove oldest file)
cleanup_old_trace_files(trace_dir, buffer_size_mb=2.0)
# Check remaining files
remaining_files = list(trace_dir.iterdir())
remaining_names = [f.name for f in remaining_files]
assert len(remaining_files) == 2
assert "newer.json" in remaining_names
assert "newest.json" in remaining_names
assert "old.json" not in remaining_names
def test_does_nothing_when_total_size_within_buffer_limit(
tmp_path_factory: pytest.TempPathFactory, mock_config: Mock
) -> None:
cwd = tmp_path_factory.mktemp("cwd")
mock_config.debug = True
mock_config.trace_all = True
mock_config.trace_buffer_size_mb = 256
mock_config.project_root = cwd
# Create test directory
trace_dir = cwd / "debug_traces"
trace_dir.mkdir()
# Create two 512KB files (total 1MB)
content = b"a" * (512 * 1024) # 512KB
(trace_dir / "file1.json").write_bytes(content)
(trace_dir / "file2.json").write_bytes(content)
# Set buffer size to 2MB (files total 1MB, should not remove anything)
cleanup_old_trace_files(trace_dir, buffer_size_mb=2.0)
remaining_files = list(trace_dir.iterdir())
assert len(remaining_files) == 2
| algorandfoundation/algokit-utils-py | tests/test_debug_utils.py | Python | MIT | 12,977 |
algorandfoundation/algokit-utils-py | tests/transactions/__init__.py | Python | MIT | 0 |
|
from algosdk.abi import ABIType, Method
from algosdk.abi.method import Returns
from algosdk.atomic_transaction_composer import ABIResult
from algokit_utils.applications.abi import ABIReturn, ABIValue
def get_abi_result(type_str: str, value: ABIValue) -> ABIReturn:
"""Helper function to simulate ABI method return value"""
abi_type = ABIType.from_string(type_str)
encoded = abi_type.encode(value)
decoded = abi_type.decode(encoded)
result = ABIResult(
method=Method(name="", args=[], returns=Returns(arg_type=type_str)),
raw_value=encoded,
return_value=decoded,
tx_id="",
tx_info={},
decode_error=None,
)
return ABIReturn(result)
class TestABIReturn:
def test_uint32(self) -> None:
assert get_abi_result("uint32", 0).value == 0
assert get_abi_result("uint32", 0).value == 0
assert get_abi_result("uint32", 1).value == 1
assert get_abi_result("uint32", 1).value == 1
assert get_abi_result("uint32", 2**32 - 1).value == 2**32 - 1
assert get_abi_result("uint32", 2**32 - 1).value == 2**32 - 1
def test_uint64(self) -> None:
assert get_abi_result("uint64", 0).value == 0
assert get_abi_result("uint64", 1).value == 1
assert get_abi_result("uint64", 2**32 - 1).value == 2**32 - 1
assert get_abi_result("uint64", 2**64 - 1).value == 2**64 - 1
def test_uint32_array(self) -> None:
assert get_abi_result("uint32[]", [0]).value == [0]
assert get_abi_result("uint32[]", [0]).value == [0]
assert get_abi_result("uint32[]", [1]).value == [1]
assert get_abi_result("uint32[]", [1]).value == [1]
assert get_abi_result("uint32[]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint32[]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint32[]", [2**32 - 1]).value == [2**32 - 1]
assert get_abi_result("uint32[]", [2**32 - 1, 1]).value == [2**32 - 1, 1]
def test_uint32_fixed_array(self) -> None:
assert get_abi_result("uint32[1]", [0]).value == [0]
assert get_abi_result("uint32[1]", [0]).value == [0]
assert get_abi_result("uint32[1]", [1]).value == [1]
assert get_abi_result("uint32[1]", [1]).value == [1]
assert get_abi_result("uint32[3]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint32[3]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint32[1]", [2**32 - 1]).value == [2**32 - 1]
assert get_abi_result("uint32[2]", [2**32 - 1, 1]).value == [2**32 - 1, 1]
def test_uint64_array(self) -> None:
assert get_abi_result("uint64[]", [0]).value == [0]
assert get_abi_result("uint64[]", [0]).value == [0]
assert get_abi_result("uint64[]", [1]).value == [1]
assert get_abi_result("uint64[]", [1]).value == [1]
assert get_abi_result("uint64[]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint64[]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint64[]", [2**32 - 1]).value == [2**32 - 1]
assert get_abi_result("uint64[]", [2**64 - 1, 1]).value == [2**64 - 1, 1]
def test_uint64_fixed_array(self) -> None:
assert get_abi_result("uint64[1]", [0]).value == [0]
assert get_abi_result("uint64[1]", [0]).value == [0]
assert get_abi_result("uint64[1]", [1]).value == [1]
assert get_abi_result("uint64[1]", [1]).value == [1]
assert get_abi_result("uint64[3]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint64[3]", [1, 2, 3]).value == [1, 2, 3]
assert get_abi_result("uint64[1]", [2**32 - 1]).value == [2**32 - 1]
assert get_abi_result("uint64[2]", [2**64 - 1, 1]).value == [2**64 - 1, 1]
def test_tuple(self) -> None:
type_str = "(uint32,uint64,(uint32,uint64),uint32[],uint64[])"
assert get_abi_result(type_str, [0, 0, [0, 0], [0], [0]]).value == [
0,
0,
[0, 0],
[0],
[0],
]
assert get_abi_result(type_str, [1, 1, [1, 1], [1], [1]]).value == [
1,
1,
[1, 1],
[1],
[1],
]
assert get_abi_result(
type_str,
[2**32 - 1, 2**64 - 1, [2**32 - 1, 2**64 - 1], [1, 2, 3], [1, 2, 3]],
).value == [
2**32 - 1,
2**64 - 1,
[2**32 - 1, 2**64 - 1],
[1, 2, 3],
[1, 2, 3],
]
| algorandfoundation/algokit-utils-py | tests/transactions/test_abi_return.py | Python | MIT | 4,514 |
import dataclasses
import json
from collections.abc import Generator
from pathlib import Path
import algosdk
import pytest
from algosdk.atomic_transaction_composer import TransactionWithSigner
from algosdk.transaction import OnComplete, PaymentTxn
from algokit_utils import SigningAccount
from algokit_utils.algorand import AlgorandClient
from algokit_utils.applications.app_client import AppClient, AppClientMethodCallParams, FundAppAccountParams
from algokit_utils.applications.app_factory import AppFactoryCreateMethodCallParams, AppFactoryCreateParams
from algokit_utils.config import config
from algokit_utils.errors.logic_error import LogicError
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import PaymentParams
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(new_account, dispenser, AlgoAmount.from_algos(100))
return new_account
def load_arc32_spec(version: int) -> str:
# Load the appropriate spec file from the resource-packer directory
spec_path = Path(__file__).parent.parent / "artifacts" / "resource-packer" / f"ResourcePackerv{version}.arc32.json"
return spec_path.read_text()
class BaseResourcePackerTest:
"""Base class for resource packing tests"""
version: int
@pytest.fixture(autouse=True)
def setup(self, algorand: AlgorandClient, funded_account: SigningAccount) -> Generator[None, None, None]:
config.configure(populate_app_call_resources=True)
# Create app based on version
spec = load_arc32_spec(self.version)
factory = algorand.client.get_app_factory(
app_spec=spec,
default_sender=funded_account.address,
)
self.app_client, _ = factory.send.create(params=AppFactoryCreateMethodCallParams(method="createApplication"))
self.app_client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_micro_algo(2334300)))
self.app_client.send.call(
AppClientMethodCallParams(method="bootstrap", static_fee=AlgoAmount.from_micro_algo(3_000))
)
yield
config.configure(populate_app_call_resources=False)
@pytest.fixture
def external_client(self, algorand: AlgorandClient, funded_account: SigningAccount) -> AppClient:
external_spec = (
Path(__file__).parent.parent / "artifacts" / "resource-packer" / "ExternalApp.arc32.json"
).read_text()
return algorand.client.get_app_client_by_id(
app_spec=external_spec,
app_id=int(self.app_client.get_global_state()["externalAppID"].value),
app_name="external",
default_sender=funded_account.address,
)
def test_accounts_address_balance_invalid_ref(self, algorand: AlgorandClient) -> None:
random_account = algorand.account.random()
with pytest.raises(LogicError, match=f"invalid Account reference {random_account.address}"):
self.app_client.send.call(
AppClientMethodCallParams(
method="addressBalance",
args=[random_account.address],
),
send_params={
"populate_app_call_resources": False,
},
)
def test_accounts_address_balance_valid_ref(self, algorand: AlgorandClient) -> None:
random_account = algorand.account.random()
self.app_client.send.call(
AppClientMethodCallParams(
method="addressBalance",
args=[random_account.address],
),
send_params={
"populate_app_call_resources": True,
},
)
def test_boxes_invalid_ref(self) -> None:
with pytest.raises(LogicError, match="invalid Box reference"):
self.app_client.send.call(
AppClientMethodCallParams(
method="smallBox",
),
send_params={
"populate_app_call_resources": False,
},
)
def test_boxes_valid_ref(self) -> None:
self.app_client.send.call(
AppClientMethodCallParams(
method="smallBox",
),
send_params={
"populate_app_call_resources": True,
},
)
self.app_client.send.call(
AppClientMethodCallParams(
method="mediumBox",
),
send_params={
"populate_app_call_resources": True,
},
)
def test_apps_external_unavailable_app(self) -> None:
with pytest.raises(LogicError, match="unavailable App"):
self.app_client.send.call(
AppClientMethodCallParams(
method="externalAppCall",
static_fee=AlgoAmount.from_micro_algo(2_000),
),
send_params={
"populate_app_call_resources": False,
},
)
def test_apps_external_app(self) -> None:
self.app_client.send.call(
AppClientMethodCallParams(
method="externalAppCall",
static_fee=AlgoAmount.from_micro_algo(2_000),
),
send_params={
"populate_app_call_resources": True,
},
)
def test_assets_unavailable_asset(self) -> None:
with pytest.raises(LogicError, match="unavailable Asset"):
self.app_client.send.call(
AppClientMethodCallParams(
method="assetTotal",
),
send_params={
"populate_app_call_resources": False,
},
)
def test_assets_valid_asset(self) -> None:
self.app_client.send.call(
AppClientMethodCallParams(
method="assetTotal",
),
send_params={
"populate_app_call_resources": True,
},
)
def test_cross_product_reference_has_asset(self, funded_account: SigningAccount) -> None:
self.app_client.send.call(
AppClientMethodCallParams(
method="hasAsset",
args=[funded_account.address],
),
send_params={
"populate_app_call_resources": True,
},
)
def test_cross_product_reference_invalid_external_local(self, funded_account: SigningAccount) -> None:
with pytest.raises(LogicError, match="unavailable App"):
self.app_client.send.call(
AppClientMethodCallParams(
method="externalLocal",
args=[funded_account.address],
),
send_params={
"populate_app_call_resources": False,
},
)
def test_cross_product_reference_external_local(
self, external_client: AppClient, funded_account: SigningAccount, algorand: AlgorandClient
) -> None:
algorand.send.app_call_method_call(
external_client.params.opt_in(
AppClientMethodCallParams(
method="optInToApplication",
sender=funded_account.address,
),
),
send_params={
"populate_app_call_resources": True,
},
)
algorand.send.app_call_method_call(
self.app_client.params.call(
AppClientMethodCallParams(
method="externalLocal",
args=[funded_account.address],
sender=funded_account.address,
),
),
send_params={
"populate_app_call_resources": True,
},
)
def test_address_balance_invalid_account_reference(
self,
) -> None:
with pytest.raises(LogicError, match="invalid Account reference"):
self.app_client.send.call(
AppClientMethodCallParams(
method="addressBalance",
args=[algosdk.account.generate_account()[1]],
),
send_params={
"populate_app_call_resources": False,
},
)
def test_address_balance(
self,
) -> None:
self.app_client.send.call(
AppClientMethodCallParams(
method="addressBalance",
args=[algosdk.account.generate_account()[1]],
on_complete=OnComplete.NoOpOC,
),
send_params={
"populate_app_call_resources": True,
},
)
def test_cross_product_reference_invalid_has_asset(self, funded_account: SigningAccount) -> None:
with pytest.raises(LogicError, match="unavailable Asset"):
self.app_client.send.call(
AppClientMethodCallParams(
method="hasAsset",
args=[funded_account.address],
),
send_params={
"populate_app_call_resources": False,
},
)
class TestResourcePackerAVM8(BaseResourcePackerTest):
"""Test resource packing with AVM 8"""
version = 8
class TestResourcePackerAVM9(BaseResourcePackerTest):
"""Test resource packing with AVM 9"""
version = 9
class TestResourcePackerMixed:
"""Test resource packing with mixed AVM versions"""
@pytest.fixture(autouse=True)
def setup(self, algorand: AlgorandClient, funded_account: SigningAccount) -> Generator[None, None, None]:
config.configure(populate_app_call_resources=True)
# Create v8 app
v8_spec = load_arc32_spec(8)
v8_factory = algorand.client.get_app_factory(
app_spec=v8_spec,
default_sender=funded_account.address,
)
self.v8_client, _ = v8_factory.send.create(params=AppFactoryCreateMethodCallParams(method="createApplication"))
# Create v9 app
v9_spec = load_arc32_spec(9)
v9_factory = algorand.client.get_app_factory(
app_spec=v9_spec,
default_sender=funded_account.address,
)
self.v9_client, _ = v9_factory.send.create(params=AppFactoryCreateMethodCallParams(method="createApplication"))
yield
config.configure(populate_app_call_resources=False)
def test_same_account(self, algorand: AlgorandClient, funded_account: SigningAccount) -> None:
rekeyed_to = algorand.account.random()
algorand.account.rekey_account(funded_account.address, rekeyed_to)
random_account = algorand.account.random()
txn_group = algorand.send.new_group()
txn_group.add_app_call_method_call(
self.v8_client.params.call(
AppClientMethodCallParams(
method="addressBalance",
args=[random_account.address],
sender=funded_account.address,
signer=rekeyed_to.signer,
),
),
)
txn_group.add_app_call_method_call(
self.v9_client.params.call(
AppClientMethodCallParams(
method="addressBalance",
args=[random_account.address],
sender=funded_account.address,
signer=rekeyed_to.signer,
)
)
)
result = txn_group.send(
{
"populate_app_call_resources": True,
}
)
v8_accounts = getattr(result.transactions[0].application_call, "accounts", None) or []
v9_accounts = getattr(result.transactions[1].application_call, "accounts", None) or []
assert len(v8_accounts) + len(v9_accounts) == 1
def test_app_account(self, algorand: AlgorandClient, funded_account: SigningAccount) -> None:
self.v8_client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_micro_algo(328500)))
self.v8_client.send.call(
AppClientMethodCallParams(
method="bootstrap",
static_fee=AlgoAmount.from_micro_algo(3_000),
),
send_params={
"populate_app_call_resources": True,
},
)
external_app_id = int(self.v8_client.get_global_state()["externalAppID"].value)
external_app_addr = algosdk.logic.get_application_address(external_app_id)
txn_group = algorand.send.new_group()
txn_group.add_app_call_method_call(
self.v8_client.params.call(
AppClientMethodCallParams(
method="externalAppCall",
static_fee=AlgoAmount.from_micro_algo(2_000),
sender=funded_account.address,
),
),
)
txn_group.add_app_call_method_call(
self.v9_client.params.call(
AppClientMethodCallParams(
method="addressBalance",
args=[external_app_addr],
sender=funded_account.address,
)
)
)
result = txn_group.send(
{
"populate_app_call_resources": True,
}
)
v8_apps = getattr(result.transactions[0].application_call, "foreign_apps", None) or []
v9_accounts = getattr(result.transactions[1].application_call, "accounts", None) or []
assert len(v8_apps) + len(v9_accounts) == 1
class TestResourcePackerMeta:
"""Test meta aspects of resource packing"""
@pytest.fixture(autouse=True)
def setup(self, algorand: AlgorandClient, funded_account: SigningAccount) -> Generator[None, None, None]:
config.configure(populate_app_call_resources=True)
external_spec = (
Path(__file__).parent.parent / "artifacts" / "resource-packer" / "ExternalApp.arc32.json"
).read_text()
factory = algorand.client.get_app_factory(
app_spec=external_spec,
default_sender=funded_account.address,
)
self.external_client, _ = factory.send.create(
params=AppFactoryCreateMethodCallParams(method="createApplication")
)
yield
config.configure(populate_app_call_resources=False)
def test_error_during_simulate(self) -> None:
with pytest.raises(LogicError) as exc_info:
self.external_client.send.call(
AppClientMethodCallParams(
method="error",
),
send_params={
"populate_app_call_resources": True,
},
)
assert "Error during resource population simulation in transaction 0" in exc_info.value.logic_error_str
def test_box_with_txn_arg(self, algorand: AlgorandClient, funded_account: SigningAccount) -> None:
payment = PaymentTxn(
sender=funded_account.address,
receiver=funded_account.address,
amt=0,
sp=algorand.client.algod.suggested_params(),
)
payment_with_signer = TransactionWithSigner(payment, funded_account.signer)
self.external_client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_micro_algo(106100)))
self.external_client.send.call(
AppClientMethodCallParams(
method="boxWithPayment",
args=[payment_with_signer],
),
send_params={
"populate_app_call_resources": True,
},
)
def test_sender_asset_holding(self) -> None:
self.external_client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_micro_algo(200_000)))
self.external_client.send.call(
AppClientMethodCallParams(
method="createAsset",
static_fee=AlgoAmount.from_micro_algo(2_000),
),
send_params={
"populate_app_call_resources": True,
},
)
result = self.external_client.send.call(AppClientMethodCallParams(method="senderAssetBalance"))
assert len(getattr(result.transaction.application_call, "accounts", None) or []) == 0
def test_rekeyed_account(self, algorand: AlgorandClient, funded_account: SigningAccount) -> None:
auth_addr = algorand.account.random()
algorand.account.rekey_account(funded_account.address, auth_addr)
self.external_client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_micro_algo(200_001)))
self.external_client.send.call(
AppClientMethodCallParams(
method="createAsset",
static_fee=AlgoAmount.from_micro_algo(2_001),
),
send_params={
"populate_app_call_resources": True,
},
)
result = self.external_client.send.call(AppClientMethodCallParams(method="senderAssetBalance"))
assert len(getattr(result.transaction.application_call, "accounts", None) or []) == 0
class TestCoverAppCallInnerFees:
"""Test covering app call inner transaction fees"""
@pytest.fixture(autouse=True)
def setup(self, algorand: AlgorandClient, funded_account: SigningAccount) -> Generator[None, None, None]:
config.configure(populate_app_call_resources=True)
# Load inner fee contract spec
spec_path = Path(__file__).parent.parent / "artifacts" / "inner-fee" / "application.json"
inner_fee_spec = json.loads(spec_path.read_text())
# Create app factory
factory = algorand.client.get_app_factory(app_spec=inner_fee_spec, default_sender=funded_account.address)
# Create 3 app instances
self.app_client1, _ = factory.send.bare.create(params=AppFactoryCreateParams(note=b"app1"))
self.app_client2, _ = factory.send.bare.create(params=AppFactoryCreateParams(note=b"app2"))
self.app_client3, _ = factory.send.bare.create(params=AppFactoryCreateParams(note=b"app3"))
# Fund app accounts
for client in [self.app_client1, self.app_client2, self.app_client3]:
client.fund_app_account(FundAppAccountParams(amount=AlgoAmount.from_algos(2)))
yield
config.configure(populate_app_call_resources=False)
def test_throws_when_no_max_fee(self) -> None:
"""Test that error is thrown when no max fee is supplied"""
with pytest.raises(ValueError, match="Please provide a `max_fee` for each app call transaction"):
self.app_client1.send.call(
AppClientMethodCallParams(
method="no_op",
),
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
def test_throws_when_inner_fees_not_covered(self) -> None:
"""Test that error is thrown when inner transaction fees are not covered"""
expected_fee = 7000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
with pytest.raises(Exception, match="fee too small"):
self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": False,
},
)
def test_does_not_alter_fee_without_inners(self) -> None:
"""Test that fee is not altered when app call has no inner transactions"""
expected_fee = 1000
params = AppClientMethodCallParams(
method="no_op",
max_fee=AlgoAmount.from_micro_algos(2000),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_throws_when_max_fee_too_small(self) -> None:
"""Test that error is thrown when max fee is too small to cover inner fees"""
expected_fee = 7000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee - 1),
)
with pytest.raises(ValueError, match="Fees were too small to resolve execution info"):
self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
def test_throws_when_static_fee_too_small_for_inner_fees(self) -> None:
"""Test that error is thrown when static fee is too small for inner transaction fees"""
expected_fee = 7000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
static_fee=AlgoAmount.from_micro_algos(expected_fee - 1),
)
with pytest.raises(ValueError, match="Fees were too small to resolve execution info"):
self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
def test_alters_fee_handling_when_no_itxns_covered(self) -> None:
"""Test that fee handling is altered when no inner transaction fees are covered"""
expected_fee = 7000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_handling_when_all_inners_covered(self) -> None:
"""Test that fee handling is altered when all inner transaction fees are covered"""
expected_fee = 1000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [1000, 1000, 1000, 1000, [1000, 1000]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_handling_when_some_inners_covered(self) -> None:
"""Test that fee handling is altered when some inner transaction fees are covered"""
expected_fee = 5300
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [1000, 0, 200, 0, [500, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_when_some_inners_have_surplus(self) -> None:
"""Test that fee handling is altered when some inner transaction fees are covered"""
expected_fee = 2000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 1000, 5000, 0, [0, 50]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_handling_multiple_app_calls_in_group_with_inners_with_varying_fees(self) -> None:
"""Test that fee handling is altered when multiple app calls are in a group with inners with varying fees"""
txn_1_expected_fee = 5800
txn_2_expected_fee = 6000
txn_1_params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 1000, 0, 0, [200, 0]]],
static_fee=AlgoAmount.from_micro_algos(txn_1_expected_fee),
note=b"txn_1",
)
txn_2_params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [1000, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(txn_2_expected_fee),
note=b"txn_2",
)
result = (
self.app_client1.algorand.new_group()
.add_app_call_method_call(self.app_client1.params.call(txn_1_params))
.add_app_call_method_call(self.app_client1.params.call(txn_2_params))
.send({"cover_app_call_inner_transaction_fees": True})
)
assert result.transactions[0].raw.fee == txn_1_expected_fee
self._assert_min_fee(self.app_client1, txn_1_params, txn_1_expected_fee)
assert result.transactions[1].raw.fee == txn_2_expected_fee
self._assert_min_fee(self.app_client1, txn_2_params, txn_2_expected_fee)
def test_does_not_alter_static_fee_with_surplus(self) -> None:
"""Test that a static fee with surplus is not altered"""
expected_fee = 6000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [1000, 0, 200, 0, [500, 0]]],
static_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
def test_alters_fee_with_large_inner_surplus_pooling(self) -> None:
"""Test fee handling with large inner fee surplus pooling to lower siblings"""
expected_fee = 7000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0, 20_000, 0, 0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_with_partial_inner_surplus_pooling(self) -> None:
"""Test fee handling with inner fee surplus pooling to some lower siblings"""
expected_fee = 6300
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 2200, 0, [0, 0, 2500, 0, 0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_with_large_inner_surplus_no_pooling(self) -> None:
"""Test fee handling with large inner fee surplus but no pooling"""
expected_fee = 10_000
params = AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0, 0, 0, 0, 20_000]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(
params,
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_alters_fee_with_multiple_inner_surplus_poolings_to_lower_siblings(self) -> None:
"""Test fee handling with multiple inner fee surplus poolings to lower siblings"""
expected_fee = 7100
params = AppClientMethodCallParams(
method="send_inners_with_fees_2",
args=[
self.app_client2.app_id,
self.app_client3.app_id,
[0, 1200, [0, 0, 4900, 0, 0, 0], 200, 1100, [0, 0, 2500, 0, 0, 0]],
],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = self.app_client1.send.call(params, send_params={"cover_app_call_inner_transaction_fees": True})
assert result.transaction.raw.fee == expected_fee
self._assert_min_fee(self.app_client1, params, expected_fee)
def test_does_not_alter_fee_when_group_covers_inner_fees(self, funded_account: SigningAccount) -> None:
"""Test that fee is not altered when another transaction in group covers inner fees"""
expected_fee = 8000
result = (
self.app_client1.algorand.new_group()
.add_payment(
params=PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
static_fee=AlgoAmount.from_micro_algos(expected_fee),
)
)
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(expected_fee),
)
)
)
.send({"cover_app_call_inner_transaction_fees": True})
)
assert result.transactions[0].raw.fee == expected_fee
# We could technically reduce the below to 0, however it adds more complexity
# and is probably unlikely to be a common use case
assert result.transactions[1].raw.fee == 1000
def test_allocates_surplus_fees_to_most_constrained_first(self, funded_account: SigningAccount) -> None:
"""Test that surplus fees are allocated to the most fee constrained transaction first"""
result = (
self.app_client1.algorand.new_group()
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(2000),
)
)
)
.add_payment(
params=PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
static_fee=AlgoAmount.from_micro_algos(7500),
)
)
.add_payment(
params=PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
static_fee=AlgoAmount.from_micro_algos(0),
)
)
.send({"cover_app_call_inner_transaction_fees": True})
)
assert result.transactions[0].raw.fee == 1500
assert result.transactions[1].raw.fee == 7500
assert result.transactions[2].raw.fee == 0
def test_handles_nested_abi_method_calls(self, funded_account: SigningAccount) -> None:
"""Test fee handling with nested ABI method calls"""
# Create nested contract app
app_spec = (Path(__file__).parent.parent / "artifacts" / "nested_contract" / "application.json").read_text()
nested_factory = self.app_client1.algorand.client.get_app_factory(
app_spec=app_spec,
default_sender=funded_account.address,
)
nested_client, _ = nested_factory.send.create(
params=AppFactoryCreateMethodCallParams(method="createApplication")
)
# Setup transaction parameters
txn_arg_call = self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 2000, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(4000),
)
)
payment_params = PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
static_fee=AlgoAmount.from_micro_algos(1500),
)
expected_fee = 2000
params = AppClientMethodCallParams(
method="nestedTxnArg",
args=[
self.app_client1.algorand.create_transaction.payment(payment_params),
txn_arg_call,
],
static_fee=AlgoAmount.from_micro_algos(expected_fee),
)
result = nested_client.send.call(params, send_params={"cover_app_call_inner_transaction_fees": True})
assert len(result.transactions) == 3
assert result.transactions[0].raw.fee == 1500
assert result.transactions[1].raw.fee == 3500
assert result.transactions[2].raw.fee == expected_fee
self._assert_min_fee(
nested_client,
dataclasses.replace(
params,
args=[self.app_client1.algorand.create_transaction.payment(payment_params), txn_arg_call],
),
expected_fee,
)
def test_throws_when_max_fee_below_calculated(self) -> None:
"""Test that error is thrown when max fee is below calculated fee"""
with pytest.raises(
ValueError, match="Calculated transaction fee 7000 µALGO is greater than max of 1200 for transaction 0"
):
(
self.app_client1.algorand.new_group()
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(1200),
)
)
)
# This transaction allows this state to be possible, without it the simulate call
# to get the execution info would fail
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="no_op",
max_fee=AlgoAmount.from_micro_algos(10_000),
)
)
)
.send({"cover_app_call_inner_transaction_fees": True})
)
def test_throws_when_nested_max_fee_below_calculated(self, funded_account: SigningAccount) -> None:
"""Test that error is thrown when nested max fee is below calculated fee"""
# Create nested contract app
app_spec = (Path(__file__).parent.parent / "artifacts" / "nested_contract" / "application.json").read_text()
nested_factory = self.app_client1.algorand.client.get_app_factory(
app_spec=app_spec,
default_sender=funded_account.address,
)
nested_client, _ = nested_factory.send.create(
params=AppFactoryCreateMethodCallParams(method="createApplication")
)
txn_arg_call = self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 2000, 0, [0, 0]]],
max_fee=AlgoAmount.from_micro_algos(2000),
)
)
with pytest.raises(
ValueError, match="Calculated transaction fee 5000 µALGO is greater than max of 2000 for transaction 1"
):
nested_client.send.call(
AppClientMethodCallParams(
method="nestedTxnArg",
args=[
self.app_client1.algorand.create_transaction.payment(
PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
)
),
txn_arg_call,
],
max_fee=AlgoAmount.from_micro_algos(10_000),
),
send_params={
"cover_app_call_inner_transaction_fees": True,
},
)
def test_throws_when_static_fee_below_calculated(self) -> None:
"""Test that error is thrown when static fee is below calculated fee"""
with pytest.raises(
ValueError, match="Calculated transaction fee 7000 µALGO is greater than max of 5000 for transaction 0"
):
(
self.app_client1.algorand.new_group()
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
static_fee=AlgoAmount.from_micro_algos(5000),
)
)
)
# This transaction allows this state to be possible, without it the simulate call
# to get the execution info would fail
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="no_op",
max_fee=AlgoAmount.from_micro_algos(10_000),
)
)
)
.send({"cover_app_call_inner_transaction_fees": True})
)
def test_throws_when_non_app_call_static_fee_too_low(self, funded_account: SigningAccount) -> None:
"""Test that error is thrown when static fee for non-app-call transaction is too low"""
with pytest.raises(
ValueError, match="An additional fee of 500 µALGO is required for non app call transaction 2"
):
(
self.app_client1.algorand.new_group()
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
static_fee=AlgoAmount.from_micro_algos(13_000),
max_fee=AlgoAmount.from_micro_algos(14_000),
)
)
)
.add_app_call_method_call(
self.app_client1.params.call(
AppClientMethodCallParams(
method="send_inners_with_fees",
args=[self.app_client2.app_id, self.app_client3.app_id, [0, 0, 0, 0, [0, 0]]],
static_fee=AlgoAmount.from_micro_algos(1000),
)
)
)
.add_payment(
params=PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_micro_algos(0),
static_fee=AlgoAmount.from_micro_algos(500),
)
)
.send({"cover_app_call_inner_transaction_fees": True})
)
def test_handles_expensive_abi_calls_with_ensure_budget(self) -> None:
"""Test fee handling with expensive ABI method calls that use ensure_budget to op-up"""
expected_fee = 10_000
params = AppClientMethodCallParams(
method="burn_ops",
args=[6200],
max_fee=AlgoAmount.from_micro_algos(12_000),
)
result = self.app_client1.send.call(params, send_params={"cover_app_call_inner_transaction_fees": True})
assert result.transaction.raw.fee == expected_fee
assert len(result.confirmation.get("inner-txns", [])) == 9 # type: ignore[union-attr]
self._assert_min_fee(self.app_client1, params, expected_fee)
def _assert_min_fee(self, app_client: AppClient, params: AppClientMethodCallParams, fee: int) -> None:
"""Helper to assert minimum required fee"""
if fee == 1000:
return
params_copy = dataclasses.replace(
params,
static_fee=None,
extra_fee=None,
)
with pytest.raises(Exception, match="fee too small"):
app_client.send.call(params_copy)
| algorandfoundation/algokit-utils-py | tests/transactions/test_resource_packing.py | Python | MIT | 43,071 |
import base64
from collections.abc import Generator
from pathlib import Path
from typing import TYPE_CHECKING, Any
from unittest.mock import Mock, patch
import algosdk
import pytest
from algosdk.transaction import (
ApplicationCallTxn,
AssetConfigTxn,
AssetCreateTxn,
PaymentTxn,
)
from algokit_utils._legacy_v2.account import get_account
from algokit_utils.algorand import AlgorandClient
from algokit_utils.models.account import MultisigMetadata, SigningAccount
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AppCallMethodCallParams,
AppCreateParams,
AssetConfigParams,
AssetCreateParams,
PaymentParams,
SendAtomicTransactionComposerResults,
TransactionComposer,
)
from legacy_v2_tests.conftest import get_unique_name
if TYPE_CHECKING:
from algokit_utils.models.transaction import Arc2TransactionNote
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture(autouse=True)
def mock_config() -> Generator[Mock, None, None]:
with patch("algokit_utils.transactions.transaction_composer.config", new_callable=Mock) as mock_config:
mock_config.debug = True
mock_config.project_root = None
yield mock_config
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
@pytest.fixture
def funded_secondary_account(algorand: AlgorandClient) -> SigningAccount:
secondary_name = get_unique_name()
return get_account(algorand.client.algod, secondary_name)
def test_add_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
txn = PaymentTxn(
sender=funded_account.address,
sp=algorand.client.algod.suggested_params(),
receiver=funded_account.address,
amt=AlgoAmount.from_algos(1).micro_algos,
)
composer.add_transaction(txn)
built = composer.build_transactions()
assert len(built.transactions) == 1
assert isinstance(built.transactions[0], PaymentTxn)
assert built.transactions[0].sender == funded_account.address
assert built.transactions[0].receiver == funded_account.address
assert built.transactions[0].amt == AlgoAmount.from_algos(1).micro_algos
def test_add_asset_create(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
expected_total = 1000
params = AssetCreateParams(
sender=funded_account.address,
total=expected_total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
composer.add_asset_create(params)
built = composer.build_transactions()
response = composer.send({"max_rounds_to_wait": 20})
created_asset = algorand.client.algod.asset_info(
algorand.client.algod.pending_transaction_info(response.tx_ids[0])["asset-index"] # type: ignore[call-overload]
)["params"]
assert len(response.tx_ids) == 1
assert response.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
assert isinstance(built.transactions[0], AssetCreateTxn)
txn = built.transactions[0]
assert txn.sender == funded_account.address
assert created_asset["creator"] == funded_account.address
assert txn.total == created_asset["total"] == expected_total
assert txn.decimals == created_asset["decimals"] == 0
assert txn.default_frozen == created_asset["default-frozen"] is False
assert txn.unit_name == created_asset["unit-name"] == "TEST"
assert txn.asset_name == created_asset["name"] == "Test Asset"
def test_add_asset_config(
algorand: AlgorandClient, funded_account: SigningAccount, funded_secondary_account: SigningAccount
) -> None:
# First create an asset
asset_txn = AssetCreateTxn(
sender=funded_account.address,
sp=algorand.client.algod.suggested_params(),
total=1000,
decimals=0,
default_frozen=False,
unit_name="CFG",
asset_name="Configurable Asset",
manager=funded_account.address,
)
signed_asset_txn = asset_txn.sign(funded_account.signer.private_key)
tx_id = algorand.client.algod.send_transaction(signed_asset_txn)
asset_before_config = algorand.client.algod.asset_info(
algorand.client.algod.pending_transaction_info(tx_id)["asset-index"] # type: ignore[call-overload]
)
asset_before_config_index = asset_before_config["index"] # type: ignore[call-overload]
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
params = AssetConfigParams(
sender=funded_account.address,
asset_id=asset_before_config_index,
manager=funded_secondary_account.address,
)
composer.add_asset_config(params)
built = composer.build_transactions()
assert len(built.transactions) == 1
assert isinstance(built.transactions[0], AssetConfigTxn)
txn = built.transactions[0]
assert txn.sender == funded_account.address
assert txn.index == asset_before_config_index
assert txn.manager == funded_secondary_account.address
composer.send({"max_rounds_to_wait": 20})
updated_asset = algorand.client.algod.asset_info(asset_id=asset_before_config_index)["params"] # type: ignore[call-overload]
assert updated_asset["manager"] == funded_secondary_account.address
def test_add_app_create(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
approval_program = "#pragma version 6\nint 1"
clear_state_program = "#pragma version 6\nint 1"
params = AppCreateParams(
sender=funded_account.address,
approval_program=approval_program,
clear_state_program=clear_state_program,
schema={"global_ints": 0, "global_byte_slices": 0, "local_ints": 0, "local_byte_slices": 0},
)
composer.add_app_create(params)
built = composer.build_transactions()
assert len(built.transactions) == 1
assert isinstance(built.transactions[0], ApplicationCallTxn)
txn = built.transactions[0]
assert txn.sender == funded_account.address
assert txn.approval_program == b"\x06\x81\x01"
assert txn.clear_program == b"\x06\x81\x01"
composer.send({"max_rounds_to_wait": 20})
def test_add_app_call_method_call(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
approval_program = Path(Path(__file__).parent.parent / "artifacts" / "hello_world" / "approval.teal").read_text()
clear_state_program = Path(Path(__file__).parent.parent / "artifacts" / "hello_world" / "clear.teal").read_text()
composer.add_app_create(
AppCreateParams(
sender=funded_account.address,
approval_program=approval_program,
clear_state_program=clear_state_program,
schema={"global_ints": 0, "global_byte_slices": 0, "local_ints": 0, "local_byte_slices": 0},
)
)
response = composer.send()
app_id = algorand.client.algod.pending_transaction_info(response.tx_ids[0])["application-index"] # type: ignore[call-overload]
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
composer.add_app_call_method_call(
AppCallMethodCallParams(
sender=funded_account.address,
app_id=app_id,
method=algosdk.abi.Method.from_signature("hello(string)string"),
args=["world"],
)
)
built = composer.build_transactions()
assert len(built.transactions) == 1
assert isinstance(built.transactions[0], ApplicationCallTxn)
txn = built.transactions[0]
assert txn.sender == funded_account.address
response = composer.send({"max_rounds_to_wait": 20})
assert response.returns[-1].value == "Hello, world"
def test_simulate(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
composer.add_payment(
PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_algos(1),
)
)
composer.build()
simulate_response = composer.simulate()
assert simulate_response
def test_send(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
composer.add_payment(
PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_algos(1),
)
)
response = composer.send()
assert isinstance(response, SendAtomicTransactionComposerResults)
assert len(response.tx_ids) == 1
assert response.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
def test_arc2_note() -> None:
note_data: Arc2TransactionNote = {
"dapp_name": "TestDApp",
"format": "j",
"data": '{"key":"value"}',
}
encoded_note = TransactionComposer.arc2_note(note_data)
expected_note = b'TestDApp:j{"key":"value"}'
assert encoded_note == expected_note
def test_arc2_note_dapp_name_validation() -> None:
invalid_names = [
"_TestDApp", # starts with underscore
"Test", # too short
"a" * 33, # too long
"Test@App!", # invalid character !
"Test App", # contains space
]
for invalid_name in invalid_names:
note_data: Arc2TransactionNote = {"dapp_name": invalid_name, "format": "j", "data": {"key": "value"}}
with pytest.raises(ValueError, match="dapp_name must be"):
TransactionComposer.arc2_note(note_data)
def test_arc2_note_valid_dapp_names() -> None:
valid_names = [
"TestDApp", # simple case
"test-dapp", # with hyphen
"test_dapp", # with underscore
"test.dapp", # with dot
"test@dapp", # with @
"test/dapp", # with /
"a" * 32, # maximum length
"12345", # minimum length, numeric
]
for valid_name in valid_names:
note_data: Arc2TransactionNote = {"dapp_name": valid_name, "format": "j", "data": {"key": "value"}}
encoded_note = TransactionComposer.arc2_note(note_data)
assert encoded_note.startswith(valid_name.encode())
def _get_test_transaction(
default_account: SigningAccount, amount: AlgoAmount | None = None, sender: SigningAccount | None = None
) -> dict[str, Any]:
return {
"sender": sender.address if sender else default_account.address,
"receiver": default_account.address,
"amount": amount or AlgoAmount.from_algos(1),
}
def test_transaction_is_capped_by_low_min_txn_fee(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
with pytest.raises(ValueError, match="Transaction fee 1000 is greater than max_fee 1 µALGO"):
algorand.send.payment(
PaymentParams(**_get_test_transaction(funded_account), max_fee=AlgoAmount.from_micro_algo(1))
)
def test_transaction_cap_is_ignored_if_higher_than_fee(
algorand: AlgorandClient, funded_account: SigningAccount
) -> None:
response = algorand.send.payment(
PaymentParams(**_get_test_transaction(funded_account), max_fee=AlgoAmount.from_micro_algo(1_000_000))
)
assert isinstance(response.confirmation, dict)
assert response.confirmation["txn"]["txn"]["fee"] == AlgoAmount.from_micro_algo(1000)
def test_transaction_fee_is_overridable(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
response = algorand.send.payment(
PaymentParams(**_get_test_transaction(funded_account), static_fee=AlgoAmount.from_algos(1))
)
assert isinstance(response.confirmation, dict)
assert response.confirmation["txn"]["txn"]["fee"] == AlgoAmount.from_algos(1)
def test_transaction_group_is_sent(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
composer.add_payment(PaymentParams(**_get_test_transaction(funded_account, amount=AlgoAmount.from_algos(1))))
composer.add_payment(PaymentParams(**_get_test_transaction(funded_account, amount=AlgoAmount.from_algos(2))))
response = composer.send()
assert isinstance(response.confirmations[0], dict)
assert isinstance(response.confirmations[1], dict)
assert response.confirmations[0].get("txn", {}).get("txn", {}).get("grp") is not None
assert response.confirmations[1].get("txn", {}).get("txn", {}).get("grp") is not None
assert response.transactions[0].payment.group is not None
assert response.transactions[1].payment.group is not None
assert len(response.confirmations) == 2
assert response.confirmations[0]["confirmed-round"] >= response.transactions[0].payment.first_valid_round
assert response.confirmations[1]["confirmed-round"] >= response.transactions[1].payment.first_valid_round
assert (
response.confirmations[0]["txn"]["txn"]["grp"]
== base64.b64encode(response.transactions[0].payment.group).decode()
)
assert (
response.confirmations[1]["txn"]["txn"]["grp"]
== base64.b64encode(response.transactions[1].payment.group).decode()
)
def test_multisig_single_account(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
multisig = algorand.account.multisig(
metadata=MultisigMetadata(
version=1,
threshold=1,
addresses=[funded_account.address],
),
signing_accounts=[funded_account],
)
algorand.send.payment(
PaymentParams(sender=funded_account.address, receiver=multisig.address, amount=AlgoAmount.from_algos(1))
)
algorand.send.payment(
PaymentParams(sender=multisig.address, receiver=funded_account.address, amount=AlgoAmount.from_micro_algo(500))
)
def test_multisig_double_account(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
account2 = algorand.account.random()
algorand.account.ensure_funded(account2, funded_account, AlgoAmount.from_algos(10))
# Setup multisig
multisig = algorand.account.multisig(
metadata=MultisigMetadata(
version=1,
threshold=2,
addresses=[funded_account.address, account2.address],
),
signing_accounts=[funded_account, account2],
)
# Fund multisig
algorand.send.payment(
PaymentParams(sender=funded_account.address, receiver=multisig.address, amount=AlgoAmount.from_algos(1))
)
# Use multisig
algorand.send.payment(
PaymentParams(sender=multisig.address, receiver=funded_account.address, amount=AlgoAmount.from_micro_algo(500))
)
@pytest.mark.usefixtures("mock_config")
def test_transactions_fails_in_debug_mode(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
txn1 = algorand.create_transaction.payment(PaymentParams(**_get_test_transaction(funded_account)))
txn2 = algorand.create_transaction.payment(
PaymentParams(**_get_test_transaction(funded_account, amount=AlgoAmount.from_micro_algo(9999999999999)))
)
composer = TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: funded_account.signer,
)
composer.add_transaction(txn1)
composer.add_transaction(txn2)
with pytest.raises(Exception) as e: # noqa: PT011
composer.send()
assert f"transaction {txn2.get_txid()}: overspend" in e.value.traces[0]["failure_message"] # type: ignore[attr-defined]
| algorandfoundation/algokit-utils-py | tests/transactions/test_transaction_composer.py | Python | MIT | 16,697 |
from pathlib import Path
import algosdk
import pytest
from algosdk.transaction import (
ApplicationCallTxn,
AssetConfigTxn,
AssetCreateTxn,
AssetDestroyTxn,
AssetFreezeTxn,
AssetTransferTxn,
KeyregTxn,
PaymentTxn,
)
from algokit_utils.algorand import AlgorandClient
from algokit_utils.models.account import SigningAccount
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AppCallMethodCallParams,
AppCreateParams,
AssetConfigParams,
AssetCreateParams,
AssetDestroyParams,
AssetFreezeParams,
AssetOptInParams,
AssetOptOutParams,
AssetTransferParams,
OnlineKeyRegistrationParams,
PaymentParams,
)
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
@pytest.fixture
def funded_secondary_account(algorand: AlgorandClient, funded_account: SigningAccount) -> SigningAccount:
account = algorand.account.random()
algorand.send.payment(
PaymentParams(sender=funded_account.address, receiver=account.address, amount=AlgoAmount.from_algos(1))
)
return account
def test_create_payment_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
txn = algorand.create_transaction.payment(
PaymentParams(
sender=funded_account.address,
receiver=funded_account.address,
amount=AlgoAmount.from_algos(1),
)
)
assert isinstance(txn, PaymentTxn)
assert txn.sender == funded_account.address
assert txn.receiver == funded_account.address
assert txn.amt == AlgoAmount.from_algos(1).micro_algos
def test_create_asset_create_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
expected_total = 1000
txn = algorand.create_transaction.asset_create(
AssetCreateParams(
sender=funded_account.address,
total=expected_total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
)
assert isinstance(txn, AssetCreateTxn)
assert txn.sender == funded_account.address
assert txn.total == expected_total
assert txn.decimals == 0
assert txn.default_frozen is False
assert txn.unit_name == "TEST"
assert txn.asset_name == "Test Asset"
assert txn.url == "https://example.com"
def test_create_asset_config_transaction(
algorand: AlgorandClient, funded_account: SigningAccount, funded_secondary_account: SigningAccount
) -> None:
txn = algorand.create_transaction.asset_config(
AssetConfigParams(
sender=funded_account.address,
asset_id=1,
manager=funded_secondary_account.address,
)
)
assert isinstance(txn, AssetConfigTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
assert txn.manager == funded_secondary_account.address
def test_create_asset_freeze_transaction(
algorand: AlgorandClient, funded_account: SigningAccount, funded_secondary_account: SigningAccount
) -> None:
txn = algorand.create_transaction.asset_freeze(
AssetFreezeParams(
sender=funded_account.address,
asset_id=1,
account=funded_secondary_account.address,
frozen=True,
)
)
assert isinstance(txn, AssetFreezeTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
assert txn.target == funded_secondary_account.address
assert txn.new_freeze_state is True
def test_create_asset_destroy_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
txn = algorand.create_transaction.asset_destroy(
AssetDestroyParams(
sender=funded_account.address,
asset_id=1,
)
)
assert isinstance(txn, AssetDestroyTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
def test_create_asset_transfer_transaction(
algorand: AlgorandClient, funded_account: SigningAccount, funded_secondary_account: SigningAccount
) -> None:
expected_amount = 100
txn = algorand.create_transaction.asset_transfer(
AssetTransferParams(
sender=funded_account.address,
asset_id=1,
amount=expected_amount,
receiver=funded_secondary_account.address,
)
)
assert isinstance(txn, AssetTransferTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
assert txn.amount == expected_amount
assert txn.receiver == funded_secondary_account.address
def test_create_asset_opt_in_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
txn = algorand.create_transaction.asset_opt_in(
AssetOptInParams(
sender=funded_account.address,
asset_id=1,
)
)
assert isinstance(txn, AssetTransferTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
assert txn.amount == 0
assert txn.receiver == funded_account.address
def test_create_asset_opt_out_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
txn = algorand.create_transaction.asset_opt_out(
AssetOptOutParams(
sender=funded_account.address,
asset_id=1,
creator=funded_account.address,
)
)
assert isinstance(txn, AssetTransferTxn)
assert txn.sender == funded_account.address
assert txn.index == 1
assert txn.amount == 0
assert txn.receiver == funded_account.address
assert txn.close_assets_to == funded_account.address
def test_create_app_create_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
approval_program = "#pragma version 6\nint 1"
clear_state_program = "#pragma version 6\nint 1"
txn = algorand.create_transaction.app_create(
AppCreateParams(
sender=funded_account.address,
approval_program=approval_program,
clear_state_program=clear_state_program,
schema={"global_ints": 0, "global_byte_slices": 0, "local_ints": 0, "local_byte_slices": 0},
)
)
assert isinstance(txn, ApplicationCallTxn)
assert txn.sender == funded_account.address
assert txn.approval_program == b"\x06\x81\x01"
assert txn.clear_program == b"\x06\x81\x01"
def test_create_app_call_method_call_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
approval_program = Path(Path(__file__).parent.parent / "artifacts" / "hello_world" / "approval.teal").read_text()
clear_state_program = Path(Path(__file__).parent.parent / "artifacts" / "hello_world" / "clear.teal").read_text()
# First create the app
create_result = algorand.send.app_create(
AppCreateParams(
sender=funded_account.address,
approval_program=approval_program,
clear_state_program=clear_state_program,
schema={"global_ints": 0, "global_byte_slices": 0, "local_ints": 0, "local_byte_slices": 0},
)
)
app_id = algorand.client.algod.pending_transaction_info(create_result.tx_ids[0])["application-index"] # type: ignore[call-overload]
# Then test creating a method call transaction
result = algorand.create_transaction.app_call_method_call(
AppCallMethodCallParams(
sender=funded_account.address,
app_id=app_id,
method=algosdk.abi.Method.from_signature("hello(string)string"),
args=["world"],
)
)
assert len(result.transactions) == 1
assert isinstance(result.transactions[0], ApplicationCallTxn)
assert result.transactions[0].sender == funded_account.address
assert result.transactions[0].index == app_id
def test_create_online_key_registration_transaction(algorand: AlgorandClient, funded_account: SigningAccount) -> None:
sp = algorand.get_suggested_params()
expected_dilution = 100
expected_first = sp.first
expected_last = sp.first + int(10e6)
txn = algorand.create_transaction.online_key_registration(
OnlineKeyRegistrationParams(
sender=funded_account.address,
vote_key="G/lqTV6MKspW6J8wH2d8ZliZ5XZVZsruqSBJMwLwlmo=",
selection_key="LrpLhvzr+QpN/bivh6IPpOaKGbGzTTB5lJtVfixmmgk=",
state_proof_key=b"RpUpNWfZMjZ1zOOjv3MF2tjO714jsBt0GKnNsw0ihJ4HSZwci+d9zvUi3i67LwFUJgjQ5Dz4zZgHgGduElnmSA==",
vote_first=expected_first,
vote_last=expected_last,
vote_key_dilution=expected_dilution,
)
)
assert isinstance(txn, KeyregTxn)
assert txn.sender == funded_account.address
assert txn.selkey == "LrpLhvzr+QpN/bivh6IPpOaKGbGzTTB5lJtVfixmmgk="
assert txn.sprfkey == b"RpUpNWfZMjZ1zOOjv3MF2tjO714jsBt0GKnNsw0ihJ4HSZwci+d9zvUi3i67LwFUJgjQ5Dz4zZgHgGduElnmSA=="
assert txn.votefst == expected_first
assert txn.votelst == expected_last
assert txn.votekd == expected_dilution
| algorandfoundation/algokit-utils-py | tests/transactions/test_transaction_creator.py | Python | MIT | 9,543 |
from pathlib import Path
from unittest.mock import MagicMock, patch
import algosdk
import pytest
from algosdk.transaction import OnComplete
from algokit_utils import SigningAccount
from algokit_utils._legacy_v2.application_specification import ApplicationSpecification
from algokit_utils.algorand import AlgorandClient
from algokit_utils.applications.app_manager import AppManager
from algokit_utils.assets.asset_manager import AssetManager
from algokit_utils.models.amount import AlgoAmount
from algokit_utils.transactions.transaction_composer import (
AppCallMethodCallParams,
AppCallParams,
AppCreateParams,
AssetConfigParams,
AssetCreateParams,
AssetDestroyParams,
AssetFreezeParams,
AssetOptInParams,
AssetOptOutParams,
AssetTransferParams,
OfflineKeyRegistrationParams,
OnlineKeyRegistrationParams,
PaymentParams,
TransactionComposer,
)
from algokit_utils.transactions.transaction_sender import AlgorandClientTransactionSender
@pytest.fixture
def algorand() -> AlgorandClient:
return AlgorandClient.default_localnet()
@pytest.fixture
def funded_account(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
algorand.set_signer(sender=new_account.address, signer=new_account.signer)
return new_account
@pytest.fixture
def sender(funded_account: SigningAccount) -> SigningAccount:
return funded_account
@pytest.fixture
def receiver(algorand: AlgorandClient) -> SigningAccount:
new_account = algorand.account.random()
dispenser = algorand.account.localnet_dispenser()
algorand.account.ensure_funded(
new_account, dispenser, AlgoAmount.from_algos(100), min_funding_increment=AlgoAmount.from_algos(1)
)
return new_account
@pytest.fixture
def raw_hello_world_arc32_app_spec() -> str:
raw_json_spec = Path(__file__).parent.parent / "artifacts" / "hello_world" / "app_spec.arc32.json"
return raw_json_spec.read_text()
@pytest.fixture
def test_hello_world_arc32_app_spec() -> ApplicationSpecification:
raw_json_spec = Path(__file__).parent.parent / "artifacts" / "hello_world" / "app_spec.arc32.json"
return ApplicationSpecification.from_json(raw_json_spec.read_text())
@pytest.fixture
def test_hello_world_arc32_app_id(
algorand: AlgorandClient, funded_account: SigningAccount, test_hello_world_arc32_app_spec: ApplicationSpecification
) -> int:
global_schema = test_hello_world_arc32_app_spec.global_state_schema
local_schema = test_hello_world_arc32_app_spec.local_state_schema
response = algorand.send.app_create(
AppCreateParams(
sender=funded_account.address,
approval_program=test_hello_world_arc32_app_spec.approval_program,
clear_state_program=test_hello_world_arc32_app_spec.clear_program,
schema={
"global_ints": int(global_schema.num_uints) if global_schema.num_uints else 0,
"global_byte_slices": int(global_schema.num_byte_slices) if global_schema.num_byte_slices else 0,
"local_ints": int(local_schema.num_uints) if local_schema.num_uints else 0,
"local_byte_slices": int(local_schema.num_byte_slices) if local_schema.num_byte_slices else 0,
},
)
)
return response.app_id
@pytest.fixture
def transaction_sender(algorand: AlgorandClient, sender: SigningAccount) -> AlgorandClientTransactionSender:
def new_group() -> TransactionComposer:
return TransactionComposer(
algod=algorand.client.algod,
get_signer=lambda _: sender.signer,
)
return AlgorandClientTransactionSender(
new_group=new_group,
asset_manager=AssetManager(algorand.client.algod, new_group),
app_manager=AppManager(algorand.client.algod),
algod_client=algorand.client.algod,
)
def test_payment(
transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount, receiver: SigningAccount
) -> None:
amount = AlgoAmount.from_algos(1)
result = transaction_sender.payment(
PaymentParams(
sender=sender.address,
receiver=receiver.address,
amount=amount,
)
)
assert len(result.tx_ids) == 1
assert result.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
txn = result.transaction.payment
assert txn
assert txn.sender == sender.address
assert txn.receiver == receiver.address
assert txn.amt == amount.micro_algos
def test_asset_create(transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount) -> None:
total = 1000
params = AssetCreateParams(
sender=sender.address,
total=total,
decimals=0,
default_frozen=False,
unit_name="TEST",
asset_name="Test Asset",
url="https://example.com",
)
result = transaction_sender.asset_create(params)
assert len(result.tx_ids) == 1
assert result.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
txn = result.transaction.asset_config
assert txn
assert txn.sender == sender.address
assert txn.total == total
assert txn.decimals == 0
assert txn.default_frozen is False
assert txn.unit_name == "TEST"
assert txn.asset_name == "Test Asset"
assert txn.url == "https://example.com"
def test_asset_config(
transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount, receiver: SigningAccount
) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
unit_name="CFG",
asset_name="Config Asset",
url="https://example.com",
manager=sender.address,
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then configure it
config_params = AssetConfigParams(
sender=sender.address,
asset_id=asset_id,
manager=receiver.address,
)
result = transaction_sender.asset_config(config_params)
assert len(result.tx_ids) == 1
assert result.transaction.asset_config
txn = result.transaction.asset_config
assert txn
assert txn.sender == sender.address
assert txn.index == asset_id
assert txn.manager == receiver.address
def test_asset_freeze(
transaction_sender: AlgorandClientTransactionSender,
sender: SigningAccount,
) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
unit_name="FRZ",
url="https://example.com",
asset_name="Freeze Asset",
freeze=sender.address,
manager=sender.address,
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then freeze it
freeze_params = AssetFreezeParams(
sender=sender.address,
asset_id=asset_id,
account=sender.address,
frozen=True,
)
result = transaction_sender.asset_freeze(freeze_params)
assert len(result.tx_ids) == 1
assert result.transaction.asset_freeze
txn = result.transaction.asset_freeze
assert txn
assert txn.sender == sender.address
assert txn.index == asset_id
assert txn.target == sender.address
assert txn.new_freeze_state is True
def test_asset_destroy(transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
unit_name="DEL",
asset_name="Delete Asset",
manager=sender.address,
url="https://example.com",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then destroy it
destroy_params = AssetDestroyParams(
sender=sender.address,
asset_id=asset_id,
)
result = transaction_sender.asset_destroy(destroy_params)
assert len(result.tx_ids) == 1
txn = result.transaction.asset_config
assert txn
assert txn.sender == sender.address
assert txn.index == asset_id
def test_asset_transfer(
transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount, receiver: SigningAccount
) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
url="https://example.com",
unit_name="XFR",
asset_name="Transfer Asset",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then opt-in receiver
transaction_sender.asset_opt_in(
AssetOptInParams(
sender=receiver.address,
asset_id=asset_id,
signer=receiver.signer,
)
)
# Then transfer it
amount = 100
transfer_params = AssetTransferParams(
sender=sender.address,
asset_id=asset_id,
receiver=receiver.address,
amount=amount,
)
result = transaction_sender.asset_transfer(transfer_params)
assert len(result.tx_ids) == 1
txn = result.transaction.asset_transfer
assert txn
assert txn.sender == sender.address
assert txn.index == asset_id
assert txn.receiver == receiver.address
assert txn.amount == amount
def test_asset_opt_in(
transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount, receiver: SigningAccount
) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
url="https://example.com",
unit_name="OPT",
asset_name="Opt Asset",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then opt-in
opt_in_params = AssetOptInParams(
sender=receiver.address,
asset_id=asset_id,
signer=receiver.signer,
)
result = transaction_sender.asset_opt_in(opt_in_params)
assert len(result.tx_ids) == 1
assert result.transaction.asset_transfer
txn = result.transaction.asset_transfer
assert txn.sender == receiver.address
assert txn.index == asset_id
assert txn.amount == 0
assert txn.receiver == receiver.address
def test_asset_opt_out(
transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount, receiver: SigningAccount
) -> None:
# First create an asset
create_result = transaction_sender.asset_create(
AssetCreateParams(
sender=sender.address,
total=1000,
decimals=0,
default_frozen=False,
url="https://example.com",
unit_name="OUT",
asset_name="Opt Out Asset",
)
)
asset_id = int(create_result.confirmation["asset-index"]) # type: ignore[call-overload]
# Then opt-in
transaction_sender.asset_opt_in(
AssetOptInParams(
sender=receiver.address,
asset_id=asset_id,
signer=receiver.signer,
)
)
# Then opt-out
opt_out_params = AssetOptOutParams(
sender=receiver.address,
asset_id=asset_id,
creator=sender.address,
signer=receiver.signer,
)
result = transaction_sender.asset_opt_out(params=opt_out_params)
assert result.transaction.asset_transfer
txn = result.transaction.asset_transfer
assert txn.sender == receiver.address
assert txn.index == asset_id
assert txn.amount == 0
assert txn.receiver == receiver.address
assert txn.close_assets_to == sender.address
def test_app_create(transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount) -> None:
approval_program = "#pragma version 6\nint 1"
clear_state_program = "#pragma version 6\nint 1"
params = AppCreateParams(
sender=sender.address,
approval_program=approval_program,
clear_state_program=clear_state_program,
schema={"global_ints": 0, "global_byte_slices": 0, "local_ints": 0, "local_byte_slices": 0},
)
result = transaction_sender.app_create(params)
assert result.app_id > 0
assert result.app_address
assert result.transaction.application_call
txn = result.transaction.application_call
assert txn.sender == sender.address
assert txn.approval_program == b"\x06\x81\x01"
assert txn.clear_program == b"\x06\x81\x01"
def test_app_call(
test_hello_world_arc32_app_id: int, transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount
) -> None:
params = AppCallParams(
app_id=test_hello_world_arc32_app_id,
sender=sender.address,
on_complete=OnComplete.NoOpOC,
args=[b"\x02\xbe\xce\x11", b"test"],
)
result = transaction_sender.app_call(params)
assert not result.abi_return # TODO: improve checks
def test_app_call_method_call(
test_hello_world_arc32_app_id: int, transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount
) -> None:
params = AppCallMethodCallParams(
app_id=test_hello_world_arc32_app_id,
sender=sender.address,
method=algosdk.abi.Method.from_signature("hello(string)string"),
args=["test"],
)
result = transaction_sender.app_call_method_call(params)
assert result.abi_return
assert result.abi_return.value == "Hello2, test"
@patch("logging.Logger.debug")
def test_payment_logging(
mock_debug: MagicMock,
transaction_sender: AlgorandClientTransactionSender,
sender: SigningAccount,
receiver: SigningAccount,
) -> None:
amount = AlgoAmount.from_algos(1)
transaction_sender.payment(
PaymentParams(
sender=sender.address,
receiver=receiver.address,
amount=amount,
)
)
assert mock_debug.call_count == 1
log_message = mock_debug.call_args[0][0]
assert "Sending 1,000,000 µALGO" in log_message
assert sender.address in log_message
assert receiver.address in log_message
def test_key_registration(transaction_sender: AlgorandClientTransactionSender, sender: SigningAccount) -> None:
sp = transaction_sender._algod.suggested_params() # noqa: SLF001
params = OnlineKeyRegistrationParams(
sender=sender.address,
vote_key="G/lqTV6MKspW6J8wH2d8ZliZ5XZVZsruqSBJMwLwlmo=",
selection_key="LrpLhvzr+QpN/bivh6IPpOaKGbGzTTB5lJtVfixmmgk=",
state_proof_key=b"RpUpNWfZMjZ1zOOjv3MF2tjO714jsBt0GKnNsw0ihJ4HSZwci+d9zvUi3i67LwFUJgjQ5Dz4zZgHgGduElnmSA==",
vote_first=sp.first,
vote_last=sp.first + int(10e6),
vote_key_dilution=100,
)
result = transaction_sender.online_key_registration(params)
assert len(result.tx_ids) == 1
assert result.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
sp = transaction_sender._algod.suggested_params() # noqa: SLF001
off_key_reg_params = OfflineKeyRegistrationParams(
sender=sender.address,
prevent_account_from_ever_participating_again=True,
)
result = transaction_sender.offline_key_registration(off_key_reg_params)
assert len(result.tx_ids) == 1
assert result.confirmations[-1]["confirmed-round"] > 0 # type: ignore[call-overload]
| algorandfoundation/algokit-utils-py | tests/transactions/test_transaction_sender.py | Python | MIT | 16,156 |
from pathlib import Path
from typing import Literal, overload
from algokit_utils.applications.app_manager import DELETABLE_TEMPLATE_NAME, UPDATABLE_TEMPLATE_NAME, AppManager
from algokit_utils.applications.app_spec import Arc32Contract, Arc56Contract
@overload
def load_app_spec(
path: Path,
arc: Literal[32],
*,
updatable: bool | None = None,
deletable: bool | None = None,
template_values: dict | None = None,
) -> Arc32Contract: ...
@overload
def load_app_spec(
path: Path,
arc: Literal[56],
*,
updatable: bool | None = None,
deletable: bool | None = None,
template_values: dict | None = None,
) -> Arc56Contract: ...
def load_app_spec(
path: Path,
arc: Literal[32, 56],
*,
updatable: bool | None = None,
deletable: bool | None = None,
template_values: dict | None = None,
) -> Arc32Contract | Arc56Contract:
arc_class = Arc32Contract if arc == 32 else Arc56Contract
spec = arc_class.from_json(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)
if isinstance(spec, Arc32Contract):
spec.approval_program = (
AppManager.replace_template_variables(spec.approval_program, template_variables)
.replace(f"// {UPDATABLE_TEMPLATE_NAME}", "// updatable")
.replace(f"// {DELETABLE_TEMPLATE_NAME}", "// deletable")
)
return spec
| algorandfoundation/algokit-utils-py | tests/utils.py | Python | MIT | 1,575 |
Subsets and Splits