Python web3.HTTPProvider() Examples
The following are 30
code examples of web3.HTTPProvider().
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: 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 #2
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 #3
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 #4
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 #5
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 #6
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
Example #7
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 #8
Source File: ethereum_processor.py From SempoBlockchain with GNU General Public License v3.0 | 6 votes |
def __init__(self, contract_address, contract_abi_string, ethereum_chain_id, http_provider, websocket_provider, gas_price_gwei, gas_limit,): self.abi_dict = json.loads(contract_abi_string) self.contract_address = utils.checksum_encode(contract_address) self.ethereum_chain_id = int(ethereum_chain_id) self.w3 = Web3(HTTPProvider(http_provider)) # self.wsw3 = Web3(WebsocketProvider(websocket_provider)) self.contract = self.w3.eth.contract(address=self.contract_address, abi=self.abi_dict) self.decimals = self.get_decimals() self.gas_price = self.w3.toWei(gas_price_gwei, 'gwei') self.gas_limit = gas_limit self.transaction_max_value = self.gas_price * self.gas_limit
Example #9
Source File: gas_station.py From safe-relay-service with MIT License | 6 votes |
def __init__(self, http_provider_uri='http://localhost:8545', number_of_blocks: int = 200, cache_timeout_seconds: int = 10 * 60, constant_gas_increment: int = 1): # Increase a little for fastest mining for API Calls self.http_provider_uri = http_provider_uri self.http_session = requests.session() self.number_of_blocks = number_of_blocks self.cache_timeout = cache_timeout_seconds self.constant_gas_increment = constant_gas_increment self.w3 = Web3(HTTPProvider(http_provider_uri)) try: if self.w3.net.version != 1: self.w3.middleware_onion.inject(geth_poa_middleware, layer=0) # For tests using dummy connections (like IPC) except (ConnectionError, FileNotFoundError): self.w3.middleware_onion.inject(geth_poa_middleware, layer=0)
Example #10
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 #11
Source File: mint_tokens.py From raiden-contracts with MIT License | 6 votes |
def main(rpc_url: URI, private_key: Path, token_address: ChecksumAddress, amount: int) -> None: web3 = Web3(HTTPProvider(rpc_url)) privkey = get_private_key(private_key) assert privkey is not None owner = private_key_to_address(privkey) web3.middleware_onion.add(construct_sign_and_send_raw_middleware(privkey)) token_code = web3.eth.getCode(token_address, "latest") assert token_code != HexBytes("") token_contract = ContractManager(contracts_precompiled_path()).get_contract( CONTRACT_CUSTOM_TOKEN ) token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"]) tx_hash = token_proxy.functions.mint(amount).transact({"from": owner}) print(f"Minting tokens for address {owner}") print(f"Transaction hash {encode_hex(tx_hash)}") balance = token_proxy.functions.balanceOf(owner).call() print(f"Balance of {owner}: {balance}")
Example #12
Source File: utils.py From snet-cli with MIT License | 5 votes |
def get_web3(rpc_endpoint): if rpc_endpoint.startswith("ws:"): provider = web3.WebsocketProvider(rpc_endpoint) else: provider = web3.HTTPProvider(rpc_endpoint) return web3.Web3(provider)
Example #13
Source File: deployer.py From plasma-mvp with MIT License | 5 votes |
def deploy_contract(self, contract_name, gas=5000000, args=(), concise=True): """Deploys a contract to the given Ethereum network using Web3 Args: contract_name (str): Name of the contract to deploy. Must already be compiled. provider (HTTPProvider): The Web3 provider to deploy with. gas (int): Amount of gas to use when creating the contract. args (obj): Any additional arguments to include with the contract creation. concise (bool): Whether to return a Contract or ConciseContract instance. Returns: Contract: A Web3 contract instance. """ abi, bytecode = self.get_contract_data(contract_name) contract = self.w3.eth.contract(abi=abi, bytecode=bytecode) # Get transaction hash from deployed contract tx_hash = contract.deploy(transaction={ 'from': self.w3.eth.accounts[0], 'gas': gas }, args=args) # Get tx receipt to get contract address tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash) contract_address = tx_receipt['contractAddress'] contract_instance = self.w3.eth.contract(address=contract_address, abi=abi) print("Successfully deployed {0} contract!".format(contract_name)) return ConciseContract(contract_instance) if concise else contract_instance
Example #14
Source File: __init__.py From snet-cli with MIT License | 5 votes |
def __init__( self, config, metadata_provider=None ): self._config = config self._metadata_provider = metadata_provider # Instantiate Ethereum client eth_rpc_endpoint = self._config.get("eth_rpc_endpoint", "https://mainnet.infura.io/v3/e7732e1f679e461b9bb4da5653ac3fc2") provider = web3.HTTPProvider(eth_rpc_endpoint) self.web3 = web3.Web3(provider) self.web3.eth.setGasPriceStrategy(medium_gas_price_strategy) # Get MPE contract address from config if specified; mostly for local testing _mpe_contract_address = self._config.get("mpe_contract_address", None) if _mpe_contract_address is None: self.mpe_contract = MPEContract(self.web3) else: self.mpe_contract = MPEContract(self.web3, _mpe_contract_address) # Instantiate IPFS client ipfs_rpc_endpoint = self._config.get("ipfs_rpc_endpoint", "https://ipfs.singularitynet.io:80") ipfs_rpc_endpoint = urlparse(ipfs_rpc_endpoint) ipfs_scheme = ipfs_rpc_endpoint.scheme if ipfs_rpc_endpoint.scheme else "http" ipfs_port = ipfs_rpc_endpoint.port if ipfs_rpc_endpoint.port else 5001 self.ipfs_client = ipfsapi.connect(urljoin(ipfs_scheme, ipfs_rpc_endpoint.hostname), ipfs_port) # Get Registry contract address from config if specified; mostly for local testing _registry_contract_address = self._config.get("registry_contract_address", None) if _registry_contract_address is None: self.registry_contract = get_contract_object(self.web3, "Registry.json") else: self.registry_contract = get_contract_object(self.web3, "Registry.json", _registry_contract_address) self.account = Account(self.web3, config, self.mpe_contract)
Example #15
Source File: blockchain.py From raiden-services with MIT License | 5 votes |
def get_web3_provider_info(web3: Web3) -> str: """ Returns information about the provider Currently works only with `HTTPProvider`. Needs to be adapted when new procviders are added. """ provider = web3.provider if isinstance(provider, HTTPProvider): endpoint = provider.endpoint_uri if endpoint is not None: return str(endpoint) elif isinstance(provider, EthereumTesterProvider): return "EthereumTesterProvider" raise RuntimeError(f"Unsupported web3 provider {provider!r}")
Example #16
Source File: token_ops.py From raiden-contracts with MIT License | 5 votes |
def __init__( self, rpc_url: URI, private_key: Path, password: Optional[Path] = None, wait: int = 10 ): self.web3 = Web3(HTTPProvider(rpc_url)) self.private_key = get_private_key(private_key, password) assert self.private_key is not None self.owner = private_key_to_address(self.private_key) self.wait = wait self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(self.private_key)) self.web3.eth.defaultAccount = self.owner # type: ignore self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
Example #17
Source File: token_ops.py From raiden-contracts with MIT License | 5 votes |
def balance(rpc_url: URI, token_address: str, address: str) -> None: token_address = to_checksum_address(token_address) address = to_checksum_address(address) web3 = Web3(HTTPProvider(rpc_url)) token_contract = ContractManager(contracts_precompiled_path()).get_contract( CONTRACT_CUSTOM_TOKEN ) token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"]) balance = token_proxy.functions.balanceOf(address).call() print(f"Balance of the {address} : {balance}")
Example #18
Source File: __main__.py From raiden-contracts with MIT License | 5 votes |
def verify(_: Any, rpc_provider: URI, contracts_version: Optional[str]) -> None: web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={"timeout": 60})) web3.middleware_onion.inject(geth_poa_middleware, layer=0) print("Web3 provider is", web3.provider) verifier = ContractVerifier(web3=web3, contracts_version=contracts_version) verifier.verify_deployed_contracts_in_filesystem()
Example #19
Source File: broadcast_users.py From CryptoKitties with MIT License | 5 votes |
def broadcast_user(self,user_info,att_list): return_dict = {} web3 = Web3(HTTPProvider('http://localhost:8545')) trigger = True counter = user_info[3] while trigger: try: url = "https://api.cryptokitties.co/auctions?offset="+str(counter)+self.urls(user_info[1]) json_data = sess.get(url).json() if counter <= user_info[4]: if json_data['auctions']: proc_json = self.process_json(json_data,user_info,att_list,return_dict,web3) if proc_json: counter += 100 #print (str(counter)+" has been scraped.") This print is for debugging purposes only. else: #if not r auctions means the api timed. time.sleep(15) else: trigger = False except Exception as e: if "Invalid Retry-After header:" not in str(e): #only log exceptions that arent invalid retries. with open('logs.txt','a') as f: f.write(str(e)) f.write(traceback.format_exc()) return return_dict
Example #20
Source File: root_event_listener.py From plasma-mvp with MIT License | 5 votes |
def __init__(self, root_chain, w3=Web3(HTTPProvider('http://localhost:8545')), confirmations=6): self.root_chain = root_chain self.w3 = w3 self.confirmations = confirmations self.seen_events = {} self.active_events = {} self.subscribers = {} self.__listen_for_event('Deposit') self.__listen_for_event('ExitStarted')
Example #21
Source File: client.py From plasma-mvp with MIT License | 5 votes |
def __init__(self, root_chain_provider=HTTPProvider('http://localhost:8545'), child_chain_url="http://localhost:8546/jsonrpc"): deployer = Deployer(root_chain_provider) self.root_chain = deployer.get_contract_at_address("RootChain", CONTRACT_ADDRESS, concise=True) self.child_chain = ChildChainService(child_chain_url)
Example #22
Source File: deployer.py From plasma-mvp with MIT License | 5 votes |
def __init__(self, provider=HTTPProvider('http://localhost:8545')): self.w3 = Web3(provider)
Example #23
Source File: ethereum.py From agents-aea with Apache License 2.0 | 5 votes |
def __init__(self, address: str, gas_price: str = DEFAULT_GAS_PRICE): """ Initialize the Ethereum ledger APIs. :param address: the endpoint for Web3 APIs. """ self._api = Web3(HTTPProvider(endpoint_uri=address)) self._gas_price = gas_price
Example #24
Source File: txbatch.py From ethgasstation-backend with GNU General Public License v3.0 | 5 votes |
def _setRequestFromProvider(self, web3_provider): """Get the RPC HTTP endpoint URI from an instantiated Web3 provider.""" for provider in web3_provider.providers: if isinstance(provider, HTTPProvider): self.endpoint_uri = provider.endpoint_uri self.timeout = provider.egs_timeout
Example #25
Source File: test_web3_service.py From django-eth-events with MIT License | 5 votes |
def test_provider_http(self): with self.settings(ETHEREUM_NODE_URL='http://localhost:8545'): web3_service = Web3ServiceProvider() provider = web3_service.web3.providers[0] self.assertTrue(isinstance(provider, HTTPProvider)) with self.settings(ETHEREUM_NODE_URL='https://localhost:8545'): web3_service = Web3ServiceProvider() provider = web3_service.web3.providers[0] self.assertTrue(isinstance(provider, HTTPProvider))
Example #26
Source File: test_reorg_detector.py From django-eth-events with MIT License | 5 votes |
def setUp(self): # Run mocked testrpc for reorgs print('Starting httpd...') self.server_process = Process(target=start_mock_server) self.server_process.start() cache.set('block_number', '0x0') sleep(1) print('served') self.provider = HTTPProvider('http://localhost:8545') self.web3_service = Web3Service(self.provider) # Mock web3 self.daemon = DaemonFactory()
Example #27
Source File: test_singleton.py From django-eth-events with MIT License | 5 votes |
def test_arg_ipc_provider(self): ipc_provider = IPCProvider( ipc_path=None, testnet=True ) service1 = Web3ServiceProvider() self.assertIsInstance(service1.web3.providers[0], HTTPProvider) service2 = Web3Service(ipc_provider) self.assertIsInstance(service2.web3.providers[0], IPCProvider) self.assertEqual(service2.web3.providers[0], ipc_provider)
Example #28
Source File: web3_service.py From django-eth-events with MIT License | 5 votes |
def has_http_provider(self): return isinstance(self.main_provider, HTTPProvider)
Example #29
Source File: web3_service.py From django-eth-events with MIT License | 5 votes |
def get_node_uri(self) -> str: if isinstance(self.provider, HTTPProvider): return self.provider.endpoint_uri
Example #30
Source File: web3_service.py From django-eth-events with MIT License | 5 votes |
def slow_provider(self): if isinstance(self.provider, HTTPProvider): return HTTPProvider(endpoint_uri=self.provider.endpoint_uri, request_kwargs={'timeout': self.slow_provider_timeout}) elif isinstance(self.provider, IPCProvider): return IPCProvider(ipc_path=self.provider.ipc_path, timeout=self.slow_provider_timeout) else: return self.provider