-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathentrypoint.py
More file actions
621 lines (485 loc) · 26.8 KB
/
entrypoint.py
File metadata and controls
621 lines (485 loc) · 26.8 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
import base64
import time
from datetime import datetime, timedelta, timezone
from multiprocessing.dummy import Pool
from typing import Any, Callable, Optional
from multiversx_sdk import (AccountOnNetwork, Address, ApiNetworkProvider,
AwaitingOptions, Message, NativeAuthClient,
NativeAuthClientConfig, NetworkEntrypoint,
NetworkProviderConfig, NetworkProviderError,
ProxyNetworkProvider, Token, TokenTransfer,
Transaction, TransactionOnNetwork, VoteType)
from multiversx_sdk.abi import (AddressValue, BigUIntValue, BytesValue,
StringValue, U64Value)
from rich import print
from wizard import ux
from wizard.accounts import AccountWrapper, IMyAccount
from wizard.configuration import Configuration
from wizard.constants import (
ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS,
ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS,
CONTRACT_RESULTS_CODE_OK_ENCODED, COSIGNER_SERVICE_ID,
COSIGNER_SIGN_TRANSACTIONS_RETRY_DELAY_IN_SECONDS,
DEFAULT_CHUNK_SIZE_OF_SEND_TRANSACTIONS, MAX_NUM_CUSTOM_TOKENS_TO_FETCH,
MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_CLAIM_REWARDS,
MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_REWARDS,
MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_VOTE, METACHAIN_ID,
NETWORK_PROVIDER_NUM_RETRIES, NETWORK_PROVIDER_TIMEOUT_SECONDS,
NETWORK_PROVIDERS_RETRY_DELAY_IN_SECONDS,
NUM_PARALLEL_GET_GUARDIAN_DATA_REQUESTS, NUM_PARALLEL_GET_NONCE_REQUESTS,
NUM_PARALLEL_GET_TRANSACTION_REQUESTS,
TRANSACTION_AWAITING_PATIENCE_IN_MILLISECONDS,
TRANSACTION_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS)
from wizard.currencies import is_native_currency
from wizard.errors import KnownError, TransientError
from wizard.governance import OnChainVote
from wizard.guardians import (AuthApp, AuthRegistrationEntry, CosignerClient,
GuardianData)
from wizard.rewards import ClaimableRewards, ReceivedRewards, RewardsType
from wizard.timecache import TimeCache
from wizard.transactions import TransactionWrapper
from wizard.utils import split_to_chunks
class MyEntrypoint:
def __init__(
self,
configuration: Configuration,
use_gas_estimator: Optional[bool] = None,
gas_limit_multiplier: Optional[float] = None
) -> None:
self.configuration = configuration
self.network_entrypoint = NetworkEntrypoint(
network_provider_url=configuration.proxy_url,
network_provider_kind="proxy",
chain_id=configuration.chain_id,
with_gas_limit_estimator=use_gas_estimator,
gas_limit_multiplier=gas_limit_multiplier
)
self.api_network_provider = ApiNetworkProvider(
url=configuration.api_url,
config=NetworkProviderConfig(requests_options={"timeout": NETWORK_PROVIDER_TIMEOUT_SECONDS})
)
self.proxy_network_provider = ProxyNetworkProvider(
url=configuration.proxy_url,
config=NetworkProviderConfig(requests_options={"timeout": NETWORK_PROVIDER_TIMEOUT_SECONDS})
)
self.deep_history_proxy_network_provider = ProxyNetworkProvider(
url=configuration.deep_history_url,
config=NetworkProviderConfig(requests_options={"timeout": NETWORK_PROVIDER_TIMEOUT_SECONDS})
)
self.account_awaiting_options = AwaitingOptions(
polling_interval_in_milliseconds=ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS,
patience_in_milliseconds=ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS
)
self.transaction_awaiting_options = AwaitingOptions(
polling_interval_in_milliseconds=TRANSACTION_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS,
patience_in_milliseconds=TRANSACTION_AWAITING_PATIENCE_IN_MILLISECONDS
)
native_auth_config = NativeAuthClientConfig(
origin=self.configuration.api_url,
api_url=self.configuration.api_url,
)
self.native_auth_client = NativeAuthClient(native_auth_config)
self.cosigner = CosignerClient(configuration.cosigner_url)
self.timecache = TimeCache()
def get_start_of_epoch_timestamp(self, epoch: int) -> int:
url = f"network/epoch-start/{METACHAIN_ID}/by-epoch/{epoch}"
data = self.proxy_network_provider.do_get_generic(url)
timestamp = data.get("epochStart", {}).get("timestamp", 0)
return timestamp
def get_start_of_epoch_nonce(self, shard: int, epoch: int) -> int:
url = f"network/epoch-start/{shard}/by-epoch/{epoch}"
data = self.proxy_network_provider.do_get_generic(url)
nonce = data.get("epochStart", {}).get("nonce", 0)
return nonce
def get_claimable_rewards(self, delegator: Address) -> list[ClaimableRewards]:
data_records = self.api_network_provider.do_get_generic(url=f"accounts/{delegator.to_bech32()}/delegation")
rewards: list[ClaimableRewards] = []
for record in data_records:
staking_provider = Address.new_from_bech32(record.get("contract"))
amount = record.get("claimableRewards", 0)
rewards.append(ClaimableRewards(staking_provider, int(amount)))
return rewards
def get_claimable_rewards_legacy(self, delegator: Address) -> int:
data = self.api_network_provider.do_get_generic(url=f"accounts/{delegator.to_bech32()}/delegation-legacy")
amount = data.get("claimableRewards", 0)
return int(amount)
def recall_nonces(self, accounts_wrappers: list[AccountWrapper]):
print("Recalling nonces...")
def recall_nonce(wrapper: AccountWrapper):
wrapper.account.nonce = self.network_entrypoint.recall_account_nonce(wrapper.account.address)
Pool(NUM_PARALLEL_GET_NONCE_REQUESTS).map(recall_nonce, accounts_wrappers)
def recall_guardians(self, accounts: list[AccountWrapper]):
print("Recalling guardians...")
def recall_guardian(wrapper: AccountWrapper):
guardian_data = self.get_guardian_data(wrapper.account.address)
wrapper.guardian = Address.new_from_bech32(guardian_data.active_guardian) if guardian_data.is_guarded else None
Pool(NUM_PARALLEL_GET_GUARDIAN_DATA_REQUESTS).map(recall_guardian, accounts)
def claim_rewards(self, delegator: AccountWrapper, staking_provider: Address, gas_price: int) -> Transaction:
controller = self.network_entrypoint.create_delegation_controller()
transaction = controller.create_transaction_for_claiming_rewards(
sender=delegator.account,
nonce=delegator.account.get_nonce_then_increment(),
delegation_contract=staking_provider,
gas_price=gas_price,
guardian=delegator.guardian
)
return transaction
def claim_rewards_legacy(self, delegator: AccountWrapper, gas_price: int) -> Transaction:
legacy_delegation_contract = Address.new_from_bech32(self.configuration.legacy_delegation_contract)
controller = self.network_entrypoint.create_smart_contract_controller()
transaction = controller.create_transaction_for_execute(
sender=delegator.account,
nonce=delegator.account.get_nonce_then_increment(),
contract=legacy_delegation_contract,
gas_limit=20_000_000,
function="claimRewards",
gas_price=gas_price,
guardian=delegator.guardian
)
return transaction
def get_claimed_rewards(self, delegator: Address, after_timestamp: int) -> list[ReceivedRewards]:
url = f"accounts/{delegator.to_bech32()}/transactions"
size = MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_CLAIM_REWARDS
transactions = self._api_do_get(url, {
"status": "success",
"function": "claimRewards",
"withScResults": "true",
"receiverShard": METACHAIN_ID,
"after": after_timestamp,
"size": size
})
if len(transactions) == size:
print(f"\tRetrieved {size} transactions. [red]There could be more![/red]")
rewards: list[ReceivedRewards] = []
for transaction in transactions:
transaction_hash = transaction.get("txHash")
timestamp = transaction.get("timestamp")
results = transaction.get("results", [])
reward_result = next((item for item in results if item.get("data") != CONTRACT_RESULTS_CODE_OK_ENCODED), None)
amount = int(reward_result.get("value", 0)) if reward_result else 0
if amount:
rewards.append(ReceivedRewards(RewardsType.Delegation, transaction_hash, timestamp, amount))
return rewards
def get_claimed_rewards_legacy(self, delegator: Address, after_timestamp: int) -> list[ReceivedRewards]:
url = f"accounts/{delegator.to_bech32()}/transactions"
size = MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_CLAIM_REWARDS
transactions = self._api_do_get(url, {
"status": "success",
"function": "claimRewards",
"withScResults": "true",
"receiver": self.configuration.legacy_delegation_contract,
"after": after_timestamp,
"size": size
})
if len(transactions) == size:
print(f"\tRetrieved {size} transactions. [red]There could be more![/red]")
rewards: list[ReceivedRewards] = []
for transaction in transactions:
transaction_hash = transaction.get("txHash")
timestamp = transaction.get("timestamp")
results = transaction.get("results", [])
reward_result = next((item for item in results if item.get("data") != CONTRACT_RESULTS_CODE_OK_ENCODED), None)
amount = int(reward_result.get("value", 0)) if reward_result else 0
if amount:
rewards.append(ReceivedRewards(RewardsType.DelegationLegacy, transaction_hash, timestamp, amount))
return rewards
def get_received_staking_rewards(self, node_owner: Address, after_timestamp: int) -> list[ReceivedRewards]:
url = f"accounts/{node_owner.to_bech32()}/transactions"
size = MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_REWARDS
transactions = self._api_do_get(url, {
"senderShard": METACHAIN_ID,
"function": "reward",
"after": after_timestamp,
"size": size
})
if len(transactions) == size:
print(f"\tRetrieved {size} transactions. [red]There could be more![/red]")
rewards: list[ReceivedRewards] = []
for transaction in transactions:
transaction_hash = transaction.get("txHash")
timestamp = transaction.get("timestamp")
amount = int(transaction.get("value", 0))
if amount:
rewards.append(ReceivedRewards(RewardsType.Staking, transaction_hash, timestamp, amount))
return rewards
def transfer_funds(self, sender: AccountWrapper, receiver: Address, transfer: TokenTransfer) -> Transaction:
controller = self.network_entrypoint.create_transfers_controller()
if is_native_currency(transfer.token.identifier):
return controller.create_transaction_for_transfer(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
receiver=receiver,
native_transfer_amount=transfer.amount,
guardian=sender.guardian
)
return controller.create_transaction_for_transfer(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
receiver=receiver,
token_transfers=[transfer],
guardian=sender.guardian
)
def get_direct_voting_power(self, voter: Address):
controller = self.network_entrypoint.create_governance_controller()
return controller.get_voting_power(voter)
def vote_directly(self, sender: AccountWrapper, proposal: int, vote: VoteType, gas_price: int) -> Transaction:
controller = self.network_entrypoint.create_governance_controller()
return controller.create_transaction_for_voting(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
proposal_nonce=proposal,
vote=vote,
gas_price=gas_price,
guardian=sender.guardian,
)
def get_voting_power_via_legacy_delegation(self, voter: Address) -> int:
legacy_delegation_contract = Address.new_from_bech32(self.configuration.legacy_delegation_contract)
controller = self.network_entrypoint.create_smart_contract_controller()
[power_encoded] = controller.query(
contract=legacy_delegation_contract,
function="getVotingPower",
arguments=[AddressValue.new_from_address(voter)],
)
power = BigUIntValue()
power.decode_top_level(power_encoded)
return power.value
def vote_via_legacy_delegation(self, sender: AccountWrapper, proposal: int, vote: VoteType, gas_price: int):
legacy_delegation_contract = Address.new_from_bech32(self.configuration.legacy_delegation_contract)
controller = self.network_entrypoint.create_smart_contract_controller()
transaction = controller.create_transaction_for_execute(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
contract=legacy_delegation_contract,
function="delegateVote",
arguments=[U64Value(proposal), StringValue(vote.value)],
# Gas estimator might not work, thus we hard-code a value here.
gas_limit=75_000_000,
gas_price=gas_price,
guardian=sender.guardian
)
return transaction
def vote_via_liquid_staking(self, sender: AccountWrapper, contract: str, proposal: int, vote: VoteType, power: int, proof: bytes, gas_price: int) -> Transaction:
controller = self.network_entrypoint.create_smart_contract_controller()
transaction = controller.create_transaction_for_execute(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
contract=Address.new_from_bech32(contract),
# Gas estimator might not work, thus we hard-code a value here.
gas_limit=100_000_000,
function="delegate_vote",
arguments=[
U64Value(proposal),
StringValue(vote.value),
BigUIntValue(power),
BytesValue(proof)
],
gas_price=gas_price,
guardian=sender.guardian
)
return transaction
def get_direct_vote(self, voter: Address, proposal: int) -> Optional[OnChainVote]:
return self._get_past_vote(voter.to_bech32(), self.configuration.system_governance_contract, "vote", "vote", proposal)
def get_vote_via_legacy_delegation(self, voter: Address, proposal: int) -> Optional[OnChainVote]:
return self._get_past_vote(voter.to_bech32(), self.configuration.legacy_delegation_contract, "delegateVote", "delegateVote", proposal)
def get_vote_via_liquid_staking(self, voter: Address, contract: str, proposal: int) -> Optional[OnChainVote]:
return self._get_past_vote(voter.to_bech32(), contract, "delegate_vote", "delegateVote", proposal)
def _get_past_vote(self, voter: str, contract: str, function: str, event_identifier: str, proposal: int) -> Optional[OnChainVote]:
url = f"accounts/{voter}/transactions"
size = MAX_NUM_TRANSACTIONS_TO_FETCH_OF_TYPE_VOTE
reasonably_recent_timestamp = int((datetime.now(timezone.utc) - timedelta(days=30)).timestamp())
transactions = self._api_do_get(url, {
"status": "success",
"receiver": contract,
"function": function,
"withLogs": "true",
"withScResults": "true",
"size": size,
"after": reasonably_recent_timestamp
})
if len(transactions) == size:
print(f"\tRetrieved {size} transactions. [red]There could be more![/red]")
for transaction in transactions:
timestamp = transaction.get("timestamp", 0)
all_events: list[Any] = []
all_events.extend(transaction.get("logs", {}).get("events", []))
for result in transaction.get("results"):
all_events.extend(result.get("logs", {}).get("events", []))
for event in all_events:
if event.get("identifier") != event_identifier:
continue
topics = event.get("topics", [])
event_proposal_base64 = topics[0]
event_proposal_bytes = base64.b64decode(event_proposal_base64)
event_proposal = U64Value()
event_proposal.decode_top_level(event_proposal_bytes)
event_vote_type_base64 = topics[1]
event_vote_type = VoteType(base64.b64decode(event_vote_type_base64).decode())
if event_proposal.value == proposal:
return OnChainVote(voter, proposal, contract, timestamp, event_vote_type)
return None
def get_guardian_data(self, address: Address):
response = self.proxy_network_provider.do_get_generic(f"address/{address.to_bech32()}/guardian-data")
response_payload = response.get("guardianData", {})
guardian_data = GuardianData.new_from_response_payload(response_payload)
return guardian_data
def register_cosigner(self, auth_app: AuthApp, account_wrapper: AccountWrapper) -> AuthRegistrationEntry:
access_token = self.get_native_auth_access_tokens(account_wrapper.account)
registration_entry = self.cosigner.register(
native_auth_access_token=access_token,
address=account_wrapper.account.address.to_bech32(),
wallet_name=account_wrapper.wallet_name,
)
secret = registration_entry.secret
code = auth_app.get_code_given_secret(secret)
self.cosigner.verify_code(
native_auth_access_token=access_token,
code=code,
guardian=registration_entry.get_guardian(),
)
auth_app.learn_registration_entry(registration_entry)
return registration_entry
def get_native_auth_init_token(self) -> str:
init_token = self.timecache.get("native_auth_init_token", lambda: (self.native_auth_client.initialize(), 60))
return init_token
def get_native_auth_access_tokens(self, account: IMyAccount) -> str:
init_token = self.get_native_auth_init_token()
token_for_signing = self.native_auth_client.get_token_for_signing(account.address, init_token)
signature = account.sign_message(Message(token_for_signing))
access_token = self.native_auth_client.get_token(address=account.address, token=init_token, signature=signature.hex())
return access_token
def set_guardian(self, sender: AccountWrapper, guardian: Address) -> Transaction:
controller = self.network_entrypoint.create_account_controller()
transaction = controller.create_transaction_for_setting_guardian(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
guardian_address=guardian,
service_id=COSIGNER_SERVICE_ID,
guardian=sender.guardian
)
return transaction
def guard_account(self, sender: AccountWrapper) -> Transaction:
controller = self.network_entrypoint.create_account_controller()
transaction = controller.create_transaction_for_guarding_account(
sender=sender.account,
nonce=sender.account.get_nonce_then_increment(),
)
return transaction
def get_custom_tokens(self, address: Address, identifier_or_collection: str) -> list[Token]:
# For the moment, we ignore NFTs.
# We have to perform this GET, so that we can observe all MetaESDTs (all nonces) held by the account, as well.
data_esdt_and_meta: list[dict[str, Any]] = self.api_network_provider.do_get_generic(
f"accounts/{address.to_bech32()}/tokens", {
"from": 0,
"size": MAX_NUM_CUSTOM_TOKENS_TO_FETCH,
"fields": "identifier,collection,nonce",
"includeMetaESDT": True,
})
tokens: list[Token] = []
for item in data_esdt_and_meta:
collection = item.get("collection", "")
identifier = item.get("identifier", "")
nonce = int(item.get("nonce", 0))
item_identifier_or_collection = identifier if nonce == 0 else collection
if item_identifier_or_collection != identifier_or_collection:
continue
tokens.append(Token(item_identifier_or_collection, nonce))
return tokens
def get_custom_token_balance(self, token: Token, address: Address, block_nonce: int) -> int:
current_state = self.api_network_provider.get_token_of_account(address, token)
current_balance = current_state.amount
if not block_nonce:
return current_state.amount
historical_balance = self.get_custom_token_balance_on_block_nonce(token, address, block_nonce)
return max(current_balance - historical_balance, 0)
def get_custom_token_balance_on_block_nonce(self, token: Token, address: Address, block_nonce: int) -> int:
if token.nonce == 0:
response = self.deep_history_proxy_network_provider.do_get_generic(f"address/{address.to_bech32()}/esdt/{token.identifier}?blockNonce={block_nonce}")
else:
response = self.deep_history_proxy_network_provider.do_get_generic(f"address/{address.to_bech32()}/nft/{token.identifier}/nonce/{token.nonce}?blockNonce={block_nonce}")
balance = response.get("balance", 0)
return balance
def send_multiple(self, auth_app: AuthApp, wrappers: list[TransactionWrapper], chunk_size: int = DEFAULT_CHUNK_SIZE_OF_SEND_TRANSACTIONS):
print("Cosigning transactions, if necessary...")
self.guard_transactions(auth_app, wrappers)
print(f"Sending {len(wrappers)} transactions...")
chunks: list[list[TransactionWrapper]] = list(split_to_chunks(wrappers, chunk_size))
for index, chunk in enumerate(chunks):
print(f"Chunk {index}:")
for item in chunk:
print(f"\t{item.get_hash()} ([yellow]{item.label}[/yellow])")
num_sent, _ = self.network_entrypoint.send_transactions([item.transaction for item in chunk])
print(f"Chunk {index}: sent {num_sent} transactions.")
if num_sent != len(chunk):
raise KnownError(f"sent {num_sent} transactions, instead of {len(chunk)}")
self.await_processing_started(chunk)
self.await_completed(wrappers)
def send_one_by_one(self, auth_app: AuthApp, wrappers: list[TransactionWrapper]):
print("Cosigning transactions, if necessary...")
self.guard_transactions(auth_app, wrappers)
print(f"Sending {len(wrappers)} transactions...")
for index, wrapper in enumerate(wrappers):
print(f"{index}: {wrapper.get_hash()} ([yellow]{wrapper.label}[/yellow])")
_ = self.network_entrypoint.send_transaction(wrapper.transaction)
self.await_processing_started([wrapper])
self.await_completed(wrappers)
def guard_transactions(self, auth_app: AuthApp, wrappers: list[TransactionWrapper]):
grouped_by_sender: dict[str, list[Transaction]] = {}
for index, wrapper in enumerate(wrappers):
if wrapper.transaction.guardian is None:
continue
sender = wrapper.transaction.sender.to_bech32()
grouped_by_sender.setdefault(sender, []).append(wrapper.transaction)
# Signatures are applied inline.
for sender, transactions in grouped_by_sender.items():
while True:
try:
print(f"Attempt to co-sign transactions from {sender}...")
code = auth_app.get_code(sender)
self.cosigner.sign_multiple_transactions(code, transactions)
break
except KnownError as error:
print(f"Unexpected error: [red]{error}[/red], will retry in {COSIGNER_SIGN_TRANSACTIONS_RETRY_DELAY_IN_SECONDS} seconds...")
time.sleep(COSIGNER_SIGN_TRANSACTIONS_RETRY_DELAY_IN_SECONDS)
def await_processing_started(self, wrappers: list[TransactionWrapper]) -> list[TransactionOnNetwork]:
print(f"Await processing started for {len(wrappers)} transactions...")
def await_processing_started_one(wrapper: TransactionWrapper) -> TransactionOnNetwork:
condition: Callable[[AccountOnNetwork], bool] = lambda account: account.nonce > wrapper.transaction.nonce
self.proxy_network_provider.await_account_on_condition(
address=wrapper.transaction.sender,
condition=condition,
options=self.account_awaiting_options,
)
transaction_on_network = self.proxy_network_provider.get_transaction(wrapper.get_hash())
print(f"Started: {self.configuration.explorer_url}/transactions/{wrapper.get_hash()}")
return transaction_on_network
transactions_on_network = Pool(NUM_PARALLEL_GET_TRANSACTION_REQUESTS).map(
await_processing_started_one,
wrappers
)
return transactions_on_network
def await_completed(self, wrappers: list[TransactionWrapper]) -> list[TransactionOnNetwork]:
def await_completed_one(wrapper: TransactionWrapper) -> TransactionOnNetwork:
transaction_on_network = self.api_network_provider.await_transaction_completed(
transaction_hash=wrapper.get_hash(),
options=self.transaction_awaiting_options
)
print(f"Completed: {self.configuration.explorer_url}/transactions/{wrapper.get_hash()}")
return transaction_on_network
ux.show_message(f"Transactions sent. Waiting for their completion...")
transactions_on_network = Pool(NUM_PARALLEL_GET_TRANSACTION_REQUESTS).map(
await_completed_one,
wrappers
)
return transactions_on_network
def _api_do_get(self, url: str, url_parameters: dict[str, Any]):
latest_error = None
for attempt in range(NETWORK_PROVIDER_NUM_RETRIES):
try:
return self.api_network_provider.do_get_generic(url, url_parameters)
except NetworkProviderError as error:
latest_error = error
print(f"Attempt #{attempt}, [red]failed to get {error.url}[/red]")
is_last_attempt = attempt == NETWORK_PROVIDER_NUM_RETRIES - 1
if not is_last_attempt:
time.sleep(NETWORK_PROVIDERS_RETRY_DELAY_IN_SECONDS)
raise TransientError(f"cannot get from API", latest_error)