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
@@ -0,0 +1,470 @@
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
+
124
+ def __init__(self, algod_client: algod.AlgodClient):
125
+ self._algod = algod_client
126
+ self._compilation_results: dict[str, CompiledTeal] = {}
127
+
128
+ def compile_teal(self, teal_code: str) -> CompiledTeal:
129
+ """Compile TEAL source code.
130
+
131
+ :param teal_code: The TEAL source code to compile
132
+ :return: The compiled TEAL code and associated metadata
133
+ """
134
+
135
+ if teal_code in self._compilation_results:
136
+ return self._compilation_results[teal_code]
137
+
138
+ compiled = self._algod.compile(teal_code, source_map=True)
139
+ result = CompiledTeal(
140
+ teal=teal_code,
141
+ compiled=compiled["result"],
142
+ compiled_hash=compiled["hash"],
143
+ compiled_base64_to_bytes=base64.b64decode(compiled["result"]),
144
+ source_map=SourceMap(compiled.get("sourcemap", {})),
145
+ )
146
+ self._compilation_results[teal_code] = result
147
+ return result
148
+
149
+ def compile_teal_template(
150
+ self,
151
+ teal_template_code: str,
152
+ template_params: TealTemplateParams | None = None,
153
+ deployment_metadata: Mapping[str, bool | None] | None = None,
154
+ ) -> CompiledTeal:
155
+ """Compile a TEAL template with parameters.
156
+
157
+ :param teal_template_code: The TEAL template code to compile
158
+ :param template_params: Parameters to substitute in the template
159
+ :param deployment_metadata: Deployment control parameters
160
+ :return: The compiled TEAL code and associated metadata
161
+ """
162
+
163
+ teal_code = AppManager.strip_teal_comments(teal_template_code)
164
+ teal_code = AppManager.replace_template_variables(teal_code, template_params or {})
165
+
166
+ if deployment_metadata:
167
+ teal_code = AppManager.replace_teal_template_deploy_time_control_params(teal_code, deployment_metadata)
168
+
169
+ return self.compile_teal(teal_code)
170
+
171
+ def get_compilation_result(self, teal_code: str) -> CompiledTeal | None:
172
+ """Get cached compilation result for TEAL code if available.
173
+
174
+ :param teal_code: The TEAL source code
175
+ :return: The cached compilation result if available, None otherwise
176
+ """
177
+
178
+ return self._compilation_results.get(teal_code)
179
+
180
+ def get_by_id(self, app_id: int) -> AppInformation:
181
+ """Get information about an application by ID.
182
+
183
+ :param app_id: The application ID
184
+ :return: Information about the application
185
+ """
186
+
187
+ app = self._algod.application_info(app_id)
188
+ assert isinstance(app, dict)
189
+ app_params = app["params"]
190
+
191
+ return AppInformation(
192
+ app_id=app_id,
193
+ app_address=get_application_address(app_id),
194
+ approval_program=base64.b64decode(app_params["approval-program"]),
195
+ clear_state_program=base64.b64decode(app_params["clear-state-program"]),
196
+ creator=app_params["creator"],
197
+ local_ints=app_params["local-state-schema"]["num-uint"],
198
+ local_byte_slices=app_params["local-state-schema"]["num-byte-slice"],
199
+ global_ints=app_params["global-state-schema"]["num-uint"],
200
+ global_byte_slices=app_params["global-state-schema"]["num-byte-slice"],
201
+ extra_program_pages=app_params.get("extra-program-pages", 0),
202
+ global_state=self.decode_app_state(app_params.get("global-state", [])),
203
+ )
204
+
205
+ def get_global_state(self, app_id: int) -> dict[str, AppState]:
206
+ """Get the global state of an application.
207
+
208
+ :param app_id: The application ID
209
+ :return: The application's global state
210
+ """
211
+
212
+ return self.get_by_id(app_id).global_state
213
+
214
+ def get_local_state(self, app_id: int, address: str) -> dict[str, AppState]:
215
+ """Get the local state for an account in an application.
216
+
217
+ :param app_id: The application ID
218
+ :param address: The account address
219
+ :return: The account's local state for the application
220
+ :raises ValueError: If local state is not found
221
+ """
222
+
223
+ app_info = self._algod.account_application_info(address, app_id)
224
+ assert isinstance(app_info, dict)
225
+ if not app_info.get("app-local-state", {}).get("key-value"):
226
+ raise ValueError("Couldn't find local state")
227
+ return self.decode_app_state(app_info["app-local-state"]["key-value"])
228
+
229
+ def get_box_names(self, app_id: int) -> list[BoxName]:
230
+ """Get names of all boxes for an application.
231
+
232
+ :param app_id: The application ID
233
+ :return: List of box names
234
+ """
235
+
236
+ box_result = self._algod.application_boxes(app_id)
237
+ assert isinstance(box_result, dict)
238
+ return [
239
+ BoxName(
240
+ name_raw=base64.b64decode(b["name"]),
241
+ name_base64=b["name"],
242
+ name=base64.b64decode(b["name"]).decode("utf-8"),
243
+ )
244
+ for b in box_result["boxes"]
245
+ ]
246
+
247
+ def get_box_value(self, app_id: int, box_name: BoxIdentifier) -> bytes:
248
+ """Get the value stored in a box.
249
+
250
+ :param app_id: The application ID
251
+ :param box_name: The box identifier
252
+ :return: The box value as bytes
253
+ """
254
+
255
+ name = AppManager.get_box_reference(box_name)[1]
256
+ box_result = self._algod.application_box_by_name(app_id, name)
257
+ assert isinstance(box_result, dict)
258
+ return base64.b64decode(box_result["value"])
259
+
260
+ def get_box_values(self, app_id: int, box_names: list[BoxIdentifier]) -> list[bytes]:
261
+ """Get values for multiple boxes.
262
+
263
+ :param app_id: The application ID
264
+ :param box_names: List of box identifiers
265
+ :return: List of box values as bytes
266
+ """
267
+
268
+ return [self.get_box_value(app_id, box_name) for box_name in box_names]
269
+
270
+ def get_box_value_from_abi_type(self, app_id: int, box_name: BoxIdentifier, abi_type: ABIType) -> ABIValue:
271
+ """Get and decode a box value using an ABI type.
272
+
273
+ :param app_id: The application ID
274
+ :param box_name: The box identifier
275
+ :param abi_type: The ABI type to decode with
276
+ :return: The decoded box value
277
+ :raises ValueError: If decoding fails
278
+ """
279
+
280
+ value = self.get_box_value(app_id, box_name)
281
+ try:
282
+ parse_to_tuple = isinstance(abi_type, algosdk.abi.TupleType)
283
+ decoded_value = abi_type.decode(value)
284
+ return tuple(decoded_value) if parse_to_tuple else decoded_value
285
+ except Exception as e:
286
+ raise ValueError(f"Failed to decode box value {value.decode('utf-8')} with ABI type {abi_type}") from e
287
+
288
+ def get_box_values_from_abi_type(
289
+ self, app_id: int, box_names: list[BoxIdentifier], abi_type: ABIType
290
+ ) -> list[ABIValue]:
291
+ """Get and decode multiple box values using an ABI type.
292
+
293
+ :param app_id: The application ID
294
+ :param box_names: List of box identifiers
295
+ :param abi_type: The ABI type to decode with
296
+ :return: List of decoded box values
297
+ """
298
+
299
+ return [self.get_box_value_from_abi_type(app_id, box_name, abi_type) for box_name in box_names]
300
+
301
+ @staticmethod
302
+ def get_box_reference(box_id: BoxIdentifier | BoxReference) -> tuple[int, bytes]:
303
+ """Get standardized box reference from various identifier types.
304
+
305
+ :param box_id: The box identifier
306
+ :return: Tuple of (app_id, box_name_bytes)
307
+ :raises ValueError: If box identifier type is invalid
308
+ """
309
+
310
+ if isinstance(box_id, (BoxReference | AlgosdkBoxReference)):
311
+ return box_id.app_index, box_id.name
312
+
313
+ name = b""
314
+ if isinstance(box_id, str):
315
+ name = box_id.encode("utf-8")
316
+ elif isinstance(box_id, bytes):
317
+ name = box_id
318
+ elif isinstance(box_id, AccountTransactionSigner):
319
+ name = cast(
320
+ bytes, algosdk.encoding.decode_address(algosdk.account.address_from_private_key(box_id.private_key))
321
+ )
322
+ else:
323
+ raise ValueError(f"Invalid box identifier type: {type(box_id)}")
324
+
325
+ return 0, name
326
+
327
+ @staticmethod
328
+ def get_abi_return(
329
+ confirmation: algosdk.v2client.algod.AlgodResponseType, method: algosdk.abi.Method | None = None
330
+ ) -> ABIReturn | None:
331
+ """Get the ABI return value from a transaction confirmation.
332
+
333
+ :param confirmation: The transaction confirmation
334
+ :param method: The ABI method
335
+ :return: The parsed ABI return value, or None if not available
336
+ """
337
+
338
+ if not method:
339
+ return None
340
+
341
+ atc = algosdk.atomic_transaction_composer.AtomicTransactionComposer()
342
+ abi_result = atc.parse_result(
343
+ method,
344
+ "dummy_txn",
345
+ confirmation, # type: ignore[arg-type]
346
+ )
347
+
348
+ if not abi_result:
349
+ return None
350
+
351
+ return ABIReturn(abi_result)
352
+
353
+ @staticmethod
354
+ def decode_app_state(state: list[dict[str, Any]]) -> dict[str, AppState]:
355
+ """Decode application state from raw format.
356
+
357
+ :param state: The raw application state
358
+ :return: Decoded application state
359
+ :raises ValueError: If unknown state data type is encountered
360
+ """
361
+
362
+ state_values: dict[str, AppState] = {}
363
+
364
+ def decode_bytes_to_str(value: bytes) -> str:
365
+ try:
366
+ return value.decode("utf-8")
367
+ except UnicodeDecodeError:
368
+ return value.hex()
369
+
370
+ for state_val in state:
371
+ key_base64 = state_val["key"]
372
+ key_raw = base64.b64decode(key_base64)
373
+ key = decode_bytes_to_str(key_raw)
374
+ teal_value = state_val["value"]
375
+
376
+ data_type_flag = teal_value.get("action", teal_value.get("type"))
377
+
378
+ if data_type_flag == DataTypeFlag.BYTES:
379
+ value_base64 = teal_value.get("bytes", "")
380
+ value_raw = base64.b64decode(value_base64)
381
+ state_values[key] = AppState(
382
+ key_raw=key_raw,
383
+ key_base64=key_base64,
384
+ value_raw=value_raw,
385
+ value_base64=value_base64,
386
+ value=decode_bytes_to_str(value_raw),
387
+ )
388
+ elif data_type_flag == DataTypeFlag.UINT:
389
+ value = teal_value.get("uint", 0)
390
+ state_values[key] = AppState(
391
+ key_raw=key_raw,
392
+ key_base64=key_base64,
393
+ value_raw=None,
394
+ value_base64=None,
395
+ value=int(value),
396
+ )
397
+ else:
398
+ raise ValueError(f"Received unknown state data type of {data_type_flag}")
399
+
400
+ return state_values
401
+
402
+ @staticmethod
403
+ def replace_template_variables(program: str, template_values: TealTemplateParams) -> str:
404
+ """Replace template variables in TEAL code.
405
+
406
+ :param program: The TEAL program code
407
+ :param template_values: Template variable values to substitute
408
+ :return: TEAL code with substituted values
409
+ :raises ValueError: If template value type is unexpected
410
+ """
411
+
412
+ program_lines = program.splitlines()
413
+ for template_variable_name, template_value in template_values.items():
414
+ match template_value:
415
+ case int():
416
+ value = str(template_value)
417
+ case str():
418
+ value = "0x" + template_value.encode("utf-8").hex()
419
+ case bytes():
420
+ value = "0x" + template_value.hex()
421
+ case _:
422
+ raise ValueError(
423
+ f"Unexpected template value type {template_variable_name}: {template_value.__class__}"
424
+ )
425
+
426
+ program_lines, _ = _replace_template_variable(program_lines, template_variable_name, value)
427
+
428
+ return "\n".join(program_lines)
429
+
430
+ @staticmethod
431
+ def replace_teal_template_deploy_time_control_params(
432
+ teal_template_code: str, params: Mapping[str, bool | None]
433
+ ) -> str:
434
+ """Replace deploy-time control parameters in TEAL template.
435
+
436
+ :param teal_template_code: The TEAL template code
437
+ :param params: The deploy-time control parameters
438
+ :return: TEAL code with substituted control parameters
439
+ :raises ValueError: If template variables not found in code
440
+ """
441
+
442
+ updatable = params.get("updatable")
443
+ if updatable is not None:
444
+ if UPDATABLE_TEMPLATE_NAME not in teal_template_code:
445
+ raise ValueError(
446
+ f"Deploy-time updatability control requested for app deployment, but {UPDATABLE_TEMPLATE_NAME} "
447
+ "not present in TEAL code"
448
+ )
449
+ teal_template_code = teal_template_code.replace(UPDATABLE_TEMPLATE_NAME, str(int(updatable)))
450
+
451
+ deletable = params.get("deletable")
452
+ if deletable is not None:
453
+ if DELETABLE_TEMPLATE_NAME not in teal_template_code:
454
+ raise ValueError(
455
+ f"Deploy-time deletability control requested for app deployment, but {DELETABLE_TEMPLATE_NAME} "
456
+ "not present in TEAL code"
457
+ )
458
+ teal_template_code = teal_template_code.replace(DELETABLE_TEMPLATE_NAME, str(int(deletable)))
459
+
460
+ return teal_template_code
461
+
462
+ @staticmethod
463
+ def strip_teal_comments(teal_code: str) -> str:
464
+ def _strip_comment(line: str) -> str:
465
+ comment_idx = _find_unquoted_string(line, "//")
466
+ if comment_idx is None:
467
+ return line
468
+ return line[:comment_idx].rstrip()
469
+
470
+ 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
@@ -0,0 +1,207 @@
1
+ import base64
2
+ import dataclasses
3
+ import json
4
+ from enum import IntFlag
5
+ from pathlib import Path
6
+ from typing import Any, Literal, TypeAlias, TypedDict
7
+
8
+ from algosdk.abi import Contract
9
+ from algosdk.abi.method import MethodDict
10
+ from algosdk.transaction import StateSchema
11
+
12
+ __all__ = [
13
+ "AppSpecStateDict",
14
+ "Arc32Contract",
15
+ "CallConfig",
16
+ "DefaultArgumentDict",
17
+ "DefaultArgumentType",
18
+ "MethodConfigDict",
19
+ "MethodHints",
20
+ "OnCompleteActionName",
21
+ "StateDict",
22
+ "StructArgDict",
23
+ ]
24
+
25
+
26
+ AppSpecStateDict: TypeAlias = dict[str, dict[str, dict]]
27
+ """Type defining Application Specification state entries"""
28
+
29
+
30
+ class CallConfig(IntFlag):
31
+ """Describes the type of calls a method can be used for based on {py:class}`algosdk.transaction.OnComplete` type"""
32
+
33
+ NEVER = 0
34
+ """Never handle the specified on completion type"""
35
+ CALL = 1
36
+ """Only handle the specified on completion type for application calls"""
37
+ CREATE = 2
38
+ """Only handle the specified on completion type for application create calls"""
39
+ ALL = 3
40
+ """Handle the specified on completion type for both create and normal application calls"""
41
+
42
+
43
+ class StructArgDict(TypedDict):
44
+ name: str
45
+ elements: list[list[str]]
46
+
47
+
48
+ OnCompleteActionName: TypeAlias = Literal[
49
+ "no_op", "opt_in", "close_out", "clear_state", "update_application", "delete_application"
50
+ ]
51
+ """String literals representing on completion transaction types"""
52
+ MethodConfigDict: TypeAlias = dict[OnCompleteActionName, CallConfig]
53
+ """Dictionary of `dict[OnCompletionActionName, CallConfig]` representing allowed actions for each on completion type"""
54
+ DefaultArgumentType: TypeAlias = Literal["abi-method", "local-state", "global-state", "constant"]
55
+ """Literal values describing the types of default argument sources"""
56
+
57
+
58
+ class DefaultArgumentDict(TypedDict):
59
+ """
60
+ DefaultArgument is a container for any arguments that may
61
+ be resolved prior to calling some target method
62
+ """
63
+
64
+ source: DefaultArgumentType
65
+ data: int | str | bytes | MethodDict
66
+
67
+
68
+ StateDict = TypedDict( # need to use function-form of TypedDict here since "global" is a reserved keyword
69
+ "StateDict", {"global": AppSpecStateDict, "local": AppSpecStateDict}
70
+ )
71
+
72
+
73
+ @dataclasses.dataclass(kw_only=True)
74
+ class MethodHints:
75
+ """MethodHints provides hints to the caller about how to call the method"""
76
+
77
+ #: hint to indicate this method can be called through Dryrun
78
+ read_only: bool = False
79
+ #: hint to provide names for tuple argument indices
80
+ #: method_name=>param_name=>{name:str, elements:[str,str]}
81
+ structs: dict[str, StructArgDict] = dataclasses.field(default_factory=dict)
82
+ #: defaults
83
+ default_arguments: dict[str, DefaultArgumentDict] = dataclasses.field(default_factory=dict)
84
+ call_config: MethodConfigDict = dataclasses.field(default_factory=dict)
85
+
86
+ def empty(self) -> bool:
87
+ return not self.dictify()
88
+
89
+ def dictify(self) -> dict[str, Any]:
90
+ d: dict[str, Any] = {}
91
+ if self.read_only:
92
+ d["read_only"] = True
93
+ if self.default_arguments:
94
+ d["default_arguments"] = self.default_arguments
95
+ if self.structs:
96
+ d["structs"] = self.structs
97
+ if any(v for v in self.call_config.values() if v != CallConfig.NEVER):
98
+ d["call_config"] = _encode_method_config(self.call_config)
99
+ return d
100
+
101
+ @staticmethod
102
+ def undictify(data: dict[str, Any]) -> "MethodHints":
103
+ return MethodHints(
104
+ read_only=data.get("read_only", False),
105
+ default_arguments=data.get("default_arguments", {}),
106
+ structs=data.get("structs", {}),
107
+ call_config=_decode_method_config(data.get("call_config", {})),
108
+ )
109
+
110
+
111
+ def _encode_method_config(mc: MethodConfigDict) -> dict[str, str | None]:
112
+ return {k: mc[k].name for k in sorted(mc) if mc[k] != CallConfig.NEVER}
113
+
114
+
115
+ def _decode_method_config(data: dict[OnCompleteActionName, Any]) -> MethodConfigDict:
116
+ return {k: CallConfig[v] for k, v in data.items()}
117
+
118
+
119
+ def _encode_source(teal_text: str) -> str:
120
+ return base64.b64encode(teal_text.encode()).decode("utf-8")
121
+
122
+
123
+ def _decode_source(b64_text: str) -> str:
124
+ return base64.b64decode(b64_text).decode("utf-8")
125
+
126
+
127
+ def _encode_state_schema(schema: StateSchema) -> dict[str, int]:
128
+ return {
129
+ "num_byte_slices": schema.num_byte_slices,
130
+ "num_uints": schema.num_uints,
131
+ } # type: ignore[unused-ignore]
132
+
133
+
134
+ def _decode_state_schema(data: dict[str, int]) -> StateSchema:
135
+ return StateSchema(
136
+ num_byte_slices=data.get("num_byte_slices", 0),
137
+ num_uints=data.get("num_uints", 0),
138
+ )
139
+
140
+
141
+ @dataclasses.dataclass(kw_only=True)
142
+ class Arc32Contract:
143
+ """ARC-0032 application specification
144
+
145
+ See <https://github.com/algorandfoundation/ARCs/pull/150>"""
146
+
147
+ approval_program: str
148
+ clear_program: str
149
+ contract: Contract
150
+ hints: dict[str, MethodHints]
151
+ schema: StateDict
152
+ global_state_schema: StateSchema
153
+ local_state_schema: StateSchema
154
+ bare_call_config: MethodConfigDict
155
+
156
+ def dictify(self) -> dict:
157
+ return {
158
+ "hints": {k: v.dictify() for k, v in self.hints.items() if not v.empty()},
159
+ "source": {
160
+ "approval": _encode_source(self.approval_program),
161
+ "clear": _encode_source(self.clear_program),
162
+ },
163
+ "state": {
164
+ "global": _encode_state_schema(self.global_state_schema),
165
+ "local": _encode_state_schema(self.local_state_schema),
166
+ },
167
+ "schema": self.schema,
168
+ "contract": self.contract.dictify(),
169
+ "bare_call_config": _encode_method_config(self.bare_call_config),
170
+ }
171
+
172
+ def to_json(self, indent: int | None = None) -> str:
173
+ return json.dumps(self.dictify(), indent=indent)
174
+
175
+ @staticmethod
176
+ def from_json(application_spec: str) -> "Arc32Contract":
177
+ json_spec = json.loads(application_spec)
178
+ return Arc32Contract(
179
+ approval_program=_decode_source(json_spec["source"]["approval"]),
180
+ clear_program=_decode_source(json_spec["source"]["clear"]),
181
+ schema=json_spec["schema"],
182
+ global_state_schema=_decode_state_schema(json_spec["state"]["global"]),
183
+ local_state_schema=_decode_state_schema(json_spec["state"]["local"]),
184
+ contract=Contract.undictify(json_spec["contract"]),
185
+ hints={k: MethodHints.undictify(v) for k, v in json_spec["hints"].items()},
186
+ bare_call_config=_decode_method_config(json_spec.get("bare_call_config", {})),
187
+ )
188
+
189
+ def export(self, directory: Path | str | None = None) -> None:
190
+ """Write out the artifacts generated by the application to disk.
191
+
192
+ Writes the approval program, clear program, contract specification and application specification
193
+ to files in the specified directory.
194
+
195
+ :param directory: Path to the directory where the artifacts should be written. If not specified,
196
+ uses the current working directory
197
+ """
198
+ if directory is None:
199
+ output_dir = Path.cwd()
200
+ else:
201
+ output_dir = Path(directory)
202
+ output_dir.mkdir(exist_ok=True, parents=True)
203
+
204
+ (output_dir / "approval.teal").write_text(self.approval_program)
205
+ (output_dir / "clear.teal").write_text(self.clear_program)
206
+ (output_dir / "contract.json").write_text(json.dumps(self.contract.dictify(), indent=4))
207
+ (output_dir / "application.json").write_text(self.to_json())