def extractBlockData(): while True: blockConfig = eth_config.find_one({'config_id': 1}) export_flag = blockConfig["export_flag"] if export_flag is False: blockid = blockConfig["blockid"] print(blockid) web3 = ThreadLocalProxy( lambda: Web3(IPCProvider(geth_ipc, timeout=300))) # web3 = ThreadLocalProxy(lambda: Web3(HTTPProvider(http_address))) blockidNow = web3.eth.blockNumber print(blockidNow) if blockidNow > blockid: blockConfig["export_flag"] = True blockid += 1 blockConfig["blockid"] = blockid t = time.time() blockConfig['timestamp'] = int(round(t * 1000)) eth_config.save(blockConfig) job = ExportBlocksJob( start_block=blockid, end_block=blockidNow, batch_size=100, ipc_wrapper=ThreadLocalProxy( lambda: IPCWrapper(geth_ipc, timeout=300)), web3=ThreadLocalProxy( lambda: Web3(IPCProvider(geth_ipc, timeout=300))), max_workers=5, blocks_output="", transactions_output="") job.run() time.sleep(3)
def setup_node_session(settings): """ Connects to appropriate node using values specified in settings.py :param str node_type: Type of node, 'Parity', 'Geth' or 'Infura' :param str node_url: url of connection if an HTTP connection """ if settings.NODE_TYPE == 'Parity': # checking if trace tables should be parsed w3 = Web3(IPCProvider(timeout=settings.TIMEOUT)) elif settings.NODE_TYPE == 'Geth': w3 = Web3(IPCProvider()) elif settings.NODE_TYPE == 'Infura': w3 = Web3(HTTPProvider(settings.NODE_URL)) elif settings.NODE_TYPE == 'ParityTCP': w3 = Web3(HTTPProvider(settings.NODE_URL)) else: raise ValueError('Node {} not supported'.format(settings.NODE_TYPE)) if w3.isConnected: logger.info('Connected to {} node'.format(settings.NODE_TYPE)) else: logger.error('{} node failed connecting to network'.format( settings.NODE_TYPE)) return w3
def web3_ipc_persistent(geth_persistent): from web3 import ( Web3, IPCProvider, ) provider = IPCProvider(ipc_path=geth_persistent.ipc_path) provider._geth = geth_persistent web3 = Web3(provider) return web3
def web3_ipc_empty(): from web3 import ( Web3, IPCProvider, ) with setup_testing_geth() as geth: provider = IPCProvider(ipc_path=geth.ipc_path) provider._geth = geth web3 = Web3(provider) yield web3
def add_provider(self, provider: Union[IPCProvider, WebsocketProvider, HTTPProvider] = None, provider_uri: str = None, timeout: int = None) -> None: if not provider_uri and not provider: raise self.NoProvider("No URI or provider instances supplied.") if provider_uri and not provider: uri_breakdown = urlparse(provider_uri) # PyEVM if uri_breakdown.scheme == 'tester': if uri_breakdown.netloc == 'pyevm': from nucypher.utilities.sandbox.constants import PYEVM_GAS_LIMIT genesis_params = PyEVMBackend._generate_genesis_params( overrides={'gas_limit': PYEVM_GAS_LIMIT}) pyevm_backend = PyEVMBackend( genesis_parameters=genesis_params) eth_tester = EthereumTester(backend=pyevm_backend, auto_mine_transactions=True) provider = EthereumTesterProvider( ethereum_tester=eth_tester) elif uri_breakdown.netloc == 'geth': # Hardcoded gethdev IPC provider provider = IPCProvider(ipc_path='/tmp/geth.ipc', timeout=timeout) else: raise ValueError( "{} is an invalid or unsupported blockchain provider URI" .format(provider_uri)) # IPC elif uri_breakdown.scheme == 'ipc': provider = IPCProvider(ipc_path=uri_breakdown.path, timeout=timeout) # Websocket elif uri_breakdown.scheme == 'ws': provider = WebsocketProvider(endpoint_uri=provider_uri) # HTTP elif uri_breakdown.scheme in ('http', 'https'): provider = HTTPProvider(endpoint_uri=provider_uri) else: raise self.InterfaceError( "'{}' is not a blockchain provider protocol".format( uri_breakdown.scheme)) self.__provider = provider
def main(ctx, tracker_address, factory_address, payment_lib_address, request_lib_address, log_level, provider, ipc_path, rpc_host, rpc_port, compiled_assets_path, back_scan_seconds, forward_scan_seconds, back_scan_blocks, forward_scan_blocks): if provider == 'ipc': web3 = Web3(IPCProvider(ipc_path=ipc_path)) elif provider == 'rpc': web3 = Web3(RPCProvider(host=rpc_host, port=rpc_port)) elif provider: provider_class = import_string(provider) web3 = Web3(provider_class()) else: raise click.ClickException("This shouldn't be possible") config = Config( web3, compiled_assets_path=compiled_assets_path, log_level=log_level, tracker_address=tracker_address, factory_address=factory_address, payment_lib_address=payment_lib_address, request_lib_address=request_lib_address, scan_timestamp_range=(back_scan_seconds, forward_scan_seconds), scan_blocks_range=(back_scan_blocks, forward_scan_blocks), ) ctx.web3 = web3 ctx.config = config
def connect(self, uri: str, timeout: int = 30) -> None: """Connects to a provider""" self._remove_middlewares() self.provider = None uri = _expand_environment_vars(uri) try: if Path(uri).exists(): self.provider = IPCProvider(uri, timeout=timeout) except OSError: pass if self.provider is None: if uri.startswith("ws"): self.provider = WebsocketProvider(uri, {"close_timeout": timeout}) elif uri.startswith("http"): self.provider = HTTPProvider(uri, {"timeout": timeout}) else: raise ValueError( "Unknown URI - must be a path to an IPC socket, a websocket " "beginning with 'ws' or a URL beginning with 'http'") try: if self.isConnected(): self.reset_middlewares() except Exception: # checking an invalid connection sometimes raises on windows systems pass
def init_data_validator(): my_provider = IPCProvider("../node/chaindata/geth.ipc") web3 = Web3(my_provider) default_account = web3.eth.accounts[0] web3.personal.unlockAccount(default_account, "", 30000) eth_account = core.utils.eth_create_new_account( web3, '../node/chaindata/keystore') eth_account_check_summ = web3.toChecksumAddress(eth_account["account"]) tx = web3.eth.sendTransaction({ 'from': default_account, 'to': eth_account_check_summ, 'value': web3.toWei(1, "ether"), 'gas': 21000 }) time.sleep(2) # while for node done transaction eth_account['balance'] = web3.eth.getBalance(eth_account_check_summ) ret = { 'blockchain_account': eth_account, } return Response(json.dumps(ret), mimetype='application/json')
def console(ipc_path: Path, use_ipython: bool=True, env: Dict[str, Any]=None, banner: str=DEFAULT_BANNER) -> Any: """ Method that starts the chain, setups the helios CLI and register the cleanup function. """ if env is None: env = {} # if ipc_path is not found, raise an exception with a useful message if not ipc_path.exists(): raise FileNotFoundError(create_missing_ipc_error_message(ipc_path)) # wait to import web3, because it's somewhat large, and not usually used from helios_web3 import HeliosWeb3 as Web3 from web3 import IPCProvider #w3 = web3.Web3(web3.IPCProvider(ipc_path)) w3 = Web3(IPCProvider(ipc_path)) namespace = merge({'w3': w3}, env) if use_ipython: ipython_shell(namespace, banner)() else: python_shell(namespace, banner)()
def __init__(self, from_block=0, ipc_provider=ipc_provider): self.web3 = Web3(IPCProvider(ipc_provider)) self.from_block = from_block self.client = self.conection_stor() self.balance = ClientBalance(balance_server) #self.web3.personal.unlockAccount('0xe630f8dd65f9be1ef2588da43c83b697a270d12e', "eth2018") self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
def main(): """ Compile the Solidity contract using the set options and write it to a file JSON file """ compiled_sol = compile_standard(create_options('contracts/Tester.sol')) # Test intstance w3 = Web3(IPCProvider(NODE_ADDRESS)) w3.middleware_onion.inject(geth_poa_middleware, layer=0) # Pre funded account w3.eth.defaultAccount = w3.eth.accounts[0] # To deploy a Solidity Contract on Ethereum you need the contract's # bytecode and ABI bytecode = compiled_sol['contracts']['contracts/Tester.sol']['Tester'][ 'evm']['bytecode']['object'] abi = json.loads(compiled_sol['contracts']['contracts/Tester.sol'] ['Tester']['metadata'])['output']['abi'] SolContract = w3.eth.contract(abi=abi, bytecode=bytecode) tx_hash = SolContract.constructor().transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) print(tx_receipt.contractAddress) contract_ = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi) tx_hash = contract_.functions.setMessage('Nihao').transact() tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) print(contract_.functions.getMessage().call())
def init_data_owner(): my_provider = IPCProvider("../node/chaindata/geth.ipc") web3 = Web3(my_provider) # data = {"data": "data owner data", # "data_validator": "0x" + secrets.token_bytes(20).hex()} data = request.get_json() if data.get("data") == None or data.get("data_validator") == None: return Response('{"error": "Bad request"}', status=400, mimetype='application/json') data_validator = data['data_validator'] encrypted = validator.encrypt2(str(data['data'])) encrypted_body = encrypted['encrypted'] encrypted_private_key = encrypted['private_key'] blockchain_account = eth_create_new_account(web3, '../node/chaindata/keystore') encrypted_file_name = f"{blockchain_account['account'].split('0x')[1]}_{data_validator.split('0x')[1]}".lower( ) url_encrypted_file = f"http://storage.prometeus.io/{encrypted_file_name}" new_file = open(f"../storage/{encrypted_file_name}", "wb") new_file.write(encrypted_body) new_file.close() ret = { 'blockchain_account': blockchain_account, 'storage_url': url_encrypted_file, 'data_validator': data_validator, 'private_key': encrypted_private_key.hex(), 'md5': hashlib.md5(encrypted_body).hexdigest() } return Response(json.dumps(ret), mimetype='application/json')
def __call__(self, *args, **kwargs): try: if self.type == 'infura': self.web3 = Web3( HTTPProvider('https://' + self.network + '.infura.io/v3/' + self.token)) if self.network == 'rinkeby': self.web3.middleware_stack.inject(geth_poa_middleware, layer=0) elif self.type == 'local' or self.type == 'ipc': #Default location for geth. self.web3 = Web3(IPCProvider()) self.time = time.asctime(time.localtime()) except Exception as e: print(e + ' ' + str(type(e))) raise exc.Connection('__call__') else: #print('...Connection established with the ' + self.network + ' Ethereum network') logging.info('...Connection established with the ' + self.network + ' Ethereum network') if self.web3.isConnected(): #print('...Active connection at : ' + self.time) logging.info('...Active connection at : ' + self.time) self.running = True return True
def __init__(self): self.work_dir = os.environ['WORK_DIR'] self.ballotregulator_ip = os.environ['TWISTED_BALLOTREGULATOR_IP'] self.web3 = Web3(IPCProvider("/usr/src/ethereumDB/testnet/geth.ipc")) # self.web3 = Web3(KeepAliveRPCProvider( host=self.ballotregulator_ip)) self.abi = Network.request_contract_abi().wait(5)
def create_provider(config): """Create a web3.py provider :param config: Provider configuration (compatible with :meth:`consensys_utils.config.schema.web3.Web3ConfigSchema`) :type config: dict """ provider, opts = config.get('ETHEREUM_PROVIDER'), config.get( 'ETHEREUM_OPTS', {}) if provider == 'http': from web3 import HTTPProvider return HTTPProvider(endpoint_uri=config.get('ETHEREUM_ENDPOINT_URI'), **opts) elif provider == 'ipc': from web3 import IPCProvider return IPCProvider(ipc_path=config.get('ETHEREUM_IPC_PATH'), **opts) elif provider == 'ws': from web3 import WebsocketProvider return WebsocketProvider( endpoint_uri=config.get('ETHEREUM_ENDPOINT_URI'), **opts) elif provider == 'test': from web3 import EthereumTesterProvider return EthereumTesterProvider() else: raise RuntimeError( "'ETHEREUM_PROVIDER' configuration must be one of 'http', 'ipc', 'ws', 'test'" )
def get_chain(provider: str, chain_name='mainnet', infura_key='') -> web3.Web3: """ A convenient wrapper for most common web3 backend sources.""" from web3 import Web3, HTTPProvider, IPCProvider, TestRPCProvider from web3.providers.eth_tester import EthereumTesterProvider from eth_tester import EthereumTester infura_url = f'https://{chain_name}.infura.io/{infura_key}' providers = { 'tester': lambda: EthereumTesterProvider(EthereumTester()), 'testrpc': lambda: TestRPCProvider(), 'http': lambda: HTTPProvider("http://localhost:8545"), 'parity': lambda: IPCProvider(parity_ipc()), 'geth': lambda: IPCProvider(geth_ipc(chain_name)), 'infura': lambda: HTTPProvider(infura_url) } return Web3(providers[provider]())
def _test_get_accounts_with_receivable_transactions(): w3 = Web3(IPCProvider(ipc_path)) INSTANCE_0 = get_primary_node_private_helios_key(0) new_account_address_hex_1 = w3.personal.newAccount(test_password) new_account_address_hex_2 = w3.personal.newAccount(test_password) tx = [{ 'from': INSTANCE_0.public_key.to_checksum_address(), 'to': new_account_address_hex_1, 'value': 1 }, { 'from': INSTANCE_0.public_key.to_checksum_address(), 'to': new_account_address_hex_1, 'value': 1 }, { 'from': INSTANCE_0.public_key.to_checksum_address(), 'to': new_account_address_hex_2, 'value': 1 }] print("Sending transactions") w3.personal.sendTransactions(tx, 'dev') time.sleep(0.5) print("Getting accounts over all time") accounts_with_receivable = w3.personal.getAccountsWithReceivableTransactions( ) assert (new_account_address_hex_1 in accounts_with_receivable and new_account_address_hex_2 in accounts_with_receivable) print("Getting accounts over short time") accounts_with_receivable = w3.personal.getAccountsWithReceivableTransactions( int(time.time()) - 10) assert (new_account_address_hex_1 in accounts_with_receivable and new_account_address_hex_2 in accounts_with_receivable) print("Getting accounts over future time") accounts_with_receivable = w3.personal.getAccountsWithReceivableTransactions( int(time.time()) + 1) assert (accounts_with_receivable == []) print("Receiving transactions") w3.personal.receiveTransactions(new_account_address_hex_1, test_password) w3.personal.receiveTransactions(new_account_address_hex_2, test_password) time.sleep(0.5) print("Getting accounts over all time") accounts_with_receivable = w3.personal.getAccountsWithReceivableTransactions( ) assert (new_account_address_hex_1 not in accounts_with_receivable and new_account_address_hex_2 not in accounts_with_receivable) print("Getting accounts over short time") accounts_with_receivable = w3.personal.getAccountsWithReceivableTransactions( int(time.time()) - 10) assert (new_account_address_hex_1 not in accounts_with_receivable and new_account_address_hex_2 not in accounts_with_receivable)
def deploy_contract(web3, contract_interface): ''' Deploys a contract to the blockchain. ''' web3 = Web3(IPCProvider(config.ipc_endpoint())) # Instantiate contract contract = web3.eth.contract(contract_interface['abi'], bytecode=contract_interface['bin']) # Get transaction hash from deployed contract tx_hash = contract.deploy(transaction={ 'from': web3.eth.accounts[0], 'gas': 1000000 }) print(f'tx_hash: {tx_hash}') # wait for contract deployment transaction to be mined tx_receipt = wait_for_mining(tx_hash) contract_address = tx_receipt['contractAddress'] print(f'Contract deployed to blockchain with address: {contract_address}') return contract_address
def __init__(self, host='localhost', port=5001, mainnet=False, mac=False): self.last_contract_address = None self.last_hash_added = None # self.api = ipfsapi.connect(host='127.0.0.1',port=port) # these are commented about because we're using IPCProvider, # rather than HTTPProvider, to connect to geth # self.web3 = Web3(HTTPProvider('http://localhost:8545')) if mainnet: #ipc_path=os.path.dirname(os.path.realpath(__file__))+'/data_mainnet/geth.ipc' if mac: ipc_path = expanduser("~") + '/Library/Ethereum/geth.ipc' else: ipc_path = expanduser("~") + '/.ethereum/geth.ipc' else: ipc_path = os.path.dirname( os.path.realpath(__file__)) + '/data_privnet/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 simbel/nfo/ self.write_ethereum_address(mainnet)
def manual_geth_ipc_provider(): """ Provider backend https:// github.com/ethereum/eth-tester """ ipc_provider = IPCProvider(ipc_path='/tmp/geth.ipc') yield ipc_provider
def on_data(self, raw_data): # TwitterStreamer.sol Smart Contract address which was provided during `truffle deploy` # contract_address = '0x244C6C98918C5c1D698334909fA77e76358c7857' <-- this already exists on Swisscom POA contract_address = '<FILL IN CONTRACT ADDRESS SHOWN AFTER TRUFFLE DEPLOY>' # Address which receives the Token - Only use if you want to hard-code recipient # receiver_address = '<FILL IN RECIPIENT ADDRESS>' try: json_load = json.loads(raw_data) text = json_load['text'] coded = text.encode('utf-8') s = str(coded) print("########## NEW TWEET: Nr: %i ########## \n" % (self.i), s[2:-1]) self.i += 1 # Receiver Address should be included in Tweet. If hard-coded above then comment out next line receiver_address = re.search("0x.{40}", s).group() print("Receiver Address is: ", receiver_address) with open("./contractJSONABI.json") as f: info_json = json.load(f) abi = info_json w3 = Web3(IPCProvider('~/poa/geth.ipc')) w3.middleware_stack.inject(geth_poa_middleware, layer=0) free_tokkens_instance = w3.eth.contract( address=contract_address, abi=abi, ) ''' set sender account (Account from ganache). Account [0] is the private key of the Smart Contract owner. Truffle deploy uses ganache-cli ganache-cli has the private key implmented in the node. Default key: [0] ''' w3.eth.defaultAccount = w3.eth.accounts[0] '''send message to contract. ''' print('Get some Tokens...') tx_hash = free_tokkens_instance.functions.tweetToken( receiver_address).transact() # Wait for transaction to be mined... w3.eth.waitForTransactionReceipt(tx_hash) ''' Read out the balance of the recipient ''' print('Balance: {}'.format( free_tokkens_instance.functions.balanceOf( receiver_address).call())) # Save tweets to file for analysis if needed with open(self.fetched_tweets_filename, 'a') as tf: tf.write(raw_data) return True except BaseException as e: print("Error on raw_data: %s" % str(e)) return True
def create_provider_from_config(rpc_config: MutableMapping): uri = rpc_config.get("uri", None) if uri is not None: logger.info(f"Autodetect provider from uri {uri}") provider = load_provider_from_uri(uri) logger.info(f"Autodetected {provider.__class__.__name__}") return provider provider_type = rpc_config["type"] if provider_type is ProviderType.HTTP: url = "{}://{}:{}".format( "https" if rpc_config["use_ssl"] else "http", rpc_config["host"], rpc_config["port"], ) logger.info("Using HTTP provider with URL {}".format(url)) return HTTPProvider(URI(url)) elif provider_type is ProviderType.WEBSOCKET: url = "{}://{}:{}".format( "wss" if rpc_config["use_ssl"] else "ws", rpc_config["host"], rpc_config["port"], ) logger.info("Using websocket provider with URL {}".format(url)) return WebsocketProvider(URI(url)) elif provider_type is ProviderType.IPC: file_path = rpc_config["file_path"] logger.info("Using IPC provider with file path {}".format(file_path)) return IPCProvider(file_path) else: raise ValueError(f"Unknown web3 provider type: {provider_type}")
def create_txs(ipc_path, rpc_host, rpc_port, signer_addr, airdropper_addr, omgtoken_addr, verify_eth, processed_file, unsigned_file): if ipc_path and (rpc_host or rpc_port): raise Exception("both ipc and rpc cannot be specified") if ipc_path: web3 = Web3(IPCProvider(ipc_path)) else: web3 = Web3(RPCProvider(host=rpc_host, port=rpc_port)) airdropper, omgToken = get_contracts(web3, airdropper_addr=airdropper_addr, omgtoken_addr=omgtoken_addr) creator = Creator(signer_addr, airdropper, omgToken, GAS_LIMIT, GAS_PRICE, GAS_RESERVE, verify_eth=verify_eth) airdrops = json.loads(processed_file.read()) unsigned = creator.create_txs(airdrops, BATCH_SIZE) unsigned_file.write(json.dumps(unsigned, sort_keys=True))
def __init__(self, ipc_path: str = DEFAULT_IPC_PATH, timeout: int = TIMEOUT): super().__init__() self.w3 = Web3(provider=IPCProvider(ipc_path=ipc_path, timeout=timeout) ) # TODO: Unify with clients or build error handling self.ipc_path = ipc_path
def create_provider(config): """Create a web3.py provider :param config: Provider configuration :type config: dict """ provider, opts = config.get('ETHEREUM_PROVIDER', ETHEREUM_PROVIDER), config.get( 'ETHEREUM_OPTS', ETHEREUM_OPTS) if provider == 'http': return HTTPProvider(endpoint_uri=config.get('ETHEREUM_ENDPOINT_URI', ETHEREUM_ENDPOINT_URI), **opts) elif provider == 'ipc': return IPCProvider(ipc_path=config.get('ETHEREUM_IPC_PATH', ETHEREUM_IPC_PATH), **opts) elif provider == 'ws': return WebsocketProvider(endpoint_uri=config.get( 'ETHEREUM_ENDPOINT_URI', ETHEREUM_ENDPOINT_URI), **opts) elif provider == 'test': return EthereumTesterProvider() else: raise Exception( "'ETHEREUM_PROVIDER' configuration must be one of 'http', 'ipc', 'ws', 'test'" )
def connect(self, node: str, timeout: int = 10) -> None: try: if os.path.exists(node): self.provider = IPCProvider(node) return except OSError: pass if node.startswith("https://") or node.startswith("http://"): self.provider = HTTPProvider(node, request_kwargs={"timeout": timeout}) elif node.startswith("ws://") or node.startswith("wss://"): self.provider = WebsocketProvider( node, websocket_kwargs={"timeout": timeout}) else: raise ValueError( "The provided node is not valid. It must start with 'http://' or 'https://' or 'ws://' or a path to an IPC socket file." ) try: self.handleEnode() except Exception: pass try: self.handleProofOfAuthorityChain() except Exception: pass
def __init__(self): self.figure = plt.figure() self.web3 = Web3(IPCProvider()) self.G = nx.DiGraph() self.proximity_tolerance = 0.03 self.run = True self.UPDATE_TIME = 0.000001
def __init__(self, settings): self.apiurl: str = settings["apiUrl"] self.testmode = False if "providerType" in settings: pT = settings["providerType"] if pT == "HTTPProvider": self.provider: Web3 = Web3( HTTPProvider(settings["providerUrl"])) elif pT == "IPCProvider": self.provider: Web3 = Web3(IPCProvider( settings["providerUrl"])) elif pT == "WebsocketProvider": self.provider: Web3 = Web3( WebsocketProvider(settings["providerUrl"])) else: self.provider: Web3 = Web3(HTTPProvider(settings["providerUrl"])) if "mnemonicKey" in settings: self.wallet: Account = Account.privateKeyToAccount( mnemonic_to_private_key(settings["mnemonicKey"])) if "privateKey" in settings: self.wallet: Account = Account.privateKeyToAccount( str(settings["privateKey"])) self.blockchain: str = str(settings["blockchain"]).lower() self.myaddress: str = self.wallet.address self.query = RequestManager(self.apiurl, self.provider, self.wallet, self.blockchain) if "testMode" in settings: if bool(settings["testMode"]) == True: print("TEST MODE ENABLED, TRANSACTION WONT BE BROADCASTED") self.testmode = True # The following flag values default to False, to allow the simplest and best trading experience for most users. # SBTKN False means TRADES ARE REQUESTED IN DECIMAL TOKEN UNITS. True means they are requested in integer subtoken units. # BNDL False means WE DO NOT ALLOW BUNDLE PRICING ON NEW ORDERS, ONLY INTEGER PRICES. True means we allow Fraction prices. # STRICT False means WE CREATE OR EXECUTE NEAREST VALID TRADE <= REQUESTED TRADE. True means invalid trades throw an error. # These flags can and should be ignored and left out of function calls unless the user wants to change them. self.SBTKN = False self.STRICT = False self.BNDL = False self.DEBUG = False if "SBTKN" in settings: self.SBTKN = settings["SBTKN"] if "STRICT" in settings: self.STRICT = settings["STRICT"] if "BNDL" in settings: self.BNDL = settings["BNDL"] if "DEBUG" in settings: self.DEBUG = settings["DEBUG"] self.exchange = ExchangeInterface(self.provider, self.wallet, self.query, self.blockchain, self.testmode, self.SBTKN, self.STRICT, self.BNDL, self.DEBUG) print("TRADING WALLET: " + self.myaddress)
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)
def __init__(self, provider=None, data_dir=None, RPC_url=None): self.data_dir = path.join(path.expanduser('~'), '.ethereum', 'sentinel') if data_dir is None else data_dir self.provider = 'ipc' if provider is None \ else provider self.ipc_path = path.join(self.data_dir, 'geth.ipc') self.web3 = Web3(IPCProvider(self.ipc_path)) if self.provider == 'ipc' \ else Web3(HTTPProvider(RPC_url))