-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathescrow.py
729 lines (570 loc) · 23.5 KB
/
escrow.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
#!/usr/bin/env python3
import datetime
import logging
import os
from decimal import Decimal
from typing import List, Optional
from human_protocol_sdk.constants import NETWORKS, ChainId, Role, Status
from human_protocol_sdk.gql.escrow import (
get_escrows_by_launcher_query,
get_filtered_escrows_query,
)
from human_protocol_sdk.utils import (
get_data_from_subgraph,
get_escrow_interface,
get_factory_interface,
get_erc20_interface,
handle_transaction,
)
from validators import url as URL
from web3 import Web3, contract
from web3.middleware import geth_poa_middleware
GAS_LIMIT = int(os.getenv("GAS_LIMIT", 4712388))
LOG = logging.getLogger("human_protocol_sdk.escrow")
class EscrowClientError(Exception):
"""
Raises when some error happens when interacting with escrow.
"""
pass
class EscrowConfig:
"""
A class used to manage escrow parameters.
"""
def __init__(
self,
recording_oracle_address: str,
reputation_oracle_address: str,
recording_oracle_fee: Decimal,
reputation_oracle_fee: Decimal,
manifest_url: str,
hash: str,
skip_manifest_url_validation: bool = False,
):
"""
Initializes a Escrow instance.
Args:
recording_oracle_address (str): Address of the Recording Oracle
reputation_oracle_address (str): Address of the Reputation Oracle
recording_oracle_fee (Decimal): Fee percentage of the Recording Oracle
reputation_oracle_fee (Decimal): Fee percentage of the Reputation Oracle
manifest_url (str): Manifest file url
hash (str): Manifest file hash
skip_manifest_url_validation (bool): Identify wether validate manifest_url
"""
if not Web3.is_address(recording_oracle_address):
raise EscrowClientError(
f"Invalid recording oracle address: {recording_oracle_address}"
)
if not Web3.is_address(reputation_oracle_address):
raise EscrowClientError(
f"Invalid reputation oracle address: {reputation_oracle_address}"
)
if not (0 <= recording_oracle_fee <= 100) or not (
0 <= reputation_oracle_fee <= 100
):
raise EscrowClientError("Fee must be between 0 and 100")
if recording_oracle_fee + reputation_oracle_fee > 100:
raise EscrowClientError("Total fee must be less than 100")
if not URL(manifest_url) and not skip_manifest_url_validation:
raise EscrowClientError(f"Invalid manifest URL: {manifest_url}")
if not hash:
raise EscrowClientError("Invalid empty manifest hash")
self.recording_oracle_address = recording_oracle_address
self.reputation_oracle_address = reputation_oracle_address
self.recording_oracle_fee = recording_oracle_fee
self.reputation_oracle_fee = reputation_oracle_fee
self.manifest_url = manifest_url
self.hash = hash
class EscrowFilter:
"""
A class used to filter escrow requests.
"""
def __init__(
self,
launcher_address: Optional[str] = None,
status: Optional[Status] = None,
date_from: Optional[datetime.datetime] = None,
date_to: Optional[datetime.datetime] = None,
):
"""
Initializes a EscrowFilter instance.
Args:
launcher_address (Optional[str]): Launcher ddress
status (Optional[Status]): Escrow status
date_from (Optional[date]): Created from date
date_to (Optional[date]): Created to date
"""
if not launcher_address and not status and not date_from and not date_to:
raise EscrowClientError(
"EscrowFilter class must have at least one parameter"
)
if launcher_address and not Web3.is_address(launcher_address):
raise EscrowClientError(f"Invalid address: {launcher_address}")
if date_from and date_to and date_from > date_to:
raise EscrowClientError(
f"Invalid dates: {date_from} must be earlier than {date_to}"
)
self.launcher_address = launcher_address
self.status = status
self.date_from = date_from
self.date_to = date_to
class EscrowClient:
"""
A class used to manage escrow on the HUMAN network.
"""
def __init__(self, web3: Web3):
"""
Initializes a Escrow instance.
Args:
web3 (Web3): The Web3 object
"""
# Initialize web3 instance
self.w3 = web3
if not self.w3.middleware_onion.get("geth_poa"):
self.w3.middleware_onion.inject(geth_poa_middleware, "geth_poa", layer=0)
# Load network configuration based on chainId
try:
chain_id = self.w3.eth.chain_id
self.network = NETWORKS[ChainId(chain_id)]
except:
raise EscrowClientError(f"Invalid ChainId: {chain_id}")
# Initialize contract instances
factory_interface = get_factory_interface()
self.factory_contract = self.w3.eth.contract(
address=self.network["factory_address"], abi=factory_interface["abi"]
)
def create_escrow(self, token_address: str, trusted_handlers: List[str]) -> str:
"""
Creates an escrow contract that uses the token passed to pay oracle fees and reward workers.
Args:
tokenAddress (str): The address of the token to use for payouts
trusted_handlers (List[str]): Array of addresses that can perform actions on the contract
Returns:
str: The address of the escrow created
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(token_address):
raise EscrowClientError(f"Invalid token address: {token_address}")
for handler in trusted_handlers:
if not Web3.is_address(handler):
raise EscrowClientError(f"Invalid handler address: {handler}")
transaction_receipt = handle_transaction(
self.w3,
"Create Escrow",
self.factory_contract.functions.createEscrow(
token_address, trusted_handlers
),
EscrowClientError,
)
return next(
(
self.factory_contract.events.Launched().process_log(log)
for log in transaction_receipt["logs"]
if log["address"] == self.network["factory_address"]
),
None,
).args.escrow
def setup(self, escrow_address: str, escrow_config: EscrowConfig) -> None:
"""
Sets up the parameters of the escrow.
Args:
escrow_address (str): Address of the escrow to setup
escrow_config (EscrowConfig): Object containing all the necessary information to setup an escrow
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
handle_transaction(
self.w3,
"Setup",
self._get_escrow_contract(escrow_address).functions.setup(
escrow_config.reputation_oracle_address,
escrow_config.recording_oracle_address,
escrow_config.reputation_oracle_fee,
escrow_config.recording_oracle_fee,
escrow_config.manifest_url,
escrow_config.hash,
),
EscrowClientError,
)
def create_and_setup_escrow(
self,
token_address: str,
trusted_handlers: List[str],
escrow_config: EscrowConfig,
) -> str:
"""
Creates and sets up an escrow.
Args:
token_address (str): Token to use for pay outs
trusted_handlers (List[str]): Array of addresses that can perform actions on the contract
escrow_config (EscrowConfig): Object containing all the necessary information to setup an escrow
Returns:
str: The address of the escrow created
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
escrow_address = self.create_escrow(token_address, trusted_handlers)
self.setup(escrow_address, escrow_config)
return escrow_address
def fund(self, escrow_address: str, amount: Decimal) -> None:
"""
Adds funds to the escrow.
Args:
escrow_address (str): Address of the escrow to setup
amount (Decimal): Amount to be added as funds
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
if 0 >= amount:
raise EscrowClientError("Amount must be positive")
token_address = self.get_token_address(escrow_address)
erc20_interface = get_erc20_interface()
token_contract = self.w3.eth.contract(token_address, abi=erc20_interface["abi"])
handle_transaction(
self.w3,
"Fund",
token_contract.functions.transfer(escrow_address, amount),
EscrowClientError,
)
def store_results(self, escrow_address: str, url: str, hash: str) -> None:
"""Stores the results url.
Args:
escrow_address (str): Address of the escrow
url (str): Results file url
hash (str): Results file hash
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
if not hash:
raise EscrowClientError("Invalid empty hash")
if not URL(url):
raise EscrowClientError(f"Invalid URL: {url}")
if not self.w3.eth.default_account:
raise EscrowClientError("You must add an account to Web3 instance")
handle_transaction(
self.w3,
"Store Results",
self._get_escrow_contract(escrow_address).functions.storeResults(url, hash),
EscrowClientError,
)
def complete(self, escrow_address: str) -> None:
"""Sets the status of an escrow to completed.
Args:
escrow_address (str): Address of the escrow to complete
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
handle_transaction(
self.w3,
"Complete",
self._get_escrow_contract(escrow_address).functions.complete(),
EscrowClientError,
)
def bulk_payout(
self,
escrow_address: str,
recipients: List[str],
amounts: List[Decimal],
final_results_url: str,
final_results_hash: str,
txId: Decimal,
) -> None:
"""Pays out the amounts specified to the workers and sets the URL of the final results file.
Args:
escrow_address (str): Address of the escrow
recipients (List[str]): Array of recipient addresses
amounts (List[Decimal]): Array of amounts the recipients will receive
final_results_url (str): Final results file url
final_results_hash (str): Final results file hash
txId (Decimal): Serial number of the bulks
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
for recipient in recipients:
if not Web3.is_address(recipient):
raise EscrowClientError(f"Invalid recipient address: {recipient}")
if len(recipients) == 0:
raise EscrowClientError("Arrays must have any value")
if len(recipients) != len(amounts):
raise EscrowClientError("Arrays must have same length")
if 0 in amounts:
raise EscrowClientError("Amounts cannot be empty")
if any(amount < 0 for amount in amounts):
raise EscrowClientError("Amounts cannot be negative")
balance = self.get_balance(escrow_address)
total_amount = sum(amounts)
if total_amount > balance:
raise EscrowClientError(
f"Escrow does not have enough balance. Current balance: {balance}. Amounts: {total_amount}"
)
if not URL(final_results_url):
raise EscrowClientError(f"Invalid final results URL: {final_results_url}")
if not final_results_hash:
raise EscrowClientError("Invalid empty final results hash")
handle_transaction(
self.w3,
"Bulk Payout",
self._get_escrow_contract(escrow_address).functions.bulkPayOut(
recipients, amounts, final_results_url, final_results_hash, txId
),
EscrowClientError,
)
def cancel(self, escrow_address: str) -> None:
"""Cancels the specified escrow and sends the balance to the canceler.
Args:
escrow_address (str): Address of the escrow to cancel
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
handle_transaction(
self.w3,
"Cancel",
self._get_escrow_contract(escrow_address).functions.cancel(),
EscrowClientError,
)
def abort(self, escrow_address: str) -> None:
"""Cancels the specified escrow, sends the balance to the canceler and selfdestructs the escrow contract.
Args:
escrow_address (str): Address of the escrow to abort
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
handle_transaction(
self.w3,
"Abort",
self._get_escrow_contract(escrow_address).functions.abort(),
EscrowClientError,
)
def add_trusted_handlers(self, escrow_address: str, handlers: List[str]) -> None:
"""Adds an array of addresses to the trusted handlers list.
Args:
escrow_address (str): Address of the escrow
handlers (List[str]): Array of trusted handler addresses
Returns:
None
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
for handler in handlers:
if not Web3.is_address(handler):
raise EscrowClientError(f"Invalid handler address: {handler}")
handle_transaction(
self.w3,
"Add Trusted Handlers",
self._get_escrow_contract(escrow_address).functions.addTrustedHandlers(
handlers
),
EscrowClientError,
)
def get_balance(self, escrow_address: str) -> Decimal:
"""Gets the balance for a specified escrow address.
Args:
escrow_address (str): Address of the escrow
Returns:
Decimal: Value of the balance
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return self._get_escrow_contract(escrow_address).functions.getBalance().call()
def get_manifest_url(self, escrow_address: str) -> str:
"""Gets the manifest file URL.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Manifest file url
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return self._get_escrow_contract(escrow_address).functions.manifestUrl().call()
def get_results_url(self, escrow_address: str) -> str:
"""Gets the results file URL.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Results file url
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return (
self._get_escrow_contract(escrow_address).functions.finalResultsUrl().call()
)
def get_intermediate_results_url(self, escrow_address: str) -> str:
"""Gets the intermediate results file URL.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Intermediate results file url
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return (
self._get_escrow_contract(escrow_address)
.functions.intermediateResultsUrl()
.call()
)
def get_token_address(self, escrow_address: str) -> str:
"""Gets the address of the token used to fund the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Address of the token
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return self._get_escrow_contract(escrow_address).functions.token().call()
def get_status(self, escrow_address: str) -> Status:
"""Gets the current status of the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
Status: Current status
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return Status(
self._get_escrow_contract(escrow_address).functions.status().call()
)
def get_launched_escrows(self, launcher_address: str) -> List[dict]:
"""Get escrows addresses created by a job launcher.
Args:
launcher_address (str): Address of the launcher
Returns:
List[dict]: List of escrows
"""
escrows_data = get_data_from_subgraph(
self.network["subgraph_url"],
query=get_escrows_by_launcher_query,
params={"launcherAddress": launcher_address},
)
escrows = escrows_data["data"]["escrows"]
return escrows
def get_escrows_filtered(self, filter: EscrowFilter) -> List[dict]:
"""Get an array of escrow addresses based on the specified filter parameters.
Args:
filter (EscrowFilter): Object containing all the necessary parameters to filter
Returns:
List[dict]: List of escrows
"""
escrows_data = get_data_from_subgraph(
self.network["subgraph_url"],
query=get_filtered_escrows_query,
params={
"launcherAddress": filter.launcher_address,
"status": filter.status.name if filter.status else None,
"from": int(filter.date_from.timestamp()) if filter.date_from else None,
"to": int(filter.date_to.timestamp()) if filter.date_to else None,
},
)
launched_escrows = escrows_data["data"]["escrows"]
return launched_escrows
def get_recording_oracle_address(self, escrow_address: str) -> str:
"""Gets the recording oracle address of the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Recording oracle address
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return (
self._get_escrow_contract(escrow_address).functions.recordingOracle().call()
)
def get_reputation_oracle_address(self, escrow_address: str) -> str:
"""Gets the reputation oracle address of the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Reputation oracle address
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return (
self._get_escrow_contract(escrow_address)
.functions.reputationOracle()
.call()
)
def get_job_launcher_address(self, escrow_address: str) -> str:
"""Gets the job launcher address of the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Job launcher address
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return self._get_escrow_contract(escrow_address).functions.launcher().call()
def get_factory_address(self, escrow_address: str) -> str:
"""Gets the escrow factory address of the escrow.
Args:
escrow_address (str): Address of the escrow
Returns:
str: Escrow factory address
Raises:
EscrowClientError: If an error occurs while checking the parameters
"""
if not Web3.is_address(escrow_address):
raise EscrowClientError(f"Invalid escrow address: {escrow_address}")
return (
self._get_escrow_contract(escrow_address).functions.escrowFactory().call()
)
def _get_escrow_contract(self, address: str) -> contract:
"""Returns the escrow contract instance.
Args:
address (str): Address of the deployed escrow
Returns:
Contract: The instance of the escrow contract
"""
if not self.factory_contract.functions.hasEscrow(address):
raise EscrowClientError("Escrow address is not provided by the factory")
# Initialize contract instance
escrow_interface = get_escrow_interface()
return self.w3.eth.contract(address=address, abi=escrow_interface["abi"])