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