-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
contract.py
651 lines (572 loc) · 19.7 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
import copy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Sequence,
Type,
cast,
)
from eth_typing import (
ChecksumAddress,
)
from eth_utils import (
combomethod,
)
from eth_utils.toolz import (
partial,
)
from hexbytes import (
HexBytes,
)
from web3._utils.abi import (
fallback_func_abi_exists,
filter_by_type,
receive_func_abi_exists,
)
from web3._utils.compat import (
Self,
)
from web3._utils.contracts import (
parse_block_identifier,
)
from web3._utils.datatypes import (
PropertyCheckingFactory,
)
from web3._utils.events import (
EventFilterBuilder,
get_event_data,
)
from web3._utils.filters import (
LogFilter,
)
from web3._utils.function_identifiers import (
FallbackFn,
ReceiveFn,
)
from web3._utils.normalizers import (
normalize_abi,
normalize_address,
normalize_bytecode,
)
from web3._utils.transactions import (
fill_transaction_defaults,
)
from web3.contract.base_contract import (
BaseContract,
BaseContractCaller,
BaseContractConstructor,
BaseContractEvent,
BaseContractEvents,
BaseContractFunction,
BaseContractFunctions,
NonExistentFallbackFunction,
NonExistentReceiveFunction,
)
from web3.contract.utils import (
build_transaction_for_function,
call_contract_function,
estimate_gas_for_function,
find_functions_by_identifier,
get_function_by_identifier,
transact_with_contract_function,
)
from web3.exceptions import (
ABIFunctionNotFound,
NoABIFound,
NoABIFunctionsFound,
Web3AttributeError,
Web3TypeError,
Web3ValidationError,
Web3ValueError,
)
from web3.types import (
ABI,
BlockIdentifier,
EventData,
StateOverride,
TxParams,
)
from web3.utils import (
get_abi_input_names,
)
if TYPE_CHECKING:
from ens import ENS # noqa: F401
from web3 import Web3 # noqa: F401
class ContractEvent(BaseContractEvent):
# mypy types
w3: "Web3"
@combomethod
def get_logs(
self,
argument_filters: Optional[Dict[str, Any]] = None,
from_block: Optional[BlockIdentifier] = None,
to_block: Optional[BlockIdentifier] = None,
block_hash: Optional[HexBytes] = None,
) -> Iterable[EventData]:
"""
Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to create_filter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(my_contract.web3.eth.block_number - 10, 1)
to = my_contract.web3.eth.block_number
events = my_contract.events.Transfer.get_logs(from_block=from, to_block=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.LocalFilterMiddleware`.
:param argument_filters: Filter by argument values. Indexed arguments are
filtered by the node while non-indexed arguments are filtered by the library.
:param from_block: block number or "latest", defaults to "latest"
:param to_block: block number or "latest". Defaults to "latest"
:param block_hash: block hash. block_hash cannot be set at the
same time as ``from_block`` or ``to_block``
:yield: Tuple of :class:`AttributeDict` instances
"""
event_abi = self._get_event_abi()
# validate ``argument_filters`` if present
if argument_filters is not None:
event_arg_names = get_abi_input_names(event_abi)
if not all(arg in event_arg_names for arg in argument_filters.keys()):
raise Web3ValidationError(
"When filtering by argument names, all argument names must be "
"present in the contract's event ABI."
)
_filter_params = self._get_event_filter_params(
event_abi, argument_filters, from_block, to_block, block_hash
)
# call JSON-RPC API
logs = self.w3.eth.get_logs(_filter_params)
# convert raw binary data to Python proxy objects as described by ABI:
all_event_logs = tuple(
get_event_data(self.w3.codec, event_abi, entry) for entry in logs
)
filtered_logs = self._process_get_logs_argument_filters(
event_abi,
all_event_logs,
argument_filters,
)
sorted_logs = sorted(filtered_logs, key=lambda e: e["logIndex"])
sorted_logs = sorted(sorted_logs, key=lambda e: e["blockNumber"])
return sorted_logs
@combomethod
def create_filter(
self,
*, # PEP 3102
argument_filters: Optional[Dict[str, Any]] = None,
from_block: Optional[BlockIdentifier] = None,
to_block: BlockIdentifier = "latest",
address: Optional[ChecksumAddress] = None,
topics: Optional[Sequence[Any]] = None,
) -> LogFilter:
"""
Create filter object that tracks logs emitted by this contract event.
"""
filter_builder = EventFilterBuilder(self._get_event_abi(), self.w3.codec)
self._set_up_filter_builder(
argument_filters,
from_block,
to_block,
address,
topics,
filter_builder,
)
log_filter = filter_builder.deploy(self.w3)
log_filter.log_entry_formatter = get_event_data(
self.w3.codec, self._get_event_abi()
)
log_filter.builder = filter_builder
return log_filter
@combomethod
def build_filter(self) -> EventFilterBuilder:
builder = EventFilterBuilder(
self._get_event_abi(),
self.w3.codec,
formatter=get_event_data(self.w3.codec, self._get_event_abi()),
)
builder.address = self.address
return builder
class ContractEvents(BaseContractEvents):
def __init__(
self, abi: ABI, w3: "Web3", address: Optional[ChecksumAddress] = None
) -> None:
super().__init__(abi, w3, ContractEvent, address)
class ContractFunction(BaseContractFunction):
# mypy types
w3: "Web3"
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
@classmethod
def factory(cls, class_name: str, **kwargs: Any) -> Self:
return PropertyCheckingFactory(class_name, (cls,), kwargs)(kwargs.get("abi"))
def call(
self,
transaction: Optional[TxParams] = None,
block_identifier: BlockIdentifier = None,
state_override: Optional[StateOverride] = None,
ccip_read_enabled: Optional[bool] = None,
) -> 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
:param block_identifier: TODO
:param state_override TODO
:param ccip_read_enabled TODO
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods
"""
call_transaction = self._get_call_txparams(transaction)
block_id = parse_block_identifier(self.w3, block_identifier)
return call_contract_function(
self.w3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
state_override,
ccip_read_enabled,
self.decode_tuples,
*self.args,
**self.kwargs,
)
def transact(self, transaction: Optional[TxParams] = None) -> HexBytes:
setup_transaction = self._transact(transaction)
return transact_with_contract_function(
self.address,
self.w3,
self.function_identifier,
setup_transaction,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs,
)
def estimate_gas(
self,
transaction: Optional[TxParams] = None,
block_identifier: Optional[BlockIdentifier] = None,
state_override: Optional[StateOverride] = None,
) -> int:
setup_transaction = self._estimate_gas(transaction)
return estimate_gas_for_function(
self.address,
self.w3,
self.function_identifier,
setup_transaction,
self.contract_abi,
self.abi,
block_identifier,
state_override,
*self.args,
**self.kwargs,
)
def build_transaction(self, transaction: Optional[TxParams] = None) -> TxParams:
built_transaction = self._build_transaction(transaction)
return build_transaction_for_function(
self.address,
self.w3,
self.function_identifier,
built_transaction,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs,
)
@staticmethod
def get_fallback_function(
abi: ABI,
w3: "Web3",
address: Optional[ChecksumAddress] = None,
) -> "ContractFunction":
if abi and fallback_func_abi_exists(abi):
return ContractFunction.factory(
"fallback",
w3=w3,
contract_abi=abi,
address=address,
function_identifier=FallbackFn,
)()
return cast(ContractFunction, NonExistentFallbackFunction())
@staticmethod
def get_receive_function(
abi: ABI,
w3: "Web3",
address: Optional[ChecksumAddress] = None,
) -> "ContractFunction":
if abi and receive_func_abi_exists(abi):
return ContractFunction.factory(
"receive",
w3=w3,
contract_abi=abi,
address=address,
function_identifier=ReceiveFn,
)()
return cast(ContractFunction, NonExistentReceiveFunction())
class ContractFunctions(BaseContractFunctions):
def __init__(
self,
abi: ABI,
w3: "Web3",
address: Optional[ChecksumAddress] = None,
decode_tuples: Optional[bool] = False,
) -> None:
super().__init__(abi, w3, ContractFunction, address, decode_tuples)
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(
f"The function '{function_name}' was not found in this contract's abi.",
" Are you sure you provided the correct contract abi?",
)
else:
return super().__getattribute__(function_name)
class Contract(BaseContract):
# mypy types
w3: "Web3"
functions: ContractFunctions = None
caller: "ContractCaller" = None
# Instance of :class:`ContractEvents` presenting available Event ABIs
events: ContractEvents = None
def __init__(self, address: Optional[ChecksumAddress] = None) -> None:
"""
Create a new smart contract proxy object.
:param address: Contract address as 0x hex string
"""
_w3 = self.w3
if _w3 is None:
raise Web3AttributeError(
"The `Contract` class has not been initialized. Please use the "
"`web3.contract` interface to create your contract class."
)
if address:
self.address = normalize_address(cast("ENS", _w3.ens), address)
if not self.address:
raise Web3TypeError(
"The address argument is required to instantiate a contract."
)
self.functions = ContractFunctions(
self.abi, _w3, self.address, decode_tuples=self.decode_tuples
)
self.caller = ContractCaller(
self.abi, _w3, self.address, decode_tuples=self.decode_tuples
)
self.events = ContractEvents(self.abi, _w3, self.address)
self.fallback = Contract.get_fallback_function(
self.abi,
_w3,
ContractFunction,
self.address,
)
self.receive = Contract.get_receive_function(
self.abi,
_w3,
ContractFunction,
self.address,
)
@classmethod
def factory(
cls, w3: "Web3", class_name: Optional[str] = None, **kwargs: Any
) -> Type[Self]:
kwargs["w3"] = w3
normalizers = {
"abi": normalize_abi,
"address": partial(normalize_address, w3.ens),
"bytecode": normalize_bytecode,
"bytecode_runtime": normalize_bytecode,
}
contract = cast(
Type[Self],
PropertyCheckingFactory(
class_name or cls.__name__,
(cls,),
kwargs,
normalizers=normalizers,
),
)
contract.functions = ContractFunctions(
contract.abi, contract.w3, decode_tuples=contract.decode_tuples
)
contract.caller = ContractCaller(
contract.abi,
contract.w3,
contract.address,
decode_tuples=contract.decode_tuples,
)
contract.events = ContractEvents(contract.abi, contract.w3)
contract.fallback = Contract.get_fallback_function(
contract.abi,
contract.w3,
ContractFunction,
)
contract.receive = Contract.get_receive_function(
contract.abi,
contract.w3,
ContractFunction,
)
return contract
@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 Web3ValueError(
"Cannot call constructor on a contract that does not have "
"'bytecode' associated with it"
)
return ContractConstructor(cls.w3, cls.abi, cls.bytecode, *args, **kwargs)
@combomethod
def find_functions_by_identifier(
cls,
contract_abi: ABI,
w3: "Web3",
address: ChecksumAddress,
callable_check: Callable[..., Any],
) -> List["ContractFunction"]:
return cast(
List["ContractFunction"],
find_functions_by_identifier(
contract_abi, w3, address, callable_check, ContractFunction
),
)
@combomethod
def get_function_by_identifier(
cls, fns: Sequence["ContractFunction"], identifier: str
) -> "ContractFunction":
return get_function_by_identifier(fns, identifier)
class ContractCaller(BaseContractCaller):
# mypy types
w3: "Web3"
def __init__(
self,
abi: ABI,
w3: "Web3",
address: ChecksumAddress,
transaction: Optional[TxParams] = None,
block_identifier: BlockIdentifier = None,
ccip_read_enabled: Optional[bool] = None,
decode_tuples: Optional[bool] = False,
) -> None:
super().__init__(abi, w3, address, decode_tuples=decode_tuples)
if self.abi:
if transaction is None:
transaction = {}
self._functions = filter_by_type("function", self.abi)
for func in self._functions:
fn = ContractFunction.factory(
func["name"],
w3=w3,
contract_abi=self.abi,
address=self.address,
function_identifier=func["name"],
decode_tuples=decode_tuples,
)
caller_method = partial(
self.call_function,
fn,
transaction=transaction,
block_identifier=block_identifier,
ccip_read_enabled=ccip_read_enabled,
)
setattr(self, func["name"], caller_method)
def __call__(
self,
transaction: Optional[TxParams] = None,
block_identifier: BlockIdentifier = None,
ccip_read_enabled: Optional[bool] = None,
) -> "ContractCaller":
if transaction is None:
transaction = {}
return type(self)(
self.abi,
self.w3,
self.address,
transaction=transaction,
block_identifier=block_identifier,
ccip_read_enabled=ccip_read_enabled,
decode_tuples=self.decode_tuples,
)
class ContractConstructor(BaseContractConstructor):
# mypy types
w3: "Web3"
@combomethod
def transact(self, transaction: Optional[TxParams] = None) -> HexBytes:
return self.w3.eth.send_transaction(self._get_transaction(transaction))
@combomethod
def build_transaction(self, transaction: Optional[TxParams] = None) -> TxParams:
"""
Build the transaction dictionary without sending
"""
built_transaction = self._build_transaction(transaction)
return fill_transaction_defaults(self.w3, built_transaction)
@combomethod
def estimate_gas(
self,
transaction: Optional[TxParams] = None,
block_identifier: Optional[BlockIdentifier] = None,
) -> int:
transaction = self._estimate_gas(transaction)
return self.w3.eth.estimate_gas(transaction, block_identifier=block_identifier)