algokit-utils 3.0.0b1__py3-none-any.whl → 3.0.0b3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of algokit-utils might be problematic. Click here for more details.

Files changed (70) hide show
  1. algokit_utils/__init__.py +23 -183
  2. algokit_utils/_debugging.py +123 -97
  3. algokit_utils/_legacy_v2/__init__.py +177 -0
  4. algokit_utils/{_ensure_funded.py → _legacy_v2/_ensure_funded.py} +19 -18
  5. algokit_utils/{_transfer.py → _legacy_v2/_transfer.py} +24 -23
  6. algokit_utils/_legacy_v2/account.py +203 -0
  7. algokit_utils/_legacy_v2/application_client.py +1471 -0
  8. algokit_utils/_legacy_v2/application_specification.py +21 -0
  9. algokit_utils/_legacy_v2/asset.py +168 -0
  10. algokit_utils/_legacy_v2/common.py +28 -0
  11. algokit_utils/_legacy_v2/deploy.py +822 -0
  12. algokit_utils/_legacy_v2/logic_error.py +14 -0
  13. algokit_utils/{models.py → _legacy_v2/models.py} +19 -142
  14. algokit_utils/_legacy_v2/network_clients.py +140 -0
  15. algokit_utils/account.py +12 -183
  16. algokit_utils/accounts/__init__.py +2 -0
  17. algokit_utils/accounts/account_manager.py +909 -0
  18. algokit_utils/accounts/kmd_account_manager.py +159 -0
  19. algokit_utils/algorand.py +265 -0
  20. algokit_utils/application_client.py +9 -1453
  21. algokit_utils/application_specification.py +39 -197
  22. algokit_utils/applications/__init__.py +7 -0
  23. algokit_utils/applications/abi.py +276 -0
  24. algokit_utils/applications/app_client.py +2054 -0
  25. algokit_utils/applications/app_deployer.py +600 -0
  26. algokit_utils/applications/app_factory.py +826 -0
  27. algokit_utils/applications/app_manager.py +470 -0
  28. algokit_utils/applications/app_spec/__init__.py +2 -0
  29. algokit_utils/applications/app_spec/arc32.py +207 -0
  30. algokit_utils/applications/app_spec/arc56.py +1023 -0
  31. algokit_utils/applications/enums.py +40 -0
  32. algokit_utils/asset.py +32 -168
  33. algokit_utils/assets/__init__.py +1 -0
  34. algokit_utils/assets/asset_manager.py +320 -0
  35. algokit_utils/beta/_utils.py +36 -0
  36. algokit_utils/beta/account_manager.py +4 -195
  37. algokit_utils/beta/algorand_client.py +4 -314
  38. algokit_utils/beta/client_manager.py +5 -74
  39. algokit_utils/beta/composer.py +5 -712
  40. algokit_utils/clients/__init__.py +2 -0
  41. algokit_utils/clients/client_manager.py +656 -0
  42. algokit_utils/clients/dispenser_api_client.py +192 -0
  43. algokit_utils/common.py +8 -26
  44. algokit_utils/config.py +71 -18
  45. algokit_utils/deploy.py +7 -892
  46. algokit_utils/dispenser_api.py +8 -176
  47. algokit_utils/errors/__init__.py +1 -0
  48. algokit_utils/errors/logic_error.py +121 -0
  49. algokit_utils/logic_error.py +7 -80
  50. algokit_utils/models/__init__.py +8 -0
  51. algokit_utils/models/account.py +197 -0
  52. algokit_utils/models/amount.py +198 -0
  53. algokit_utils/models/application.py +61 -0
  54. algokit_utils/models/network.py +25 -0
  55. algokit_utils/models/simulate.py +11 -0
  56. algokit_utils/models/state.py +59 -0
  57. algokit_utils/models/transaction.py +100 -0
  58. algokit_utils/network_clients.py +7 -152
  59. algokit_utils/protocols/__init__.py +2 -0
  60. algokit_utils/protocols/account.py +22 -0
  61. algokit_utils/protocols/typed_clients.py +108 -0
  62. algokit_utils/transactions/__init__.py +3 -0
  63. algokit_utils/transactions/transaction_composer.py +2287 -0
  64. algokit_utils/transactions/transaction_creator.py +156 -0
  65. algokit_utils/transactions/transaction_sender.py +574 -0
  66. {algokit_utils-3.0.0b1.dist-info → algokit_utils-3.0.0b3.dist-info}/METADATA +13 -8
  67. algokit_utils-3.0.0b3.dist-info/RECORD +70 -0
  68. {algokit_utils-3.0.0b1.dist-info → algokit_utils-3.0.0b3.dist-info}/WHEEL +1 -1
  69. algokit_utils-3.0.0b1.dist-info/RECORD +0 -24
  70. {algokit_utils-3.0.0b1.dist-info → algokit_utils-3.0.0b3.dist-info}/LICENSE +0 -0
