Python web3.Web3() Examples
The following are 30
code examples of web3.Web3().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
web3
, or try the search function
.
Example #1
Source File: blockchain.py From raiden-services with MIT License | 8 votes |
def query_blockchain_events( web3: Web3, contract_addresses: List[Address], from_block: BlockNumber, to_block: BlockNumber ) -> List[Dict]: """Returns events emmitted by a contract for a given event name, within a certain range. Args: web3: A Web3 instance contract_addresses: The address(es) of the contract(s) to be filtered from_block: The block to start search events to_block: The block to stop searching for events Returns: All matching events """ filter_params = FilterParams( {"fromBlock": from_block, "toBlock": to_block, "address": contract_addresses} ) events = web3.eth.getLogs(filter_params) return [decode_event(web3.codec, log_entry) for log_entry in events]
Example #2
Source File: test_time_based_gas_price_strategy.py From web3.py with MIT License | 7 votes |
def test_time_based_gas_price_strategy_zero_sample(strategy_params_zero, expected_exception_message): with pytest.raises(ValidationError) as excinfo: fixture_middleware = construct_result_generator_middleware({ 'eth_getBlockByHash': _get_block_by_something, 'eth_getBlockByNumber': _get_block_by_something, }) w3 = Web3( provider=BaseProvider(), middlewares=[fixture_middleware], ) time_based_gas_price_strategy_zero = construct_time_based_gas_price_strategy( **strategy_params_zero, ) w3.eth.setGasPriceStrategy(time_based_gas_price_strategy_zero) w3.eth.generateGasPrice() assert str(excinfo.value) == expected_exception_message
Example #3
Source File: test_service_registry.py From raiden-services with MIT License | 7 votes |
def test_registration( web3: Web3, service_registry: Contract, get_accounts: Callable, get_private_key: Callable, ) -> None: (account,) = get_accounts(1) pk1 = get_private_key(account) assert service_registry.functions.hasValidRegistration(account).call() is False assert service_registry.functions.urls(account).call() == "" register_account( private_key=pk1, web3=web3, contracts={CONTRACT_SERVICE_REGISTRY: service_registry}, start_block=BlockNumber(0), service_url="test", accept_disclaimer=True, accept_all=True, ) # check that registration worked assert service_registry.functions.hasValidRegistration(account).call() is True assert service_registry.functions.urls(account).call() == "test"
Example #4
Source File: web3.py From raiden-services with MIT License | 7 votes |
def mockchain(monkeypatch): state: Dict[str, List[List[Event]]] = dict(block_events=[]) def get_blockchain_events( web3: Web3, blockchain_state: BlockchainState, token_network_addresses: List[TokenNetworkAddress], latest_confirmed_block: BlockNumber, ): # pylint: disable=unused-argument blocks = state["block_events"][ blockchain_state.latest_committed_block : latest_confirmed_block + 1 ] events = [ev for block in blocks for ev in block] # flatten return events def set_events(events): state["block_events"] = events monkeypatch.setattr( "monitoring_service.service.get_blockchain_events_adaptive", get_blockchain_events ) monkeypatch.setattr( "pathfinding_service.service.get_blockchain_events_adaptive", get_blockchain_events ) return set_events
Example #5
Source File: test_blockchain.py From raiden-services with MIT License | 7 votes |
def test_get_blockchain_events_returns_early_for_invalid_interval( web3: Web3, token_network_registry_contract: Contract ): events = get_blockchain_events( web3=web3, token_network_addresses=[], chain_state=BlockchainState( chain_id=ChainID(1), token_network_registry_address=to_canonical_address( token_network_registry_contract.address ), latest_committed_block=BlockNumber(4), ), from_block=BlockNumber(10), to_block=BlockNumber(5), ) assert len(events) == 0
Example #6
Source File: bcinterface.py From ddash with MIT License | 7 votes |
def __init__(self,host='localhost',port=5001,mainnet=False): self.last_contract_address = None self.last_hash_added = None #self.api = ipfsapi.connect(host='127.0.0.1',port=port) # self.web3 = Web3(HTTPProvider('http://localhost:8545')) if mainnet: ipc_path=os.path.dirname(os.path.realpath(__file__))+'/data_mainnet/geth.ipc' else: ipc_path = os.path.dirname(os.path.realpath(__file__))+'/data/geth.ipc' print("IPCProvider path: ",ipc_path) self.web3 = Web3(IPCProvider(ipc_path)) self.blockNumber = self.web3.eth.blockNumber self.eth_accounts = self.web3.personal.listAccounts self.account_index = 0 self.ethereum_acc_pass = None self.tx = {} print("Initializing a DDASH Interface object.") # log Ethereum accounts to ddash/nfo/ self.write_ethereum_address(mainnet) # contract_name is without the sol extension
Example #7
Source File: test_blockchain.py From raiden-services with MIT License | 7 votes |
def test_get_blockchain_events_adaptive_reduces_block_interval_after_timeout( web3: Web3, token_network_registry_contract: Contract ): chain_state = BlockchainState( chain_id=ChainID(1), token_network_registry_address=to_canonical_address( token_network_registry_contract.address ), latest_committed_block=BlockNumber(4), ) assert chain_state.current_event_filter_interval == DEFAULT_FILTER_INTERVAL with patch("raiden_libs.blockchain.get_blockchain_events", side_effect=ReadTimeout): _ = get_blockchain_events_adaptive( web3=web3, token_network_addresses=[], blockchain_state=chain_state, latest_confirmed_block=BlockNumber(1), ) assert chain_state.current_event_filter_interval == DEFAULT_FILTER_INTERVAL // 5
Example #8
Source File: game.py From agents-aea with Apache License 2.0 | 7 votes |
def has_matching_signatures(self) -> bool: """ Check that the signatures match the terms of trade. :return: True if the transaction has been signed by both parties """ w3 = Web3() singable_message = encode_defunct(primitive=self.sender_hash) result = ( w3.eth.account.recover_message( # pylint: disable=no-member signable_message=singable_message, signature=HexBytes(self.sender_signature), ) == self.sender_addr ) counterparty_signable_message = encode_defunct(primitive=self.counterparty_hash) result = ( result and w3.eth.account.recover_message( # pylint: disable=no-member signable_message=counterparty_signable_message, signature=HexBytes(self.counterparty_signature), ) == self.counterparty_addr ) return result
Example #9
Source File: web3_service.py From django-ethereum-events with MIT License | 7 votes |
def __init__(self, *args, **kwargs): """Initializes the `web3` object. Args: rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional) """ rpc_provider = kwargs.pop('rpc_provider', None) if not rpc_provider: timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10) uri = settings.ETHEREUM_NODE_URI rpc_provider = HTTPProvider( endpoint_uri=uri, request_kwargs={ "timeout": timeout } ) self.web3 = Web3(rpc_provider) # If running in a network with PoA consensus, inject the middleware if getattr(settings, "ETHEREUM_GETH_POA", False): self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) super(Web3Service, self).__init__()
Example #10
Source File: test_service.py From raiden-services with MIT License | 7 votes |
def test_check_pending_transactions( web3: Web3, wait_for_blocks: Callable[[int], None], monitoring_service: MonitoringService ): monitoring_service.context.required_confirmations = 3 monitoring_service.database.add_waiting_transaction(waiting_tx_hash=make_transaction_hash()) for tx_status in (0, 1): tx_receipt = {"blockNumber": web3.eth.blockNumber, "status": tx_status} with patch.object( web3.eth, "getTransactionReceipt", Mock(return_value=tx_receipt) ), patch.object(monitoring_service.database, "remove_waiting_transaction") as remove_mock: for should_call in (False, False, False, True): monitoring_service._check_pending_transactions() # pylint: disable=protected-access # noqa assert remove_mock.called == should_call wait_for_blocks(1)
Example #11
Source File: uri.py From web3.py with MIT License | 7 votes |
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str: """ Return a single block URI after validating that it is the *only* URI in all_blockchain_uris that matches the w3 instance. """ from ethpm.uri import check_if_chain_matches_chain_uri matching_uris = [ uri for uri in all_blockchain_uris if check_if_chain_matches_chain_uri(w3, uri) ] if not matching_uris: raise EthPMValidationError("Package has no matching URIs on chain.") elif len(matching_uris) != 1: raise EthPMValidationError( f"Package has too many ({len(matching_uris)}) matching URIs: {matching_uris}." ) return matching_uris[0]
Example #12
Source File: web3_service.py From django-eth-events with MIT License | 7 votes |
def get_transaction_receipt(self, transaction_hash): """ :param transaction_hash: :raises Web3ConnectionException :raises UnknownTransaction :return: """ try: receipt = self.web3.eth.getTransactionReceipt(transaction_hash) if not receipt: # Might be because a reorg raise UnknownTransaction return receipt except self.connection_exceptions as e: raise Web3ConnectionException('Web3 provider is not connected') from e except Exception as e: raise UnknownTransaction from e
Example #13
Source File: uri.py From web3.py with MIT License | 7 votes |
def create_latest_block_uri(w3: Web3, from_blocks_ago: int = 3) -> URI: """ Creates a block uri for the given w3 instance. Defaults to 3 blocks prior to the "latest" block to accommodate for block reorgs. If using a testnet with less than 3 mined blocks, adjust :from_blocks_ago:. """ chain_id = to_hex(get_genesis_block_hash(w3)) latest_block_tx_receipt = w3.eth.getBlock("latest") target_block_number = BlockNumber(latest_block_tx_receipt["number"] - from_blocks_ago) if target_block_number < 0: raise Exception( f"Only {latest_block_tx_receipt['number']} blocks avaible on provided w3, " f"cannot create latest block uri for {from_blocks_ago} blocks ago." ) recent_block = to_hex(w3.eth.getBlock(target_block_number)["hash"]) return create_block_uri(chain_id, recent_block)
Example #14
Source File: uri.py From web3.py with MIT License | 7 votes |
def check_if_chain_matches_chain_uri(web3: Web3, blockchain_uri: URI) -> bool: chain_id, resource_type, resource_hash = parse_BIP122_uri(blockchain_uri) genesis_block = web3.eth.getBlock("earliest") if encode_hex(genesis_block["hash"]) != chain_id: return False if resource_type == BLOCK: resource = web3.eth.getBlock(resource_hash) else: raise ValueError(f"Unsupported resource type: {resource_type}") if encode_hex(resource["hash"]) == resource_hash: return True else: return False
Example #15
Source File: ethereum_classic.py From clove with GNU General Public License v3.0 | 7 votes |
def find_transaction_details_in_redeem_event(self, recipient_address: str, secret_hash: str, block_number: int): # web3.gastracker.io node does not support filtering # etc-geth.0xinfra.com not is not stable so it is used only for filtering filterable_web3 = Web3(HTTPProvider('https://etc-geth.0xinfra.com/')) event_signature_hash = self.web3.sha3(text="RedeemSwap(address,bytes20,bytes32)").hex() filter_options = { 'fromBlock': block_number, 'address': self.contract_address, 'topics': [ event_signature_hash, '0x' + encode_single('address', recipient_address).hex(), '0x' + encode_single('bytes20', bytes.fromhex(secret_hash)).hex() ] } event_filter = filterable_web3.eth.filter(filter_options) for _ in range(ETH_FILTER_MAX_ATTEMPTS): events = event_filter.get_all_entries() if events: return { 'secret': events[0]['data'][2:], 'transaction_hash': events[0]['transactionHash'].hex() }
Example #16
Source File: time_based.py From web3.py with MIT License | 7 votes |
def _get_weighted_avg_block_time(w3: Web3, sample_size: int) -> float: latest_block_number = w3.eth.getBlock('latest')['number'] constrained_sample_size = min(sample_size, latest_block_number) if constrained_sample_size == 0: raise ValidationError('Constrained sample size is 0') oldest_block = w3.eth.getBlock(BlockNumber(latest_block_number - constrained_sample_size)) oldest_block_number = oldest_block['number'] prev_timestamp = oldest_block['timestamp'] weighted_sum = 0.0 sum_of_weights = 0.0 for i in range(oldest_block_number + 1, latest_block_number + 1): curr_timestamp = w3.eth.getBlock(BlockNumber(i))['timestamp'] time = curr_timestamp - prev_timestamp weight = (i - oldest_block_number) / constrained_sample_size weighted_sum += (time * weight) sum_of_weights += weight prev_timestamp = curr_timestamp return weighted_sum / sum_of_weights
Example #17
Source File: control.py From IPDC with MIT License | 7 votes |
def __init__(self): # Path setting self.Fpath = "/tmp" self.DbPath = "/tmp/.db" # Web3 setting self.web3 = Web3(HTTPProvider('http://localhost:8545')) # DB setting self.conn = sqlite3.connect(self.DbPath+"/FileSign.db") self.c = self.conn.cursor() self.c.execute("create table if not exists AccountEhash(account text, Ehash text, PRIMARY KEY(account))") self.conn.commit() self.c.execute("create table if not exists SendLog(account text, Thash text)") self.conn.commit() self.c.execute("create table if not exists SignFhash(SignHash text, Fhash text, PRIMARY KEY(SignHash))") self.conn.commit() try: self.c.execute("insert into AccountEhash values ('admin','"+str(self.web3.eth.coinbase)+"')") self.conn.commit() except: pass
Example #18
Source File: pm.py From web3.py with MIT License | 7 votes |
def __init__(self, address: Address, w3: Web3) -> None: """ Initializes the class with the on-chain address of the registry, and a web3 instance connected to the chain where the registry can be found. Must set the following properties... * ``self.registry``: A `web3.contract` instance of the target registry. * ``self.address``: The address of the target registry. * ``self.w3``: The *web3* instance connected to the chain where the registry can be found. """ pass # # Write API #
Example #19
Source File: test_time_based_gas_price_strategy.py From web3.py with MIT License | 7 votes |
def test_time_based_gas_price_strategy(strategy_params, expected): fixture_middleware = construct_result_generator_middleware({ 'eth_getBlockByHash': _get_block_by_something, 'eth_getBlockByNumber': _get_block_by_something, }) w3 = Web3( provider=BaseProvider(), middlewares=[fixture_middleware], ) time_based_gas_price_strategy = construct_time_based_gas_price_strategy( **strategy_params, ) w3.eth.setGasPriceStrategy(time_based_gas_price_strategy) actual = w3.eth.generateGasPrice() assert actual == expected
Example #20
Source File: web3_service.py From django-eth-events with MIT License | 7 votes |
def get_block(self, block_identifier, full_transactions=False): """ :param block_identifier: :param full_transactions: :raises Web3ConnectionException :raises UnknownBlock :return: """ try: block = self.web3.eth.getBlock(block_identifier, full_transactions) if not block: raise UnknownBlock return block except self.connection_exceptions: raise Web3ConnectionException('Web3 provider is not connected') except Exception as e: raise UnknownBlock from e
Example #21
Source File: send_echo.py From django-ethereum-events with MIT License | 6 votes |
def handle(self, *args, **options): web3 = Web3(HTTPProvider('http://localhost:8545')) echo_contract = web3.eth.contract(echo_address, abi=echo_abi) txn_hash = echo_contract.functions.echo("hello").transact({'from': settings.WALLET_ADDRESS}) print('Received txn_hash={} ...'.format(txn_hash)) print('Waiting for transaction receipt...') txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash) print('Received transaction receipt: {}'.format(txn_receipt))
Example #22
Source File: decoder.py From django-ethereum-events with MIT License | 6 votes |
def __init__(self, block_number, *args, **kwargs): super(Decoder, self).__init__(*args, **kwargs) self.refresh_state(block_number) self.web3 = Web3()
Example #23
Source File: analyzer.py From pakala with GNU General Public License v3.0 | 6 votes |
def __init__(self, max_wei_to_send, min_wei_to_receive, block="latest"): self.web3 = Web3() self.web3.eth.defaultBlock = block self.max_wei_to_send = max_wei_to_send self.min_wei_to_receive = min_wei_to_receive self.actual_storage = None # Whether or not actual_storage is guaranteed to contain all the storage, # or just a subset of it. Will be False for contracts with a lot of keys # so that we cannot load them all. # For testing we can replace actual_storage with a dict so it's never # actually filled. In that case we can assume it's exhaustive. self.actual_storage_exhaustive = True
Example #24
Source File: web3_service.py From django-eth-events with MIT License | 6 votes |
def get_current_block_number(self) -> int: """ :raises Web3ConnectionException :return: <int> """ try: return self.web3.eth.blockNumber except self.connection_exceptions as e: raise Web3ConnectionException('Web3 provider is not connected') from e
Example #25
Source File: web3_service.py From django-eth-events with MIT License | 6 votes |
def __init__(self, provider, max_workers: int=10, max_batch_requests: int=10, slow_provider_timeout: int=400): """ :param node_uri: Node http address. If uri starts with 'test', EthereumTester will be used :param max_workers: Max workers for multithread calls. 1 -> No multithread :param max_batch_requests: Max requests in the same batch for RPC :param self.slow_provider_timeout: Timeout for time lasting requests (like filters) """ self.provider = provider self.max_workers = max_workers self.max_batch_requests = max_batch_requests self.slow_provider_timeout = slow_provider_timeout self.node_uri = self.get_node_uri() self.web3 = Web3(provider) self.web3_slow = Web3(self.slow_provider) self.http_session = requests.session() # If rinkeby, inject Geth PoA middleware # http://web3py.readthedocs.io/en/latest/middleware.html#geth-style-proof-of-authority try: if int(self.web3.net.version) == RINKEBY_CHAIN_ID: self.web3.middleware_stack.inject(geth_poa_middleware, layer=0) # For tests using dummy connections (like IPC) except (UnhandledRequest, ConnectionError, ConnectionRefusedError, FileNotFoundError): pass
Example #26
Source File: web3.py From brownie with MIT License | 6 votes |
def __init__(self, make_request: Callable, w3: _Web3): self.w3 = w3 self.make_request = make_request
Example #27
Source File: conftest.py From beacon_chain with MIT License | 6 votes |
def w3(tester): web3 = Web3(EthereumTesterProvider(tester)) return web3
Example #28
Source File: Dmqtt.py From IPDC with MIT License | 6 votes |
def AddPeer(message): print("AddPeer : "+message) from web3 import Web3, HTTPProvider web3 = Web3(HTTPProvider('http://localhost:8545')) try: web3.admin.addPeer(message) except: print("Add Peer Fail!!!")
Example #29
Source File: web3.py From brownie with MIT License | 6 votes |
def __init__(self) -> None: super().__init__(HTTPProvider("null")) self.enable_unstable_package_management_api() self.provider = None self._mainnet_w3: Optional[_Web3] = None self._genesis_hash: Optional[str] = None self._chain_uri: Optional[str] = None self._custom_middleware: Set = set()
Example #30
Source File: web3.py From brownie with MIT License | 6 votes |
def _mainnet(self) -> _Web3: # a web3 instance connected to the mainnet if self.isConnected() and CONFIG.active_network["id"] == "mainnet": return self try: mainnet = CONFIG.networks["mainnet"] except KeyError: raise MainnetUndefined("No 'mainnet' network defined") from None if not self._mainnet_w3: uri = _expand_environment_vars(mainnet["host"]) self._mainnet_w3 = _Web3(HTTPProvider(uri)) self._mainnet_w3.enable_unstable_package_management_api() return self._mainnet_w3