idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
27,600 | def check_for_insufficient_eth ( self , transaction_name : str , transaction_executed : bool , required_gas : int , block_identifier : BlockSpecification , ) : if transaction_executed : return our_address = to_checksum_address ( self . address ) balance = self . web3 . eth . getBalance ( our_address , block_identifier ... | After estimate gas failure checks if our address has enough balance . |
27,601 | def get_db_version ( db_filename : Path ) -> int : assert os . path . exists ( db_filename ) conn = sqlite3 . connect ( str ( db_filename ) , detect_types = sqlite3 . PARSE_DECLTYPES , ) cursor = conn . cursor ( ) try : cursor . execute ( 'SELECT value FROM settings WHERE name="version";' ) result = cursor . fetchone (... | Return the version value stored in the db |
27,602 | def get_or_deploy_token ( runner ) -> Tuple [ ContractProxy , int ] : token_contract = runner . contract_manager . get_contract ( CONTRACT_CUSTOM_TOKEN ) token_config = runner . scenario . get ( 'token' , { } ) if not token_config : token_config = { } address = token_config . get ( 'address' ) block = token_config . ge... | Deploy or reuse |
27,603 | def get_udc_and_token ( runner ) -> Tuple [ Optional [ ContractProxy ] , Optional [ ContractProxy ] ] : from scenario_player . runner import ScenarioRunner assert isinstance ( runner , ScenarioRunner ) udc_config = runner . scenario . services . get ( 'udc' , { } ) if not udc_config . get ( 'enable' , False ) : return ... | Return contract proxies for the UserDepositContract and associated token |
27,604 | def mint_token_if_balance_low ( token_contract : ContractProxy , target_address : str , min_balance : int , fund_amount : int , gas_limit : int , mint_msg : str , no_action_msg : str = None , ) -> Optional [ TransactionHash ] : balance = token_contract . contract . functions . balanceOf ( target_address ) . call ( ) if... | Check token balance and mint if below minimum |
27,605 | def log_and_dispatch ( self , state_change ) : with self . _lock : timestamp = datetime . utcnow ( ) . isoformat ( timespec = 'milliseconds' ) state_change_id = self . storage . write_state_change ( state_change , timestamp ) self . state_change_id = state_change_id events = self . state_manager . dispatch ( state_chan... | Log and apply a state change . |
27,606 | def snapshot ( self ) : with self . _lock : current_state = self . state_manager . current_state state_change_id = self . state_change_id if state_change_id : self . storage . write_state_snapshot ( state_change_id , current_state ) | Snapshot the application state . |
27,607 | def handle_tokennetwork_new ( raiden : 'RaidenService' , event : Event ) : data = event . event_data args = data [ 'args' ] block_number = data [ 'block_number' ] token_network_address = args [ 'token_network_address' ] token_address = typing . TokenAddress ( args [ 'token_address' ] ) block_hash = data [ 'block_hash' ... | Handles a TokenNetworkCreated event . |
27,608 | def query_blockchain_events ( web3 : Web3 , contract_manager : ContractManager , contract_address : Address , contract_name : str , topics : List , from_block : BlockNumber , to_block : BlockNumber , ) -> List [ Dict ] : filter_params = { 'fromBlock' : from_block , 'toBlock' : to_block , 'address' : to_checksum_address... | Returns events emmitted by a contract for a given event name within a certain range . |
27,609 | def upgrade_v16_to_v17 ( storage : SQLiteStorage , old_version : int , current_version : int , ** kwargs ) : if old_version == SOURCE_VERSION : _transform_snapshots ( storage ) return TARGET_VERSION | InitiatorPaymentState was changed so that the initiator attribute is renamed to initiator_transfers and converted to a list . |
27,610 | def filter_db_names ( paths : List [ str ] ) -> List [ str ] : return [ db_path for db_path in paths if VERSION_RE . match ( os . path . basename ( db_path ) ) ] | Returns a filtered list of paths where every name matches our format . |
27,611 | def compare_contract_versions ( proxy : ContractProxy , expected_version : str , contract_name : str , address : Address , ) -> None : assert isinstance ( expected_version , str ) try : deployed_version = proxy . contract . functions . contract_version ( ) . call ( ) except BadFunctionCallOutput : raise AddressWrongCon... | Compare version strings of a contract . |
27,612 | def get_onchain_locksroots ( chain : 'BlockChainService' , canonical_identifier : CanonicalIdentifier , participant1 : Address , participant2 : Address , block_identifier : BlockSpecification , ) -> Tuple [ Locksroot , Locksroot ] : payment_channel = chain . payment_channel ( canonical_identifier = canonical_identifier... | Return the locksroot for participant1 and participant2 at block_identifier . |
27,613 | def inplace_delete_message_queue ( chain_state : ChainState , state_change : Union [ ReceiveDelivered , ReceiveProcessed ] , queueid : QueueIdentifier , ) -> None : queue = chain_state . queueids_to_queues . get ( queueid ) if not queue : return inplace_delete_message ( message_queue = queue , state_change = state_chan... | Filter messages from queue if the queue becomes empty cleanup the queue itself . |
27,614 | def inplace_delete_message ( message_queue : List [ SendMessageEvent ] , state_change : Union [ ReceiveDelivered , ReceiveProcessed ] , ) -> None : for message in list ( message_queue ) : message_found = ( message . message_identifier == state_change . message_identifier and message . recipient == state_change . sender... | Check if the message exists in queue with ID queueid and exclude if found . |
27,615 | def handle_delivered ( chain_state : ChainState , state_change : ReceiveDelivered , ) -> TransitionResult [ ChainState ] : queueid = QueueIdentifier ( state_change . sender , CHANNEL_IDENTIFIER_GLOBAL_QUEUE ) inplace_delete_message_queue ( chain_state , state_change , queueid ) return TransitionResult ( chain_state , [... | Check if the Delivered message exists in the global queue and delete if found . |
27,616 | def is_transaction_effect_satisfied ( chain_state : ChainState , transaction : ContractSendEvent , state_change : StateChange , ) -> bool : is_valid_update_transfer = ( isinstance ( state_change , ContractReceiveUpdateTransfer ) and isinstance ( transaction , ContractSendChannelUpdateTransfer ) and state_change . token... | True if the side - effect of transaction is satisfied by state_change . |
27,617 | def is_transaction_invalidated ( transaction , state_change ) : is_our_failed_update_transfer = ( isinstance ( state_change , ContractReceiveChannelSettled ) and isinstance ( transaction , ContractSendChannelUpdateTransfer ) and state_change . token_network_identifier == transaction . token_network_identifier and state... | True if the transaction is made invalid by state_change . |
27,618 | def is_transaction_expired ( transaction , block_number ) : is_update_expired = ( isinstance ( transaction , ContractSendChannelUpdateTransfer ) and transaction . expiration < block_number ) if is_update_expired : return True is_secret_register_expired = ( isinstance ( transaction , ContractSendSecretReveal ) and trans... | True if transaction cannot be mined because it has expired . |
27,619 | def deposit ( self , beneficiary : Address , total_deposit : TokenAmount , block_identifier : BlockSpecification , ) -> None : token_address = self . token_address ( block_identifier ) token = Token ( jsonrpc_client = self . client , token_address = token_address , contract_manager = self . contract_manager , ) log_det... | Deposit provided amount into the user - deposit contract to the beneficiary s account . |
27,620 | def effective_balance ( self , address : Address , block_identifier : BlockSpecification ) -> Balance : fn = getattr ( self . proxy . contract . functions , 'effectiveBalance' ) balance = fn ( address ) . call ( block_identifier = block_identifier ) if balance == b'' : raise RuntimeError ( f"Call to 'effectiveBalance' ... | The user s balance with planned withdrawals deducted . |
27,621 | def validate ( self , value : int ) : if not isinstance ( value , int ) : raise ValueError ( 'value is not an integer' ) if self . minimum > value or self . maximum < value : msg = ( '{} is outside the valide range [{},{}]' ) . format ( value , self . minimum , self . maximum ) raise ValueError ( msg ) | Validates the integer is in the value range . |
27,622 | def event_filter_for_payments ( event : architecture . Event , token_network_identifier : TokenNetworkID = None , partner_address : Address = None , ) -> bool : is_matching_event = ( isinstance ( event , EVENTS_PAYMENT_HISTORY_RELATED ) and ( token_network_identifier is None or token_network_identifier == event . token... | Filters out non payment history related events |
27,623 | def token_network_register ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , channel_participant_deposit_limit : TokenAmount , token_network_deposit_limit : TokenAmount , retry_timeout : NetworkTimeout = DEFAULT_RETRY_TIMEOUT , ) -> TokenNetworkAddress : if not is_binary_address ( registry_a... | Register the token_address in the blockchain . If the address is already registered but the event has not been processed this function will block until the next block to make sure the event is processed . |
27,624 | def token_network_connect ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , funds : TokenAmount , initial_channel_target : int = 3 , joinable_funds_target : float = 0.4 , ) -> None : if not is_binary_address ( registry_address ) : raise InvalidAddress ( 'registry_address must be a valid addr... | Automatically maintain channels open for the given token network . |
27,625 | def token_network_leave ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , ) -> List [ NettingChannelState ] : if not is_binary_address ( registry_address ) : raise InvalidAddress ( 'registry_address must be a valid address in binary' ) if not is_binary_address ( token_address ) : raise Inval... | Close all channels and wait for settlement . |
27,626 | def channel_open ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , settle_timeout : BlockTimeout = None , retry_timeout : NetworkTimeout = DEFAULT_RETRY_TIMEOUT , ) -> ChannelID : if settle_timeout is None : settle_timeout = self . raiden . config [ 'settle_timeou... | Open a channel with the peer at partner_address with the given token_address . |
27,627 | def set_total_channel_deposit ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , total_deposit : TokenAmount , retry_timeout : NetworkTimeout = DEFAULT_RETRY_TIMEOUT , ) : chain_state = views . state_from_raiden ( self . raiden ) token_addresses = views . get_token... | Set the total_deposit in the channel with the peer at partner_address and the given token_address in order to be able to do transfers . |
27,628 | def get_node_network_state ( self , node_address : Address ) : return views . get_node_network_status ( chain_state = views . state_from_raiden ( self . raiden ) , node_address = node_address , ) | Returns the currently network status of node_address . |
27,629 | def get_tokens_list ( self , registry_address : PaymentNetworkID ) : tokens_list = views . get_token_identifiers ( chain_state = views . state_from_raiden ( self . raiden ) , payment_network_id = registry_address , ) return tokens_list | Returns a list of tokens the node knows about |
27,630 | def transfer_and_wait ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , amount : TokenAmount , target : Address , identifier : PaymentID = None , transfer_timeout : int = None , secret : Secret = None , secret_hash : SecretHash = None , ) : payment_status = self . transfer_async ( registry_a... | Do a transfer with target with the given amount of token_address . |
27,631 | def get_blockchain_events_token_network ( self , token_address : TokenAddress , from_block : BlockSpecification = GENESIS_BLOCK_NUMBER , to_block : BlockSpecification = 'latest' , ) : if not is_binary_address ( token_address ) : raise InvalidAddress ( 'Expected binary address format for token in get_blockchain_events_t... | Returns a list of blockchain events coresponding to the token_address . |
27,632 | def create_monitoring_request ( self , balance_proof : BalanceProofSignedState , reward_amount : TokenAmount , ) -> Optional [ RequestMonitoring ] : monitor_request = RequestMonitoring . from_balance_proof_signed_state ( balance_proof = balance_proof , reward_amount = reward_amount , ) monitor_request . sign ( self . r... | This method can be used to create a RequestMonitoring message . It will contain all data necessary for an external monitoring service to - send an updateNonClosingBalanceProof transaction to the TokenNetwork contract for the balance_proof that we received from a channel partner . - claim the reward_amount from the UDC ... |
27,633 | def lockedtransfersigned_from_message ( message : 'LockedTransfer' ) -> 'LockedTransferSignedState' : balance_proof = balanceproof_from_envelope ( message ) lock = HashTimeLockState ( message . lock . amount , message . lock . expiration , message . lock . secrethash , ) transfer_state = LockedTransferSignedState ( mes... | Create LockedTransferSignedState from a LockedTransfer message . |
27,634 | def version ( short ) : if short : print ( get_system_spec ( ) [ 'raiden' ] ) else : print ( json . dumps ( get_system_spec ( ) , indent = 2 , ) ) | Print version information and exit . |
27,635 | def connect ( self , funds : typing . TokenAmount , initial_channel_target : int = 3 , joinable_funds_target : float = 0.4 , ) : token = self . raiden . chain . token ( self . token_address ) token_balance = token . balance_of ( self . raiden . address ) if token_balance < funds : raise InvalidAmount ( f'Insufficient b... | Connect to the network . |
27,636 | def leave ( self , registry_address ) : with self . lock : self . initial_channel_target = 0 channels_to_close = views . get_channelstate_open ( chain_state = views . state_from_raiden ( self . raiden ) , payment_network_id = registry_address , token_address = self . token_address , ) partner_addresses = [ channel_stat... | Leave the token network . |
27,637 | def join_channel ( self , partner_address , partner_deposit ) : token_network_proxy = self . raiden . chain . token_network ( self . token_network_identifier ) with self . lock , token_network_proxy . channel_operations_lock [ partner_address ] : channel_state = views . get_channelstate_for ( views . state_from_raiden ... | Will be called when we were selected as channel partner by another node . It will fund the channel with up to the partners deposit but not more than remaining funds or the initial funding per channel . |
27,638 | def retry_connect ( self ) : with self . lock : if self . _funds_remaining > 0 and not self . _leaving_state : self . _open_channels ( ) | Will be called when new channels in the token network are detected . If the minimum number of channels was not yet established it will try to open new channels . |
27,639 | def _find_new_partners ( self ) : open_channels = views . get_channelstate_open ( chain_state = views . state_from_raiden ( self . raiden ) , payment_network_id = self . registry_address , token_address = self . token_address , ) known = set ( channel_state . partner_state . address for channel_state in open_channels )... | Search the token network for potential channel partners . |
27,640 | def _join_partner ( self , partner : Address ) : try : self . api . channel_open ( self . registry_address , self . token_address , partner , ) except DuplicatedChannelError : pass total_deposit = self . _initial_funding_per_partner if total_deposit == 0 : return try : self . api . set_total_channel_deposit ( registry_... | Ensure a channel exists with partner and is funded in our side |
27,641 | def _open_channels ( self ) -> bool : open_channels = views . get_channelstate_open ( chain_state = views . state_from_raiden ( self . raiden ) , payment_network_id = self . registry_address , token_address = self . token_address , ) open_channels = [ channel_state for channel_state in open_channels if channel_state . ... | Open channels until there are self . initial_channel_target channels open . Do nothing if there are enough channels open already . |
27,642 | def _initial_funding_per_partner ( self ) -> int : if self . initial_channel_target : return int ( self . funds * ( 1 - self . joinable_funds_target ) / self . initial_channel_target , ) return 0 | The calculated funding per partner depending on configuration and overall funding of the ConnectionManager . |
27,643 | def _funds_remaining ( self ) -> int : if self . funds > 0 : token = self . raiden . chain . token ( self . token_address ) token_balance = token . balance_of ( self . raiden . address ) sum_deposits = views . get_our_capacity_for_token_network ( views . state_from_raiden ( self . raiden ) , self . registry_address , s... | The remaining funds after subtracting the already deposited amounts . |
27,644 | def _make_regex ( self ) : rxp = "|" . join ( map ( self . _address_rxp , self . keys ( ) ) , ) self . _regex = re . compile ( rxp , re . IGNORECASE , ) | Compile rxp with all keys concatenated . |
27,645 | def get ( self ) : return self . rest_api . get_tokens_list ( self . rest_api . raiden_api . raiden . default_registry . address , ) | this translates to get all token addresses we have channels open for |
27,646 | def is_safe_to_wait ( lock_expiration : BlockExpiration , reveal_timeout : BlockTimeout , block_number : BlockNumber , ) -> SuccessOrError : assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_number if lock_timeout > reveal_timeout : return T... | True if waiting is safe i . e . there are more than enough blocks to safely unlock on chain . |
27,647 | def is_send_transfer_almost_equal ( send_channel : NettingChannelState , send : LockedTransferUnsignedState , received : LockedTransferSignedState , ) -> bool : return ( isinstance ( send , LockedTransferUnsignedState ) and isinstance ( received , LockedTransferSignedState ) and send . payment_identifier == received . ... | True if both transfers are for the same mediated transfer . |
27,648 | def filter_reachable_routes ( routes : List [ RouteState ] , nodeaddresses_to_networkstates : NodeNetworkStateMap , ) -> List [ RouteState ] : reachable_routes = [ ] for route in routes : node_network_state = nodeaddresses_to_networkstates . get ( route . node_address , NODE_NETWORK_UNREACHABLE , ) if node_network_stat... | This function makes sure we use reachable routes only . |
27,649 | def filter_used_routes ( transfers_pair : List [ MediationPairState ] , routes : List [ RouteState ] , ) -> List [ RouteState ] : channelid_to_route = { r . channel_identifier : r for r in routes } routes_order = { route . node_address : index for index , route in enumerate ( routes ) } for pair in transfers_pair : cha... | This function makes sure we filter routes that have already been used . |
27,650 | def get_payee_channel ( channelidentifiers_to_channels : ChannelMap , transfer_pair : MediationPairState , ) -> Optional [ NettingChannelState ] : payee_channel_identifier = transfer_pair . payee_transfer . balance_proof . channel_identifier return channelidentifiers_to_channels . get ( payee_channel_identifier ) | Returns the payee channel of a given transfer pair or None if it s not found |
27,651 | def get_payer_channel ( channelidentifiers_to_channels : ChannelMap , transfer_pair : MediationPairState , ) -> Optional [ NettingChannelState ] : payer_channel_identifier = transfer_pair . payer_transfer . balance_proof . channel_identifier return channelidentifiers_to_channels . get ( payer_channel_identifier ) | Returns the payer channel of a given transfer pair or None if it s not found |
27,652 | def get_pending_transfer_pairs ( transfers_pair : List [ MediationPairState ] , ) -> List [ MediationPairState ] : pending_pairs = list ( pair for pair in transfers_pair if pair . payee_state not in STATE_TRANSFER_FINAL or pair . payer_state not in STATE_TRANSFER_FINAL ) return pending_pairs | Return the transfer pairs that are not at a final state . |
27,653 | def get_lock_amount_after_fees ( lock : HashTimeLockState , payee_channel : NettingChannelState , ) -> PaymentWithFeeAmount : return PaymentWithFeeAmount ( lock . amount - payee_channel . mediation_fee ) | Return the lock . amount after fees are taken . |
27,654 | def sanity_check ( state : MediatorTransferState , channelidentifiers_to_channels : ChannelMap , ) -> None : all_transfers_states = itertools . chain ( ( pair . payee_state for pair in state . transfers_pair ) , ( pair . payer_state for pair in state . transfers_pair ) , ) if any ( state in STATE_TRANSFER_PAID for stat... | Check invariants that must hold . |
27,655 | def clear_if_finalized ( iteration : TransitionResult , channelidentifiers_to_channels : ChannelMap , ) -> TransitionResult [ MediatorTransferState ] : state = cast ( MediatorTransferState , iteration . new_state ) if state is None : return iteration secrethash = state . secrethash for pair in state . transfers_pair : ... | Clear the mediator task if all the locks have been finalized . |
27,656 | def forward_transfer_pair ( payer_transfer : LockedTransferSignedState , available_routes : List [ 'RouteState' ] , channelidentifiers_to_channels : Dict , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> Tuple [ Optional [ MediationPairState ] , List [ Event ] ] : transfer_pair = None medi... | Given a payer transfer tries a new route to proceed with the mediation . |
27,657 | def backward_transfer_pair ( backward_channel : NettingChannelState , payer_transfer : LockedTransferSignedState , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> Tuple [ Optional [ MediationPairState ] , List [ Event ] ] : transfer_pair = None events : List [ Event ] = list ( ) lock = pay... | Sends a transfer backwards allowing the previous hop to try a new route . |
27,658 | def events_for_expired_pairs ( channelidentifiers_to_channels : ChannelMap , transfers_pair : List [ MediationPairState ] , waiting_transfer : Optional [ WaitingTransferState ] , block_number : BlockNumber , ) -> List [ Event ] : pending_transfers_pairs = get_pending_transfer_pairs ( transfers_pair ) events : List [ Ev... | Informational events for expired locks . |
27,659 | def events_for_secretreveal ( transfers_pair : List [ MediationPairState ] , secret : Secret , pseudo_random_generator : random . Random , ) -> List [ Event ] : events : List [ Event ] = list ( ) for pair in reversed ( transfers_pair ) : payee_knows_secret = pair . payee_state in STATE_SECRET_KNOWN payer_knows_secret =... | Reveal the secret off - chain . |
27,660 | def events_for_balanceproof ( channelidentifiers_to_channels : ChannelMap , transfers_pair : List [ MediationPairState ] , pseudo_random_generator : random . Random , block_number : BlockNumber , secret : Secret , secrethash : SecretHash , ) -> List [ Event ] : events : List [ Event ] = list ( ) for pair in reversed ( ... | While it s safe do the off - chain unlock . |
27,661 | def events_for_onchain_secretreveal_if_dangerzone ( channelmap : ChannelMap , secrethash : SecretHash , transfers_pair : List [ MediationPairState ] , block_number : BlockNumber , block_hash : BlockHash , ) -> List [ Event ] : events : List [ Event ] = list ( ) all_payer_channels = [ ] for pair in transfers_pair : chan... | Reveal the secret on - chain if the lock enters the unsafe region and the secret is not yet on - chain . |
27,662 | def events_for_onchain_secretreveal_if_closed ( channelmap : ChannelMap , transfers_pair : List [ MediationPairState ] , secret : Secret , secrethash : SecretHash , block_hash : BlockHash , ) -> List [ Event ] : events : List [ Event ] = list ( ) all_payer_channels = [ ] for pair in transfers_pair : channel_state = get... | Register the secret on - chain if the payer channel is already closed and the mediator learned the secret off - chain . |
27,663 | def events_to_remove_expired_locks ( mediator_state : MediatorTransferState , channelidentifiers_to_channels : ChannelMap , block_number : BlockNumber , pseudo_random_generator : random . Random , ) -> List [ Event ] : events : List [ Event ] = list ( ) for transfer_pair in mediator_state . transfers_pair : balance_pro... | Clear the channels which have expired locks . |
27,664 | def secret_learned ( state : MediatorTransferState , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , block_number : BlockNumber , block_hash : BlockHash , secret : Secret , secrethash : SecretHash , payee_address : Address , ) -> TransitionResult [ MediatorTransferState ] : sec... | Unlock the payee lock reveal the lock to the payer and if necessary register the secret on - chain . |
27,665 | def mediate_transfer ( state : MediatorTransferState , possible_routes : List [ 'RouteState' ] , payer_channel : NettingChannelState , channelidentifiers_to_channels : ChannelMap , nodeaddresses_to_networkstates : NodeNetworkStateMap , pseudo_random_generator : random . Random , payer_transfer : LockedTransferSignedSta... | Try a new route or fail back to a refund . |
27,666 | def handle_onchain_secretreveal ( mediator_state : MediatorTransferState , onchain_secret_reveal : ContractReceiveSecretReveal , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , block_number : BlockNumber , ) -> TransitionResult [ MediatorTransferState ] : secrethash = onchain_s... | The secret was revealed on - chain set the state of all transfers to secret known . |
27,667 | def handle_unlock ( mediator_state : MediatorTransferState , state_change : ReceiveUnlock , channelidentifiers_to_channels : ChannelMap , ) -> TransitionResult [ MediatorTransferState ] : events = list ( ) balance_proof_sender = state_change . balance_proof . sender channel_identifier = state_change . balance_proof . c... | Handle a ReceiveUnlock state change . |
27,668 | def service_count ( self , block_identifier : BlockSpecification ) -> int : result = self . proxy . contract . functions . serviceCount ( ) . call ( block_identifier = block_identifier , ) return result | Get the number of registered services |
27,669 | def get_service_address ( self , block_identifier : BlockSpecification , index : int , ) -> Optional [ AddressHex ] : try : result = self . proxy . contract . functions . service_addresses ( index ) . call ( block_identifier = block_identifier , ) except web3 . exceptions . BadFunctionCallOutput : result = None return ... | Gets the address of a service by index . If index is out of range return None |
27,670 | def get_service_url ( self , block_identifier : BlockSpecification , service_hex_address : AddressHex , ) -> Optional [ str ] : result = self . proxy . contract . functions . urls ( service_hex_address ) . call ( block_identifier = block_identifier , ) if result == '' : return None return result | Gets the URL of a service by address . If does not exist return None |
27,671 | def set_url ( self , url : str ) : gas_limit = self . proxy . estimate_gas ( 'latest' , 'setURL' , url ) transaction_hash = self . proxy . transact ( 'setURL' , gas_limit , url ) self . client . poll ( transaction_hash ) assert not check_transaction_threw ( self . client , transaction_hash ) | Sets the url needed to access the service via HTTP for the caller |
27,672 | def recover ( data : bytes , signature : Signature , hasher : Callable [ [ bytes ] , bytes ] = eth_sign_sha3 , ) -> Address : _hash = hasher ( data ) if signature [ - 1 ] >= 27 : signature = Signature ( signature [ : - 1 ] + bytes ( [ signature [ - 1 ] - 27 ] ) ) try : sig = keys . Signature ( signature_bytes = signatu... | eth_recover address from data hash and signature |
27,673 | def sign ( self , data : bytes , v : int = 27 ) -> Signature : assert v in ( 0 , 27 ) , 'Raiden is only signing messages with v in (0, 27)' _hash = eth_sign_sha3 ( data ) signature = self . private_key . sign_msg_hash ( message_hash = _hash ) sig_bytes = signature . to_bytes ( ) return sig_bytes [ : - 1 ] + bytes ( [ s... | Sign data hash with local private key |
27,674 | def approve ( self , allowed_address : Address , allowance : TokenAmount , ) : log_details = { 'node' : pex ( self . node_address ) , 'contract' : pex ( self . address ) , 'allowed_address' : pex ( allowed_address ) , 'allowance' : allowance , } checking_block = self . client . get_checking_block ( ) error_prefix = 'Ca... | Aprove allowed_address to transfer up to deposit amount of token . |
27,675 | def balance_of ( self , address , block_identifier = 'latest' ) : return self . proxy . contract . functions . balanceOf ( to_checksum_address ( address ) , ) . call ( block_identifier = block_identifier ) | Return the balance of address . |
27,676 | def total_supply ( self , block_identifier = 'latest' ) : return self . proxy . contract . functions . totalSupply ( ) . call ( block_identifier = block_identifier ) | Return the total supply of the token at the given block identifier . |
27,677 | def clear_if_finalized ( iteration : TransitionResult , ) -> TransitionResult [ InitiatorPaymentState ] : state = cast ( InitiatorPaymentState , iteration . new_state ) if state is None : return iteration if len ( state . initiator_transfers ) == 0 : return TransitionResult ( None , iteration . events ) return iteratio... | Clear the initiator payment task if all transfers have been finalized or expired . |
27,678 | def cancel_current_route ( payment_state : InitiatorPaymentState , initiator_state : InitiatorTransferState , ) -> List [ Event ] : assert can_cancel ( initiator_state ) , 'Cannot cancel a route after the secret is revealed' transfer_description = initiator_state . transfer_description payment_state . cancelled_channel... | Cancel current route . |
27,679 | def subdispatch_to_all_initiatortransfer ( payment_state : InitiatorPaymentState , state_change : StateChange , channelidentifiers_to_channels : ChannelMap , pseudo_random_generator : random . Random , ) -> TransitionResult [ InitiatorPaymentState ] : events = list ( ) for secrethash in list ( payment_state . initiator... | Copy and iterate over the list of keys because this loop will alter the initiator_transfers list and this is not allowed if iterating over the original list . |
27,680 | def handle_cancelpayment ( payment_state : InitiatorPaymentState , channelidentifiers_to_channels : ChannelMap , ) -> TransitionResult [ InitiatorPaymentState ] : events = list ( ) for initiator_state in payment_state . initiator_transfers . values ( ) : channel_identifier = initiator_state . channel_identifier channel... | Cancel the payment and all related transfers . |
27,681 | def handle_lock_expired ( payment_state : InitiatorPaymentState , state_change : ReceiveLockExpired , channelidentifiers_to_channels : ChannelMap , block_number : BlockNumber , ) -> TransitionResult [ InitiatorPaymentState ] : initiator_state = payment_state . initiator_transfers . get ( state_change . secrethash ) if ... | Initiator also needs to handle LockExpired messages when refund transfers are involved . |
27,682 | def http_retry_with_backoff_middleware ( make_request , web3 , errors : Tuple = ( exceptions . ConnectionError , exceptions . HTTPError , exceptions . Timeout , exceptions . TooManyRedirects , ) , retries : int = 10 , first_backoff : float = 0.2 , backoff_factor : float = 2 , ) : def middleware ( method , params ) : ba... | Retry requests with exponential backoff Creates middleware that retries failed HTTP requests and exponentially increases the backoff between retries . Meant to replace the default middleware http_retry_request_middleware for HTTPProvider . |
27,683 | def get_random_service ( service_registry : ServiceRegistry , block_identifier : BlockSpecification , ) -> Tuple [ Optional [ str ] , Optional [ str ] ] : count = service_registry . service_count ( block_identifier = block_identifier ) if count == 0 : return None , None index = random . SystemRandom ( ) . randint ( 0 ,... | Selects a random PFS from service_registry . |
27,684 | def configure_pfs_or_exit ( pfs_address : Optional [ str ] , pfs_eth_address : Optional [ str ] , routing_mode : RoutingMode , service_registry , ) -> Optional [ PFSConfiguration ] : if routing_mode == RoutingMode . BASIC : msg = 'Not using path finding services, falling back to basic routing.' log . info ( msg ) click... | Take in the given pfs_address argument the service registry and find out a pfs address to use . |
27,685 | def query_paths ( service_config : Dict [ str , Any ] , our_address : Address , privkey : bytes , current_block_number : BlockNumber , token_network_address : Union [ TokenNetworkAddress , TokenNetworkID ] , route_from : InitiatorAddress , route_to : TargetAddress , value : PaymentAmount , ) -> List [ Dict [ str , Any ... | Query paths from the PFS . |
27,686 | def single_queue_send ( transport : 'UDPTransport' , recipient : Address , queue : Queue_T , queue_identifier : QueueIdentifier , event_stop : Event , event_healthy : Event , event_unhealthy : Event , message_retries : int , message_retry_timeout : int , message_retry_max_timeout : int , ) : if not isinstance ( queue ,... | Handles a single message queue for recipient . |
27,687 | def get_health_events ( self , recipient ) : if recipient not in self . addresses_events : self . start_health_check ( recipient ) return self . addresses_events [ recipient ] | Starts a healthcheck task for recipient and returns a HealthEvents with locks to react on its current state . |
27,688 | def start_health_check ( self , recipient ) : if recipient not in self . addresses_events : self . whitelist ( recipient ) ping_nonce = self . nodeaddresses_to_nonces . setdefault ( recipient , { 'nonce' : 0 } , ) events = healthcheck . HealthEvents ( event_healthy = Event ( ) , event_unhealthy = Event ( ) , ) self . a... | Starts a task for healthchecking recipient if there is not one yet . |
27,689 | def init_queue_for ( self , queue_identifier : QueueIdentifier , items : List [ QueueItem_T ] , ) -> NotifyingQueue : recipient = queue_identifier . recipient queue = self . queueids_to_queues . get ( queue_identifier ) assert queue is None queue = NotifyingQueue ( items = items ) self . queueids_to_queues [ queue_iden... | Create the queue identified by the queue_identifier and initialize it with items . |
27,690 | def get_queue_for ( self , queue_identifier : QueueIdentifier , ) -> NotifyingQueue : queue = self . queueids_to_queues . get ( queue_identifier ) if queue is None : items : List [ QueueItem_T ] = list ( ) queue = self . init_queue_for ( queue_identifier , items ) return queue | Return the queue identified by the given queue identifier . |
27,691 | def send_async ( self , queue_identifier : QueueIdentifier , message : Message , ) : recipient = queue_identifier . recipient if not is_binary_address ( recipient ) : raise ValueError ( 'Invalid address {}' . format ( pex ( recipient ) ) ) if isinstance ( message , ( Delivered , Ping , Pong ) ) : raise ValueError ( 'Do... | Send a new ordered message to recipient . |
27,692 | def receive ( self , messagedata : bytes , host_port : Tuple [ str , int ] , ) -> bool : if len ( messagedata ) > self . UDP_MAX_MESSAGE_SIZE : self . log . warning ( 'Invalid message: Packet larger than maximum size' , message = encode_hex ( messagedata ) , length = len ( messagedata ) , ) return False try : message =... | Handle an UDP packet . |
27,693 | def receive_message ( self , message : Message ) : self . raiden . on_message ( message ) delivered_message = Delivered ( delivered_message_identifier = message . message_identifier ) self . raiden . sign ( delivered_message ) self . maybe_send ( message . sender , delivered_message , ) | Handle a Raiden protocol message . |
27,694 | def receive_delivered ( self , delivered : Delivered ) : self . raiden . on_message ( delivered ) message_id = delivered . delivered_message_identifier async_result = self . raiden . transport . messageids_to_asyncresults . get ( message_id ) if async_result is not None : del self . messageids_to_asyncresults [ message... | Handle a Delivered message . |
27,695 | def receive_ping ( self , ping : Ping ) : self . log_healthcheck . debug ( 'Ping received' , message_id = ping . nonce , message = ping , sender = pex ( ping . sender ) , ) pong = Pong ( nonce = ping . nonce ) self . raiden . sign ( pong ) try : self . maybe_send ( ping . sender , pong ) except ( InvalidAddress , Unkno... | Handle a Ping message by answering with a Pong . |
27,696 | def receive_pong ( self , pong : Pong ) : message_id = ( 'ping' , pong . nonce , pong . sender ) async_result = self . messageids_to_asyncresults . get ( message_id ) if async_result is not None : self . log_healthcheck . debug ( 'Pong received' , sender = pex ( pong . sender ) , message_id = pong . nonce , ) async_res... | Handles a Pong message . |
27,697 | def get_ping ( self , nonce : Nonce ) -> bytes : message = Ping ( nonce = nonce , current_protocol_version = constants . PROTOCOL_VERSION , ) self . raiden . sign ( message ) return message . encode ( ) | Returns a signed Ping message . |
27,698 | def apply_config_file ( command_function : Union [ click . Command , click . Group ] , cli_params : Dict [ str , Any ] , ctx , config_file_option_name = 'config_file' , ) : paramname_to_param = { param . name : param for param in command_function . params } path_params = { param . name for param in command_function . p... | Applies all options set in the config file to cli_params |
27,699 | def get_matrix_servers ( url : str ) -> List [ str ] : try : response = requests . get ( url ) if response . status_code != 200 : raise requests . RequestException ( 'Response: {response!r}' ) except requests . RequestException as ex : raise RuntimeError ( f'Could not fetch matrix servers list: {url!r} => {ex!r}' ) fro... | Fetch a list of matrix servers from a text url |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.