-
Notifications
You must be signed in to change notification settings - Fork 11
/
application_client.py
1414 lines (1241 loc) · 55.3 KB
/
application_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import copy
import json
import logging
import re
import typing
from http import HTTPStatus
from math import ceil
from pathlib import Path
from typing import Any, Literal, cast, overload
import algosdk
from algosdk import transaction
from algosdk.abi import ABIType, Method, Returns
from algosdk.account import address_from_private_key
from algosdk.atomic_transaction_composer import (
ABI_RETURN_HASH,
ABIResult,
AccountTransactionSigner,
AtomicTransactionComposer,
AtomicTransactionResponse,
LogicSigTransactionSigner,
MultisigTransactionSigner,
SimulateAtomicTransactionResponse,
TransactionSigner,
TransactionWithSigner,
)
from algosdk.constants import APP_PAGE_MAX_SIZE
from algosdk.error import AlgodHTTPError
from algosdk.logic import get_application_address
from algosdk.source_map import SourceMap
import algokit_utils.application_specification as au_spec
import algokit_utils.deploy as au_deploy
from algokit_utils._simulate_315_compat import simulate_atc_315
from algokit_utils.logic_error import LogicError, parse_logic_error
from algokit_utils.models import (
ABIArgsDict,
ABIArgType,
ABIMethod,
ABITransactionResponse,
Account,
CreateCallParameters,
CreateCallParametersDict,
OnCompleteCallParameters,
OnCompleteCallParametersDict,
TransactionParameters,
TransactionParametersDict,
TransactionResponse,
)
if typing.TYPE_CHECKING:
from algosdk.v2client.algod import AlgodClient
from algosdk.v2client.indexer import IndexerClient
logger = logging.getLogger(__name__)
"""A dictionary `dict[str, Any]` representing ABI argument names and values"""
__all__ = [
"ApplicationClient",
"Program",
"execute_atc_with_logic_error",
"get_next_version",
"get_sender_from_signer",
"num_extra_program_pages",
]
"""Alias for {py:class}`pyteal.ABIReturnSubroutine`, {py:class}`algosdk.abi.method.Method` or a {py:class}`str`
representing an ABI method name or signature"""
class Program:
"""A compiled TEAL program"""
def __init__(self, program: str, client: "AlgodClient"):
"""
Fully compile the program source to binary and generate a
source map for matching pc to line number
"""
self.teal = program
result: dict = client.compile(au_deploy.strip_comments(self.teal), source_map=True)
self.raw_binary = base64.b64decode(result["result"])
self.binary_hash: str = result["hash"]
self.source_map = SourceMap(result["sourcemap"])
def num_extra_program_pages(approval: bytes, clear: bytes) -> int:
"""Calculate minimum number of extra_pages required for provided approval and clear programs"""
return ceil(((len(approval) + len(clear)) - APP_PAGE_MAX_SIZE) / APP_PAGE_MAX_SIZE)
class ApplicationClient:
"""A class that wraps an ARC-0032 app spec and provides high productivity methods to deploy and call the app"""
@overload
def __init__(
self,
algod_client: "AlgodClient",
app_spec: au_spec.ApplicationSpecification | Path,
*,
app_id: int = 0,
signer: TransactionSigner | Account | None = None,
sender: str | None = None,
suggested_params: transaction.SuggestedParams | None = None,
template_values: au_deploy.TemplateValueMapping | None = None,
):
...
@overload
def __init__(
self,
algod_client: "AlgodClient",
app_spec: au_spec.ApplicationSpecification | Path,
*,
creator: str | Account,
indexer_client: "IndexerClient | None" = None,
existing_deployments: au_deploy.AppLookup | None = None,
signer: TransactionSigner | Account | None = None,
sender: str | None = None,
suggested_params: transaction.SuggestedParams | None = None,
template_values: au_deploy.TemplateValueMapping | None = None,
app_name: str | None = None,
):
...
def __init__(
self,
algod_client: "AlgodClient",
app_spec: au_spec.ApplicationSpecification | Path,
*,
app_id: int = 0,
creator: str | Account | None = None,
indexer_client: "IndexerClient | None" = None,
existing_deployments: au_deploy.AppLookup | None = None,
signer: TransactionSigner | Account | None = None,
sender: str | None = None,
suggested_params: transaction.SuggestedParams | None = None,
template_values: au_deploy.TemplateValueMapping | None = None,
app_name: str | None = None,
):
"""ApplicationClient can be created with an app_id to interact with an existing application, alternatively
it can be created with a creator and indexer_client specified to find existing applications by name and creator.
:param AlgodClient algod_client: AlgoSDK algod client
:param ApplicationSpecification | Path app_spec: An Application Specification or the path to one
:param int app_id: The app_id of an existing application, to instead find the application by creator and name
use the creator and indexer_client parameters
:param str | Account creator: The address or Account of the app creator to resolve the app_id
:param IndexerClient indexer_client: AlgoSDK indexer client, only required if deploying or finding app_id by
creator and app name
:param AppLookup existing_deployments:
:param TransactionSigner | Account signer: Account or signer to use to sign transactions, if not specified and
creator was passed as an Account will use that.
:param str sender: Address to use as the sender for all transactions, will use the address associated with the
signer if not specified.
:param TemplateValueMapping template_values: Values to use for TMPL_* template variables, dictionary keys should
*NOT* include the TMPL_ prefix
:param str | None app_name: Name of application to use when deploying, defaults to name defined on the
Application Specification
"""
self.algod_client = algod_client
self.app_spec = (
au_spec.ApplicationSpecification.from_json(app_spec.read_text()) if isinstance(app_spec, Path) else app_spec
)
self._app_name = app_name
self._approval_program: Program | None = None
self._approval_source_map: SourceMap | None = None
self._clear_program: Program | None = None
self._use_simulate_315 = False # flag to determine if old simulate 3.15 encoding should be used
self.template_values: au_deploy.TemplateValueMapping = template_values or {}
self.existing_deployments = existing_deployments
self._indexer_client = indexer_client
if creator is not None:
if not self.existing_deployments and not self._indexer_client:
raise Exception(
"If using the creator parameter either existing_deployments or indexer_client must also be provided"
)
self._creator: str | None = creator.address if isinstance(creator, Account) else creator
if self.existing_deployments and self.existing_deployments.creator != self._creator:
raise Exception(
"Attempt to create application client with invalid existing_deployments against"
f"a different creator ({self.existing_deployments.creator} instead of "
f"expected creator {self._creator}"
)
self.app_id = 0
else:
self.app_id = app_id
self._creator = None
self.signer: TransactionSigner | None
if signer:
self.signer = (
signer if isinstance(signer, TransactionSigner) else AccountTransactionSigner(signer.private_key)
)
elif isinstance(creator, Account):
self.signer = AccountTransactionSigner(creator.private_key)
else:
self.signer = None
self.sender = sender
self.suggested_params = suggested_params
@property
def app_name(self) -> str:
return self._app_name or self.app_spec.contract.name
@app_name.setter
def app_name(self, value: str) -> None:
self._app_name = value
@property
def app_address(self) -> str:
return get_application_address(self.app_id)
@property
def approval(self) -> Program | None:
return self._approval_program
@property
def approval_source_map(self) -> SourceMap | None:
if self._approval_source_map:
return self._approval_source_map
if self._approval_program:
return self._approval_program.source_map
return None
@approval_source_map.setter
def approval_source_map(self, value: SourceMap) -> None:
self._approval_source_map = value
@property
def clear(self) -> Program | None:
return self._clear_program
def prepare(
self,
signer: TransactionSigner | Account | None = None,
sender: str | None = None,
app_id: int | None = None,
template_values: au_deploy.TemplateValueDict | None = None,
) -> "ApplicationClient":
"""Creates a copy of this ApplicationClient, using the new signer, sender and app_id values if provided.
Will also substitute provided template_values into the associated app_spec in the copy"""
new_client: "ApplicationClient" = copy.copy(self)
new_client._prepare( # noqa: SLF001
new_client, signer=signer, sender=sender, app_id=app_id, template_values=template_values
)
return new_client
def _prepare(
self,
target: "ApplicationClient",
*,
signer: TransactionSigner | Account | None = None,
sender: str | None = None,
app_id: int | None = None,
template_values: au_deploy.TemplateValueDict | None = None,
) -> None:
target.app_id = self.app_id if app_id is None else app_id
target.signer, target.sender = target.get_signer_sender(
AccountTransactionSigner(signer.private_key) if isinstance(signer, Account) else signer, sender
)
target.template_values = self.template_values | (template_values or {})
def deploy(
self,
version: str | None = None,
*,
signer: TransactionSigner | None = None,
sender: str | None = None,
allow_update: bool | None = None,
allow_delete: bool | None = None,
on_update: au_deploy.OnUpdate = au_deploy.OnUpdate.Fail,
on_schema_break: au_deploy.OnSchemaBreak = au_deploy.OnSchemaBreak.Fail,
template_values: au_deploy.TemplateValueMapping | None = None,
create_args: au_deploy.ABICreateCallArgs
| au_deploy.ABICreateCallArgsDict
| au_deploy.DeployCreateCallArgs
| None = None,
update_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None,
delete_args: au_deploy.ABICallArgs | au_deploy.ABICallArgsDict | au_deploy.DeployCallArgs | None = None,
) -> au_deploy.DeployResponse:
"""Deploy an application and update client to reference it.
Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator
account, including deploy-time template placeholder substitutions.
To understand the architecture decisions behind this functionality please see
<https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md>
```{note}
If there is a breaking state schema change to an existing app (and `on_schema_break` is set to
'ReplaceApp' the existing app will be deleted and re-created.
```
```{note}
If there is an update (different TEAL code) to an existing app (and `on_update` is set to 'ReplaceApp')
the existing app will be deleted and re-created.
```
:param str version: version to use when creating or updating app, if None version will be auto incremented
:param algosdk.atomic_transaction_composer.TransactionSigner signer: signer to use when deploying app
, if None uses self.signer
:param str sender: sender address to use when deploying app, if None uses self.sender
:param bool allow_delete: Used to set the `TMPL_DELETABLE` template variable to conditionally control if an app
can be deleted
:param bool allow_update: Used to set the `TMPL_UPDATABLE` template variable to conditionally control if an app
can be updated
:param OnUpdate on_update: Determines what action to take if an application update is required
:param OnSchemaBreak on_schema_break: Determines what action to take if an application schema requirements
has increased beyond the current allocation
:param dict[str, int|str|bytes] template_values: Values to use for `TMPL_*` template variables, dictionary keys
should *NOT* include the TMPL_ prefix
:param ABICreateCallArgs create_args: Arguments used when creating an application
:param ABICallArgs | ABICallArgsDict update_args: Arguments used when updating an application
:param ABICallArgs | ABICallArgsDict delete_args: Arguments used when deleting an application
:return DeployResponse: details action taken and relevant transactions
:raises DeploymentError: If the deployment failed
"""
# check inputs
if self.app_id:
raise au_deploy.DeploymentFailedError(
f"Attempt to deploy app which already has an app index of {self.app_id}"
)
try:
resolved_signer, resolved_sender = self.resolve_signer_sender(signer, sender)
except ValueError as ex:
raise au_deploy.DeploymentFailedError(f"{ex}, unable to deploy app") from None
if not self._creator:
raise au_deploy.DeploymentFailedError("No creator provided, unable to deploy app")
if self._creator != resolved_sender:
raise au_deploy.DeploymentFailedError(
f"Attempt to deploy contract with a sender address {resolved_sender} that differs "
f"from the given creator address for this application client: {self._creator}"
)
# make a copy and prepare variables
template_values = self.template_values | dict(template_values or {})
au_deploy.add_deploy_template_variables(template_values, allow_update=allow_update, allow_delete=allow_delete)
existing_app_metadata_or_reference = self._load_app_reference()
self._approval_program, self._clear_program = substitute_template_and_compile(
self.algod_client, self.app_spec, template_values
)
deployer = au_deploy.Deployer(
app_client=self,
creator=self._creator,
signer=resolved_signer,
sender=resolved_sender,
new_app_metadata=self._get_app_deploy_metadata(version, allow_update, allow_delete),
existing_app_metadata_or_reference=existing_app_metadata_or_reference,
on_update=on_update,
on_schema_break=on_schema_break,
create_args=create_args,
update_args=update_args,
delete_args=delete_args,
)
return deployer.deploy()
def compose_create(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with application id == 0 and the schema and source of client's app_spec to atc"""
approval_program, clear_program = self._check_is_compiled()
transaction_parameters = _convert_transaction_parameters(transaction_parameters)
extra_pages = transaction_parameters.extra_pages or num_extra_program_pages(
approval_program.raw_binary, clear_program.raw_binary
)
self.add_method_call(
atc,
app_id=0,
abi_method=call_abi_method,
abi_args=abi_kwargs,
on_complete=transaction_parameters.on_complete or transaction.OnComplete.NoOpOC,
call_config=au_spec.CallConfig.CREATE,
parameters=transaction_parameters,
approval_program=approval_program.raw_binary,
clear_program=clear_program.raw_binary,
global_schema=self.app_spec.global_state_schema,
local_schema=self.app_spec.local_state_schema,
extra_pages=extra_pages,
)
@overload
def create(
self,
call_abi_method: Literal[False],
transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
) -> TransactionResponse:
...
@overload
def create(
self,
call_abi_method: ABIMethod | Literal[True],
transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def create(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def create(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: CreateCallParameters | CreateCallParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with application id == 0 and the schema and source of client's app_spec"""
atc = AtomicTransactionComposer()
self.compose_create(
atc,
call_abi_method,
transaction_parameters,
**abi_kwargs,
)
create_result = self._execute_atc_tr(atc)
self.app_id = au_deploy.get_app_id_from_tx_id(self.algod_client, create_result.tx_id)
return create_result
def compose_update(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with on_complete=UpdateApplication to atc"""
approval_program, clear_program = self._check_is_compiled()
self.add_method_call(
atc=atc,
abi_method=call_abi_method,
abi_args=abi_kwargs,
parameters=transaction_parameters,
on_complete=transaction.OnComplete.UpdateApplicationOC,
approval_program=approval_program.raw_binary,
clear_program=clear_program.raw_binary,
)
@overload
def update(
self,
call_abi_method: ABIMethod | Literal[True],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def update(
self,
call_abi_method: Literal[False],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
) -> TransactionResponse:
...
@overload
def update(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def update(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with on_complete=UpdateApplication"""
atc = AtomicTransactionComposer()
self.compose_update(
atc,
call_abi_method,
transaction_parameters=transaction_parameters,
**abi_kwargs,
)
return self._execute_atc_tr(atc)
def compose_delete(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with on_complete=DeleteApplication to atc"""
self.add_method_call(
atc,
call_abi_method,
abi_args=abi_kwargs,
parameters=transaction_parameters,
on_complete=transaction.OnComplete.DeleteApplicationOC,
)
@overload
def delete(
self,
call_abi_method: ABIMethod | Literal[True],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def delete(
self,
call_abi_method: Literal[False],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
) -> TransactionResponse:
...
@overload
def delete(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def delete(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with on_complete=DeleteApplication"""
atc = AtomicTransactionComposer()
self.compose_delete(
atc,
call_abi_method,
transaction_parameters=transaction_parameters,
**abi_kwargs,
)
return self._execute_atc_tr(atc)
def compose_call(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with specified parameters to atc"""
_parameters = _convert_transaction_parameters(transaction_parameters)
self.add_method_call(
atc,
abi_method=call_abi_method,
abi_args=abi_kwargs,
parameters=_parameters,
on_complete=_parameters.on_complete or transaction.OnComplete.NoOpOC,
)
@overload
def call(
self,
call_abi_method: ABIMethod | Literal[True],
transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def call(
self,
call_abi_method: Literal[False],
transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
) -> TransactionResponse:
...
@overload
def call(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def call(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: OnCompleteCallParameters | OnCompleteCallParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with specified parameters"""
atc = AtomicTransactionComposer()
_parameters = _convert_transaction_parameters(transaction_parameters)
self.compose_call(
atc,
call_abi_method=call_abi_method,
transaction_parameters=_parameters,
**abi_kwargs,
)
method = self._resolve_method(
call_abi_method, abi_kwargs, _parameters.on_complete or transaction.OnComplete.NoOpOC
)
if method:
hints = self._method_hints(method)
if hints and hints.read_only:
return self._simulate_readonly_call(method, atc)
return self._execute_atc_tr(atc)
def compose_opt_in(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with on_complete=OptIn to atc"""
self.add_method_call(
atc,
abi_method=call_abi_method,
abi_args=abi_kwargs,
parameters=transaction_parameters,
on_complete=transaction.OnComplete.OptInOC,
)
@overload
def opt_in(
self,
call_abi_method: ABIMethod | Literal[True] = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def opt_in(
self,
call_abi_method: Literal[False] = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
) -> TransactionResponse:
...
@overload
def opt_in(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def opt_in(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with on_complete=OptIn"""
atc = AtomicTransactionComposer()
self.compose_opt_in(
atc,
call_abi_method=call_abi_method,
transaction_parameters=transaction_parameters,
**abi_kwargs,
)
return self._execute_atc_tr(atc)
def compose_close_out(
self,
atc: AtomicTransactionComposer,
/,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> None:
"""Adds a signed transaction with on_complete=CloseOut to ac"""
self.add_method_call(
atc,
abi_method=call_abi_method,
abi_args=abi_kwargs,
parameters=transaction_parameters,
on_complete=transaction.OnComplete.CloseOutOC,
)
@overload
def close_out(
self,
call_abi_method: ABIMethod | Literal[True],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> ABITransactionResponse:
...
@overload
def close_out(
self,
call_abi_method: Literal[False],
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
) -> TransactionResponse:
...
@overload
def close_out(
self,
call_abi_method: ABIMethod | bool | None = ...,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = ...,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
...
def close_out(
self,
call_abi_method: ABIMethod | bool | None = None,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
**abi_kwargs: ABIArgType,
) -> TransactionResponse | ABITransactionResponse:
"""Submits a signed transaction with on_complete=CloseOut"""
atc = AtomicTransactionComposer()
self.compose_close_out(
atc,
call_abi_method=call_abi_method,
transaction_parameters=transaction_parameters,
**abi_kwargs,
)
return self._execute_atc_tr(atc)
def compose_clear_state(
self,
atc: AtomicTransactionComposer,
/,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
app_args: list[bytes] | None = None,
) -> None:
"""Adds a signed transaction with on_complete=ClearState to atc"""
return self.add_method_call(
atc,
parameters=transaction_parameters,
on_complete=transaction.OnComplete.ClearStateOC,
app_args=app_args,
)
def clear_state(
self,
transaction_parameters: TransactionParameters | TransactionParametersDict | None = None,
app_args: list[bytes] | None = None,
) -> TransactionResponse:
"""Submits a signed transaction with on_complete=ClearState"""
atc = AtomicTransactionComposer()
self.compose_clear_state(
atc,
transaction_parameters=transaction_parameters,
app_args=app_args,
)
return self._execute_atc_tr(atc)
def get_global_state(self, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]:
"""Gets the global state info associated with app_id"""
global_state = self.algod_client.application_info(self.app_id)
assert isinstance(global_state, dict)
return cast(
dict[bytes | str, bytes | str | int],
_decode_state(global_state.get("params", {}).get("global-state", {}), raw=raw),
)
def get_local_state(self, account: str | None = None, *, raw: bool = False) -> dict[bytes | str, bytes | str | int]:
"""Gets the local state info for associated app_id and account/sender"""
if account is None:
_, account = self.resolve_signer_sender(self.signer, self.sender)
acct_state = self.algod_client.account_application_info(account, self.app_id)
assert isinstance(acct_state, dict)
return cast(
dict[bytes | str, bytes | str | int],
_decode_state(acct_state.get("app-local-state", {}).get("key-value", {}), raw=raw),
)
def resolve(self, to_resolve: au_spec.DefaultArgumentDict) -> int | str | bytes:
"""Resolves the default value for an ABI method, based on app_spec"""
def _data_check(value: object) -> int | str | bytes:
if isinstance(value, int | str | bytes):
return value
raise ValueError(f"Unexpected type for constant data: {value}")
match to_resolve:
case {"source": "constant", "data": data}:
return _data_check(data)
case {"source": "global-state", "data": str() as key}:
global_state = self.get_global_state(raw=True)
return global_state[key.encode()]
case {"source": "local-state", "data": str() as key}:
_, sender = self.resolve_signer_sender(self.signer, self.sender)
acct_state = self.get_local_state(sender, raw=True)
return acct_state[key.encode()]
case {"source": "abi-method", "data": dict() as method_dict}:
method = Method.undictify(method_dict)
response = self.call(method)
assert isinstance(response, ABITransactionResponse)
return _data_check(response.return_value)
case {"source": source}:
raise ValueError(f"Unrecognized default argument source: {source}")
case _:
raise TypeError("Unable to interpret default argument specification")
def _get_app_deploy_metadata(
self, version: str | None, allow_update: bool | None, allow_delete: bool | None
) -> au_deploy.AppDeployMetaData:
updatable = (
allow_update
if allow_update is not None
else au_deploy.get_deploy_control(
self.app_spec, au_deploy.UPDATABLE_TEMPLATE_NAME, transaction.OnComplete.UpdateApplicationOC
)
)
deletable = (
allow_delete
if allow_delete is not None
else au_deploy.get_deploy_control(
self.app_spec, au_deploy.DELETABLE_TEMPLATE_NAME, transaction.OnComplete.DeleteApplicationOC
)
)
app = self._load_app_reference()
if version is None:
if app.app_id == 0:
version = "v1.0"
else:
assert isinstance(app, au_deploy.AppDeployMetaData)
version = get_next_version(app.version)
return au_deploy.AppDeployMetaData(self.app_name, version, updatable=updatable, deletable=deletable)
def _check_is_compiled(self) -> tuple[Program, Program]:
if self._approval_program is None or self._clear_program is None:
self._approval_program, self._clear_program = substitute_template_and_compile(
self.algod_client, self.app_spec, self.template_values
)
return self._approval_program, self._clear_program
def _simulate_readonly_call(
self, method: Method, atc: AtomicTransactionComposer
) -> ABITransactionResponse | TransactionResponse:
simulate_response = self._simulate_atc(atc)
if simulate_response.failure_message:
raise _try_convert_to_logic_error(
simulate_response.failure_message,
self.app_spec.approval_program,
self._get_approval_source_map,
) or Exception(
f"Simulate failed for readonly method {method.get_signature()}: {simulate_response.failure_message}"
)
return TransactionResponse.from_atr(simulate_response)
def _simulate_atc(self, atc: AtomicTransactionComposer) -> SimulateAtomicTransactionResponse:
# TODO: remove this once 3.16 is in mainnet
# there was a breaking change in algod 3.16 to the simulate endpoint
# attempt to transparently handle this by calling the endpoint with the old behaviour if
# 3.15 is detected
if self._use_simulate_315:
return simulate_atc_315(atc, self.algod_client)
try:
return atc.simulate(self.algod_client)
except AlgodHTTPError as ex:
if ex.code == HTTPStatus.BAD_REQUEST.value and (
"msgpack decode error [pos 12]: no matching struct field found when decoding stream map with key "
"txn-groups" in ex.args
):
self._use_simulate_315 = True
return simulate_atc_315(atc, self.algod_client)
raise ex
def _load_reference_and_check_app_id(self) -> None:
self._load_app_reference()
self._check_app_id()
def _load_app_reference(self) -> au_deploy.AppReference | au_deploy.AppMetaData:
if not self.existing_deployments and self._creator:
assert self._indexer_client
self.existing_deployments = au_deploy.get_creator_apps(self._indexer_client, self._creator)
if self.existing_deployments:
app = self.existing_deployments.apps.get(self.app_name)
if app:
if self.app_id == 0:
self.app_id = app.app_id
return app
return au_deploy.AppReference(self.app_id, self.app_address)
def _check_app_id(self) -> None:
if self.app_id == 0:
raise Exception(
"ApplicationClient is not associated with an app instance, to resolve either:\n"
"1.) provide an app_id on construction OR\n"
"2.) provide a creator address so an app can be searched for OR\n"
"3.) create an app first using create or deploy methods"
)
def _resolve_method(
self,
abi_method: ABIMethod | bool | None,
args: ABIArgsDict | None,
on_complete: transaction.OnComplete,
call_config: au_spec.CallConfig = au_spec.CallConfig.CALL,
) -> Method | None:
matches: list[Method | None] = []
match abi_method:
case str() | Method(): # abi method specified
return self._resolve_abi_method(abi_method)
case bool() | None: # find abi method
has_bare_config = (
call_config in au_deploy.get_call_config(self.app_spec.bare_call_config, on_complete)
or on_complete == transaction.OnComplete.ClearStateOC
)
abi_methods = self._find_abi_methods(args, on_complete, call_config)
if abi_method is not False:
matches += abi_methods
if has_bare_config and abi_method is not True:
matches += [None]
case _:
return abi_method.method_spec()
if len(matches) == 1: # exact match
return matches[0]
elif len(matches) > 1: # ambiguous match
signatures = ", ".join((m.get_signature() if isinstance(m, Method) else "bare") for m in matches)
raise Exception(
f"Could not find an exact method to use for {on_complete.name} with call_config of {call_config.name}, "
f"specify the exact method using abi_method and args parameters, considered: {signatures}"
)
else: # no match
raise Exception(
f"Could not find any methods to use for {on_complete.name} with call_config of {call_config.name}"
)
def _get_approval_source_map(self) -> SourceMap | None:
if self.approval_source_map:
return self.approval_source_map
try:
approval, _ = self._check_is_compiled()
except au_deploy.DeploymentFailedError:
return None
return approval.source_map
def export_source_map(self) -> str | None:
"""Export approval source map to JSON, can be later re-imported with `import_source_map`"""
source_map = self._get_approval_source_map()
if source_map:
return json.dumps(
{
"version": source_map.version,
"sources": source_map.sources,
"mappings": source_map.mappings,
}
)
return None
def import_source_map(self, source_map_json: str) -> None:
"""Import approval source from JSON exported by `export_source_map`"""
source_map = json.loads(source_map_json)
self._approval_source_map = SourceMap(source_map)
def add_method_call(
self,
atc: AtomicTransactionComposer,
abi_method: ABIMethod | bool | None = None,
*,
abi_args: ABIArgsDict | None = None,