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,578 @@
1
+ import base64
2
+ from collections.abc import Mapping
3
+ from typing import Any, cast
4
+
5
+ import algosdk
6
+ import algosdk.atomic_transaction_composer
7
+ import algosdk.box_reference
8
+ from algosdk.atomic_transaction_composer import AccountTransactionSigner
9
+ from algosdk.box_reference import BoxReference as AlgosdkBoxReference
10
+ from algosdk.logic import get_application_address
11
+ from algosdk.source_map import SourceMap
12
+ from algosdk.v2client import algod
13
+
14
+ from algokit_utils.applications.abi import ABIReturn, ABIType, ABIValue
15
+ from algokit_utils.models.application import (
16
+ AppInformation,
17
+ AppState,
18
+ CompiledTeal,
19
+ )
20
+ from algokit_utils.models.state import BoxIdentifier, BoxName, BoxReference, DataTypeFlag, TealTemplateParams
21
+
22
+ __all__ = [
23
+ "DELETABLE_TEMPLATE_NAME",
24
+ "UPDATABLE_TEMPLATE_NAME",
25
+ "AppManager",
26
+ ]
27
+
28
+
29
+ UPDATABLE_TEMPLATE_NAME = "TMPL_UPDATABLE"
30
+ """The name of the TEAL template variable for deploy-time immutability control."""
31
+
32
+ DELETABLE_TEMPLATE_NAME = "TMPL_DELETABLE"
33
+ """The name of the TEAL template variable for deploy-time permanence control."""
34
+
35
+
36
+ def _is_valid_token_character(char: str) -> bool:
37
+ return char.isalnum() or char == "_"
38
+
39
+
40
+ def _last_token_base64(line: str, idx: int) -> bool:
41
+ try:
42
+ *_, last = line[:idx].split()
43
+ except ValueError:
44
+ return False
45
+ return last in ("base64", "b64")
46
+
47
+
48
+ def _find_template_token(line: str, token: str, start: int = 0, end: int = -1) -> int | None:
49
+ if end < 0:
50
+ end = len(line)
51
+
52
+ idx = start
53
+ while idx < end:
54
+ token_idx = _find_unquoted_string(line, token, idx, end)
55
+ if token_idx is None:
56
+ break
57
+ trailing_idx = token_idx + len(token)
58
+ if (token_idx == 0 or not _is_valid_token_character(line[token_idx - 1])) and (
59
+ trailing_idx >= len(line) or not _is_valid_token_character(line[trailing_idx])
60
+ ):
61
+ return token_idx
62
+ idx = trailing_idx
63
+ return None
64
+
65
+
66
+ def _find_unquoted_string(line: str, token: str, start: int = 0, end: int = -1) -> int | None:
67
+ if end < 0:
68
+ end = len(line)
69
+ idx = start
70
+ in_quotes = in_base64 = False
71
+ while idx < end:
72
+ current_char = line[idx]
73
+ match current_char:
74
+ case " " | "(" if not in_quotes and _last_token_base64(line, idx):
75
+ in_base64 = True
76
+ case " " | ")" if not in_quotes and in_base64:
77
+ in_base64 = False
78
+ case "\\" if in_quotes:
79
+ idx += 1
80
+ case '"':
81
+ in_quotes = not in_quotes
82
+ case _ if not in_quotes and not in_base64 and line.startswith(token, idx):
83
+ return idx
84
+ idx += 1
85
+ return None
86
+
87
+
88
+ def _replace_template_variable(program_lines: list[str], template_variable: str, value: str) -> tuple[list[str], int]:
89
+ result: list[str] = []
90
+ match_count = 0
91
+ token = f"TMPL_{template_variable}" if not template_variable.startswith("TMPL_") else template_variable
92
+ token_idx_offset = len(value) - len(token)
93
+ for line in program_lines:
94
+ comment_idx = _find_unquoted_string(line, "//")
95
+ if comment_idx is None:
96
+ comment_idx = len(line)
97
+ code = line[:comment_idx]
98
+ comment = line[comment_idx:]
99
+ trailing_idx = 0
100
+ while True:
101
+ token_idx = _find_template_token(code, token, trailing_idx)
102
+ if token_idx is None:
103
+ break
104
+
105
+ trailing_idx = token_idx + len(token)
106
+ prefix = code[:token_idx]
107
+ suffix = code[trailing_idx:]
108
+ code = f"{prefix}{value}{suffix}"
109
+ match_count += 1
110
+ trailing_idx += token_idx_offset
111
+ result.append(code + comment)
112
+ return result, match_count
113
+
114
+
115
+ class AppManager:
116
+ """A manager class for interacting with Algorand applications.
117
+
118
+ Provides functionality for compiling TEAL code, managing application state,
119
+ and interacting with application boxes.
120
+
121
+ :param algod_client: The Algorand client instance to use for interacting with the network
122
+
123
+ :example:
124
+ >>> app_manager = AppManager(algod_client)
125
+ """
126
+
127
+ def __init__(self, algod_client: algod.AlgodClient):
128
+ self._algod = algod_client
129
+ self._compilation_results: dict[str, CompiledTeal] = {}
130
+
131
+ def compile_teal(self, teal_code: str) -> CompiledTeal:
132
+ """Compile TEAL source code.
133
+
134
+ :param teal_code: The TEAL source code to compile
135
+ :return: The compiled TEAL code and associated metadata
136
+ """
137
+
138
+ if teal_code in self._compilation_results:
139
+ return self._compilation_results[teal_code]
140
+
141
+ compiled = self._algod.compile(teal_code, source_map=True)
142
+ result = CompiledTeal(
143
+ teal=teal_code,
144
+ compiled=compiled["result"],
145
+ compiled_hash=compiled["hash"],
146
+ compiled_base64_to_bytes=base64.b64decode(compiled["result"]),
147
+ source_map=SourceMap(compiled.get("sourcemap", {})),
148
+ )
149
+ self._compilation_results[teal_code] = result
150
+ return result
151
+
152
+ def compile_teal_template(
153
+ self,
154
+ teal_template_code: str,
155
+ template_params: TealTemplateParams | None = None,
156
+ deployment_metadata: Mapping[str, bool | None] | None = None,
157
+ ) -> CompiledTeal:
158
+ """Compile a TEAL template with parameters.
159
+
160
+ :param teal_template_code: The TEAL template code to compile
161
+ :param template_params: Parameters to substitute in the template
162
+ :param deployment_metadata: Deployment control parameters
163
+ :return: The compiled TEAL code and associated metadata
164
+
165
+ :example:
166
+ >>> app_manager = AppManager(algod_client)
167
+ >>> teal_template_code =
168
+ ... # This is a TEAL template
169
+ ... # It can contain template variables like {TMPL_UPDATABLE} and {TMPL_DELETABLE}
170
+ ...
171
+ >>> compiled_teal = app_manager.compile_teal_template(teal_template_code)
172
+ """
173
+
174
+ teal_code = AppManager.strip_teal_comments(teal_template_code)
175
+ teal_code = AppManager.replace_template_variables(teal_code, template_params or {})
176
+
177
+ if deployment_metadata:
178
+ teal_code = AppManager.replace_teal_template_deploy_time_control_params(teal_code, deployment_metadata)
179
+
180
+ return self.compile_teal(teal_code)
181
+
182
+ def get_compilation_result(self, teal_code: str) -> CompiledTeal | None:
183
+ """Get cached compilation result for TEAL code if available.
184
+
185
+ :param teal_code: The TEAL source code
186
+ :return: The cached compilation result if available, None otherwise
187
+
188
+ :example:
189
+ >>> app_manager = AppManager(algod_client)
190
+ >>> teal_code = "RETURN 1"
191
+ >>> compiled_teal = app_manager.compile_teal(teal_code)
192
+ >>> compilation_result = app_manager.get_compilation_result(teal_code)
193
+ """
194
+ return self._compilation_results.get(teal_code)
195
+
196
+ def get_by_id(self, app_id: int) -> AppInformation:
197
+ """Get information about an application by ID.
198
+
199
+ :param app_id: The application ID
200
+ :return: Information about the application
201
+
202
+ :example:
203
+ >>> app_manager = AppManager(algod_client)
204
+ >>> app_id = 1234567890
205
+ >>> app_info = app_manager.get_by_id(app_id)
206
+ """
207
+
208
+ app = self._algod.application_info(app_id)
209
+ assert isinstance(app, dict)
210
+ app_params = app["params"]
211
+
212
+ return AppInformation(
213
+ app_id=app_id,
214
+ app_address=get_application_address(app_id),
215
+ approval_program=base64.b64decode(app_params["approval-program"]),
216
+ clear_state_program=base64.b64decode(app_params["clear-state-program"]),
217
+ creator=app_params["creator"],
218
+ local_ints=app_params["local-state-schema"]["num-uint"],
219
+ local_byte_slices=app_params["local-state-schema"]["num-byte-slice"],
220
+ global_ints=app_params["global-state-schema"]["num-uint"],
221
+ global_byte_slices=app_params["global-state-schema"]["num-byte-slice"],
222
+ extra_program_pages=app_params.get("extra-program-pages", 0),
223
+ global_state=self.decode_app_state(app_params.get("global-state", [])),
224
+ )
225
+
226
+ def get_global_state(self, app_id: int) -> dict[str, AppState]:
227
+ """Get the global state of an application.
228
+
229
+ :param app_id: The application ID
230
+ :return: The application's global state
231
+
232
+ :example:
233
+ >>> app_manager = AppManager(algod_client)
234
+ >>> app_id = 123
235
+ >>> global_state = app_manager.get_global_state(app_id)
236
+ """
237
+
238
+ return self.get_by_id(app_id).global_state
239
+
240
+ def get_local_state(self, app_id: int, address: str) -> dict[str, AppState]:
241
+ """Get the local state for an account in an application.
242
+
243
+ :param app_id: The application ID
244
+ :param address: The account address
245
+ :return: The account's local state for the application
246
+ :raises ValueError: If local state is not found
247
+
248
+ :example:
249
+ >>> app_manager = AppManager(algod_client)
250
+ >>> app_id = 123
251
+ >>> address = "SENDER_ADDRESS"
252
+ >>> local_state = app_manager.get_local_state(app_id, address)
253
+ """
254
+
255
+ app_info = self._algod.account_application_info(address, app_id)
256
+ assert isinstance(app_info, dict)
257
+ if not app_info.get("app-local-state", {}).get("key-value"):
258
+ raise ValueError("Couldn't find local state")
259
+ return self.decode_app_state(app_info["app-local-state"]["key-value"])
260
+
261
+ def get_box_names(self, app_id: int) -> list[BoxName]:
262
+ """Get names of all boxes for an application.
263
+
264
+ :param app_id: The application ID
265
+ :return: List of box names
266
+
267
+ :example:
268
+ >>> app_manager = AppManager(algod_client)
269
+ >>> app_id = 123
270
+ >>> box_names = app_manager.get_box_names(app_id)
271
+ """
272
+
273
+ box_result = self._algod.application_boxes(app_id)
274
+ assert isinstance(box_result, dict)
275
+ return [
276
+ BoxName(
277
+ name_raw=base64.b64decode(b["name"]),
278
+ name_base64=b["name"],
279
+ name=base64.b64decode(b["name"]).decode("utf-8"),
280
+ )
281
+ for b in box_result["boxes"]
282
+ ]
283
+
284
+ def get_box_value(self, app_id: int, box_name: BoxIdentifier) -> bytes:
285
+ """Get the value stored in a box.
286
+
287
+ :param app_id: The application ID
288
+ :param box_name: The box identifier
289
+ :return: The box value as bytes
290
+
291
+ :example:
292
+ >>> app_manager = AppManager(algod_client)
293
+ >>> app_id = 123
294
+ >>> box_name = "BOX_NAME"
295
+ >>> box_value = app_manager.get_box_value(app_id, box_name)
296
+ """
297
+
298
+ name = AppManager.get_box_reference(box_name)[1]
299
+ box_result = self._algod.application_box_by_name(app_id, name)
300
+ assert isinstance(box_result, dict)
301
+ return base64.b64decode(box_result["value"])
302
+
303
+ def get_box_values(self, app_id: int, box_names: list[BoxIdentifier]) -> list[bytes]:
304
+ """Get values for multiple boxes.
305
+
306
+ :param app_id: The application ID
307
+ :param box_names: List of box identifiers
308
+ :return: List of box values as bytes
309
+
310
+ :example:
311
+ >>> app_manager = AppManager(algod_client)
312
+ >>> app_id = 123
313
+ >>> box_names = ["BOX_NAME_1", "BOX_NAME_2"]
314
+ >>> box_values = app_manager.get_box_values(app_id, box_names)
315
+ """
316
+
317
+ return [self.get_box_value(app_id, box_name) for box_name in box_names]
318
+
319
+ def get_box_value_from_abi_type(self, app_id: int, box_name: BoxIdentifier, abi_type: ABIType) -> ABIValue:
320
+ """Get and decode a box value using an ABI type.
321
+
322
+ :param app_id: The application ID
323
+ :param box_name: The box identifier
324
+ :param abi_type: The ABI type to decode with
325
+ :return: The decoded box value
326
+ :raises ValueError: If decoding fails
327
+
328
+ :example:
329
+ >>> app_manager = AppManager(algod_client)
330
+ >>> app_id = 123
331
+ >>> box_name = "BOX_NAME"
332
+ >>> abi_type = ABIType.UINT
333
+ >>> box_value = app_manager.get_box_value_from_abi_type(app_id, box_name, abi_type)
334
+ """
335
+
336
+ value = self.get_box_value(app_id, box_name)
337
+ try:
338
+ parse_to_tuple = isinstance(abi_type, algosdk.abi.TupleType)
339
+ decoded_value = abi_type.decode(value)
340
+ return tuple(decoded_value) if parse_to_tuple else decoded_value
341
+ except Exception as e:
342
+ raise ValueError(f"Failed to decode box value {value.decode('utf-8')} with ABI type {abi_type}") from e
343
+
344
+ def get_box_values_from_abi_type(
345
+ self, app_id: int, box_names: list[BoxIdentifier], abi_type: ABIType
346
+ ) -> list[ABIValue]:
347
+ """Get and decode multiple box values using an ABI type.
348
+
349
+ :param app_id: The application ID
350
+ :param box_names: List of box identifiers
351
+ :param abi_type: The ABI type to decode with
352
+ :return: List of decoded box values
353
+
354
+ :example:
355
+ >>> app_manager = AppManager(algod_client)
356
+ >>> app_id = 123
357
+ >>> box_names = ["BOX_NAME_1", "BOX_NAME_2"]
358
+ >>> abi_type = ABIType.UINT
359
+ >>> box_values = app_manager.get_box_values_from_abi_type(app_id, box_names, abi_type)
360
+ """
361
+
362
+ return [self.get_box_value_from_abi_type(app_id, box_name, abi_type) for box_name in box_names]
363
+
364
+ @staticmethod
365
+ def get_box_reference(box_id: BoxIdentifier | BoxReference) -> tuple[int, bytes]:
366
+ """Get standardized box reference from various identifier types.
367
+
368
+ :param box_id: The box identifier
369
+ :return: Tuple of (app_id, box_name_bytes)
370
+ :raises ValueError: If box identifier type is invalid
371
+
372
+ :example:
373
+ >>> app_manager = AppManager(algod_client)
374
+ >>> app_id = 123
375
+ >>> box_name = "BOX_NAME"
376
+ >>> box_reference = app_manager.get_box_reference(box_name)
377
+ """
378
+
379
+ if isinstance(box_id, (BoxReference | AlgosdkBoxReference)):
380
+ return box_id.app_index, box_id.name
381
+
382
+ name = b""
383
+ if isinstance(box_id, str):
384
+ name = box_id.encode("utf-8")
385
+ elif isinstance(box_id, bytes):
386
+ name = box_id
387
+ elif isinstance(box_id, AccountTransactionSigner):
388
+ name = cast(
389
+ bytes, algosdk.encoding.decode_address(algosdk.account.address_from_private_key(box_id.private_key))
390
+ )
391
+ else:
392
+ raise ValueError(f"Invalid box identifier type: {type(box_id)}")
393
+
394
+ return 0, name
395
+
396
+ @staticmethod
397
+ def get_abi_return(
398
+ confirmation: algosdk.v2client.algod.AlgodResponseType, method: algosdk.abi.Method | None = None
399
+ ) -> ABIReturn | None:
400
+ """Get the ABI return value from a transaction confirmation.
401
+
402
+ :param confirmation: The transaction confirmation
403
+ :param method: The ABI method
404
+ :return: The parsed ABI return value, or None if not available
405
+
406
+ :example:
407
+ >>> app_manager = AppManager(algod_client)
408
+ >>> app_id = 123
409
+ >>> method = "METHOD_NAME"
410
+ >>> confirmation = algod_client.pending_transaction_info(tx_id)
411
+ >>> abi_return = app_manager.get_abi_return(confirmation, method)
412
+ """
413
+ if not method:
414
+ return None
415
+
416
+ atc = algosdk.atomic_transaction_composer.AtomicTransactionComposer()
417
+ abi_result = atc.parse_result(
418
+ method,
419
+ "dummy_txn",
420
+ confirmation, # type: ignore[arg-type]
421
+ )
422
+
423
+ if not abi_result:
424
+ return None
425
+
426
+ return ABIReturn(abi_result)
427
+
428
+ @staticmethod
429
+ def decode_app_state(state: list[dict[str, Any]]) -> dict[str, AppState]:
430
+ """Decode application state from raw format.
431
+
432
+ :param state: The raw application state
433
+ :return: Decoded application state
434
+ :raises ValueError: If unknown state data type is encountered
435
+
436
+ :example:
437
+ >>> app_manager = AppManager(algod_client)
438
+ >>> app_id = 123
439
+ >>> state = app_manager.get_global_state(app_id)
440
+ >>> decoded_state = app_manager.decode_app_state(state)
441
+ """
442
+
443
+ state_values: dict[str, AppState] = {}
444
+
445
+ def decode_bytes_to_str(value: bytes) -> str:
446
+ try:
447
+ return value.decode("utf-8")
448
+ except UnicodeDecodeError:
449
+ return value.hex()
450
+
451
+ for state_val in state:
452
+ key_base64 = state_val["key"]
453
+ key_raw = base64.b64decode(key_base64)
454
+ key = decode_bytes_to_str(key_raw)
455
+ teal_value = state_val["value"]
456
+
457
+ data_type_flag = teal_value.get("action", teal_value.get("type"))
458
+
459
+ if data_type_flag == DataTypeFlag.BYTES:
460
+ value_base64 = teal_value.get("bytes", "")
461
+ value_raw = base64.b64decode(value_base64)
462
+ state_values[key] = AppState(
463
+ key_raw=key_raw,
464
+ key_base64=key_base64,
465
+ value_raw=value_raw,
466
+ value_base64=value_base64,
467
+ value=decode_bytes_to_str(value_raw),
468
+ )
469
+ elif data_type_flag == DataTypeFlag.UINT:
470
+ value = teal_value.get("uint", 0)
471
+ state_values[key] = AppState(
472
+ key_raw=key_raw,
473
+ key_base64=key_base64,
474
+ value_raw=None,
475
+ value_base64=None,
476
+ value=int(value),
477
+ )
478
+ else:
479
+ raise ValueError(f"Received unknown state data type of {data_type_flag}")
480
+
481
+ return state_values
482
+
483
+ @staticmethod
484
+ def replace_template_variables(program: str, template_values: TealTemplateParams) -> str:
485
+ """Replace template variables in TEAL code.
486
+
487
+ :param program: The TEAL program code
488
+ :param template_values: Template variable values to substitute
489
+ :return: TEAL code with substituted values
490
+ :raises ValueError: If template value type is unexpected
491
+
492
+ :example:
493
+ >>> app_manager = AppManager(algod_client)
494
+ >>> app_id = 123
495
+ >>> program = "RETURN 1"
496
+ >>> template_values = {"TMPL_UPDATABLE": True, "TMPL_DELETABLE": True}
497
+ >>> updated_program = app_manager.replace_template_variables(program, template_values)
498
+ """
499
+
500
+ program_lines = program.splitlines()
501
+ for template_variable_name, template_value in template_values.items():
502
+ match template_value:
503
+ case int():
504
+ value = str(template_value)
505
+ case str():
506
+ value = "0x" + template_value.encode("utf-8").hex()
507
+ case bytes():
508
+ value = "0x" + template_value.hex()
509
+ case _:
510
+ raise ValueError(
511
+ f"Unexpected template value type {template_variable_name}: {template_value.__class__}"
512
+ )
513
+
514
+ program_lines, _ = _replace_template_variable(program_lines, template_variable_name, value)
515
+
516
+ return "\n".join(program_lines)
517
+
518
+ @staticmethod
519
+ def replace_teal_template_deploy_time_control_params(
520
+ teal_template_code: str, params: Mapping[str, bool | None]
521
+ ) -> str:
522
+ """Replace deploy-time control parameters in TEAL template.
523
+
524
+ :param teal_template_code: The TEAL template code
525
+ :param params: The deploy-time control parameters
526
+ :return: TEAL code with substituted control parameters
527
+ :raises ValueError: If template variables not found in code
528
+
529
+ :example:
530
+ >>> app_manager = AppManager(algod_client)
531
+ >>> app_id = 123
532
+ >>> teal_template_code = "RETURN 1"
533
+ >>> params = {"TMPL_UPDATABLE": True, "TMPL_DELETABLE": True}
534
+ >>> updated_teal_code = app_manager.replace_teal_template_deploy_time_control_params(
535
+ teal_template_code, params
536
+ )
537
+ """
538
+
539
+ updatable = params.get("updatable")
540
+ if updatable is not None:
541
+ if UPDATABLE_TEMPLATE_NAME not in teal_template_code:
542
+ raise ValueError(
543
+ f"Deploy-time updatability control requested for app deployment, but {UPDATABLE_TEMPLATE_NAME} "
544
+ "not present in TEAL code"
545
+ )
546
+ teal_template_code = teal_template_code.replace(UPDATABLE_TEMPLATE_NAME, str(int(updatable)))
547
+
548
+ deletable = params.get("deletable")
549
+ if deletable is not None:
550
+ if DELETABLE_TEMPLATE_NAME not in teal_template_code:
551
+ raise ValueError(
552
+ f"Deploy-time deletability control requested for app deployment, but {DELETABLE_TEMPLATE_NAME} "
553
+ "not present in TEAL code"
554
+ )
555
+ teal_template_code = teal_template_code.replace(DELETABLE_TEMPLATE_NAME, str(int(deletable)))
556
+
557
+ return teal_template_code
558
+
559
+ @staticmethod
560
+ def strip_teal_comments(teal_code: str) -> str:
561
+ """Strip comments from TEAL code.
562
+
563
+ :param teal_code: The TEAL code to strip comments from
564
+ :return: The TEAL code with comments stripped
565
+
566
+ :example:
567
+ >>> app_manager = AppManager(algod_client)
568
+ >>> teal_code = "RETURN 1"
569
+ >>> stripped_teal_code = app_manager.strip_teal_comments(teal_code)
570
+ """
571
+
572
+ def _strip_comment(line: str) -> str:
573
+ comment_idx = _find_unquoted_string(line, "//")
574
+ if comment_idx is None:
575
+ return line
576
+ return line[:comment_idx].rstrip()
577
+
578
+ return "\n".join(_strip_comment(line) for line in teal_code.splitlines())
@@ -0,0 +1,2 @@
1
+ from algokit_utils.applications.app_spec.arc32 import * # noqa: F403
2
+ from algokit_utils.applications.app_spec.arc56 import * # noqa: F403