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