def bootstrap_network( cls, economics: BaseEconomics = None ) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']: """For use with metric testing scripts""" registry = InMemoryContractRegistry() testerchain = cls(compiler=SolidityCompiler()) BlockchainInterfaceFactory.register_interface(testerchain) power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD, account=testerchain.etherbase_account) power.activate() testerchain.transacting_power = power origin = testerchain.client.etherbase deployer = ContractAdministrator(deployer_address=origin, registry=registry, economics=economics or cls._default_token_economics, staking_escrow_test_mode=True) secrets = dict() for deployer_class in deployer.upgradeable_deployer_classes: secrets[ deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD _receipts = deployer.deploy_network_contracts(secrets=secrets, interactive=False) return testerchain, registry
def get_registry(self, emitter, debug): try: eth_node = None if self.geth: eth_node = get_provider_process() # Note: For test compatibility. if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=self.provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=self.provider_uri, provider_process=eth_node, poa=self.poa, light=self.light, sync=False, emitter=emitter) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=self.provider_uri) emitter.echo(message="Reading Latest Chaindata...") blockchain.connect() except Exception as e: if debug: raise click.secho(str(e), bold=True, fg='red') raise click.Abort if self.registry_filepath: registry = LocalContractRegistry(filepath=self.registry_filepath) else: registry = InMemoryContractRegistry.from_latest_publication( network=self.network) return registry
def bootstrap_network( cls, registry: Optional[BaseContractRegistry] = None, economics: Economics = None ) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']: """For use with metric testing scripts""" # Provider connection if registry is None: registry = InMemoryContractRegistry() testerchain = cls() if not BlockchainInterfaceFactory.is_interface_initialized( eth_provider_uri=testerchain.eth_provider_uri): BlockchainInterfaceFactory.register_interface( interface=testerchain) # Produce actor deployer_power = TransactingPower( signer=Web3Signer(testerchain.client), account=testerchain.etherbase_account) admin = ContractAdministrator(registry=registry, domain=TEMPORARY_DOMAIN, transacting_power=deployer_power, economics=economics or cls.DEFAULT_ECONOMICS) gas_limit = None # TODO: Gas management - #842 for deployer_class in admin.primary_deployer_classes: admin.deploy_contract(contract_name=deployer_class.contract_name, gas_limit=gas_limit) return testerchain, registry
def connect_blockchain(self, emitter, debug): try: eth_node = None if self.geth: eth_node = get_provider_process() # Note: For test compatibility. if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=self.provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=self.provider_uri, provider_process=eth_node, poa=self.poa, light=self.light, sync=False, emitter=emitter) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=self.provider_uri) emitter.echo(message="Reading Latest Chaindata...") blockchain.connect() return blockchain except Exception as e: if debug: raise click.secho(str(e), bold=True, fg='red') raise click.Abort
def _get_staking_agent(click_config, emitter, geth, poa, provider_uri, registry_filepath): try: ETH_NODE = None if geth: ETH_NODE = get_provider_process() # Note: For test compatibility. if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=provider_uri, provider_process=ETH_NODE, poa=poa, sync=False, show_sync_progress=False) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=provider_uri) emitter.echo(message="Reading Latest Chaindata...") blockchain.connect() except Exception as e: if click_config.debug: raise click.secho(str(e), bold=True, fg='red') raise click.Abort if registry_filepath: registry = LocalContractRegistry(filepath=registry_filepath) else: registry = InMemoryContractRegistry.from_latest_publication() staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=registry) return staking_agent
def _make_testerchain(): """ https://github.com/ethereum/eth-tester # available-backends """ # Monkey patch to prevent gas adjustment import eth eth._utils.headers.GAS_LIMIT_MINIMUM = TEST_GAS_LIMIT eth._utils.headers.GENESIS_GAS_LIMIT = TEST_GAS_LIMIT eth.vm.forks.frontier.headers.GENESIS_GAS_LIMIT = TEST_GAS_LIMIT # Monkey patch to prevent gas estimates def _get_buffered_gas_estimate(web3, transaction, gas_buffer=100000): return TEST_GAS_LIMIT import web3 web3.eth.get_buffered_gas_estimate = _get_buffered_gas_estimate # Create the blockchain testerchain = TesterBlockchain(eth_airdrop=True, free_transactions=True) BlockchainInterfaceFactory.register_interface(interface=testerchain) # Mock TransactingPower Consumption (Deployer) testerchain.transacting_power = TransactingPower( password=INSECURE_DEVELOPMENT_PASSWORD, account=testerchain.etherbase_account) testerchain.transacting_power.activate() return testerchain
def test_geth_deployment_integration(instant_geth_dev_node, test_registry): # TODO: Move to decorator if 'CIRCLECI' in os.environ: pytest.skip("Do not run Geth nodes in CI") blockchain = BlockchainDeployerInterface( provider_process=instant_geth_dev_node) BlockchainInterfaceFactory.register_interface(interface=blockchain) # Make Deployer etherbase = to_checksum_address(instant_geth_dev_node.accounts[0].decode( )) # TODO: Make property on nucypher geth node instances? administrator = ContractAdministrator( registry=test_registry, deployer_address=etherbase, client_password=None) # dev accounts have no password. assert int(blockchain.client.chain_id) == 1337 # Deploy secrets = dict() for deployer_class in administrator.upgradeable_deployer_classes: secrets[deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD administrator.deploy_network_contracts(secrets=secrets, interactive=False)
def testerchain(_testerchain) -> TesterBlockchain: testerchain = _testerchain # Reset chain state pyevm_backend = testerchain.provider.ethereum_tester.backend snapshot = pyevm_backend.chain.get_canonical_block_by_number(0).hash pyevm_backend.revert_to_snapshot(snapshot) coinbase, *addresses = testerchain.client.accounts for address in addresses: balance = testerchain.client.get_balance(address) spent = DEVELOPMENT_ETH_AIRDROP_AMOUNT - balance if spent > 0: tx = {'to': address, 'from': coinbase, 'value': spent} txhash = testerchain.w3.eth.sendTransaction(tx) _receipt = testerchain.wait_for_receipt(txhash) eth_amount = Web3().fromWei(spent, 'ether') testerchain.log.info("Airdropped {} ETH {} -> {}".format( eth_amount, tx['from'], tx['to'])) BlockchainInterfaceFactory.register_interface(interface=testerchain, force=True) yield testerchain
def _get_registry(provider_uri, registry_filepath): BlockchainInterfaceFactory.initialize_interface(provider_uri=provider_uri) if registry_filepath: registry = LocalContractRegistry.from_latest_publication() else: registry = InMemoryContractRegistry.from_latest_publication() return registry
def crawl( general_config, teacher_uri, registry_filepath, min_stake, network, learn_on_launch, provider_uri, influx_host, influx_port, http_port, dry_run, eager, poa, ): """ Gather NuCypher network information. """ # Banner emitter = general_config.emitter emitter.clear() emitter.banner(MONITOR_BANNER.format(CRAWLER)) # Setup BlockchainInterfaceFactory.initialize_interface(provider_uri=provider_uri, poa=poa) registry = _get_registry(registry_filepath, network) middleware = RestMiddleware() # Teacher Ursula sage_node = None if teacher_uri: sage_node = Ursula.from_teacher_uri( teacher_uri=teacher_uri, min_stake=0, # TODO: Where to get this? federated_only=False, # always False network_middleware=middleware, registry=registry) crawler = Crawler(domain=network if network else None, network_middleware=middleware, known_nodes=[sage_node] if teacher_uri else None, registry=registry, start_learning_now=eager, learn_on_same_thread=learn_on_launch, influx_host=influx_host, influx_port=influx_port) emitter.message(f"Network: {network.capitalize()}", color='blue') emitter.message(f"InfluxDB: {influx_host}:{influx_port}", color='blue') emitter.message(f"Provider: {provider_uri}", color='blue') emitter.message(f"Refresh Rate: {crawler._refresh_rate}s", color='blue') message = f"Running Nucypher Crawler JSON endpoint at http://localhost:{http_port}/stats" emitter.message(message, color='green', bold=True) if not dry_run: crawler.start(eager=eager) reactor.run()
def select_client_account(emitter, provider_uri: str, prompt: str = None, default: int = 0, registry=None, show_balances: bool = True, network: str = None) -> str: """ Note: Setting show_balances to True, causes an eager contract and blockchain connection. """ if not provider_uri: raise ValueError( "Provider URI must be provided to select a wallet account.") # Lazy connect the blockchain interface if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=provider_uri, emitter=emitter) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=provider_uri) # Lazy connect to contracts token_agent = None if show_balances: if not registry: registry = InMemoryContractRegistry.from_latest_publication( network) token_agent = NucypherTokenAgent(registry=registry) # Real wallet accounts enumerated_accounts = dict(enumerate(blockchain.client.accounts)) if len(enumerated_accounts) < 1: emitter.echo("No ETH accounts were found.", color='red', bold=True) raise click.Abort() # Display account info header = f'| # | Account ---------------------------------- | Balance -----' \ f'\n=================================================================' emitter.echo(header) for index, account in enumerated_accounts.items(): message = f"| {index} | {account} " if show_balances: message += f" | {NU.from_nunits(token_agent.get_balance(address=account))}" emitter.echo(message) # Prompt the user for selection, and return prompt = prompt or "Select Account" account_range = click.IntRange(min=0, max=len(enumerated_accounts) - 1) choice = click.prompt(prompt, type=account_range, default=default) chosen_account = enumerated_accounts[choice] emitter.echo(f"Selected {choice}:{chosen_account}", color='blue') return chosen_account
def test_upgradeability(temp_dir_path): # Prepare remote source for compilation download_github_dir(GITHUB_SOURCE_LINK, temp_dir_path) solidity_compiler = SolidityCompiler(source_dirs=[SourceDirs(SolidityCompiler.default_contract_dir()), SourceDirs(temp_dir_path)]) # Prepare the blockchain provider_uri = 'tester://pyevm/2' try: blockchain_interface = BlockchainDeployerInterface(provider_uri=provider_uri, compiler=solidity_compiler, gas_strategy=free_gas_price_strategy) blockchain_interface.connect() origin = blockchain_interface.client.accounts[0] BlockchainInterfaceFactory.register_interface(interface=blockchain_interface) blockchain_interface.transacting_power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD, account=origin) blockchain_interface.transacting_power.activate() # Check contracts with multiple versions raw_contracts = blockchain_interface._raw_contract_cache contract_name = AdjudicatorDeployer.contract_name test_adjudicator = len(raw_contracts[contract_name]) > 1 contract_name = StakingEscrowDeployer.contract_name test_staking_escrow = len(raw_contracts[contract_name]) > 1 contract_name = PolicyManagerDeployer.contract_name test_policy_manager = len(raw_contracts[contract_name]) > 1 if not test_adjudicator and not test_staking_escrow and not test_policy_manager: return # Prepare master version of contracts and upgrade to the latest registry = InMemoryContractRegistry() token_deployer = NucypherTokenDeployer(registry=registry, deployer_address=origin) token_deployer.deploy() staking_escrow_deployer = StakingEscrowDeployer(registry=registry, deployer_address=origin) deploy_earliest_contract(blockchain_interface, staking_escrow_deployer) if test_staking_escrow: staking_escrow_deployer.upgrade(contract_version="latest", confirmations=0) if test_policy_manager: policy_manager_deployer = PolicyManagerDeployer(registry=registry, deployer_address=origin) deploy_earliest_contract(blockchain_interface, policy_manager_deployer) policy_manager_deployer.upgrade(contract_version="latest", confirmations=0) if test_adjudicator: adjudicator_deployer = AdjudicatorDeployer(registry=registry, deployer_address=origin) deploy_earliest_contract(blockchain_interface, adjudicator_deployer) adjudicator_deployer.upgrade(contract_version="latest", confirmations=0) finally: # Unregister interface with contextlib.suppress(KeyError): del BlockchainInterfaceFactory._interfaces[provider_uri]
def _initialize_blockchain(poa, provider_uri, emitter): if not BlockchainInterfaceFactory.is_interface_initialized(provider_uri=provider_uri): # Note: For test compatibility. deployer_interface = BlockchainDeployerInterface(provider_uri=provider_uri, poa=poa) BlockchainInterfaceFactory.register_interface(interface=deployer_interface, sync=False, emitter=emitter) else: deployer_interface = BlockchainInterfaceFactory.get_interface(provider_uri=provider_uri) deployer_interface.connect() return deployer_interface
def connect_web3_provider(provider_uri: str) -> None: """ Convenience function for connecting to an ethereum provider now. This may be used to optimize the startup time of some applications by establishing the connection eagarly. """ from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=provider_uri) interface = BlockchainInterfaceFactory.get_interface( provider_uri=provider_uri) interface.connect()
def token_economics(testerchain): # Get current blocktime blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=testerchain.provider_uri) now = blockchain.w3.eth.getBlock(block_identifier='latest').timestamp # Calculate instant start time one_hour_in_seconds = (60 * 60) start_date = now bidding_start_date = start_date # Ends in one hour bidding_end_date = start_date + one_hour_in_seconds cancellation_end_date = bidding_end_date + one_hour_in_seconds economics = StandardTokenEconomics( worklock_boosting_refund_rate=200, worklock_commitment_duration=60, # periods worklock_supply=10 * BaseEconomics._default_maximum_allowed_locked, bidding_start_date=bidding_start_date, bidding_end_date=bidding_end_date, cancellation_end_date=cancellation_end_date, worklock_min_allowed_bid=Web3.toWei(1, "ether")) return economics
def _initialize_blockchain(poa, provider_uri, emitter, ignore_solidity_check, gas_strategy=None): if not BlockchainInterfaceFactory.is_interface_initialized(provider_uri=provider_uri): # Note: For test compatibility. deployer_interface = BlockchainDeployerInterface(provider_uri=provider_uri, poa=poa, ignore_solidity_check=ignore_solidity_check, gas_strategy=gas_strategy) BlockchainInterfaceFactory.register_interface(interface=deployer_interface, sync=False, emitter=emitter) else: deployer_interface = BlockchainInterfaceFactory.get_interface(provider_uri=provider_uri) deployer_interface.connect() return deployer_interface
def paint_contract_status(registry, emitter): blockchain = BlockchainInterfaceFactory.get_interface() application_agent = ContractAgency.get_agent(PREApplicationAgent, registry=registry) contracts = f""" | Contract Deployments | {application_agent.contract_name} .............. {application_agent.contract_address} """ blockchain = f""" | '{blockchain.client.chain_name}' Blockchain Network | Gas Price ................ {Web3.fromWei(blockchain.client.gas_price, 'gwei')} Gwei ETH Provider URI ......... {blockchain.eth_provider_uri} Registry ................. {registry.filepath} """ staking = f""" | PREApplication | Staking Provider Population ....... {application_agent.get_staking_providers_population()} """ sep = '-' * 45 emitter.echo(sep) emitter.echo(contracts) emitter.echo(sep) emitter.echo(blockchain) emitter.echo(sep) emitter.echo(staking) emitter.echo(sep)
def __init__(self, account: str, provider_uri: str = None, password: str = None, cache: bool = False,): """ Instantiates a TransactingPower for the given checksum_address. """ self.blockchain = BlockchainInterfaceFactory.get_or_create_interface(provider_uri=provider_uri) self.__account = account # TODO: Temporary fix for #1128 and #1385. It's ugly af, but it works. Move somewhere else? try: wallets = self.blockchain.client.wallets except AttributeError: is_from_hw_wallet = False else: HW_WALLET_URL_PREFIXES = ('trezor', 'ledger') hw_accounts = [w['accounts'] for w in wallets if w['url'].startswith(HW_WALLET_URL_PREFIXES)] hw_addresses = [to_checksum_address(account['address']) for sublist in hw_accounts for account in sublist] is_from_hw_wallet = account in hw_addresses self.device = is_from_hw_wallet self.__password = password self.__unlocked = False self.__activated = False self.__cache = cache
def __init__(self, registry: BaseContractRegistry, contract: Contract = None, transaction_gas: int = None) -> None: self.log = Logger(self.__class__.__name__) self.registry = registry # NOTE: Entry-point for multi-provider support self.blockchain = BlockchainInterfaceFactory.get_interface() if contract is None: # Fetch the contract contract = self.blockchain.get_contract_by_name( registry=self.registry, name=self.registry_contract_name, proxy_name=self._proxy_name, use_proxy_address=self._forward_address) self.__contract = contract if not transaction_gas: transaction_gas = EthereumContractAgent.DEFAULT_TRANSACTION_GAS_LIMITS self.transaction_gas = transaction_gas super().__init__() self.log.info("Initialized new {} for {} with {} and {}".format( self.__class__.__name__, self.contract.address, self.blockchain.provider_uri, self.registry))
def __init__( self, registry: BaseContractRegistry = None, # TODO: Consider make it non-optional again. See comment in InstanceAgent. eth_provider_uri: Optional[str] = None, contract: Optional[Contract] = None, transaction_gas: Optional[Wei] = None, contract_version: Optional[str] = None): self.log = Logger(self.__class__.__name__) self.registry = registry self.blockchain = BlockchainInterfaceFactory.get_or_create_interface( eth_provider_uri=eth_provider_uri) if not contract: # Fetch the contract contract = self.blockchain.get_contract_by_name( registry=registry, contract_name=self.contract_name, contract_version=contract_version, proxy_name=self._proxy_name, use_proxy_address=self._forward_address) self.__contract = contract self.events = ContractEvents(contract) if not transaction_gas: transaction_gas = EthereumContractAgent.DEFAULT_TRANSACTION_GAS_LIMITS[ 'default'] self.transaction_gas = transaction_gas self.log.info("Initialized new {} for {} with {} and {}".format( self.__class__.__name__, self.contract.address, self.blockchain.eth_provider_uri, str(self.registry)))
def _create_stakeholder(config_file, provider_uri, poa, light, registry_filepath, staking_address, beneficiary_address, allocation_filepath): stakeholder_config = _get_stakeholder_config(config_file, provider_uri, poa, light, registry_filepath) # Now let's check whether we're dealing here with a regular staker or a preallocation staker is_preallocation_staker = (beneficiary_address and staking_address) or allocation_filepath # Configure the individual allocation registry, if needed individual_allocation = None if is_preallocation_staker: if allocation_filepath: if beneficiary_address or staking_address: message = "--allocation-filepath is incompatible with --beneficiary-address and --staking-address." raise click.BadOptionUsage(option_name="--allocation-filepath", message=message) # This assumes the user has an individual allocation file in disk individual_allocation = IndividualAllocationRegistry.from_allocation_file(allocation_filepath) elif beneficiary_address and staking_address: individual_allocation = IndividualAllocationRegistry(beneficiary_address=beneficiary_address, contract_address=staking_address) else: option = "--beneficiary_address" if beneficiary_address else "--staking-address" raise click.BadOptionUsage(option_name=option, message=f"You must specify both --beneficiary-address and --staking-address. " f"Only {option} was provided. As an alternative, you can simply " f"provide an individual allocation with --allocation-file <PATH>") # Lazy initialization of StakeHolder stakeholder = stakeholder_config.produce(initial_address=None, individual_allocation=individual_allocation) blockchain = BlockchainInterfaceFactory.get_interface(provider_uri=provider_uri) # Eager connection return stakeholder, blockchain
def paint_receipt_summary(emitter, receipt, chain_name: str = None, transaction_type=None, provider_uri: str = None): tx_hash = receipt['transactionHash'].hex() emitter.echo("OK", color='green', nl=False, bold=True) if transaction_type: emitter.echo(f" | {transaction_type} | {tx_hash}", color='yellow', nl=False) else: emitter.echo(f" | {tx_hash}", color='yellow', nl=False) emitter.echo(f" ({receipt['gasUsed']} gas)") emitter.echo( f"Block #{receipt['blockNumber']} | {receipt['blockHash'].hex()}") if not chain_name: blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=provider_uri) chain_name = blockchain.client.chain_name try: url = etherscan_url(item=tx_hash, network=chain_name) except ValueError as e: emitter.log.info("Failed Etherscan URL construction: " + str(e)) else: emitter.echo(f" See {url}\n")
def initialize_deployer_interface(emitter: StdoutEmitter, poa: bool, provider_uri, ignore_solidity_check: bool, gas_strategy: str = None, max_gas_price: int = None ) -> BlockchainDeployerInterface: if not BlockchainInterfaceFactory.is_interface_initialized(provider_uri=provider_uri): deployer_interface = BlockchainDeployerInterface(provider_uri=provider_uri, poa=poa, gas_strategy=gas_strategy, max_gas_price=max_gas_price) BlockchainInterfaceFactory.register_interface(interface=deployer_interface, emitter=emitter) else: deployer_interface = BlockchainInterfaceFactory.get_interface(provider_uri=provider_uri) deployer_interface.connect(ignore_solidity_check=ignore_solidity_check) return deployer_interface
def __init__(self, domain: str = None, registry: BaseContractRegistry = None, controller: bool = True, federated_only: bool = False, node_class: object = Ursula, eth_provider_uri: str = None, execution_timeout: int = DEFAULT_EXECUTION_TIMEOUT, *args, **kwargs): self.federated_only = federated_only if not self.federated_only: if not eth_provider_uri: raise ValueError( 'ETH Provider URI is required for decentralized Porter.') if not BlockchainInterfaceFactory.is_interface_initialized( eth_provider_uri=eth_provider_uri): BlockchainInterfaceFactory.initialize_interface( eth_provider_uri=eth_provider_uri) self.registry = registry or InMemoryContractRegistry.from_latest_publication( network=domain) self.application_agent = ContractAgency.get_agent( PREApplicationAgent, registry=self.registry) else: self.registry = NO_BLOCKCHAIN_CONNECTION.bool_value(False) node_class.set_federated_mode(federated_only) super().__init__(save_metadata=True, domain=domain, node_class=node_class, *args, **kwargs) self.log = Logger(self.__class__.__name__) self.execution_timeout = execution_timeout # Controller Interface self.interface = self._interface_class(porter=self) self.controller = NO_CONTROL_PROTOCOL if controller: # TODO need to understand this better - only made it analogous to what was done for characters self.make_cli_controller() self.log.info(self.BANNER)
def test_geth_deployment_integration(instant_geth_dev_node, test_registry): blockchain = BlockchainDeployerInterface( provider_process=instant_geth_dev_node, poa=True) # always poa here. BlockchainInterfaceFactory.register_interface(interface=blockchain) # Make Deployer etherbase = to_checksum_address(instant_geth_dev_node.accounts[0].decode( )) # TODO: Make property on nucypher geth node instances? administrator = ContractAdministrator( registry=test_registry, deployer_address=etherbase, client_password=None) # dev accounts have no password. assert int(blockchain.client.chain_id) == 1337 # Deploy administrator.deploy_network_contracts(interactive=False) # just do it
def from_signer_uri(cls, uri: str, testnet: bool = False) -> 'Web3Signer': from nucypher.blockchain.eth.interfaces import BlockchainInterface, BlockchainInterfaceFactory try: blockchain = BlockchainInterfaceFactory.get_or_create_interface( provider_uri=uri) except BlockchainInterface.UnsupportedProvider: raise cls.InvalidSignerURI(uri) signer = cls(client=blockchain.client) return signer
def events(general_config, registry_options, contract_name, from_block, to_block, event_name): """ Show events associated to NuCypher contracts """ emitter = _setup_emitter(general_config) registry = registry_options.get_registry(emitter, general_config.debug) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=registry_options.provider_uri) if not contract_name: if event_name: raise click.BadOptionUsage( option_name='--event-name', message='--event-name requires --contract-name') contract_names = [ STAKING_ESCROW_CONTRACT_NAME, POLICY_MANAGER_CONTRACT_NAME ] else: contract_names = [contract_name] if from_block is None: # Sketch of logic for getting the approximate block height of current period start, # so by default, this command only shows events of the current period last_block = blockchain.client.w3.eth.blockNumber staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=registry) current_period = staking_agent.get_current_period() current_period_start = datetime_at_period( period=current_period, seconds_per_period=staking_agent.staking_parameters()[0], start_of_period=True) seconds_from_midnight = int( (maya.now() - current_period_start).total_seconds()) blocks_from_midnight = seconds_from_midnight // AVERAGE_BLOCK_TIME_IN_SECONDS from_block = last_block - blocks_from_midnight if to_block is None: to_block = 'latest' # TODO: additional input validation for block numbers emitter.echo(f"Showing events from block {from_block} to {to_block}") for contract_name in contract_names: title = f" {contract_name} Events ".center(40, "-") emitter.echo(f"\n{title}\n", bold=True, color='green') agent = ContractAgency.get_agent_by_contract_name( contract_name, registry) names = agent.events.names if not event_name else [event_name] for name in names: emitter.echo(f"{name}:", bold=True, color='yellow') event_method = agent.events[name] for event_record in event_method(from_block=from_block, to_block=to_block): emitter.echo(f" - {event_record}")
def __fetch_principal_contract(self, contract_address: str = None) -> None: """Fetch the PreallocationEscrow deployment directly from the AllocationRegistry.""" if contract_address is not None: contract_data = self.__allocation_registry.search(contract_address=contract_address) else: contract_data = self.__allocation_registry.search(beneficiary_address=self.beneficiary) address, abi = contract_data blockchain = BlockchainInterfaceFactory.get_interface() principal_contract = blockchain.client.get_contract(abi=abi, address=address, ContractFactoryClass=Contract) self.__principal_contract = principal_contract
def connect_to_blockchain(emitter: StdoutEmitter, provider_uri: str, debug: bool = False, light: bool = False ) -> BlockchainInterface: try: # Note: Conditional for test compatibility. if not BlockchainInterfaceFactory.is_interface_initialized(provider_uri=provider_uri): BlockchainInterfaceFactory.initialize_interface(provider_uri=provider_uri, light=light, emitter=emitter) emitter.echo(message=CONNECTING_TO_BLOCKCHAIN) blockchain = BlockchainInterfaceFactory.get_interface(provider_uri=provider_uri) return blockchain except Exception as e: if debug: raise emitter.echo(str(e), bold=True, color='red') raise click.Abort
def bootstrap_network(cls, economics: BaseEconomics = None) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']: """For use with metric testing scripts""" registry = InMemoryContractRegistry() testerchain = cls() BlockchainInterfaceFactory.register_interface(testerchain) power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD, account=testerchain.etherbase_account) power.activate() testerchain.transacting_power = power origin = testerchain.client.etherbase deployer = ContractAdministrator(deployer_address=origin, registry=registry, economics=economics or cls.DEFAULT_ECONOMICS, staking_escrow_test_mode=True) _receipts = deployer.deploy_network_contracts(interactive=False) return testerchain, registry