-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
contract.py
1681 lines (1395 loc) · 56.3 KB
/
contract.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
"""Interaction with smart contracts over Web3 connector.
"""
import copy
import itertools
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Dict,
Generator,
Iterable,
List,
NoReturn,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
import warnings
from eth_abi.exceptions import (
DecodingError,
)
from eth_typing import (
Address,
BlockNumber,
ChecksumAddress,
HexStr,
)
from eth_utils import (
add_0x_prefix,
combomethod,
encode_hex,
function_abi_to_4byte_selector,
is_list_like,
is_text,
to_tuple,
)
from eth_utils.toolz import (
compose,
partial,
)
from hexbytes import (
HexBytes,
)
from web3._utils.abi import (
abi_to_signature,
check_if_arguments_can_be_encoded,
fallback_func_abi_exists,
filter_by_type,
get_abi_input_names,
get_abi_input_types,
get_abi_output_types,
get_constructor_abi,
is_array_type,
map_abi_data,
merge_args_and_kwargs,
receive_func_abi_exists,
)
from web3._utils.blocks import (
is_hex_encoded_block_hash,
)
from web3._utils.contracts import (
encode_abi,
find_matching_event_abi,
find_matching_fn_abi,
get_function_info,
prepare_transaction,
)
from web3._utils.datatypes import (
PropertyCheckingFactory,
)
from web3._utils.decorators import (
deprecated_for,
)
from web3._utils.empty import (
empty,
)
from web3._utils.encoding import (
to_4byte_hex,
to_hex,
)
from web3._utils.events import (
EventFilterBuilder,
get_event_data,
is_dynamic_sized_type,
)
from web3._utils.filters import (
LogFilter,
construct_event_filter_params,
)
from web3._utils.function_identifiers import (
FallbackFn,
ReceiveFn,
)
from web3._utils.normalizers import (
BASE_RETURN_NORMALIZERS,
normalize_abi,
normalize_address,
normalize_bytecode,
)
from web3._utils.transactions import (
fill_transaction_defaults,
)
from web3.datastructures import (
AttributeDict,
MutableAttributeDict,
)
from web3.exceptions import (
ABIEventFunctionNotFound,
ABIFunctionNotFound,
BadFunctionCallOutput,
BlockNumberOutofRange,
FallbackNotFound,
InvalidEventABI,
LogTopicError,
MismatchedABI,
NoABIEventsFound,
NoABIFound,
NoABIFunctionsFound,
ValidationError,
)
from web3.logs import (
DISCARD,
IGNORE,
STRICT,
WARN,
EventLogErrorFlags,
)
from web3.types import ( # noqa: F401
ABI,
ABIEvent,
ABIFunction,
BlockIdentifier,
EventData,
FunctionIdentifier,
LogReceipt,
TxParams,
TxReceipt,
)
if TYPE_CHECKING:
from web3 import Web3 # noqa: F401
ACCEPTABLE_EMPTY_STRINGS = ["0x", b"0x", "", b""]
class ContractFunctions:
"""Class containing contract function objects
"""
def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None) -> None:
self.abi = abi
self.web3 = web3
self.address = address
if self.abi:
self._functions = filter_by_type('function', self.abi)
for func in self._functions:
setattr(
self,
func['name'],
ContractFunction.factory(
func['name'],
web3=self.web3,
contract_abi=self.abi,
address=self.address,
function_identifier=func['name']))
def __iter__(self) -> Generator[str, None, None]:
if not hasattr(self, '_functions') or not self._functions:
return
for func in self._functions:
yield func['name']
def __getattr__(self, function_name: str) -> "ContractFunction":
if self.abi is None:
raise NoABIFound(
"There is no ABI found for this contract.",
)
if '_functions' not in self.__dict__:
raise NoABIFunctionsFound(
"The abi for this contract contains no function definitions. ",
"Are you sure you provided the correct contract abi?"
)
elif function_name not in self.__dict__['_functions']:
raise ABIFunctionNotFound(
"The function '{}' was not found in this contract's abi. ".format(function_name),
"Are you sure you provided the correct contract abi?"
)
else:
return super().__getattribute__(function_name)
def __getitem__(self, function_name: str) -> ABIFunction:
return getattr(self, function_name)
def __hasattr__(self, event_name: str) -> bool:
try:
return event_name in self.__dict__['_events']
except ABIFunctionNotFound:
return False
class ContractEvents:
"""Class containing contract event objects
This is available via:
.. code-block:: python
>>> mycontract.events
<web3.contract.ContractEvents object at 0x108afde10>
To get list of all supported events in the contract ABI.
This allows you to iterate over :class:`ContractEvent` proxy classes.
.. code-block:: python
>>> for e in mycontract.events: print(e)
<class 'web3._utils.datatypes.LogAnonymous'>
...
"""
def __init__(self, abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None) -> None:
if abi:
self.abi = abi
self._events = filter_by_type('event', self.abi)
for event in self._events:
setattr(
self,
event['name'],
ContractEvent.factory(
event['name'],
web3=web3,
contract_abi=self.abi,
address=address,
event_name=event['name']))
def __getattr__(self, event_name: str) -> Type['ContractEvent']:
if '_events' not in self.__dict__:
raise NoABIEventsFound(
"The abi for this contract contains no event definitions. ",
"Are you sure you provided the correct contract abi?"
)
elif event_name not in self.__dict__['_events']:
raise ABIEventFunctionNotFound(
"The event '{}' was not found in this contract's abi. ".format(event_name),
"Are you sure you provided the correct contract abi?"
)
else:
return super().__getattribute__(event_name)
def __getitem__(self, event_name: str) -> Type['ContractEvent']:
return getattr(self, event_name)
def __iter__(self) -> Iterable[Type['ContractEvent']]:
"""Iterate over supported
:return: Iterable of :class:`ContractEvent`
"""
for event in self._events:
yield self[event['name']]
def __hasattr__(self, event_name: str) -> bool:
try:
return event_name in self.__dict__['_events']
except ABIEventFunctionNotFound:
return False
class Contract:
"""Base class for Contract proxy classes.
First you need to create your Contract classes using
:meth:`web3.eth.Eth.contract` that takes compiled Solidity contract
ABI definitions as input. The created class object will be a subclass of
this base class.
After you have your Contract proxy class created you can interact with
smart contracts
* Create a Contract proxy object for an existing deployed smart contract by
its address using :meth:`__init__`
* Deploy a new smart contract using :py:meth:`Contract.constructor.transact()`
"""
# set during class construction
web3: 'Web3' = None
# instance level properties
address: ChecksumAddress = None
# class properties (overridable at instance level)
abi: ABI = None
asm = None
ast = None
bytecode = None
bytecode_runtime = None
clone_bin = None
functions: ContractFunctions = None
caller: 'ContractCaller' = None
#: Instance of :class:`ContractEvents` presenting available Event ABIs
events: ContractEvents = None
dev_doc = None
interface = None
metadata = None
opcodes = None
src_map = None
src_map_runtime = None
user_doc = None
def __init__(self, address: Optional[ChecksumAddress] = None) -> None:
"""Create a new smart contract proxy object.
:param address: Contract address as 0x hex string
"""
if self.web3 is None:
raise AttributeError(
'The `Contract` class has not been initialized. Please use the '
'`web3.contract` interface to create your contract class.'
)
if address:
self.address = normalize_address(self.web3.ens, address)
if not self.address:
raise TypeError("The address argument is required to instantiate a contract.")
self.functions = ContractFunctions(self.abi, self.web3, self.address)
self.caller = ContractCaller(self.abi, self.web3, self.address)
self.events = ContractEvents(self.abi, self.web3, self.address)
self.fallback = Contract.get_fallback_function(self.abi, self.web3, self.address)
self.receive = Contract.get_receive_function(self.abi, self.web3, self.address)
@classmethod
def factory(cls, web3: 'Web3', class_name: Optional[str] = None, **kwargs: Any) -> 'Contract':
kwargs['web3'] = web3
normalizers = {
'abi': normalize_abi,
'address': partial(normalize_address, kwargs['web3'].ens),
'bytecode': normalize_bytecode,
'bytecode_runtime': normalize_bytecode,
}
contract = cast(Contract, PropertyCheckingFactory(
class_name or cls.__name__,
(cls,),
kwargs,
normalizers=normalizers,
))
contract.functions = ContractFunctions(contract.abi, contract.web3)
contract.caller = ContractCaller(contract.abi, contract.web3, contract.address)
contract.events = ContractEvents(contract.abi, contract.web3)
contract.fallback = Contract.get_fallback_function(contract.abi, contract.web3)
contract.receive = Contract.get_receive_function(contract.abi, contract.web3)
return contract
#
# Contract Methods
#
@classmethod
def constructor(cls, *args: Any, **kwargs: Any) -> 'ContractConstructor':
"""
:param args: The contract constructor arguments as positional arguments
:param kwargs: The contract constructor arguments as keyword arguments
:return: a contract constructor object
"""
if cls.bytecode is None:
raise ValueError(
"Cannot call constructor on a contract that does not have 'bytecode' associated "
"with it"
)
return ContractConstructor(cls.web3,
cls.abi,
cls.bytecode,
*args,
**kwargs)
# Public API
#
@combomethod
def encodeABI(cls, fn_name: str, args: Optional[Any] = None,
kwargs: Optional[Any] = None, data: Optional[HexStr] = None) -> HexStr:
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
fn_abi, fn_selector, fn_arguments = get_function_info(
fn_name, cls.web3.codec, contract_abi=cls.abi, args=args, kwargs=kwargs,
)
if data is None:
data = fn_selector
return encode_abi(cls.web3, fn_abi, fn_arguments, data)
@combomethod
def all_functions(self) -> List['ContractFunction']:
return find_functions_by_identifier(
self.abi, self.web3, self.address, lambda _: True
)
@combomethod
def get_function_by_signature(self, signature: str) -> 'ContractFunction':
if ' ' in signature:
raise ValueError(
'Function signature should not contain any spaces. '
'Found spaces in input: %s' % signature
)
def callable_check(fn_abi: ABIFunction) -> bool:
return abi_to_signature(fn_abi) == signature
fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check)
return get_function_by_identifier(fns, 'signature')
@combomethod
def find_functions_by_name(self, fn_name: str) -> List['ContractFunction']:
def callable_check(fn_abi: ABIFunction) -> bool:
return fn_abi['name'] == fn_name
return find_functions_by_identifier(
self.abi, self.web3, self.address, callable_check
)
@combomethod
def get_function_by_name(self, fn_name: str) -> 'ContractFunction':
fns = self.find_functions_by_name(fn_name)
return get_function_by_identifier(fns, 'name')
@combomethod
def get_function_by_selector(self, selector: Union[bytes, int, HexStr]) -> 'ContractFunction':
def callable_check(fn_abi: ABIFunction) -> bool:
# typed dict cannot be used w/ a normal Dict
# https://github.com/python/mypy/issues/4976
return encode_hex(function_abi_to_4byte_selector(fn_abi)) == to_4byte_hex(selector) # type: ignore # noqa: E501
fns = find_functions_by_identifier(self.abi, self.web3, self.address, callable_check)
return get_function_by_identifier(fns, 'selector')
@combomethod
def decode_function_input(self, data: HexStr) -> Tuple['ContractFunction', Dict[str, Any]]:
# type ignored b/c expects data arg to be HexBytes
data = HexBytes(data) # type: ignore
selector, params = data[:4], data[4:]
func = self.get_function_by_selector(selector)
names = get_abi_input_names(func.abi)
types = get_abi_input_types(func.abi)
decoded = self.web3.codec.decode_abi(types, cast(HexBytes, params))
normalized = map_abi_data(BASE_RETURN_NORMALIZERS, types, decoded)
return func, dict(zip(names, normalized))
@combomethod
def find_functions_by_args(self, *args: Any) -> List['ContractFunction']:
def callable_check(fn_abi: ABIFunction) -> bool:
return check_if_arguments_can_be_encoded(fn_abi, self.web3.codec, args=args, kwargs={})
return find_functions_by_identifier(
self.abi, self.web3, self.address, callable_check
)
@combomethod
def get_function_by_args(self, *args: Any) -> 'ContractFunction':
fns = self.find_functions_by_args(*args)
return get_function_by_identifier(fns, 'args')
#
# Private Helpers
#
_return_data_normalizers: Tuple[Callable[..., Any], ...] = tuple()
@classmethod
def _prepare_transaction(cls,
fn_name: str,
fn_args: Optional[Any] = None,
fn_kwargs: Optional[Any] = None,
transaction: Optional[TxParams] = None) -> TxParams:
return prepare_transaction(
cls.address,
cls.web3,
fn_identifier=fn_name,
contract_abi=cls.abi,
transaction=transaction,
fn_args=fn_args,
fn_kwargs=fn_kwargs,
)
@classmethod
def _find_matching_fn_abi(
cls, fn_identifier: Optional[str] = None, args: Optional[Any] = None,
kwargs: Optional[Any] = None
) -> ABIFunction:
return find_matching_fn_abi(cls.abi,
cls.web3.codec,
fn_identifier=fn_identifier,
args=args,
kwargs=kwargs)
@classmethod
def _find_matching_event_abi(
cls, event_name: Optional[str] = None, argument_names: Optional[Sequence[str]] = None
) -> ABIEvent:
return find_matching_event_abi(
abi=cls.abi,
event_name=event_name,
argument_names=argument_names)
@staticmethod
def get_fallback_function(
abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None
) -> 'ContractFunction':
if abi and fallback_func_abi_exists(abi):
return ContractFunction.factory(
'fallback',
web3=web3,
contract_abi=abi,
address=address,
function_identifier=FallbackFn)()
return cast('ContractFunction', NonExistentFallbackFunction())
@staticmethod
def get_receive_function(
abi: ABI, web3: 'Web3', address: Optional[ChecksumAddress] = None
) -> 'ContractFunction':
if abi and receive_func_abi_exists(abi):
return ContractFunction.factory(
'receive',
web3=web3,
contract_abi=abi,
address=address,
function_identifier=ReceiveFn)()
return cast('ContractFunction', NonExistentReceiveFunction())
@combomethod
def _encode_constructor_data(cls, args: Optional[Any] = None,
kwargs: Optional[Any] = None) -> HexStr:
constructor_abi = get_constructor_abi(cls.abi)
if constructor_abi:
if args is None:
args = tuple()
if kwargs is None:
kwargs = {}
arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)
deploy_data = add_0x_prefix(
encode_abi(cls.web3, constructor_abi, arguments, data=cls.bytecode)
)
else:
if args is not None or kwargs is not None:
msg = "Constructor args were provided, but no constructor function was provided."
raise TypeError(msg)
deploy_data = to_hex(cls.bytecode)
return deploy_data
def mk_collision_prop(fn_name: str) -> Callable[[], None]:
def collision_fn() -> NoReturn:
msg = "Namespace collision for function name {0} with ConciseContract API.".format(fn_name)
raise AttributeError(msg)
collision_fn.__name__ = fn_name
return collision_fn
class ContractConstructor:
"""
Class for contract constructor API.
"""
def __init__(
self, web3: 'Web3', abi: ABI, bytecode: HexStr, *args: Any, **kwargs: Any
) -> None:
self.web3 = web3
self.abi = abi
self.bytecode = bytecode
self.data_in_transaction = self._encode_data_in_transaction(*args, **kwargs)
@combomethod
def _encode_data_in_transaction(self, *args: Any, **kwargs: Any) -> HexStr:
constructor_abi = get_constructor_abi(self.abi)
if constructor_abi:
if not args:
args = tuple()
if not kwargs:
kwargs = {}
arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)
data = add_0x_prefix(
encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode)
)
else:
data = to_hex(self.bytecode)
return data
@combomethod
def estimateGas(
self, transaction: Optional[TxParams] = None,
block_identifier: Optional[BlockIdentifier] = None
) -> int:
if transaction is None:
estimate_gas_transaction: TxParams = {}
else:
estimate_gas_transaction = cast(TxParams, dict(**transaction))
self.check_forbidden_keys_in_transaction(estimate_gas_transaction,
["data", "to"])
if self.web3.eth.default_account is not empty:
# type ignored b/c check prevents an empty default_account
estimate_gas_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore # noqa: E501
estimate_gas_transaction['data'] = self.data_in_transaction
return self.web3.eth.estimateGas(
estimate_gas_transaction, block_identifier=block_identifier
)
@combomethod
def transact(self, transaction: Optional[TxParams] = None) -> HexBytes:
if transaction is None:
transact_transaction: TxParams = {}
else:
transact_transaction = cast(TxParams, dict(**transaction))
self.check_forbidden_keys_in_transaction(transact_transaction,
["data", "to"])
if self.web3.eth.default_account is not empty:
# type ignored b/c check prevents an empty default_account
transact_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore
transact_transaction['data'] = self.data_in_transaction
# TODO: handle asynchronous contract creation
return self.web3.eth.sendTransaction(transact_transaction)
@combomethod
def buildTransaction(self, transaction: Optional[TxParams] = None) -> TxParams:
"""
Build the transaction dictionary without sending
"""
if transaction is None:
built_transaction: TxParams = {}
else:
built_transaction = cast(TxParams, dict(**transaction))
self.check_forbidden_keys_in_transaction(built_transaction,
["data", "to"])
if self.web3.eth.default_account is not empty:
# type ignored b/c check prevents an empty default_account
built_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore
built_transaction['data'] = self.data_in_transaction
built_transaction['to'] = Address(b'')
return fill_transaction_defaults(self.web3, built_transaction)
@staticmethod
def check_forbidden_keys_in_transaction(
transaction: TxParams, forbidden_keys: Optional[Collection[str]] = None
) -> None:
keys_found = set(transaction.keys()) & set(forbidden_keys)
if keys_found:
raise ValueError("Cannot set {} in transaction".format(', '.join(keys_found)))
class ConciseMethod:
ALLOWED_MODIFIERS = {'call', 'estimateGas', 'transact', 'buildTransaction'}
def __init__(
self, function: 'ContractFunction',
normalizers: Optional[Tuple[Callable[..., Any], ...]] = None
) -> None:
self._function = function
self._function._return_data_normalizers = normalizers
def __call__(self, *args: Any, **kwargs: Any) -> 'ContractFunction':
return self.__prepared_function(*args, **kwargs)
def __prepared_function(self, *args: Any, **kwargs: Any) -> 'ContractFunction':
modifier_dict: Dict[Any, Any]
if not kwargs:
modifier, modifier_dict = 'call', {}
elif len(kwargs) == 1:
modifier, modifier_dict = kwargs.popitem()
if modifier not in self.ALLOWED_MODIFIERS:
raise TypeError(
"The only allowed keyword arguments are: %s" % self.ALLOWED_MODIFIERS)
else:
raise TypeError("Use up to one keyword argument, one of: %s" % self.ALLOWED_MODIFIERS)
return getattr(self._function(*args), modifier)(modifier_dict)
class ConciseContract:
"""
An alternative Contract Factory which invokes all methods as `call()`,
unless you add a keyword argument. The keyword argument assigns the prep method.
This call
> contract.withdraw(amount, transact={'from': eth.accounts[1], 'gas': 100000, ...})
is equivalent to this call in the classic contract:
> contract.functions.withdraw(amount).transact({'from': eth.accounts[1], 'gas': 100000, ...})
"""
@deprecated_for(
"contract.caller.<method name> or contract.caller({transaction_dict}).<method name>"
)
def __init__(
self,
classic_contract: Contract,
method_class: Union[Type['ConciseMethod'], Type['ImplicitMethod']] = ConciseMethod
) -> None:
classic_contract._return_data_normalizers += CONCISE_NORMALIZERS
self._classic_contract = classic_contract
self.address = self._classic_contract.address
protected_fn_names = [fn for fn in dir(self) if not fn.endswith('__')]
for fn_name in self._classic_contract.functions:
# Override namespace collisions
if fn_name in protected_fn_names:
_concise_method = cast('ConciseMethod', mk_collision_prop(fn_name))
else:
_classic_method = getattr(
self._classic_contract.functions,
fn_name)
_concise_method = method_class(
_classic_method,
self._classic_contract._return_data_normalizers
)
setattr(self, fn_name, _concise_method)
@classmethod
def factory(cls, *args: Any, **kwargs: Any) -> Contract:
return compose(cls, Contract.factory(*args, **kwargs))
def _none_addr(datatype: str, data: ChecksumAddress) -> Tuple[str, Optional[ChecksumAddress]]:
if datatype == 'address' and int(data, base=16) == 0:
return (datatype, None)
else:
return (datatype, data)
CONCISE_NORMALIZERS: Tuple[Callable[..., Any]] = (
_none_addr,
)
class ImplicitMethod(ConciseMethod):
def __call_by_default(self, args: Any) -> bool:
function_abi = find_matching_fn_abi(self._function.contract_abi,
self._function.web3.codec,
fn_identifier=self._function.function_identifier,
args=args)
return function_abi['constant'] if 'constant' in function_abi.keys() else False
@deprecated_for("classic contract syntax. Ex: contract.functions.withdraw(amount).transact({})")
def __call__(self, *args: Any, **kwargs: Any) -> 'ContractFunction':
# Modifier is not provided and method is not constant/pure do a transaction instead
if not kwargs and not self.__call_by_default(args):
return super().__call__(*args, transact={})
else:
return super().__call__(*args, **kwargs)
class ImplicitContract(ConciseContract):
"""
ImplicitContract class is similar to the ConciseContract class
however it performs a transaction instead of a call if no modifier
is given and the method is not marked 'constant' in the ABI.
The transaction will use the default account to send the transaction.
This call
> contract.withdraw(amount)
is equivalent to this call in the classic contract:
> contract.functions.withdraw(amount).transact({})
"""
def __init__(
self,
classic_contract: Contract,
method_class: Union[Type[ImplicitMethod], Type[ConciseMethod]] = ImplicitMethod
) -> None:
super().__init__(classic_contract, method_class=method_class)
class NonExistentFallbackFunction:
@staticmethod
def _raise_exception() -> NoReturn:
raise FallbackNotFound("No fallback function was found in the contract ABI.")
def __getattr__(self, attr: Any) -> Callable[[], None]:
return self._raise_exception
class NonExistentReceiveFunction:
@staticmethod
def _raise_exception() -> NoReturn:
raise FallbackNotFound("No receive function was found in the contract ABI.")
def __getattr__(self, attr: Any) -> Callable[[], None]:
return self._raise_exception
class ContractFunction:
"""Base class for contract functions
A function accessed via the api contract.functions.myMethod(*args, **kwargs)
is a subclass of this class.
"""
address: ChecksumAddress = None
function_identifier: FunctionIdentifier = None
web3: 'Web3' = None
contract_abi: ABI = None
abi: ABIFunction = None
transaction: TxParams = None
arguments: Tuple[Any, ...] = None
args: Any = None
kwargs: Any = None
def __init__(self, abi: Optional[ABIFunction] = None) -> None:
self.abi = abi
self.fn_name = type(self).__name__
def __call__(self, *args: Any, **kwargs: Any) -> 'ContractFunction':
clone = copy.copy(self)
if args is None:
clone.args = tuple()
else:
clone.args = args
if kwargs is None:
clone.kwargs = {}
else:
clone.kwargs = kwargs
clone._set_function_info()
return clone
def _set_function_info(self) -> None:
if not self.abi:
self.abi = find_matching_fn_abi(
self.contract_abi,
self.web3.codec,
self.function_identifier,
self.args,
self.kwargs
)
if self.function_identifier is FallbackFn:
self.selector = encode_hex(b'')
elif self.function_identifier is ReceiveFn:
self.selector = encode_hex(b'')
elif is_text(self.function_identifier):
# https://github.com/python/mypy/issues/4976
self.selector = encode_hex(function_abi_to_4byte_selector(self.abi)) # type: ignore
else:
raise TypeError("Unsupported function identifier")
self.arguments = merge_args_and_kwargs(self.abi, self.args, self.kwargs)
def call(
self, transaction: Optional[TxParams] = None, block_identifier: BlockIdentifier = 'latest'
) -> Any:
"""
Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods
"""
if transaction is None:
call_transaction: TxParams = {}
else:
call_transaction = cast(TxParams, dict(**transaction))
if 'data' in call_transaction:
raise ValueError("Cannot set data in call transaction")
if self.address:
call_transaction.setdefault('to', self.address)
if self.web3.eth.default_account is not empty:
# type ignored b/c check prevents an empty default_account
call_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore
if 'to' not in call_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.[methodtype].[method].call()` from"
" a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
block_id = parse_block_identifier(self.web3, block_identifier)
return call_contract_function(
self.web3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
)
def transact(self, transaction: Optional[TxParams] = None) -> HexBytes:
if transaction is None:
transact_transaction: TxParams = {}
else:
transact_transaction = cast(TxParams, dict(**transaction))
if 'data' in transact_transaction:
raise ValueError("Cannot set data in transact transaction")
if self.address is not None:
transact_transaction.setdefault('to', self.address)
if self.web3.eth.default_account is not empty:
# type ignored b/c check prevents an empty default_account
transact_transaction.setdefault('from', self.web3.eth.default_account) # type: ignore
if 'to' not in transact_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.transact` from a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
return transact_with_contract_function(
self.address,
self.web3,
self.function_identifier,
transact_transaction,
self.contract_abi,
self.abi,
*self.args,