-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharc4.py
More file actions
1451 lines (1152 loc) Β· 45.2 KB
/
arc4.py
File metadata and controls
1451 lines (1152 loc) Β· 45.2 KB
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
from __future__ import annotations
import dataclasses
import decimal
import functools
import types
import typing
import algosdk
from Cryptodome.Hash import SHA512
from _algopy_testing.constants import (
ARC4_RETURN_PREFIX,
BITS_IN_BYTE,
MAX_UINT64,
UINT64_SIZE,
UINT512_SIZE,
)
from _algopy_testing.models.account import Account
from _algopy_testing.models.contract import ARC4Contract
from _algopy_testing.mutable import (
MutableBytes,
add_mutable_callback,
set_item_on_mutate,
)
from _algopy_testing.primitives import Bytes
from _algopy_testing.protocols import BytesBacked
from _algopy_testing.utils import (
as_bytes,
as_int,
as_int16,
as_int64,
as_int512,
as_string,
int_to_bytes,
raise_mocked_function_error,
)
if typing.TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator, Sequence
import algopy
__all__ = [
"ARC4Client",
"ARC4Contract",
"Address",
"BigUFixedNxM",
"BigUIntN",
"Bool",
"Byte",
"DynamicArray",
"DynamicBytes",
"StaticArray",
"String",
"Struct",
"Tuple",
"UFixedNxM",
"UInt8",
"UInt16",
"UInt32",
"UInt64",
"UInt128",
"UInt256",
"UInt512",
"UIntN",
"abi_call",
"arc4_create",
"arc4_signature",
"arc4_update",
"emit",
]
_ABI_LENGTH_SIZE = 2
_TBitSize = typing.TypeVar("_TBitSize", bound=int)
_P = typing.ParamSpec("_P")
_R = typing.TypeVar("_R")
class _TypeInfo:
@property
def typ(self) -> type:
raise NotImplementedError
@property
def arc4_name(self) -> str:
raise NotImplementedError
@property
def is_dynamic(self) -> bool:
return False
def __eq__(self, other: object) -> bool:
return isinstance(other, _TypeInfo) and self.arc4_name == other.arc4_name
def __hash__(self) -> int:
return hash(self.arc4_name)
def __repr__(self) -> str:
return self.arc4_name
def _get_int_literal(literal_type: type) -> int:
type_args = typing.get_args(literal_type)
try:
(int_arg,) = type_args
except ValueError:
int_arg = 0
return int(int_arg)
def _create_int_literal(value: int) -> type:
return typing.cast(type, typing.Literal[value])
def _parameterize_type(type_: type, *params: type) -> type:
if len(params) == 1:
return typing.cast(type, type_[params[0]]) # type: ignore[index]
return typing.cast(type, type_[params]) # type: ignore[index]
def _get_type_param_name(typ: type) -> str:
if typ.__name__ == "Literal":
int_arg = _get_int_literal(typ)
return str(int_arg)
return typ.__name__
def _new_parameterized_class(cls: type, type_params: Sequence[type], type_info: _TypeInfo) -> type:
cls_name = f"{cls.__name__}[{','.join(_get_type_param_name(t) for t in type_params)}]"
return types.new_class(
cls_name,
bases=(cls,),
exec_body=lambda ns: ns.update(
_type_info=type_info,
),
)
def _check_is_arc4(items: Sequence[typing.Any]) -> Sequence[_ABIEncoded]:
for item in items:
if not isinstance(item, _ABIEncoded):
raise TypeError("expected ARC4 type")
return items
class _ABIEncoded(BytesBacked):
_type_info: _TypeInfo
_value: bytes
@classmethod
def from_bytes(cls, value: algopy.Bytes | bytes, /) -> typing.Self:
"""Construct an instance from the underlying bytes (no validation)"""
instance = cls()
instance._value = as_bytes(value)
return instance
@classmethod
def from_log(cls, log: algopy.Bytes, /) -> typing.Self:
"""Load an ABI type from application logs, checking for the ABI return prefix
`0x151f7c75`"""
if log[:4] == ARC4_RETURN_PREFIX:
return cls.from_bytes(log[4:])
raise ValueError("ABI return prefix not found")
@property
def bytes(self) -> algopy.Bytes:
"""Get the underlying Bytes."""
import algopy
return algopy.Bytes(self._value)
def __eq__(self, other: object) -> bool:
if isinstance(other, _ABIEncoded):
return self._type_info == other._type_info and self.bytes == other.bytes
else:
return NotImplemented
def __hash__(self) -> int:
return hash(self.bytes)
def arc4_signature(signature: str | Callable[_P, _R], /) -> algopy.Bytes:
"""Convert a signature to ARC4 bytes."""
import algopy
from _algopy_testing.decorators.arc4 import get_arc4_metadata
if isinstance(signature, str):
method_signature = signature
else:
arc4_signature = get_arc4_metadata(signature).arc4_signature
if arc4_signature is None:
raise ValueError("signature not found")
method_signature = arc4_signature
hashed_signature = SHA512.new(truncate="256")
hashed_signature.update(method_signature.encode("utf-8"))
return_value = hashed_signature.digest()[:4]
return algopy.Bytes(return_value)
class _StringTypeInfo(_TypeInfo):
@property
def typ(self) -> type:
return String
@property
def arc4_name(self) -> str:
return "string"
@property
def is_dynamic(self) -> bool:
return True
class String(_ABIEncoded):
"""An ARC4 sequence of bytes containing a UTF8 string."""
_type_info = _StringTypeInfo()
_value: bytes
def __init__(self, value: algopy.String | str = "", /) -> None:
import algopy
match value:
case algopy.String():
bytes_value = as_bytes(value.bytes)
case str(value):
bytes_value = value.encode("utf-8")
case _:
raise TypeError(
f"value must be a string or String type, not {type(value).__name__!r}"
)
self._value = as_bytes(_encode_length(len(bytes_value)) + bytes_value)
@property
def native(self) -> algopy.String:
"""Return the String representation of the UTF8 string after ARC4 decoding."""
import algopy
return algopy.String.from_bytes(self._value[_ABI_LENGTH_SIZE:])
def __add__(self, other: String | str) -> String:
return String(self.native + as_string(other))
def __radd__(self, other: String | str) -> String:
return String(as_string(other) + self.native)
def __eq__(self, other: String | str) -> bool: # type: ignore[override]
try:
other_string = as_string(other)
except TypeError:
return NotImplemented
return self.native == other_string
def __bool__(self) -> bool:
"""Returns `True` if length is not zero."""
return bool(self.native)
def __str__(self) -> str:
return str(self.native)
def __repr__(self) -> str:
return _arc4_repr(self)
class _UIntTypeInfo(_TypeInfo):
def __init__(self, size: int) -> None:
self.bit_size = size
if size <= UINT64_SIZE:
self.max_bits_len = UINT64_SIZE
self._type: type = UIntN
else:
self.max_bits_len = UINT512_SIZE
self._type = BigUIntN
self.max_int = 2**self.bit_size - 1
self.max_bytes_len = self.bit_size // BITS_IN_BYTE
@property
def typ(self) -> type:
return _parameterize_type(self._type, _create_int_literal(self.bit_size))
@property
def arc4_name(self) -> str:
return f"uint{self.bit_size}"
# https://stackoverflow.com/a/75395800
class _UIntNMeta(type(_ABIEncoded), typing.Generic[_TBitSize]): # type: ignore[misc]
__concrete__: typing.ClassVar[dict[type, type]] = {}
def __getitem__(cls, key_t: type[_TBitSize]) -> type:
cache = cls.__concrete__
if c := cache.get(key_t, None):
return c
size = _get_int_literal(key_t)
cache[key_t] = c = _new_parameterized_class(cls, [key_t], _UIntTypeInfo(size))
return c
class _UIntN(_ABIEncoded, typing.Generic[_TBitSize], metaclass=_UIntNMeta):
_type_info: _UIntTypeInfo
_value: bytes # underlying 'bytes' value representing the UIntN
def __init__(
self,
value: algopy.BigUInt | algopy.UInt64 | int = 0,
/,
) -> None:
value = as_int(value, max=self._type_info.max_int)
bytes_value = int_to_bytes(value, self._type_info.max_bytes_len)
self._value = as_bytes(bytes_value)
def __bool__(self) -> bool:
"""Returns `True` if not equal to zero."""
raise NotImplementedError
@functools.total_ordering
class UIntN(_UIntN, typing.Generic[_TBitSize]): # type: ignore[type-arg]
"""An ARC4 UInt consisting of the number of bits specified.
Max Size: 64 bits
"""
@property
def native(self) -> algopy.UInt64:
"""Return the UInt64 representation of the value after ARC4 decoding."""
import algopy
return algopy.UInt64(int.from_bytes(self._value))
def __eq__(self, other: object) -> bool:
try:
other_int = as_int64(other)
except (TypeError, ValueError):
return NotImplemented
return as_int64(self.native) == other_int
def __lt__(self, other: object) -> bool:
try:
other_int = as_int64(other)
except (TypeError, ValueError):
return NotImplemented
return as_int64(self.native) < other_int
def __bool__(self) -> bool:
return bool(self.native)
def __str__(self) -> str:
return str(self.native)
def __repr__(self) -> str:
return _arc4_repr(self)
@functools.total_ordering
class BigUIntN(_UIntN, typing.Generic[_TBitSize]): # type: ignore[type-arg]
"""An ARC4 UInt consisting of the number of bits specified.
Max size: 512 bits
"""
@property
def native(self) -> algopy.BigUInt:
"""Return the UInt64 representation of the value after ARC4 decoding."""
import algopy
return algopy.BigUInt.from_bytes(self._value)
def __eq__(self, other: object) -> bool:
try:
other_int = as_int512(other)
except (TypeError, ValueError):
return NotImplemented
return as_int512(self.native) == other_int
def __lt__(self, other: object) -> bool:
try:
other_int = as_int512(other)
except (TypeError, ValueError):
return NotImplemented
return as_int512(self.native) < other_int
def __bool__(self) -> bool:
return bool(self.native)
def __str__(self) -> str:
return str(self.native)
def __repr__(self) -> str:
return _arc4_repr(self)
_TDecimalPlaces = typing.TypeVar("_TDecimalPlaces", bound=int)
_MAX_M_SIZE = 160
class _UFixedTypeInfo(_UIntTypeInfo):
def __init__(self, size: int, precision: int) -> None:
super().__init__(size)
self.precision = precision
@property
def typ(self) -> type:
return _parameterize_type(
_UFixedNxM, _create_int_literal(self.bit_size), _create_int_literal(self.precision)
)
@property
def arc4_name(self) -> str:
return f"ufixed{self.bit_size}x{self.precision}"
class _UFixedNxMMeta(type(_ABIEncoded), typing.Generic[_TBitSize, _TDecimalPlaces]): # type: ignore[misc]
__concrete__: typing.ClassVar[dict[tuple[type, type], type]] = {}
def __getitem__(cls, key_t: tuple[type[_TBitSize], type[_TDecimalPlaces]]) -> type:
cache = cls.__concrete__
if c := cache.get(key_t, None):
return c
size_t, precision_t = key_t
size = _get_int_literal(size_t)
precision = _get_int_literal(precision_t)
cache[key_t] = c = _new_parameterized_class(
cls,
key_t,
_UFixedTypeInfo(
size=size,
precision=precision,
),
)
return c
class _UFixedNxM(
_ABIEncoded, typing.Generic[_TBitSize, _TDecimalPlaces], metaclass=_UFixedNxMMeta
):
_type_info: _UFixedTypeInfo
_value: bytes # underlying 'bytes' value representing the UFixedNxM
def __init__(self, value: str = "0.0", /) -> None:
value = as_string(value)
with decimal.localcontext(
decimal.Context(
prec=160,
traps=[
decimal.Rounded,
decimal.InvalidOperation,
decimal.Overflow,
decimal.DivisionByZero,
],
)
):
try:
d = decimal.Decimal(value)
except ArithmeticError as ex:
raise ValueError(f"Invalid decimal literal: {value}") from ex
if d < 0:
raise ValueError("Negative numbers not allowed")
try:
q = d.quantize(decimal.Decimal(f"1e-{self._type_info.precision}"))
except ArithmeticError as ex:
raise ValueError(
f"Too many decimals, expected max of {self._type_info.precision}"
) from ex
int_value = round(q * (10**self._type_info.precision))
int_value = as_int(int_value, max=self._type_info.max_int)
bytes_value = int_to_bytes(int_value, self._type_info.max_bytes_len)
self._value = as_bytes(bytes_value, max_size=self._type_info.max_bytes_len)
def __bool__(self) -> bool:
"""Returns `True` if not equal to zero."""
return bool(int.from_bytes(self._value))
def __str__(self) -> str:
int_str = str(int.from_bytes(self._value))
whole = int_str[: -self._type_info.precision]
fractional = int_str[-self._type_info.precision :]
return f"{whole}.{fractional}"
def __repr__(self) -> str:
return _arc4_repr(self)
# implementations are effectively the same for these types
UFixedNxM = _UFixedNxM
BigUFixedNxM = _UFixedNxM
class _ByteTypeInfo(_UIntTypeInfo):
def __init__(self) -> None:
super().__init__(8)
@property
def typ(self) -> type:
return Byte
@property
def arc4_name(self) -> str:
return "byte"
class Byte(UIntN[typing.Literal[8]]):
"""An ARC4 alias for a UInt8."""
_type_info = _ByteTypeInfo()
UInt8: typing.TypeAlias = UIntN[typing.Literal[8]]
UInt16: typing.TypeAlias = UIntN[typing.Literal[16]]
UInt32: typing.TypeAlias = UIntN[typing.Literal[32]]
UInt64: typing.TypeAlias = UIntN[typing.Literal[64]]
UInt128: typing.TypeAlias = BigUIntN[typing.Literal[128]]
UInt256: typing.TypeAlias = BigUIntN[typing.Literal[256]]
UInt512: typing.TypeAlias = BigUIntN[typing.Literal[512]]
class _BoolTypeInfo(_TypeInfo):
@property
def typ(self) -> type:
return Bool
@property
def arc4_name(self) -> str:
return "bool"
class Bool(_ABIEncoded):
"""An ARC4 encoded bool."""
_type_info = _BoolTypeInfo()
_value: bytes
# True value is encoded as having a 1 on the most significant bit (0x80 = 128)
_true_int_value = 128
_false_int_value = 0
def __init__(self, value: bool = False, /) -> None: # noqa: FBT001, FBT002
self._value = int_to_bytes(self._true_int_value if value else self._false_int_value, 1)
def __bool__(self) -> bool:
"""Allow Bool to be used in boolean contexts."""
return self.native
@property
def native(self) -> bool:
"""Return the bool representation of the value after ARC4 decoding."""
int_value = int.from_bytes(self._value)
return int_value == self._true_int_value
def __str__(self) -> str:
return f"{self.native}"
def __repr__(self) -> str:
return _arc4_repr(self)
_TArrayItem = typing.TypeVar("_TArrayItem", bound=_ABIEncoded)
_TArrayLength = typing.TypeVar("_TArrayLength", bound=int)
class _StaticArrayTypeInfo(_TypeInfo):
def __init__(self, item_type: _TypeInfo, size: int):
self.item_type = item_type
self.size = size
@property
def typ(self) -> type:
return _parameterize_type(StaticArray, self.item_type.typ, _create_int_literal(self.size))
@property
def arc4_name(self) -> str:
return f"{self.item_type.arc4_name}[{self.size}]"
@property
def is_dynamic(self) -> bool:
return self.item_type.is_dynamic
class _StaticArrayMeta(type(_ABIEncoded), typing.Generic[_TArrayItem, _TArrayLength]): # type: ignore # noqa: PGH003
__concrete__: typing.ClassVar[dict[tuple[type, type], type]] = {}
def __getitem__(cls, key_t: tuple[type[_TArrayItem], type[_TArrayLength]]) -> type:
cache = cls.__concrete__
if c := cache.get(key_t, None):
return c
item_t, size_t = key_t
assert issubclass(item_t, _ABIEncoded)
size = _get_int_literal(size_t)
cache[key_t] = c = _new_parameterized_class(
cls,
key_t,
_StaticArrayTypeInfo(
item_type=item_t._type_info,
size=size,
),
)
return c
class StaticArray(
_ABIEncoded,
MutableBytes,
typing.Generic[_TArrayItem, _TArrayLength],
metaclass=_StaticArrayMeta,
):
"""A fixed length ARC4 Array of the specified type and length."""
_type_info: _StaticArrayTypeInfo
def __new__(cls, *items: _TArrayItem) -> typing.Self:
try:
assert cls._type_info
except AttributeError:
try:
item = items[0]
except IndexError:
raise TypeError("array must have an item type") from None
size = len(items)
cls = _parameterize_type(cls, type(item), _create_int_literal(size))
instance = super().__new__(cls)
return instance
def __init__(self, *_items: _TArrayItem):
super().__init__()
items = _check_is_arc4(_items)
for item in items:
if len(items) != self._type_info.size:
raise TypeError(f"expected {self._type_info.size} items, not {len(items)}")
if self._type_info.item_type != item._type_info:
raise TypeError(
f"item must be of type {self._type_info.item_type!r}, not {item._type_info!r}"
)
self._value = _encode(items)
def __iter__(self) -> Iterator[_TArrayItem]:
# """Returns an iterator for the items in the array"""
return iter(self._list())
def __reversed__(self) -> Iterator[_TArrayItem]:
# """Returns an iterator for the items in the array, in reverse order"""
return reversed(self._list())
@property
def length(self) -> algopy.UInt64:
# """Returns the current length of the array"""
import algopy
return algopy.UInt64(self._type_info.size)
def __getitem__(self, index: algopy.UInt64 | int) -> _TArrayItem:
value = self._list()[index]
return set_item_on_mutate(self, index, value)
def __setitem__(self, index: algopy.UInt64 | int, item: _TArrayItem) -> _TArrayItem:
if item._type_info != self._type_info.item_type:
raise TypeError(
f"item must be of type {self._type_info.item_type!r}, not {item._type_info!r}"
)
x = self._list()
x[index] = item
self._value = _encode(x)
return item
def _list(self) -> list[_TArrayItem]:
return _decode_tuple_items(self._value, [self._type_info.item_type] * self._type_info.size)
def __str__(self) -> str:
items = map(str, self._list())
return f"[{', '.join(items)}]"
def __repr__(self) -> str:
items = map(repr, self._list())
return f"{_arc4_type_repr(type(self))}({', '.join(items)})"
class _AddressTypeInfo(_StaticArrayTypeInfo):
def __init__(self) -> None:
super().__init__(Byte._type_info, 32)
@property
def typ(self) -> type:
return Address
@property
def arc4_name(self) -> str:
return "address"
class Address(StaticArray[Byte, typing.Literal[32]]):
_type_info = _AddressTypeInfo()
def __init__(self, value: Account | str | algopy.Bytes = algosdk.constants.ZERO_ADDRESS):
super().__init__()
if isinstance(value, str):
try:
bytes_value = algosdk.encoding.decode_address(value)
except Exception as e:
raise ValueError(f"cannot encode the following address: {value!r}") from e
elif isinstance(value, Account):
bytes_value = value.bytes.value
else:
bytes_value = as_bytes(value)
if len(bytes_value) != 32:
raise ValueError(f"expected 32 bytes, got: {len(bytes_value)}")
self._value = bytes_value
@property
def native(self) -> Account:
# """Return the Account representation of the address after ARC4 decoding"""
return Account(self.bytes)
def __bool__(self) -> bool:
# """Returns `True` if not equal to the zero address"""
zero_bytes: bytes = algosdk.encoding.decode_address(algosdk.constants.ZERO_ADDRESS)
return self.bytes != zero_bytes
def __eq__(self, other: Address | Account | str) -> bool: # type: ignore[override]
"""Address equality is determined by the address of another `arc4.Address`,
`Account` or `str`"""
if isinstance(other, Address | Account):
return self.bytes == other.bytes
elif isinstance(other, str):
other_bytes: bytes = algosdk.encoding.decode_address(other)
return self.bytes == other_bytes
else:
return NotImplemented
def __str__(self) -> str:
return str(self.native)
def __repr__(self) -> str:
return _arc4_repr(self)
class _DynamicArrayTypeInfo(_TypeInfo):
def __init__(self, item_type: _TypeInfo):
self.item_type = item_type
@property
def typ(self) -> type:
return _parameterize_type(DynamicArray, self.item_type.typ)
@property
def arc4_name(self) -> str:
return f"{self.item_type.arc4_name}[]"
@property
def is_dynamic(self) -> bool:
return True
class _DynamicArrayMeta(type(_ABIEncoded), typing.Generic[_TArrayItem]): # type: ignore[misc]
__concrete__: typing.ClassVar[dict[type, type]] = {}
def __getitem__(cls, key_t: type[_TArrayItem]) -> type:
cache = cls.__concrete__
if c := cache.get(key_t, None):
return c
cache[key_t] = c = _new_parameterized_class(
cls, [key_t], _DynamicArrayTypeInfo(key_t._type_info)
)
return c
class DynamicArray( # TODO: inherit from StaticArray?
_ABIEncoded,
MutableBytes,
typing.Generic[_TArrayItem],
metaclass=_DynamicArrayMeta,
):
"""A dynamically sized ARC4 Array of the specified type."""
_type_info: _DynamicArrayTypeInfo
def __new__(cls, *items: _TArrayItem) -> typing.Self:
try:
assert cls._type_info
except AttributeError:
try:
item = items[0]
except IndexError:
raise TypeError("array must have an item type") from None
cls = _parameterize_type(cls, type(item))
instance = super().__new__(cls)
return instance
def __init__(self, *_items: _TArrayItem):
super().__init__()
items = _check_is_arc4(_items)
for item in items:
if self._type_info.item_type != item._type_info:
raise TypeError(
f"item must be of type {self._type_info.item_type!r}, not {item._type_info!r}"
)
self._value = self._encode_with_length(items)
def __iter__(self) -> typing.Iterator[_TArrayItem]:
"""Returns an iterator for the items in the array."""
return iter(self._list())
def __reversed__(self) -> typing.Iterator[_TArrayItem]:
"""Returns an iterator for the items in the array, in reverse order."""
return reversed(self._list())
@property
def length(self) -> algopy.UInt64:
"""Returns the current length of the array."""
import algopy
return algopy.UInt64(len(self._list()))
def __getitem__(self, index: algopy.UInt64 | int) -> _TArrayItem:
value = self._list()[index]
return set_item_on_mutate(self, index, value)
def __setitem__(self, index: algopy.UInt64 | int, item: _TArrayItem) -> _TArrayItem:
if item._type_info != self._type_info.item_type:
raise TypeError(
f"item must be of type {self._type_info.item_type!r}, not {item._type_info!r}"
)
x = self._list()
x[index] = item
self._value = self._encode_with_length(x)
return item
def append(self, item: _TArrayItem, /) -> None:
"""Append items to this array."""
if item._type_info != self._type_info.item_type:
raise TypeError(
f"item must be of type {self._type_info.item_type!r}, not {item._type_info!r}"
)
x = self._list()
x.append(item)
self._value = self._encode_with_length(x)
def extend(self, other: Iterable[_TArrayItem], /) -> None:
"""Extend this array with the contents of another array."""
incorrect_types = [
o._type_info for o in other if o._type_info != self._type_info.item_type
]
if incorrect_types:
other_types_str = ", ".join(sorted(set(map(str, incorrect_types))))
raise TypeError(
f"items must be of type {self._type_info.item_type!r}: {other_types_str}"
)
x = self._list()
x.extend(other)
self._value = self._encode_with_length(x)
def __add__(self, other: Iterable[_TArrayItem]) -> typing.Self:
self.extend(other)
return self
def pop(self) -> _TArrayItem:
"""Remove and return the last item in the array."""
x = self._list()
item = x.pop()
self._value = self._encode_with_length(x)
return item
def __bool__(self) -> bool:
"""Returns `True` if not an empty array."""
return bool(self._list())
def _list(self) -> list[_TArrayItem]:
length, data = _read_length(self._value)
return _decode_tuple_items(data, [self._type_info.item_type] * length)
def _encode_with_length(self, items: Sequence[_ABIEncoded]) -> bytes:
return _encode_length(len(items)) + _encode(items)
def __str__(self) -> str:
items = map(str, self._list())
return f"[{', '.join(items)}]"
def __repr__(self) -> str:
items = map(repr, self._list())
return f"{_arc4_type_repr(type(self))}({', '.join(items)})"
class DynamicBytes(DynamicArray[Byte]):
"""A variable sized array of bytes."""
@typing.overload
def __init__(self, *values: Byte | UInt8 | int): ...
@typing.overload
def __init__(self, value: algopy.Bytes | bytes, /): ...
def __init__(self, *value: algopy.Bytes | bytes | Byte | UInt8 | int):
items = []
for x in value:
match x:
case Bytes() | bytes():
if len(value) > 1:
raise ValueError("expected single Bytes value")
items.extend([Byte(b) for b in as_bytes(x)])
case UIntN(_type_info=_UIntTypeInfo(bit_size=8)) as uint:
items.append(Byte(as_int(uint.native, max=2**8)))
case int(int_value):
items.append(Byte(int_value))
case _:
raise TypeError("expected algopy.Bytes | bytes | Byte | UInt8 | int")
super().__init__(*items)
@property
def native(self) -> algopy.Bytes:
return self.bytes[_ABI_LENGTH_SIZE:]
def __str__(self) -> str:
return str(self.native)
def __repr__(self) -> str:
return _arc4_repr(self)
_TTuple = typing.TypeVarTuple("_TTuple")
class _TupleTypeInfo(_TypeInfo):
def __init__(self, child_types: list[_TypeInfo]) -> None:
self.child_types = child_types
@property
def typ(self) -> type:
return _parameterize_type(Tuple, *(t.typ for t in self.child_types))
@property
def arc4_name(self) -> str:
inner_name = ",".join([t.arc4_name for t in self.child_types])
return f"({inner_name})"
@property
def is_dynamic(self) -> bool:
return any(t.is_dynamic for t in self.child_types)
class _TupleMeta(type(_ABIEncoded), typing.Generic[typing.Unpack[_TTuple]]): # type: ignore # noqa: PGH003
__concrete__: typing.ClassVar[dict[tuple, type]] = {} # type: ignore[type-arg]
def __getitem__(cls, key_t: tuple[type[_ABIEncoded], ...]) -> type:
cache = cls.__concrete__
if c := cache.get(key_t, None):
return c
cache[key_t] = c = _new_parameterized_class(
cls, key_t, _TupleTypeInfo([t._type_info for t in key_t])
)
return c
class Tuple(
_ABIEncoded,
MutableBytes,
tuple[typing.Unpack[_TTuple]],
typing.Generic[typing.Unpack[_TTuple]],
metaclass=_TupleMeta,
):
"""An ARC4 ABI tuple, containing other ARC4 ABI types."""
__slots__ = () # to satisfy SLOT001
_type_info: _TupleTypeInfo
def __new__(
cls,
items: tuple[typing.Unpack[_TTuple]] = (), # type: ignore[assignment]
) -> typing.Self:
try:
assert cls._type_info
except AttributeError:
if not items:
raise TypeError("empty tuple not supported") from None
cls = _parameterize_type(cls, *map(type, items))
instance = super().__new__(cls)
return instance
def __init__(self, _items: tuple[typing.Unpack[_TTuple]] = (), /): # type: ignore[assignment]
super().__init__()
items = _check_is_arc4(_items)
if items:
for item, expected_type in zip(items, self._type_info.child_types, strict=True):
item_type_info = item._type_info
if expected_type != item_type_info:
raise TypeError(
f"item must be of type {self._type_info!r}, not {item_type_info!r}"
)
self._value = _encode(items)
def __len__(self) -> int:
return len(self.native)