def load_proj(proj_name: str): p = project.load(f'../{proj_name}', name=proj_name) p.load_config() # from brownie.project.oracles import * if not network.is_connected(): network.connect('development') return p
def make_project(db, configuration: Config): rmtree(brownie_project_folder, ignore_errors=True) # init brownie project structure project.new(brownie_project_folder) brownie_contracts_folder = os.path.join(brownie_project_folder, 'contracts') multisig_contract = os.path.join(contracts_folder, 'MultiSigSwapWallet.sol') copy(multisig_contract, os.path.join(brownie_contracts_folder, 'MultiSigSwapWallet.sol')) # load and compile contracts to project try: brownie_project = project.load(brownie_project_folder, name="IntegrationTests") brownie_project.load_config() except ProjectAlreadyLoaded: pass # noinspection PyUnresolvedReferences network.connect('development') # connect to ganache cli yield # cleanup del brownie_project sleep(1) rmtree(brownie_project_folder, ignore_errors=True)
def _release(project_path, registry_address, sender): network.connect("mainnet") with project_path.joinpath("ethpm-config.yaml").open() as fp: project_config = yaml.safe_load(fp) print("Generating manifest and pinning assets to IPFS...") manifest, uri = ethpm.create_manifest(project_path, project_config, True, False) if sender in accounts: account = accounts.at(sender) else: try: account = accounts.load(sender) except FileNotFoundError: raise UnknownAccount(f"Unknown account '{sender}'") name = f'{manifest["package_name"]}@{manifest["version"]}' print(f'Releasing {name} on "{registry_address}"...') try: tx = ethpm.release_package(registry_address, account, manifest["package_name"], manifest["version"], uri) if tx.status == 1: notify("SUCCESS", f"{name} has been released!") print( f"\nURI: {color('bright magenta')}ethpm://{registry_address}:1/{name}{color}" ) return except Exception: pass notify( "ERROR", f'Transaction reverted when releasing {name} on "{registry_address}"')
def main(): args = docopt(__doc__) name = args['<filename>'].replace(".py", "") fn = args['<function>'] or "main" if not Path(CONFIG['folders']['project']).joinpath( 'scripts/{}.py'.format(name)): sys.exit( "{0[error]}ERROR{0}: Cannot find {0[module]}scripts/{1}.py{0}". format(color, name)) network.connect(config.ARGV['network'], True) module = importlib.import_module("scripts." + name) if not hasattr(module, fn): sys.exit( "{0[error]}ERROR{0}: {0[module]}scripts/{1}.py{0} has no '{0[callable]}{2}{0}' function." .format(color, name, fn)) print("Running '{0[module]}{1}{0}.{0[callable]}{2}{0}'...".format( color, name, fn)) try: getattr(module, fn)() print( "\n{0[success]}SUCCESS{0}: script '{0[module]}{1}{0}' completed.". format(color, name)) except Exception as e: if CONFIG['logging']['exc'] >= 2: print("\n" + color.format_tb(sys.exc_info())) print( "\n{0[error]}ERROR{0}: Script '{0[module]}{1}{0}' failed from unhandled {2}: {3}" .format(color, name, type(e).__name__, e))
def test_connect_raises_missing_host(): host = config['networks']['ropsten']['host'] del config['networks']['ropsten']['host'] with pytest.raises(KeyError): network.connect('ropsten') config._unlock() config['networks']['ropsten']['host'] = host
def test_connect_ropsten(): try: network.connect('ropsten') assert network.show_active() == "ropsten" except Exception: network.connect('development') raise
def main(*args): env = ENV_BASE() from brownie import network, project _args = make_tuple(str(args)) network.connect("bloxberg") project = project.load(env.CONTRACT_PROJECT_PATH) ebb = project.eBlocBroker.at(env.CONTRACT_ADDRESS) provider = cfg.w3.toChecksumAddress(_args[0]) job_requester = cfg.w3.toChecksumAddress(_args[1]) try: source_code_hash = ipfs_to_bytes32(_args[2]) except: source_code_hash = _args[2].encode("utf-8") try: output = ebb.getStorageDeposit(provider, job_requester, source_code_hash) print(output) except: print("0") # if its the first submitted job for the user try: output = ebb.getStorageInfo(provider, source_code_hash) print(output) except: print("(0, 0, False, False)") sys.exit(0)
def main(): args = docopt(__doc__, more_magic=True) _update_argv_from_docopt(args) active_project = None if project.check_for_project(): active_project = project.load() active_project.load_config() print(f"{active_project._name} is the active project.") network.connect(CONFIG.argv["network"]) path, _ = _get_path(args["<filename>"]) path_str = path.absolute().as_posix() try: return_value, frame = run( args["<filename>"], method_name=args["<function>"] or "main", args=args["<arg>"], _include_frame=True, ) exit_code = 0 except Exception as e: print(color.format_tb(e)) frame = next( (i.frame for i in inspect.trace()[::-1] if Path(i.filename).as_posix() == path_str), None, ) if frame is None: # exception was an internal brownie issue - do not open the console sys.exit(1) exit_code = 1 return_value = None try: if args["--interactive"]: # filter internal objects from the namespace prior to opening the console globals_dict = { k: v for k, v in frame.f_globals.items() if not k.startswith("__") } extra_locals = { "_": return_value, **globals_dict, **frame.f_locals } shell = Console(active_project, extra_locals) shell.interact( banner="\nInteractive mode enabled. Use quit() to close.", exitmsg="") finally: # the console terminates from a SystemExit - make sure we still deliver the final gas report if CONFIG.argv["gas"]: print("\n======= Gas profile =======") for line in _build_gas_profile_output(): print(line) sys.exit(exit_code)
def setup(): network.disconnect() yield if not network.is_connected(): network.connect('development') elif network.show_active() != "development": network.disconnect() network.connect('development')
def main(): args = docopt(__doc__) update_argv_from_docopt(args) project.load() network.connect(ARGV['network']) run(args['<filename>'], args['<function>'] or "main", gas_profile=ARGV['gas'])
def session_setup(): network.connect('development') project.load('tests/brownie-test-project') yield for path in ("build", "reports"): path = Path('tests/brownie-test-project').joinpath(path) if path.exists(): shutil.rmtree(str(path))
def main(): args = docopt(__doc__) update_argv_from_docopt(args) project.load() network.connect(ARGV['network']) shell = Console() shell.interact(banner="Brownie environment is ready.", exitmsg="")
def mainnet_uri(): prev = network.show_active() if prev: network.disconnect(False) network.connect("mainnet") uri = web3.chain_uri network.disconnect(False) if prev: network.connect(prev) yield uri
def test(): from brownie import network, project print_msg( f"parent pid: {psutil.Process().parent().pid}, start calculate()") network.connect("bloxberg") project = project.load(env.CONTRACT_PROJECT_PATH) ebb = project.eBlocBroker.at("0xccD25f5Ae21037a6DCCff829B01034E2fD332796") print(ebb.getOwner()) print_msg(f"parent pid: {psutil.Process().parent().pid}, end calculate()")
def main(): docopt(__doc__) network.connect(config.ARGV['network'], True) console = Console() print("Brownie environment is ready.") try: console._run() except EOFError: sys.stdout.write('\n')
def __init__(self, eth_network, token_addr): p = project.load() p.load_config() network.connect(eth_network) self.token = p.Token.at(token_addr) with open("keys/keys.json", "r") as keyfile: keys = json.load(keyfile) for pair in keys: # print (pair) accounts.add(pair['sk'])
def test_repopulate(): network.rpc.reset() assert len(accounts) == 10 a = list(accounts) network.rpc.reset() assert a == list(accounts) network.disconnect() assert len(accounts) == 0 network.connect('development') assert len(accounts) == 10 assert a != list(accounts)
def connect_into_eblocbroker() -> None: """Connect into ebloc-broker contract in the given blockchain.""" if config.ebb: return if not cfg.w3: connect_into_web3() if not env.EBLOCPATH: log("E: EBLOCPATH variable is empty") raise QuietExit try: abi_file = env.EBLOCPATH / "broker" / "eblocbroker_scripts" / "abi.json" abi = read_json(abi_file, is_dict=False) except Exception as e: raise Exception( f"E: could not read the abi.json file: {abi_file}") from e try: if env.IS_BLOXBERG: if not cfg.IS_BROWNIE_TEST: from brownie import network, project try: network.connect("bloxberg") except Exception as e: print_tb(e) add_bloxberg_into_network_config.main() # network.connect("bloxberg") try: log("warning: [green]bloxberg[/green] key is added into the " "[magenta]~/.brownie/network-config.yaml[/magenta] yaml file. Please try again." ) network.connect("bloxberg") except KeyError: sys.exit(1) project = project.load(env.CONTRACT_PROJECT_PATH) config.ebb = project.eBlocBroker.at(env.CONTRACT_ADDRESS) config.ebb.contract_address = cfg.w3.toChecksumAddress( env.CONTRACT_ADDRESS) #: for the contract's events config._eBlocBroker = cfg.w3.eth.contract(env.CONTRACT_ADDRESS, abi=abi) elif env.IS_EBLOCPOA: config.ebb = cfg.w3.eth.contract(env.CONTRACT_ADDRESS, abi=abi) config._eBlocBroker = config.ebb config.ebb.contract_address = cfg.w3.toChecksumAddress( env.CONTRACT_ADDRESS) except Exception as e: print_tb(e) raise e
def cli( ctx, etherscan_token, gas_speed, gas_max_speed, gas_increment, gas_block_duration, network, ): ctx.ensure_object(dict) # put this into the environment so that brownie sees it os.environ["ETHERSCAN_TOKEN"] = etherscan_token # setup the project and network the same way brownie's run helper does brownie_project = project.load(get_project_root()) brownie_project.load_config() if network != "none": brownie_network.connect(network) logger.info( f"{brownie_project._name} is the active {network} project.") if network in ["mainnet", "mainnet-fork"]: # TODO: write my own strategy gas_strategy = GasNowScalingStrategy( initial_speed=gas_speed, max_speed=gas_max_speed, increment=gas_increment, block_duration=gas_block_duration, ) gas_price(gas_strategy) logger.info(f"Default gas strategy: {gas_strategy}") elif network in ["bsc", "bsc-fork"]: gas_strategy = "10 gwei" gas_price(gas_strategy) logger.info(f"Default gas price: {gas_strategy}") elif network in ["matic", "matic-fork"]: gas_strategy = "1 gwei" gas_price(gas_strategy) logger.info(f"Default gas price: {gas_strategy}") else: logger.warning( "No default gas price or gas strategy has been set!") else: logger.warning( f"{brownie_project._name} is the active project. It is not conencted to any networks" ) # pass the project on to the other functions ctx.obj["brownie_project"] = brownie_project
def main(): args = docopt(__doc__) _update_argv_from_docopt(args) if project.check_for_project(): active_project = project.load() active_project.load_config() print(f"{active_project._name} is the active project.") else: raise ProjectNotFound network.connect(ARGV["network"]) run(args["<filename>"], method_name=args["<function>"] or "main") if ARGV["gas"]: _print_gas_profile()
def main(): args = docopt(__doc__) _update_argv_from_docopt(args) if project.check_for_project(): active_project = project.load() active_project.load_config() print(f"{active_project._name} is the active project.") else: active_project = None print("No project was loaded.") network.connect(CONFIG.argv["network"]) shell = Console(active_project) shell.interact(banner="Brownie environment is ready.", exitmsg="")
def main(): args = docopt(__doc__) _update_argv_from_docopt(args) if project.check_for_project(): active_project = project.load() active_project.load_config() print(f"{active_project._name} is the active project.") else: raise ProjectNotFound network.connect(CONFIG.argv["network"]) path, _ = _get_path(args["<filename>"]) path_str = path.absolute().as_posix() try: run(args["<filename>"], method_name=args["<function>"] or "main") except Exception as e: print(color.format_tb(e)) if args["--interactive"]: frame = next( (i.frame for i in inspect.trace()[::-1] if Path(i.filename).as_posix() == path_str), None, ) if frame is not None: globals_dict = { k: v for k, v in frame.f_globals.items() if not k.startswith("__") } shell = Console(active_project, { **globals_dict, **frame.f_locals }) shell.interact( banner="\nInteractive mode enabled. Use quit() to close.", exitmsg="") sys.exit(1) if CONFIG.argv["gas"]: print("\n======= Gas profile =======") for line in _build_gas_profile_output(): print(line)
def main(): args = docopt(__doc__) traceback_info = [] test_files = get_test_files(args['<filename>']) if len(test_files) == 1 and args['<range>']: try: idx = args['<range>'] if ':' in idx: idx = slice(*[int(i)-1 for i in idx.split(':')]) else: idx = slice(int(idx)-1, int(idx)) except: sys.exit("{0[error]}ERROR{0}: Invalid range. Must be an integer or slice (eg. 1:4)".format(color)) elif args['<range>']: sys.exit("{0[error]}ERROR:{0} Cannot specify a range when running multiple tests files.".format(color)) else: idx = slice(0, None) network.connect(config.ARGV['network'], True) if args['--always-transact']: CONFIG['test']['always_transact'] = True print("Contract calls will be handled as: {0[value]}{1}{0}".format( color, "transactions" if CONFIG['test']['always_transact'] else "calls" )) for filename in test_files: test_history, tb = run_test(filename, network, idx) if tb: traceback_info += tb if not traceback_info: print("\n{0[success]}SUCCESS{0}: All tests passed.".format(color)) if config.ARGV['gas']: print('\nGas Profile:') for i in sorted(transaction.gas_profile): print("{0} - avg: {1[avg]:.0f} low: {1[low]} high: {1[high]}".format(i, transaction.gas_profile[i])) sys.exit() print("\n{0[error]}WARNING{0}: {1} test{2} failed.{0}".format( color, len(traceback_info), "s" if len(traceback_info) > 1 else "" )) for err in traceback_info: print("\nException info for {0[0]}:\n{0[1]}".format(err))
def main(): args = docopt(__doc__) update_argv_from_docopt(args) if project.check_for_project(): active_project = project.load() active_project.load_config() print(f"{active_project._name} is the active project.") else: active_project = None print("No project was loaded.") network.connect(ARGV['network']) run(args['<filename>'], method_name=args['<function>'] or "main", project=active_project) if ARGV['gas']: print_gas_profile()
def main(): acct = accounts.load('TestUser') network.disconnect() network.connect('ropsten') print('----------------------------------------') print('Ethereum (Ropsten) Minting. ') print('----------------------------------------') BrownieWrap_Token.at('0xBD2231994722D8a47244C4166Bc6Ac4bF8Bbc110').mint( acct, 20, {'from': acct}) network.disconnect() network.connect('bsc-test') print('----------------------------------------') print('Binance Smart Chain Minting') print('----------------------------------------') BrownieWrap_Token.at('0x926A513fdd63e1010e6C0627EB12204ADA45d550').mint( acct, 20, {'from': acct})
def main(): wltBadgerTeam = accounts.load('GasWallet') network.disconnect() network.connect('ropsten') print('----------------------------------------') print('Deploying Ethereum (Ropsten) contracts. ') print('----------------------------------------') ctrBadgerLpToken = BrownieWrap_Token.deploy("Sett Vault Badger LP", "bBadger", {'from': wltBadgerTeam}, publish_source=True) ctrBadgerHolderValidation = TokenHolderThresholdValidator.deploy( ctrBadgerLpToken.address, 10, 1, {'from': wltBadgerTeam}, publish_source=True) network.disconnect() network.connect('bsc-test') print('----------------------------------------') print('Deploying Binance Smart Chain contracts.') print('----------------------------------------') ctrBadgerLpToken = BrownieWrap_Token.deploy("Sett Vault Badger LP", "bBadger", {'from': wltBadgerTeam}, publish_source=True) ctrBadgerHolderValidation = TokenHolderThresholdValidator.deploy( ctrBadgerLpToken.address, 10, 1, {'from': wltBadgerTeam}, publish_source=True) ctrFaucet = Faucet.deploy(10, Wei("50 gwei"), [], { 'from': wltBadgerTeam, 'value': Wei("500 gwei") }, publish_source=True) print('Contract chain deployment complete.')
def brownie_connect(): # this allows later click commands to set the default. there might be a better way network = ctx.obj["brownie_network"] or ctx.obj.get("default_brownie_network") # setup the project and network the same way brownie's run helper does brownie_project = project.load(get_project_root(), "ArgobytesBrownieProject") brownie_project.load_config() ctx.obj["brownie_project"] = brownie_project if network == "none" or network is None: logger.warning(f"{brownie_project._name} is the active project. Not connected to any networks") else: brownie_network.connect(network) logger.info(f"{brownie_project._name} is the active {network} project.") if flashbot_account: print(f"Using {flashbot_account} for signing flashbot bundles.") flashbot(web3, flashbot_account) if network in ["mainnet", "mainnet-fork"]: # TODO: write my own strategy gas_strategy = GasNowScalingStrategy( initial_speed=gas_speed, max_speed=gas_max_speed, increment=gas_increment, block_duration=gas_block_duration, ) gas_price(gas_strategy) logger.info(f"Default gas strategy: {gas_strategy}") elif network in ["bsc-main", "bsc-main-fork"]: gas_strategy = "5010000000" # 5.01 gwei gas_price(gas_strategy) logger.info(f"Default gas price: {gas_strategy}") elif network in ["polygon", "polygon-fork"]: gas_strategy = "1010000000" # "1.01 gwei" gas_price(gas_strategy) logger.info(f"Default gas price: {gas_strategy}") else: logger.warning("No default gas price or gas strategy has been set!")
def setup_brownie_mainnet_fork(pytestconfig): project_root = get_project_root() # setup the project and network the same way brownie's run helper does brownie_project = project.load(project_root) brownie_project.load_config() # override some config CONFIG.argv["revert"] = True network.connect("mainnet-fork") # TODO: brownie does some other setup for hypothesis and multiple-processes fixtures = PytestBrownieFixtures(pytestconfig, brownie_project) pytestconfig.pluginmanager.register(fixtures, "brownie-fixtures") brownie.reverts = RevertContextManager yield network.disconnect()
def wrapper(*args, **kwargs): initial_network_id = network.show_active() is_mainnet = "main" in initial_network_id if environment_name == "ethereum": swap_network_id = "mainnet" if is_mainnet else "goerli" elif environment_name == "polygon": swap_network_id = "polygon-main" if is_mainnet else "polygon-testnet" if initial_network_id == swap_network_id: return func(*args, **kwargs) network.disconnect() network.connect(swap_network_id) result = func(*args, **kwargs) network.disconnect() network.connect(initial_network_id) return result
from brownie import network network.connect('mainnet')