@@ -0,0 +1,1471 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import copy
5
+ import json
6
+ import logging
7
+ import re
8
+ import typing
9
+ from math import ceil
10
+ from pathlib import Path
11
+ from typing import Any, Literal, cast, overload
12
+
13
+ import algosdk
14
+ from algosdk import transaction
15
+ from algosdk.abi import ABIType, Method, Returns
16
+ from algosdk.account import address_from_private_key
17
+ from algosdk.atomic_transaction_composer import (
18
+ ABI_RETURN_HASH,
19
+ ABIResult,
20
+ AccountTransactionSigner,
21
+ AtomicTransactionComposer,
22
+ AtomicTransactionResponse,
23
+ LogicSigTransactionSigner,
24
+ MultisigTransactionSigner,
25
+ SimulateAtomicTransactionResponse,
26
+ TransactionSigner,
27
+ TransactionWithSigner,
28
+ )
29
+ from algosdk.constants import APP_PAGE_MAX_SIZE
30
+ from algosdk.logic import get_application_address
31
+ from algosdk.source_map import SourceMap
32
+ from typing_extensions import deprecated
33
+
34
+ import algokit_utils._legacy_v2.application_specification as au_spec
35
+ import algokit_utils._legacy_v2.deploy as au_deploy
36
+ from algokit_utils._legacy_v2.common import Program
37
+ from algokit_utils._legacy_v2.logic_error import LogicError, parse_logic_error
38
+ from algokit_utils._legacy_v2.models import (
39
+ ABIArgsDict,
40
+ ABIArgType,
41
+ ABIMethod,
42
+ ABITransactionResponse,
43
+ Account,
44
+ CreateCallParameters,
45
+ CreateCallParametersDict,
46
+ OnCompleteCallParameters,
47
+ OnCompleteCallParametersDict,
48
+ SimulationTrace,
49
+ TransactionParameters,
50
+ TransactionParametersDict,
51
+ TransactionResponse,
52
+ )
53
+ from algokit_utils.config import config
54
+
55
+ if typing.TYPE_CHECKING:
56
+ from algosdk.v2client.algod import AlgodClient
57
+ from algosdk.v2client.indexer import IndexerClient
58
+
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+
63
+ """A dictionary `dict[str, Any]` representing ABI argument names and values"""
64
+
65
+ __all__ = [
66
+ "ApplicationClient",
67
+ "execute_atc_with_logic_error",
68
+ "get_next_version",
69
+ "get_sender_from_signer",
70
+ "num_extra_program_pages",
71
+ ]
72
+
73
+ """Alias for {py:class}`pyteal.ABIReturnSubroutine`, {py:class}`algosdk.abi.method.Method` or a {py:class}`str`
74
+ representing an ABI method name or signature"""
75
+
76
+
77
+ def num_extra_program_pages(approval: bytes, clear: bytes) -> int:
78
+ """Calculate minimum number of extra_pages required for provided approval and clear programs"""
79
+
80
+ return ceil(((len(approval) + len(clear)) - APP_PAGE_MAX_SIZE) / APP_PAGE_MAX_SIZE)
81
+
82
+
83
+ @deprecated(
84
+ "Use AppClient from algokit_utils.applications instead. Example:\n"
85
+ "```python\n"
86
+ "from algokit_utils import AlgorandClient\n"
87
+ "from algokit_utils.models.application import Arc56Contract\n"
88
+ "algorand_client = AlgorandClient.from_environment()\n"
89
+ "app_client = AppClient.from_network(app_spec=Arc56Contract.from_json(app_spec_json), "
90
+ "algorand=algorand_client, app_id=123)\n"
91
+ "```"
92
+ )
93
+ class ApplicationClient:
94
+ """A class that wraps an ARC-0032 app spec and provides high productivity methods to deploy and call the app
95
+
96
+ ApplicationClient can be created with an app_id to interact with an existing application, alternatively
97
+ it can be created with a creator and indexer_client specified to find existing applications by name and creator.
98
+
99
+ :param AlgodClient algod_client: AlgoSDK algod client
100
+ :param ApplicationSpecification | Path app_spec: An Application Specification or the path to one
101
+ :param int app_id: The app_id of an existing application, to instead find the application by creator and name
102
+ use the creator and indexer_client parameters
103
+ :param str | Account creator: The address or Account of the app creator to resolve the app_id
104
+ :param IndexerClient indexer_client: AlgoSDK indexer client, only required if deploying or finding app_id by
105
+ creator and app name
106
+ :param AppLookup existing_deployments:
107
+ :param TransactionSigner | Account signer: Account or signer to use to sign transactions, if not specified and
108
+ creator was passed as an Account will use that.
109
+ :param str sender: Address to use as the sender for all transactions, will use the address associated with the
110
+ signer if not specified.
111
+ :param TemplateValueMapping template_values: Values to use for TMPL_* template variables, dictionary keys should
112
+ *NOT* include the TMPL_ prefix
113
+ :param str | None app_name: Name of application to use when deploying, defaults to name defined on the
114
+ Application Specification
115
+ """
116
+
117
+ @overload
118
+ def __init__(
119
+ self,
120
+ algod_client: AlgodClient,
121
+ app_spec: au_spec.ApplicationSpecification | Path,
122
+ *,
123
+ app_id: int = 0,
124
+ signer: TransactionSigner | Account | None = None,
125
+ sender: str | None = None,
126
+ suggested_params: transaction.SuggestedParams | None = None,
127
+ template_values: au_deploy.TemplateValueMapping | None = None,
128
+ ): ...
129
+
130
+ @overload
131
+ def __init__(
132
+ self,
133
+ algod_client: AlgodClient,
134
+ app_spec: au_spec.ApplicationSpecification | Path,
135
+ *,
136
+ creator: str | Account,
137
+ indexer_client: IndexerClient | None = None,
138
+ existing_deployments: au_deploy.AppLookup | None = None,
139
+ signer: TransactionSigner | Account | None = None,
140
+ sender: str | None = None,
141
+ suggested_params: transaction.SuggestedParams | None = None,
142
+ template_values: au_deploy.TemplateValueMapping | None = None,
143
+ app_name: str | None = None,
144
+ ): ...
145
+
146
+ def __init__( # noqa: PLR0913
147
+ self,
148
+ algod_client: AlgodClient,
149
+ app_spec: au_spec.ApplicationSpecification | Path,
150
+ *,
151
+ app_id: int = 0,
152
+ creator: str | Account | None = None,
153
+ indexer_client: IndexerClient | None = None,
154
+ existing_deployments: au_deploy.AppLookup | None = None,
155
+ signer: TransactionSigner | Account | None = None,
156
+ sender: str | None = None,
157
+ suggested_params: transaction.SuggestedParams | None = None,
158
+ template_values: au_deploy.TemplateValueMapping | None = None,
159
+ app_name: str | None = None,
160
+ ):
161
+ self.algod_client = algod_client
162
+ self.app_spec = (
163
+ au_spec.ApplicationSpecification.from_json(app_spec.read_text()) if isinstance(app_spec, Path) else app_spec
164
+ )
165
+ self._app_name = app_name
166
+ self._approval_program: Program | None = None
167
+ self._approval_source_map: SourceMap | None = None
168
+ self._clear_program: Program | None = None
169
+
170
+ self.template_values: au_deploy.TemplateValueMapping = template_values or {}
171
+ self.existing_deployments = existing_deployments
172
+ self._indexer_client = indexer_client
173
+ if creator is not None:
174
+ if not self.existing_deployments and not self._indexer_client:
175
+ raise Exception(
176
+ "If using the creator parameter either existing_deployments or indexer_client must also be provided"
177
+ )
178
+ self._creator: str | None = creator.address if isinstance(creator, Account) else creator
179
+ if self.existing_deployments and self.existing_deployments.creator != self._creator:
180
+ raise Exception(
181
+ "Attempt to create application client with invalid existing_deployments against"
182
+ f"a different creator ({self.existing_deployments.creator} instead of "
183
+ f"expected creator {self._creator}"
184
+ )
185
+ self.app_id = 0
186
+ else:
187
+ self.app_id = app_id
188
+ self._creator = None
189
+
190
+ self.signer: TransactionSigner | None
191
+ if signer:
192
+ self.signer = (
193
+ signer if isinstance(signer, TransactionSigner) else AccountTransactionSigner(signer.private_key)
194
+ )
195
+ elif isinstance(creator, Account):
196
+ self.signer = AccountTransactionSigner(creator.private_key)
197
+ else:
198
+ self.signer = None
199
+
200
+ self.sender = sender
201
+ self.suggested_params = suggested_params
202
+
203
+ @property
204
+ def app_name(self) -> str:
205
+ return self._app_name or self.app_spec.contract.name
206
+
207
+ @app_name.setter
208
+ def app_name(self, value: str) -> None:
209
+ self._app_name = value
210
+
211
+ @property
212
+ def app_address(self) -> str:
213
+ return get_application_address(self.app_id)
214
+
215
+ @property
216
+ def approval(self) -> Program | None:
217
+ return self._approval_program
218
+
219
+ @property
220
+ def approval_source_map(self) -> SourceMap | None:
221
+ if self._approval_source_map:
222
+ return self._approval_source_map
223
+ if self._approval_program:
224
+ return self._approval_program.source_map
225
+ return None
226
+
227
+ @approval_source_map.setter
228
+ def approval_source_map(self, value: SourceMap) -> None:
229
+ self._approval_source_map = value
230
+
231
+ @property
232
+ def clear(self) -> Program | None:
233
+ return self._clear_program
234
+
235
+ def prepare(
236
+ self,
237
+ signer: TransactionSigner | Account | None = None,
238
+ sender: str | None = None,
239
+ app_id: int | None = None,
240
+ template_values: au_deploy.TemplateValueDict | None = None,
241
+ ) -> ApplicationClient:
242
+ """Creates a copy of this ApplicationClient, using the new signer, sender and app_id values if provided.
243
+ Will also substitute provided template_values into the associated app_spec in the copy"""
244
+ new_client: ApplicationClient = copy.copy(self)
245
+ new_client._prepare( # noqa: SLF001
246
+ new_client, signer=signer, sender=sender, app_id=app_id, template_values=template_values
247
+ )
248
+ return new_client
249
+
250
+ def _prepare(
251
+ self,
252
+ target: ApplicationClient,
253
+ *,
254
+ signer: TransactionSigner | Account | None = None,
255
+ sender: str | None = None,
256
+ app_id: int | None = None,
257
+ template_values: au_deploy.TemplateValueDict | None = None,
258
+ ) -> None:
259
+ target.app_id = self.app_id if app_id is None else app_id
260
+ target.signer, target.sender = target.get_signer_sender(
261
+ AccountTransactionSigner(signer.private_key) if isinstance(signer, Account) else signer, sender
262
+ )
263
+ target.template_values = {**self.template_values, **(template_values or {})}
264
+
265
+ def deploy( # noqa: PLR0913
266
+ self,
267
+ version: str | None = None,
268
+ *,
269
+ signer: TransactionSigner | None = None,
270
+ sender: str | None = None,
271
+ allow_update: bool | None = None,
272
+ allow_delete: bool | None = None,
273
+ on_update: au_deploy.OnUpdate = au_deploy.OnUpdate.Fail,
274
+ on_schema_break: au_deploy.OnSchemaBreak = au_deploy.OnSchemaBreak.Fail,
275
+ template_values: au_deploy.TemplateValueMapping | None = None,
276
+ create_args: au_deploy.ABICreateCallArgs
277
+ | au_deploy.ABICreateCallArgsDict
278
+ | au_deploy.DeployCreateCallArgs
279
+ | None = None,
280
+ update_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None,
281
+ delete_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None,
282
+ ) -> au_deploy.DeployResponse:
283
+ """Deploy an application and update client to reference it.
284
+
285
+ Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator
286
+ account, including deploy-time template placeholder substitutions.
287
+ To understand the architecture decisions behind this functionality please see
288
+ <https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md>
289
+
290
+ ```{note}
291
+ If there is a breaking state schema change to an existing app (and `on_schema_break` is set to
292
+ 'ReplaceApp' the existing app will be deleted and re-created.
293
+ ```
294
+
295
+ ```{note}
296
+ If there is an update (different TEAL code) to an existing app (and `on_update` is set to 'ReplaceApp')
297
+ the existing app will be deleted and re-created.
298
+ ```
299
+
300
+ :param str version: version to use when creating or updating app, if None version will be auto incremented
301
+ :param algosdk.atomic_transaction_composer.TransactionSigner signer: signer to use when deploying app
302
+ , if None uses self.signer
303
+ :param str sender: sender address to use when deploying app, if None uses self.sender
304
+ :param bool allow_delete: Used to set the `TMPL_DELETABLE` template variable to conditionally control if an app
305
+ can be deleted
306
+ :param bool allow_update: Used to set the `TMPL_UPDATABLE` template variable to conditionally control if an app
307
+ can be updated
308
+ :param OnUpdate on_update: Determines what action to take if an application update is required
309
+ :param OnSchemaBreak on_schema_break: Determines what action to take if an application schema requirements
310
+ has increased beyond the current allocation
311
+ :param dict[str, int|str|bytes] template_values: Values to use for `TMPL_*` template variables, dictionary keys
312
+ should *NOT* include the TMPL_ prefix
313
+ :param ABICreateCallArgs create_args: Arguments used when creating an application
314
+ :param ABICallArgs | ABICallArgsDict update_args: Arguments used when updating an application
315
+ :param ABICallArgs | ABICallArgsDict delete_args: Arguments used when deleting an application
316
+ :return DeployResponse: details action taken and relevant transactions
317
+ :raises DeploymentError: If the deployment failed
318
+ """
319
+ # check inputs
320
+ if self.app_id:
321
+ raise au_deploy.DeploymentFailedError(
322
+ f"Attempt to deploy app which already has an app index of {self.app_id}"
323
+ )
324
+ try:
325
+ resolved_signer, resolved_sender = self.resolve_signer_sender(signer, sender)
326
+ except ValueError as ex:
327
+ raise au_deploy.DeploymentFailedError(f"{ex}, unable to deploy app") from None
328
+ if not self._creator:
329
+ raise au_deploy.DeploymentFailedError("No creator provided, unable to deploy app")
330
+ if self._creator != resolved_sender:
331
+ raise au_deploy.DeploymentFailedError(
332
+ f"Attempt to deploy contract with a sender address {resolved_sender} that differs "
333
+ f"from the given creator address for this application client: {self._creator}"
334
+ )
335
+
336
+ # make a copy and prepare variables
337
+ template_values = {**self.template_values, **(template_values or {})}
338
+ au_deploy.add_deploy_template_variables(template_values, allow_update=allow_update, allow_delete=allow_delete)
339
+
340
+ existing_app_metadata_or_reference = self._load_app_reference()
341
+
342
+ self._approval_program, self._clear_program = substitute_template_and_compile(
343
+ self.algod_client, self.app_spec, template_values
344
+ )
345
+
346
+ if config.debug and config.project_root:
347
+ from algokit_utils._debugging import PersistSourceMapInput, persist_sourcemaps
348
+
349
+ persist_sourcemaps(
350
+ sources=[
351
+ PersistSourceMapInput(
352
+ compiled_teal=self._approval_program, app_name=self.app_name, file_name="approval.teal"
353
+ ),
354
+ PersistSourceMapInput(
355
+ compiled_teal=self._clear_program, app_name=self.app_name, file_name="clear.teal"
356
+ ),
357
+ ],
358
+ project_root=config.project_root,
359
+ client=self.algod_client,
360
+ with_sources=True,
361
+ )
362
+
363
+ deployer = au_deploy.Deployer(
364
+ app_client=self,
365
+ creator=self._creator,
366
+ signer=resolved_signer,
367
+ sender=resolved_sender,
368
+ new_app_metadata=self._get_app_deploy_metadata(version, allow_update, allow_delete),
369
+ existing_app_metadata_or_reference=existing_app_metadata_or_reference,
370
+ on_update=on_update,
371
+ on_schema_break=on_schema_break,
372
+ create_args=create_args,
373
+ update_args=update_args,
374
+ delete_args=delete_args,
375
+ )
376
+
377
+ return deployer.deploy()
378
+
379
+ def compose_create(
380
+ self,
381
+ atc: AtomicTransactionComposer,
382
+ /,
383
+ call_abi_method: ABIMethod | bool | None = None,
384
+ transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None,
385
+ **abi_kwargs: ABIArgType,
386
+ ) -> None:
387
+ """Adds a signed transaction with application id == 0 and the schema and source of client's app_spec to atc"""
388
+ approval_program, clear_program = self._check_is_compiled()
389
+ transaction_parameters = _convert_transaction_parameters(transaction_parameters)
390
+
391
+ extra_pages = transaction_parameters.extra_pages or num_extra_program_pages(
392
+ approval_program.raw_binary, clear_program.raw_binary
393
+ )
394
+
395
+ self.add_method_call(
396
+ atc,
397
+ app_id=0,
398
+ abi_method=call_abi_method,
399
+ abi_args=abi_kwargs,
400
+ on_complete=transaction_parameters.on_complete or transaction.OnComplete.NoOpOC,
401
+ call_config=au_spec.CallConfig.CREATE,
402
+ parameters=transaction_parameters,
403
+ approval_program=approval_program.raw_binary,
404
+ clear_program=clear_program.raw_binary,
405
+ global_schema=self.app_spec.global_state_schema,
406
+ local_schema=self.app_spec.local_state_schema,
407
+ extra_pages=extra_pages,
408
+ )
409
+
410
+ @overload
411
+ def create(
412
+ self,
413
+ call_abi_method: Literal[False],
414
+ transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
415
+ ) -> TransactionResponse: ...
416
+
417
+ @overload
418
+ def create(
419
+ self,
420
+ call_abi_method: ABIMethod | Literal[True],
421
+ transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
422
+ **abi_kwargs: ABIArgType,
423
+ ) -> ABITransactionResponse: ...
424
+
425
+ @overload
426
+ def create(
427
+ self,
428
+ call_abi_method: ABIMethod | bool | None = ...,
429
+ transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
430
+ **abi_kwargs: ABIArgType,
431
+ ) -> TransactionResponse | ABITransactionResponse: ...
432
+
433
+ def create(
434
+ self,
435
+ call_abi_method: ABIMethod | bool | None = None,
436
+ transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None,
437
+ **abi_kwargs: ABIArgType,
438
+ ) -> TransactionResponse | ABITransactionResponse:
439
+ """Submits a signed transaction with application id == 0 and the schema and source of client's app_spec"""
440
+
441
+ atc = AtomicTransactionComposer()
442
+
443
+ self.compose_create(
444
+ atc,
445
+ call_abi_method,
446
+ transaction_parameters,
447
+ **abi_kwargs,
448
+ )
449
+ create_result = self._execute_atc_tr(atc)
450
+ self.app_id = au_deploy.get_app_id_from_tx_id(self.algod_client, create_result.tx_id)
451
+ return create_result
452
+
453
+ def compose_update(
454
+ self,
455
+ atc: AtomicTransactionComposer,
456
+ /,
457
+ call_abi_method: ABIMethod | bool | None = None,
458
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
459
+ **abi_kwargs: ABIArgType,
460
+ ) -> None:
461
+ """Adds a signed transaction with on_complete=UpdateApplication to atc"""
462
+ approval_program, clear_program = self._check_is_compiled()
463
+
464
+ self.add_method_call(
465
+ atc=atc,
466
+ abi_method=call_abi_method,
467
+ abi_args=abi_kwargs,
468
+ parameters=transaction_parameters,
469
+ on_complete=transaction.OnComplete.UpdateApplicationOC,
470
+ approval_program=approval_program.raw_binary,
471
+ clear_program=clear_program.raw_binary,
472
+ )
473
+
474
+ @overload
475
+ def update(
476
+ self,
477
+ call_abi_method: ABIMethod | Literal[True],
478
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
479
+ **abi_kwargs: ABIArgType,
480
+ ) -> ABITransactionResponse: ...
481
+
482
+ @overload
483
+ def update(
484
+ self,
485
+ call_abi_method: Literal[False],
486
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
487
+ ) -> TransactionResponse: ...
488
+
489
+ @overload
490
+ def update(
491
+ self,
492
+ call_abi_method: ABIMethod | bool | None = ...,
493
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
494
+ **abi_kwargs: ABIArgType,
495
+ ) -> TransactionResponse | ABITransactionResponse: ...
496
+
497
+ def update(
498
+ self,
499
+ call_abi_method: ABIMethod | bool | None = None,
500
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
501
+ **abi_kwargs: ABIArgType,
502
+ ) -> TransactionResponse | ABITransactionResponse:
503
+ """Submits a signed transaction with on_complete=UpdateApplication"""
504
+
505
+ atc = AtomicTransactionComposer()
506
+ self.compose_update(
507
+ atc,
508
+ call_abi_method,
509
+ transaction_parameters=transaction_parameters,
510
+ **abi_kwargs,
511
+ )
512
+ return self._execute_atc_tr(atc)
513
+
514
+ def compose_delete(
515
+ self,
516
+ atc: AtomicTransactionComposer,
517
+ /,
518
+ call_abi_method: ABIMethod | bool | None = None,
519
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
520
+ **abi_kwargs: ABIArgType,
521
+ ) -> None:
522
+ """Adds a signed transaction with on_complete=DeleteApplication to atc"""
523
+
524
+ self.add_method_call(
525
+ atc,
526
+ call_abi_method,
527
+ abi_args=abi_kwargs,
528
+ parameters=transaction_parameters,
529
+ on_complete=transaction.OnComplete.DeleteApplicationOC,
530
+ )
531
+
532
+ @overload
533
+ def delete(
534
+ self,
535
+ call_abi_method: ABIMethod | Literal[True],
536
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
537
+ **abi_kwargs: ABIArgType,
538
+ ) -> ABITransactionResponse: ...
539
+
540
+ @overload
541
+ def delete(
542
+ self,
543
+ call_abi_method: Literal[False],
544
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
545
+ ) -> TransactionResponse: ...
546
+
547
+ @overload
548
+ def delete(
549
+ self,
550
+ call_abi_method: ABIMethod | bool | None = ...,
551
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
552
+ **abi_kwargs: ABIArgType,
553
+ ) -> TransactionResponse | ABITransactionResponse: ...
554
+
555
+ def delete(
556
+ self,
557
+ call_abi_method: ABIMethod | bool | None = None,
558
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
559
+ **abi_kwargs: ABIArgType,
560
+ ) -> TransactionResponse | ABITransactionResponse:
561
+ """Submits a signed transaction with on_complete=DeleteApplication"""
562
+
563
+ atc = AtomicTransactionComposer()
564
+ self.compose_delete(
565
+ atc,
566
+ call_abi_method,
567
+ transaction_parameters=transaction_parameters,
568
+ **abi_kwargs,
569
+ )
570
+ return self._execute_atc_tr(atc)
571
+
572
+ def compose_call(
573
+ self,
574
+ atc: AtomicTransactionComposer,
575
+ /,
576
+ call_abi_method: ABIMethod | bool | None = None,
577
+ transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None,
578
+ **abi_kwargs: ABIArgType,
579
+ ) -> None:
580
+ """Adds a signed transaction with specified parameters to atc"""
581
+ _parameters = _convert_transaction_parameters(transaction_parameters)
582
+ self.add_method_call(
583
+ atc,
584
+ abi_method=call_abi_method,
585
+ abi_args=abi_kwargs,
586
+ parameters=_parameters,
587
+ on_complete=_parameters.on_complete or transaction.OnComplete.NoOpOC,
588
+ )
589
+
590
+ @overload
591
+ def call(
592
+ self,
593
+ call_abi_method: ABIMethod | Literal[True],
594
+ transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
595
+ **abi_kwargs: ABIArgType,
596
+ ) -> ABITransactionResponse: ...
597
+
598
+ @overload
599
+ def call(
600
+ self,
601
+ call_abi_method: Literal[False],
602
+ transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
603
+ ) -> TransactionResponse: ...
604
+
605
+ @overload
606
+ def call(
607
+ self,
608
+ call_abi_method: ABIMethod | bool | None = ...,
609
+ transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
610
+ **abi_kwargs: ABIArgType,
611
+ ) -> TransactionResponse | ABITransactionResponse: ...
612
+
613
+ def call(
614
+ self,
615
+ call_abi_method: ABIMethod | bool | None = None,
616
+ transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None,
617
+ **abi_kwargs: ABIArgType,
618
+ ) -> TransactionResponse | ABITransactionResponse:
619
+ """Submits a signed transaction with specified parameters"""
620
+ atc = AtomicTransactionComposer()
621
+ _parameters = _convert_transaction_parameters(transaction_parameters)
622
+ self.compose_call(
623
+ atc,
624
+ call_abi_method=call_abi_method,
625
+ transaction_parameters=_parameters,
626
+ **abi_kwargs,
627
+ )
628
+
629
+ method = self._resolve_method(
630
+ call_abi_method, abi_kwargs, _parameters.on_complete or transaction.OnComplete.NoOpOC
631
+ )
632
+ if method:
633
+ hints = self._method_hints(method)
634
+ if hints and hints.read_only:
635
+ if config.debug and config.project_root and config.trace_all:
636
+ from algokit_utils._debugging import simulate_and_persist_response
637
+
638
+ simulate_and_persist_response(
639
+ atc, config.project_root, self.algod_client, config.trace_buffer_size_mb
640
+ )
641
+
642
+ return self._simulate_readonly_call(method, atc)
643
+
644
+ return self._execute_atc_tr(atc)
645
+
646
+ def compose_opt_in(
647
+ self,
648
+ atc: AtomicTransactionComposer,
649
+ /,
650
+ call_abi_method: ABIMethod | bool | None = None,
651
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
652
+ **abi_kwargs: ABIArgType,
653
+ ) -> None:
654
+ """Adds a signed transaction with on_complete=OptIn to atc"""
655
+ self.add_method_call(
656
+ atc,
657
+ abi_method=call_abi_method,
658
+ abi_args=abi_kwargs,
659
+ parameters=transaction_parameters,
660
+ on_complete=transaction.OnComplete.OptInOC,
661
+ )
662
+
663
+ @overload
664
+ def opt_in(
665
+ self,
666
+ call_abi_method: ABIMethod | Literal[True] = ...,
667
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
668
+ **abi_kwargs: ABIArgType,
669
+ ) -> ABITransactionResponse: ...
670
+
671
+ @overload
672
+ def opt_in(
673
+ self,
674
+ call_abi_method: Literal[False] = ...,
675
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
676
+ ) -> TransactionResponse: ...
677
+
678
+ @overload
679
+ def opt_in(
680
+ self,
681
+ call_abi_method: ABIMethod | bool | None = ...,
682
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
683
+ **abi_kwargs: ABIArgType,
684
+ ) -> TransactionResponse | ABITransactionResponse: ...
685
+
686
+ def opt_in(
687
+ self,
688
+ call_abi_method: ABIMethod | bool | None = None,
689
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
690
+ **abi_kwargs: ABIArgType,
691
+ ) -> TransactionResponse | ABITransactionResponse:
692
+ """Submits a signed transaction with on_complete=OptIn"""
693
+ atc = AtomicTransactionComposer()
694
+ self.compose_opt_in(
695
+ atc,
696
+ call_abi_method=call_abi_method,
697
+ transaction_parameters=transaction_parameters,
698
+ **abi_kwargs,
699
+ )
700
+ return self._execute_atc_tr(atc)
701
+
702
+ def compose_close_out(
703
+ self,
704
+ atc: AtomicTransactionComposer,
705
+ /,
706
+ call_abi_method: ABIMethod | bool | None = None,
707
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
708
+ **abi_kwargs: ABIArgType,
709
+ ) -> None:
710
+ """Adds a signed transaction with on_complete=CloseOut to ac"""
711
+ self.add_method_call(
712
+ atc,
713
+ abi_method=call_abi_method,
714
+ abi_args=abi_kwargs,
715
+ parameters=transaction_parameters,
716
+ on_complete=transaction.OnComplete.CloseOutOC,
717
+ )
718
+
719
+ @overload
720
+ def close_out(
721
+ self,
722
+ call_abi_method: ABIMethod | Literal[True],
723
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
724
+ **abi_kwargs: ABIArgType,
725
+ ) -> ABITransactionResponse: ...
726
+
727
+ @overload
728
+ def close_out(
729
+ self,
730
+ call_abi_method: Literal[False],
731
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
732
+ ) -> TransactionResponse: ...
733
+
734
+ @overload
735
+ def close_out(
736
+ self,
737
+ call_abi_method: ABIMethod | bool | None = ...,
738
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
739
+ **abi_kwargs: ABIArgType,
740
+ ) -> TransactionResponse | ABITransactionResponse: ...
741
+
742
+ def close_out(
743
+ self,
744
+ call_abi_method: ABIMethod | bool | None = None,
745
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
746
+ **abi_kwargs: ABIArgType,
747
+ ) -> TransactionResponse | ABITransactionResponse:
748
+ """Submits a signed transaction with on_complete=CloseOut"""
749
+ atc = AtomicTransactionComposer()
750
+ self.compose_close_out(
751
+ atc,
752
+ call_abi_method=call_abi_method,
753
+ transaction_parameters=transaction_parameters,
754
+ **abi_kwargs,
755
+ )
756
+ return self._execute_atc_tr(atc)
757
+
758
+ def compose_clear_state(
759
+ self,
760
+ atc: AtomicTransactionComposer,
761
+ /,
762
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
763
+ app_args: list[bytes] | None = None,
764
+ ) -> None:
765
+ """Adds a signed transaction with on_complete=ClearState to atc"""
766
+ return self.add_method_call(
767
+ atc,
768
+ parameters=transaction_parameters,
769
+ on_complete=transaction.OnComplete.ClearStateOC,
770
+ app_args=app_args,
771
+ )
772
+
773
+ def clear_state(
774
+ self,
775
+ transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
776
+ app_args: list[bytes] | None = None,
777
+ ) -> TransactionResponse:
778
+ """Submits a signed transaction with on_complete=ClearState"""
779
+ atc = AtomicTransactionComposer()
780
+ self.compose_clear_state(
781
+ atc,
782
+ transaction_parameters=transaction_parameters,
783
+ app_args=app_args,
784
+ )
785
+ return self._execute_atc_tr(atc)
786
+
787
+ def get_global_state(self, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]:
788
+ """Gets the global state info associated with app_id"""
789
+ global_state = self.algod_client.application_info(self.app_id)
790
+ assert isinstance(global_state, dict)
791
+ return cast(
792
+ dict[bytes | str, bytes | str | int],
793
+ _decode_state(global_state.get("params", {}).get("global-state", {}), raw=raw),
794
+ )
795
+
796
+ def get_local_state(self, account: str | None = None, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]:
797
+ """Gets the local state info for associated app_id and account/sender"""
798
+
799
+ if account is None:
800
+ _, account = self.resolve_signer_sender(self.signer, self.sender)
801
+
802
+ acct_state = self.algod_client.account_application_info(account, self.app_id)
803
+ assert isinstance(acct_state, dict)
804
+ return cast(
805
+ dict[bytes | str, bytes | str | int],
806
+ _decode_state(acct_state.get("app-local-state", {}).get("key-value", {}), raw=raw),
807
+ )
808
+
809
+ def resolve(self, to_resolve: au_spec.DefaultArgumentDict) -> int | str | bytes:
810
+ """Resolves the default value for an ABI method, based on app_spec"""
811
+
812
+ def _data_check(value: object) -> int | str | bytes:
813
+ if isinstance(value, int | str | bytes):
814
+ return value
815
+ raise ValueError(f"Unexpected type for constant data: {value}")
816
+
817
+ match to_resolve:
818
+ case {"source": "constant", "data": data}:
819
+ return _data_check(data)
820
+ case {"source": "global-state", "data": str() as key}:
821
+ global_state = self.get_global_state(raw=True)
822
+ return global_state[key.encode()]
823
+ case {"source": "local-state", "data": str() as key}:
824
+ _, sender = self.resolve_signer_sender(self.signer, self.sender)
825
+ acct_state = self.get_local_state(sender, raw=True)
826
+ return acct_state[key.encode()]
827
+ case {"source": "abi-method", "data": dict() as method_dict}:
828
+ method = Method.undictify(method_dict)
829
+ response = self.call(method)
830
+ assert isinstance(response, ABITransactionResponse)
831
+ return _data_check(response.return_value)
832
+
833
+ case {"source": source}:
834
+ raise ValueError(f"Unrecognized default argument source: {source}")
835
+ case _:
836
+ raise TypeError("Unable to interpret default argument specification")
837
+
838
+ def _get_app_deploy_metadata(
839
+ self, version: str | None, allow_update: bool | None, allow_delete: bool | None
840
+ ) -> au_deploy.AppDeployMetaData:
841
+ updatable = (
842
+ allow_update
843
+ if allow_update is not None
844
+ else au_deploy.get_deploy_control(
845
+ self.app_spec, au_deploy.UPDATABLE_TEMPLATE_NAME, transaction.OnComplete.UpdateApplicationOC
846
+ )
847
+ )
848
+ deletable = (
849
+ allow_delete
850
+ if allow_delete is not None
851
+ else au_deploy.get_deploy_control(
852
+ self.app_spec, au_deploy.DELETABLE_TEMPLATE_NAME, transaction.OnComplete.DeleteApplicationOC
853
+ )
854
+ )
855
+
856
+ app = self._load_app_reference()
857
+
858
+ if version is None:
859
+ if app.app_id == 0:
860
+ version = "v1.0"
861
+ else:
862
+ assert isinstance(app, au_deploy.AppDeployMetaData)
863
+ version = get_next_version(app.version)
864
+ return au_deploy.AppDeployMetaData(self.app_name, version, updatable=updatable, deletable=deletable)
865
+
866
+ def _check_is_compiled(self) -> tuple[Program, Program]:
867
+ if self._approval_program is None or self._clear_program is None:
868
+ self._approval_program, self._clear_program = substitute_template_and_compile(
869
+ self.algod_client, self.app_spec, self.template_values
870
+ )
871
+
872
+ if config.debug and config.project_root:
873
+ from algokit_utils._debugging import PersistSourceMapInput, persist_sourcemaps
874
+
875
+ persist_sourcemaps(
876
+ sources=[
877
+ PersistSourceMapInput(
878
+ compiled_teal=self._approval_program, app_name=self.app_name, file_name="approval.teal"
879
+ ),
880
+ PersistSourceMapInput(
881
+ compiled_teal=self._clear_program, app_name=self.app_name, file_name="clear.teal"
882
+ ),
883
+ ],
884
+ project_root=config.project_root,
885
+ client=self.algod_client,
886
+ with_sources=True,
887
+ )
888
+
889
+ return self._approval_program, self._clear_program
890
+
891
+ def _simulate_readonly_call(
892
+ self, method: Method, atc: AtomicTransactionComposer
893
+ ) -> ABITransactionResponse | TransactionResponse:
894
+ from algokit_utils._debugging import simulate_response
895
+
896
+ response = simulate_response(atc, self.algod_client)
897
+ traces = None
898
+ if config.debug:
899
+ traces = _create_simulate_traces(response)
900
+ if response.failure_message:
901
+ raise _try_convert_to_logic_error(
902
+ response.failure_message,
903
+ self.app_spec.approval_program,
904
+ self._get_approval_source_map,
905
+ traces,
906
+ ) or Exception(f"Simulate failed for readonly method {method.get_signature()}: {response.failure_message}")
907
+
908
+ return TransactionResponse.from_atr(response)
909
+
910
+ def _load_reference_and_check_app_id(self) -> None:
911
+ self._load_app_reference()
912
+ self._check_app_id()
913
+
914
+ def _load_app_reference(self) -> au_deploy.AppReference | au_deploy.AppMetaData:
915
+ if not self.existing_deployments and self._creator:
916
+ assert self._indexer_client
917
+ self.existing_deployments = au_deploy.get_creator_apps(self._indexer_client, self._creator)
918
+
919
+ if self.existing_deployments:
920
+ app = self.existing_deployments.apps.get(self.app_name)
921
+ if app:
922
+ if self.app_id == 0:
923
+ self.app_id = app.app_id
924
+ return app
925
+
926
+ return au_deploy.AppReference(self.app_id, self.app_address)
927
+
928
+ def _check_app_id(self) -> None:
929
+ if self.app_id == 0:
930
+ raise Exception(
931
+ "ApplicationClient is not associated with an app instance, to resolve either:\n"
932
+ "1.provide an app_id on construction OR\n"
933
+ "2.provide a creator address so an app can be searched for OR\n"
934
+ "3.create an app first using create or deploy methods"
935
+ )
936
+
937
+ def _resolve_method(
938
+ self,
939
+ abi_method: ABIMethod | bool | None,
940
+ args: ABIArgsDict | None,
941
+ on_complete: transaction.OnComplete,
942
+ call_config: au_spec.CallConfig = au_spec.CallConfig.CALL,
943
+ ) -> Method | None:
944
+ matches: list[Method | None] = []
945
+ match abi_method:
946
+ case str() | Method(): # abi method specified
947
+ return self._resolve_abi_method(abi_method)
948
+ case bool() | None: # find abi method
949
+ has_bare_config = (
950
+ call_config in au_deploy.get_call_config(self.app_spec.bare_call_config, on_complete)
951
+ or on_complete == transaction.OnComplete.ClearStateOC
952
+ )
953
+ abi_methods = self._find_abi_methods(args, on_complete, call_config)
954
+ if abi_method is not False:
955
+ matches += abi_methods
956
+ if has_bare_config and abi_method is not True:
957
+ matches += [None]
958
+ case _:
959
+ return abi_method.method_spec()
960
+
961
+ if len(matches) == 1: # exact match
962
+ return matches[0]
963
+ elif len(matches) > 1: # ambiguous match
964
+ signatures = ", ".join((m.get_signature() if isinstance(m, Method) else "bare") for m in matches)
965
+ raise Exception(
966
+ f"Could not find an exact method to use for {on_complete.name} with call_config of {call_config.name}, "
967
+ f"specify the exact method using abi_method and args parameters, considered: {signatures}"
968
+ )
969
+ else: # no match
970
+ raise Exception(
971
+ f"Could not find any methods to use for {on_complete.name} with call_config of {call_config.name}"
972
+ )
973
+
974
+ def _get_approval_source_map(self) -> SourceMap | None:
975
+ if self.approval_source_map:
976
+ return self.approval_source_map
977
+
978
+ try:
979
+ approval, _ = self._check_is_compiled()
980
+ except au_deploy.DeploymentFailedError:
981
+ return None
982
+ return approval.source_map
983
+
984
+ def export_source_map(self) -> str | None:
985
+ """Export approval source map to JSON, can be later re-imported with `import_source_map`"""
986
+ source_map = self._get_approval_source_map()
987
+ if source_map:
988
+ return json.dumps(
989
+ {
990
+ "version": source_map.version,
991
+ "sources": source_map.sources,
992
+ "mappings": source_map.mappings,
993
+ }
994
+ )
995
+ return None
996
+
997
+ def import_source_map(self, source_map_json: str) -> None:
998
+ """Import approval source from JSON exported by `export_source_map`"""
999
+ source_map = json.loads(source_map_json)
1000
+ self._approval_source_map = SourceMap(source_map)
1001
+
1002
+ def add_method_call( # noqa: PLR0913
1003
+ self,
1004
+ atc: AtomicTransactionComposer,
1005
+ abi_method: ABIMethod | bool | None = None,
1006
+ *,
1007
+ abi_args: ABIArgsDict | None = None,
1008
+ app_id: int | None = None,
1009
+ parameters: TransactionParameters | TransactionParametersDict | None = None,
1010
+ on_complete: transaction.OnComplete = transaction.OnComplete.NoOpOC,
1011
+ local_schema: transaction.StateSchema | None = None,
1012
+ global_schema: transaction.StateSchema | None = None,
1013
+ approval_program: bytes | None = None,
1014
+ clear_program: bytes | None = None,
1015
+ extra_pages: int | None = None,
1016
+ app_args: list[bytes] | None = None,
1017
+ call_config: au_spec.CallConfig = au_spec.CallConfig.CALL,
1018
+ ) -> None:
1019
+ """Adds a transaction to the AtomicTransactionComposer passed"""
1020
+ if app_id is None:
1021
+ self._load_reference_and_check_app_id()
1022
+ app_id = self.app_id
1023
+ parameters = _convert_transaction_parameters(parameters)
1024
+ method = self._resolve_method(abi_method, abi_args, on_complete, call_config)
1025
+ sp = parameters.suggested_params or self.suggested_params or self.algod_client.suggested_params()
1026
+ signer, sender = self.resolve_signer_sender(parameters.signer, parameters.sender)
1027
+ if parameters.boxes is not None:
1028
+ # TODO: algosdk actually does this, but it's type hints say otherwise...
1029
+ encoded_boxes = [(id_, algosdk.encoding.encode_as_bytes(name)) for id_, name in parameters.boxes]
1030
+ else:
1031
+ encoded_boxes = None
1032
+
1033
+ encoded_lease = parameters.lease.encode("utf-8") if isinstance(parameters.lease, str) else parameters.lease
1034
+
1035
+ if not method: # not an abi method, treat as a regular call
1036
+ if abi_args:
1037
+ raise Exception(f"ABI arguments specified on a bare call: {', '.join(abi_args)}")
1038
+ atc.add_transaction(
1039
+ TransactionWithSigner(
1040
+ txn=transaction.ApplicationCallTxn(
1041
+ sender=sender,
1042
+ sp=sp,
1043
+ index=app_id,
1044
+ on_complete=on_complete,
1045
+ approval_program=approval_program,
1046
+ clear_program=clear_program,
1047
+ global_schema=global_schema,
1048
+ local_schema=local_schema,
1049
+ extra_pages=extra_pages,
1050
+ accounts=parameters.accounts,
1051
+ foreign_apps=parameters.foreign_apps,
1052
+ foreign_assets=parameters.foreign_assets,
1053
+ boxes=encoded_boxes,
1054
+ note=parameters.note,
1055
+ lease=encoded_lease,
1056
+ rekey_to=parameters.rekey_to,
1057
+ app_args=app_args,
1058
+ ),
1059
+ signer=signer,
1060
+ )
1061
+ )
1062
+ return
1063
+ # resolve ABI method args
1064
+ args = self._get_abi_method_args(abi_args, method)
1065
+ atc.add_method_call(
1066
+ app_id,
1067
+ method,
1068
+ sender,
1069
+ sp,
1070
+ signer,
1071
+ method_args=args,
1072
+ on_complete=on_complete,
1073
+ local_schema=local_schema,
1074
+ global_schema=global_schema,
1075
+ approval_program=approval_program,
1076
+ clear_program=clear_program,
1077
+ extra_pages=extra_pages or 0,
1078
+ accounts=parameters.accounts,
1079
+ foreign_apps=parameters.foreign_apps,
1080
+ foreign_assets=parameters.foreign_assets,
1081
+ boxes=encoded_boxes,
1082
+ note=parameters.note.encode("utf-8") if isinstance(parameters.note, str) else parameters.note,
1083
+ lease=encoded_lease,
1084
+ rekey_to=parameters.rekey_to,
1085
+ )
1086
+
1087
+ def _get_abi_method_args(self, abi_args: ABIArgsDict | None, method: Method) -> list:
1088
+ args: list = []
1089
+ hints = self._method_hints(method)
1090
+ # copy args so we don't mutate original
1091
+ abi_args = dict(abi_args or {})
1092
+ for method_arg in method.args:
1093
+ name = method_arg.name
1094
+ if name in abi_args:
1095
+ argument = abi_args.pop(name)
1096
+ if isinstance(argument, dict):
1097
+ if hints.structs is None or name not in hints.structs:
1098
+ raise Exception(f"Argument missing struct hint: {name}. Check argument name and type")
1099
+
1100
+ elements = hints.structs[name]["elements"]
1101
+
1102
+ argument_tuple = tuple(argument[field_name] for field_name, field_type in elements)
1103
+ args.append(argument_tuple)
1104
+ else:
1105
+ args.append(argument)
1106
+
1107
+ elif hints.default_arguments is not None and name in hints.default_arguments:
1108
+ default_arg = hints.default_arguments[name]
1109
+ if default_arg is not None:
1110
+ args.append(self.resolve(default_arg))
1111
+ else:
1112
+ raise Exception(f"Unspecified argument: {name}")
1113
+ if abi_args:
1114
+ raise Exception(f"Unused arguments specified: {', '.join(abi_args)}")
1115
+ return args
1116
+
1117
+ def _method_matches(
1118
+ self,
1119
+ method: Method,
1120
+ args: ABIArgsDict | None,
1121
+ on_complete: transaction.OnComplete,
1122
+ call_config: au_spec.CallConfig,
1123
+ ) -> bool:
1124
+ hints = self._method_hints(method)
1125
+ if call_config not in au_deploy.get_call_config(hints.call_config, on_complete):
1126
+ return False
1127
+ method_args = {m.name for m in method.args}
1128
+ provided_args = set(args or {}) | set(hints.default_arguments)
1129
+
1130
+ # TODO: also match on types?
1131
+ return method_args == provided_args
1132
+
1133
+ def _find_abi_methods(
1134
+ self, args: ABIArgsDict | None, on_complete: transaction.OnComplete, call_config: au_spec.CallConfig
1135
+ ) -> list[Method]:
1136
+ return [
1137
+ method
1138
+ for method in self.app_spec.contract.methods
1139
+ if self._method_matches(method, args, on_complete, call_config)
1140
+ ]
1141
+
1142
+ def _resolve_abi_method(self, method: ABIMethod) -> Method:
1143
+ if isinstance(method, str):
1144
+ try:
1145
+ return next(iter(m for m in self.app_spec.contract.methods if m.get_signature() == method))
1146
+ except StopIteration:
1147
+ pass
1148
+ return self.app_spec.contract.get_method_by_name(method)
1149
+ elif hasattr(method, "method_spec"):
1150
+ return method.method_spec()
1151
+ else:
1152
+ return method
1153
+
1154
+ def _method_hints(self, method: Method) -> au_spec.MethodHints:
1155
+ sig = method.get_signature()
1156
+ if sig not in self.app_spec.hints:
1157
+ return au_spec.MethodHints()
1158
+ return self.app_spec.hints[sig]
1159
+
1160
+ def _execute_atc_tr(self, atc: AtomicTransactionComposer) -> TransactionResponse:
1161
+ result = self.execute_atc(atc)
1162
+ return TransactionResponse.from_atr(result)
1163
+
1164
+ def execute_atc(self, atc: AtomicTransactionComposer) -> AtomicTransactionResponse:
1165
+ return execute_atc_with_logic_error(
1166
+ atc,
1167
+ self.algod_client,
1168
+ approval_program=self.app_spec.approval_program,
1169
+ approval_source_map=self._get_approval_source_map,
1170
+ )
1171
+
1172
+ def get_signer_sender(
1173
+ self, signer: TransactionSigner | None = None, sender: str | None = None
1174
+ ) -> tuple[TransactionSigner | None, str | None]:
1175
+ """Return signer and sender, using default values on client if not specified
1176
+
1177
+ Will use provided values if given, otherwise will fall back to values defined on client.
1178
+ If no sender is specified then will attempt to obtain sender from signer"""
1179
+ resolved_signer = signer or self.signer
1180
+ resolved_sender = sender or get_sender_from_signer(signer) or self.sender or get_sender_from_signer(self.signer)
1181
+ return resolved_signer, resolved_sender
1182
+
1183
+ def resolve_signer_sender(
1184
+ self, signer: TransactionSigner | None = None, sender: str | None = None
1185
+ ) -> tuple[TransactionSigner, str]:
1186
+ """Return signer and sender, using default values on client if not specified
1187
+
1188
+ Will use provided values if given, otherwise will fall back to values defined on client.
1189
+ If no sender is specified then will attempt to obtain sender from signer
1190
+
1191
+ :raises ValueError: Raised if a signer or sender is not provided. See `get_signer_sender`
1192
+ for variant with no exception"""
1193
+ resolved_signer, resolved_sender = self.get_signer_sender(signer, sender)
1194
+ if not resolved_signer:
1195
+ raise ValueError("No signer provided")
1196
+ if not resolved_sender:
1197
+ raise ValueError("No sender provided")
1198
+ return resolved_signer, resolved_sender
1199
+
1200
+ # TODO: remove private implementation, kept in the 1.0.2 release to not impact existing beaker 1.0 installs
1201
+ _resolve_signer_sender = resolve_signer_sender
1202
+
1203
+
1204
+ def substitute_template_and_compile(
1205
+ algod_client: AlgodClient,
1206
+ app_spec: au_spec.ApplicationSpecification,
1207
+ template_values: au_deploy.TemplateValueMapping,
1208
+ ) -> tuple[Program, Program]:
1209
+ """Substitutes the provided template_values into app_spec and compiles"""
1210
+ template_values = dict(template_values or {})
1211
+ clear = au_deploy.replace_template_variables(app_spec.clear_program, template_values)
1212
+
1213
+ au_deploy.check_template_variables(app_spec.approval_program, template_values)
1214
+ approval = au_deploy.replace_template_variables(app_spec.approval_program, template_values)
1215
+
1216
+ approval_app, clear_app = Program(approval, algod_client), Program(clear, algod_client)
1217
+
1218
+ return approval_app, clear_app
1219
+
1220
+
1221
+ def get_next_version(current_version: str) -> str:
1222
+ """Calculates the next version from `current_version`
1223
+
1224
+ Next version is calculated by finding a semver like
1225
+ version string and incrementing the lower. This function is used by {py:meth}`ApplicationClient.deploy` when
1226
+ a version is not specified, and is intended mostly for convenience during local development.
1227
+
1228
+ :params str current_version: An existing version string with a semver like version contained within it,
1229
+ some valid inputs and incremented outputs:
1230
+ `1` -> `2`
1231
+ `1.0` -> `1.1`
1232
+ `v1.1` -> `v1.2`
1233
+ `v1.1-beta1` -> `v1.2-beta1`
1234
+ `v1.2.3.4567` -> `v1.2.3.4568`
1235
+ `v1.2.3.4567-alpha` -> `v1.2.3.4568-alpha`
1236
+ :raises DeploymentFailedError: If `current_version` cannot be parsed"""
1237
+ pattern = re.compile(r"(?P<prefix>\w*)(?P<version>(?:\d+\.)*\d+)(?P<suffix>\w*)")
1238
+ match = pattern.match(current_version)
1239
+ if match:
1240
+ version = match.group("version")
1241
+ new_version = _increment_version(version)
1242
+
1243
+ def replacement(m: re.Match) -> str:
1244
+ return f"{m.group('prefix')}{new_version}{m.group('suffix')}"
1245
+
1246
+ return re.sub(pattern, replacement, current_version)
1247
+ raise au_deploy.DeploymentFailedError(
1248
+ f"Could not auto increment {current_version}, please specify the next version using the version parameter"
1249
+ )
1250
+
1251
+
1252
+ def _try_convert_to_logic_error(
1253
+ source_ex: Exception | str,
1254
+ approval_program: str,
1255
+ approval_source_map: SourceMap | typing.Callable[[], SourceMap | None] | None = None,
1256
+ simulate_traces: list[SimulationTrace] | None = None,
1257
+ ) -> Exception | None:
1258
+ source_ex_str = str(source_ex)
1259
+ logic_error_data = parse_logic_error(source_ex_str)
1260
+ if logic_error_data:
1261
+ return LogicError(
1262
+ logic_error_str=source_ex_str,
1263
+ logic_error=source_ex if isinstance(source_ex, Exception) else None,
1264
+ program=approval_program,
1265
+ source_map=approval_source_map() if callable(approval_source_map) else approval_source_map,
1266
+ **logic_error_data,
1267
+ traces=simulate_traces,
1268
+ )
1269
+
1270
+ return None
1271
+
1272
+
1273
+ @deprecated(
1274
+ "The execute_atc_with_logic_error function is deprecated; use AppClient's error handling and TransactionComposer's "
1275
+ "send method for equivalent functionality and improved error management."
1276
+ )
1277
+ def execute_atc_with_logic_error(
1278
+ atc: AtomicTransactionComposer,
1279
+ algod_client: AlgodClient,
1280
+ approval_program: str,
1281
+ wait_rounds: int = 4,
1282
+ approval_source_map: SourceMap | typing.Callable[[], SourceMap | None] | None = None,
1283
+ ) -> AtomicTransactionResponse:
1284
+ """Calls {py:meth}`AtomicTransactionComposer.execute` on provided `atc`, but will parse any errors
1285
+ and raise a {py:class}`LogicError` if possible
1286
+
1287
+ ```{note}
1288
+ `approval_program` and `approval_source_map` are required to be able to parse any errors into a
1289
+ {py:class}`LogicError`
1290
+ ```
1291
+ """
1292
+ from algokit_utils._debugging import simulate_and_persist_response, simulate_response
1293
+
1294
+ try:
1295
+ if config.debug and config.project_root and config.trace_all:
1296
+ simulate_and_persist_response(atc, config.project_root, algod_client, config.trace_buffer_size_mb)
1297
+
1298
+ return atc.execute(algod_client, wait_rounds=wait_rounds)
1299
+ except Exception as ex:
1300
+ if config.debug:
1301
+ simulate = None
1302
+ if config.project_root and not config.trace_all:
1303
+ # if trace_all is enabled, we already have the traces executed above
1304
+ # hence we only need to simulate if trace_all is disabled and
1305
+ # project_root is set
1306
+ simulate = simulate_and_persist_response(
1307
+ atc, config.project_root, algod_client, config.trace_buffer_size_mb
1308
+ )
1309
+ else:
1310
+ simulate = simulate_response(atc, algod_client)
1311
+ traces = _create_simulate_traces(simulate)
1312
+ else:
1313
+ traces = None
1314
+ logger.info("An error occurred while executing the transaction.")
1315
+ logger.info("To see more details, enable debug mode by setting config.debug = True ")
1316
+
1317
+ logic_error = _try_convert_to_logic_error(ex, approval_program, approval_source_map, traces)
1318
+ if logic_error:
1319
+ raise logic_error from ex
1320
+ raise ex
1321
+
1322
+
1323
+ def _create_simulate_traces(simulate: SimulateAtomicTransactionResponse) -> list[SimulationTrace]:
1324
+ traces = []
1325
+ if hasattr(simulate, "simulate_response") and hasattr(simulate, "failed_at") and simulate.failed_at:
1326
+ for txn_group in simulate.simulate_response["txn-groups"]:
1327
+ app_budget_added = txn_group.get("app-budget-added", None)
1328
+ app_budget_consumed = txn_group.get("app-budget-consumed", None)
1329
+ failure_message = txn_group.get("failure-message", None)
1330
+ txn_result = txn_group.get("txn-results", [{}])[0]
1331
+ exec_trace = txn_result.get("exec-trace", {})
1332
+ traces.append(
1333
+ SimulationTrace(
1334
+ app_budget_added=app_budget_added,
1335
+ app_budget_consumed=app_budget_consumed,
1336
+ failure_message=failure_message,
1337
+ exec_trace=exec_trace,
1338
+ )
1339
+ )
1340
+ return traces
1341
+
1342
+
1343
+ def _convert_transaction_parameters(
1344
+ args: TransactionParameters | TransactionParametersDict | None,
1345
+ ) -> CreateCallParameters:
1346
+ _args = args.__dict__ if isinstance(args, TransactionParameters) else (args or {})
1347
+ return CreateCallParameters(**_args)
1348
+
1349
+
1350
+ def get_sender_from_signer(signer: TransactionSigner | None) -> str | None:
1351
+ """Returns the associated address of a signer, return None if no address found"""
1352
+
1353
+ if isinstance(signer, AccountTransactionSigner):
1354
+ sender = address_from_private_key(signer.private_key)
1355
+ assert isinstance(sender, str)
1356
+ return sender
1357
+ elif isinstance(signer, MultisigTransactionSigner):
1358
+ sender = signer.msig.address()
1359
+ assert isinstance(sender, str)
1360
+ return sender
1361
+ elif isinstance(signer, LogicSigTransactionSigner):
1362
+ return signer.lsig.address()
1363
+ return None
1364
+
1365
+
1366
+ # TEMPORARY, use SDK one when available
1367
+ def _parse_result(
1368
+ methods: dict[int, Method],
1369
+ txns: list[dict[str, Any]],
1370
+ txids: list[str],
1371
+ ) -> list[ABIResult]:
1372
+ method_results = []
1373
+ for i, tx_info in enumerate(txns):
1374
+ raw_value = b""
1375
+ return_value = None
1376
+ decode_error = None
1377
+
1378
+ if i not in methods:
1379
+ continue
1380
+
1381
+ # Parse log for ABI method return value
1382
+ try:
1383
+ if methods[i].returns.type == Returns.VOID:
1384
+ method_results.append(
1385
+ ABIResult(
1386
+ tx_id=txids[i],
1387
+ raw_value=raw_value,
1388
+ return_value=return_value,
1389
+ decode_error=decode_error,
1390
+ tx_info=tx_info,
1391
+ method=methods[i],
1392
+ )
1393
+ )
1394
+ continue
1395
+
1396
+ logs = tx_info.get("logs", [])
1397
+
1398
+ # Look for the last returned value in the log
1399
+ if not logs:
1400
+ raise Exception("No logs")
1401
+
1402
+ result = logs[-1]
1403
+ # Check that the first four bytes is the hash of "return"
1404
+ result_bytes = base64.b64decode(result)
1405
+ if len(result_bytes) < len(ABI_RETURN_HASH) or result_bytes[: len(ABI_RETURN_HASH)] != ABI_RETURN_HASH:
1406
+ raise Exception("no logs")
1407
+
1408
+ raw_value = result_bytes[4:]
1409
+ abi_return_type = methods[i].returns.type
1410
+ if isinstance(abi_return_type, ABIType):
1411
+ return_value = abi_return_type.decode(raw_value)
1412
+ else:
1413
+ return_value = raw_value
1414
+
1415
+ except Exception as e:
1416
+ decode_error = e
1417
+
1418
+ method_results.append(
1419
+ ABIResult(
1420
+ tx_id=txids[i],
1421
+ raw_value=raw_value,
1422
+ return_value=return_value,
1423
+ decode_error=decode_error,
1424
+ tx_info=tx_info,
1425
+ method=methods[i],
1426
+ )
1427
+ )
1428
+
1429
+ return method_results
1430
+
1431
+
1432
+ def _increment_version(version: str) -> str:
1433
+ split = list(map(int, version.split(".")))
1434
+ split[-1] = split[-1] + 1
1435
+ return ".".join(str(x) for x in split)
1436
+
1437
+
1438
+ def _str_or_hex(v: bytes) -> str:
1439
+ decoded: str
1440
+ try:
1441
+ decoded = v.decode("utf-8")
1442
+ except UnicodeDecodeError:
1443
+ decoded = v.hex()
1444
+
1445
+ return decoded
1446
+
1447
+
1448
+ def _decode_state(state: list[dict[str, Any]], *, raw: bool = False) -> dict[str | bytes, bytes | str | int | None]:
1449
+ decoded_state: dict[str | bytes, bytes | str | int | None] = {}
1450
+
1451
+ for state_value in state:
1452
+ raw_key = base64.b64decode(state_value["key"])
1453
+
1454
+ key: str | bytes = raw_key if raw else _str_or_hex(raw_key)
1455
+ val: str | bytes | int | None
1456
+
1457
+ action = state_value["value"]["action"] if "action" in state_value["value"] else state_value["value"]["type"]
1458
+
1459
+ match action:
1460
+ case 1:
1461
+ raw_val = base64.b64decode(state_value["value"]["bytes"])
1462
+ val = raw_val if raw else _str_or_hex(raw_val)
1463
+ case 2:
1464
+ val = state_value["value"]["uint"]
1465
+ case 3:
1466
+ val = None
1467
+ case _:
1468
+ raise NotImplementedError
1469
+
1470
+ decoded_state[key] = val
1471
+ return decoded_state