def test_pull(noload, testpath): path = project.pull('token') assert config['folders']['project'] != path != testpath assert Path(path).joinpath('brownie-config.json').exists() assert Path(path).joinpath('contracts/Token.sol').exists() assert Path(path).joinpath('contracts/SafeMath.sol').exists() project.load(path)
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 test_new_raises(noload, tmpdir): project.new(tmpdir) project.load(tmpdir) with pytest.raises(ProjectAlreadyLoaded): project.new(tmpdir) project.close() with pytest.raises(SystemError): project.new(tmpdir+"/contracts")
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 main(): args = docopt(__doc__) project_path = project.check_for_project(".") if project_path is None: raise ProjectNotFound build_path = project_path.joinpath("build/contracts") if args["--all"]: shutil.rmtree(build_path, ignore_errors=True) project.load(project_path) print(f"Brownie project has been compiled at {build_path}")
def main(): args = docopt(__doc__) project_path = project.check_for_project(".") if project_path is None: raise ProjectNotFound contract_artifact_path = project_path.joinpath("build/contracts") interface_artifact_path = project_path.joinpath("build/interfaces") if args["--all"]: shutil.rmtree(contract_artifact_path, ignore_errors=True) shutil.rmtree(interface_artifact_path, ignore_errors=True) project.load(project_path) print( f"Project has been compiled. Build artifacts saved at {contract_artifact_path}" )
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 pytest_configure(config): if project.check_for_project("."): active_project = project.load() active_project.load_config() active_project._add_to_main_namespace() # enable verbose output if stdout capture is disabled if config.getoption("capture") == "no": config.option.verbose = True if config.getoption("numprocesses"): if config.getoption("interactive"): raise ValueError("Cannot use --interactive mode with xdist") Plugin = PytestBrownieMaster elif hasattr(config, "workerinput"): Plugin = PytestBrownieXdistRunner else: Plugin = PytestBrownieRunner session = Plugin(config, active_project) config.pluginmanager.register(session, "brownie-core") if not config.getoption("numprocesses"): fixtures = PytestBrownieFixtures(config, active_project) config.pluginmanager.register(fixtures, "brownie-fixtures")
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 pytest_configure(config): if project.check_for_project("."): try: active_project = project.load() active_project.load_config() active_project._add_to_main_namespace() except Exception as e: # prevent pytest INTERNALERROR traceback when project fails to compile print(f"{color.format_tb(e)}\n") raise pytest.UsageError("Unable to load project") # enable verbose output if stdout capture is disabled if config.getoption("capture") == "no": config.option.verbose = True if config.getoption("numprocesses"): if config.getoption("interactive"): raise ValueError("Cannot use --interactive mode with xdist") Plugin = PytestBrownieMaster elif hasattr(config, "workerinput"): Plugin = PytestBrownieXdistRunner else: Plugin = PytestBrownieRunner session = Plugin(config, active_project) config.pluginmanager.register(session, "brownie-core") if not config.getoption("numprocesses"): fixtures = PytestBrownieFixtures(config, active_project) config.pluginmanager.register(fixtures, "brownie-fixtures")
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(): project.load(".", name="shutter") connect(network="goerli", launch_rpc=False) import brownie.project.shutter for name, addr in contracts.items(): try: cls = getattr(brownie.project.shutter, name) except AttributeError: print(f"Cannot find contract {name}") continue c = cls.at(addr) print(f"======> Verify {name}") try: cls.publish_source(c) except ValueError as e: print(f"{e}")
def main(): """The main entry point of the MythX plugin for Brownie.""" args = docopt(__doc__) _update_argv_from_docopt(args) if CONFIG.argv["mode"] not in ANALYSIS_MODES: raise ValidationError( "Invalid analysis mode: Must be one of [{}]".format( ", ".join(ANALYSIS_MODES))) project_path = project.check_for_project(".") if project_path is None: raise ProjectNotFound build = project.load()._build submission = SubmissionPipeline(build) print("Preparing project data for submission to MythX...") submission.prepare_requests() print("Sending analysis requests to MythX...") submission.send_requests() # exit if user wants an async analysis run if CONFIG.argv["async"]: print( "\nAll contracts were submitted successfully. Check the dashboard at " "https://dashboard.mythx.io/ for the progress and results of your analyses" ) return print("\nWaiting for results...") submission.wait_for_jobs() submission.generate_stdout_report() submission.generate_highlighting_report() # erase previous report report_path = project_path.joinpath( _load_project_structure_config(project_path)["reports"]) report_path = report_path.joinpath("security.json") if report_path.exists(): report_path.unlink() print_console_report(submission.stdout_report) # Write report to Brownie directory with report_path.open("w+") as fp: json.dump(submission.highlight_report, fp, indent=2, sort_keys=True) # Launch GUI if user requested it if CONFIG.argv["gui"]: print("Launching the Brownie GUI") gui = importlib.import_module("brownie._gui").Gui gui().mainloop()
def main(): # dev = accounts.add(os.getenv(config["wallets"]["from_key"])) print(f"Network: {network.show_active()}") # pm("alphachainio/[email protected]").LinkToken p = project.load("alphachainio/[email protected]") print(project.get_loaded_projects()) print(sources.get_contract_list())
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 pytest_load_initial_conftests(): if project.check_for_project("."): try: active_project = project.load() active_project.load_config() active_project._add_to_main_namespace() except Exception as e: # prevent pytest INTERNALERROR traceback when project fails to compile print(f"{color.format_tb(e)}\n") raise pytest.UsageError("Unable to load project")
def pytest_configure(config): if project.check_for_project("."): try: active_project = project.load() active_project.load_config() active_project._add_to_main_namespace() except Exception as e: # prevent pytest INTERNALERROR traceback when project fails to compile print(f"{color.format_tb(e)}\n") raise pytest.UsageError("Unable to load project") if not config.getoption("showinternal"): # do not include brownie internals in tracebacks base_path = Path(sys.modules["brownie"].__file__).parent.as_posix() for module in [ v for v in sys.modules.values() if getattr(v, "__file__", None) and v.__file__.startswith(base_path) ]: module.__tracebackhide__ = True module.__hypothesistracebackhide__ = True # enable verbose output if stdout capture is disabled if config.getoption("capture") == "no": config.option.verbose = True # if verbose mode is enabled, also enable hypothesis verbose mode if config.option.verbose: _modify_hypothesis_settings({"verbosity": 2}, "brownie-verbose") if config.getoption("numprocesses"): if config.getoption("interactive"): raise ValueError("Cannot use --interactive mode with xdist") Plugin = PytestBrownieMaster elif hasattr(config, "workerinput"): Plugin = PytestBrownieXdistRunner else: Plugin = PytestBrownieRunner if config.getoption("interactive"): config.option.failfast = True if config.getoption("failfast"): _modify_hypothesis_settings( {"phases": {"explicit": True, "generate": True, "target": True}}, "brownie-failfast" ) session = Plugin(config, active_project) config.pluginmanager.register(session, "brownie-core") if not config.getoption("numprocesses"): fixtures = PytestBrownieFixtures(config, active_project) config.pluginmanager.register(fixtures, "brownie-fixtures")
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 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(): deployer = accounts.load("deployer") UniswapV3Core = project.load("Uniswap/[email protected]") gas_strategy = GasNowScalingStrategy() balance = keeper.balance() pool = UniswapV3Core.interface.IUniswapV3Pool(POOL) pool.increaseObservationCardinalityNext( CARDINALITY, {"from": deployer, "gas_price": gas_strategy} ) print(f"Gas used: {(balance - keeper.balance()) / 1e18:.4f} ETH") print(f"New balance: {keeper.balance() / 1e18:.4f} ETH")
def main(): UniswapV3Core = project.load("Uniswap/[email protected]") pool = UniswapV3Core.interface.IUniswapV3Pool(POOL) while True: (before, after), _ = pool.observe([SECONDS_AGO, 0]) twap = (after - before) / SECONDS_AGO last = pool.slot0()[1] print(f"twap\t{twap}\t{1.0001**twap}") print(f"last\t{last}\t{1.0001**last}") print(f"trend\t{last-twap}") print() time.sleep(max(SECONDS_AGO, 60))
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 pytest_load_initial_conftests(early_config): capsys = early_config.pluginmanager.get_plugin("capturemanager") if project.check_for_project("."): # suspend stdout capture to display compilation data capsys.suspend() try: active_project = project.load() active_project.load_config() active_project._add_to_main_namespace() except Exception as e: # prevent pytest INTERNALERROR traceback when project fails to compile print(f"{color.format_tb(e)}\n") raise pytest.UsageError("Unable to load project") finally: capsys.resume()
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 test_verification_info(tmp_path_factory, version): header = f""" // SPDX-License-Identifier: MIT pragma solidity {version}; """ # setup directory dir: Path = tmp_path_factory.mktemp("verify-project") # initialize brownie project new(dir.as_posix()) modded_sources = {} for fp, src in sources: with dir.joinpath(fp).open("w") as f: f.write(header + src) modded_sources[fp] = header + src find_best_solc_version(modded_sources, install_needed=True) project = load(dir, "TestImportProject") for contract_name in ("Foo", "Bar", "Baz"): contract = getattr(project, contract_name) input_data = contract.get_verification_info()["standard_json_input"] # output selection isn't included in the verification info because # etherscan replaces it regardless. Here we just replicate with what they # would include input_data["settings"]["outputSelection"] = { "*": {"*": ["evm.bytecode", "evm.deployedBytecode", "abi"]} } compiler_version, _ = contract._build["compiler"]["version"].split("+") output_data = solcx.compile_standard(input_data, solc_version=compiler_version) # keccak256 = 0xd61b13a841b15bc814760b36086983db80788946ca38aa90a06bebf287a67205 build_info = output_data["contracts"][f"{contract_name}.sol"][contract_name] assert build_info["abi"] == contract.abi # ignore the metadata at the end of the bytecode, etherscan does the same assert build_info["evm"]["bytecode"]["object"][:-96] == contract.bytecode[:-96] assert ( build_info["evm"]["deployedBytecode"]["object"][:-96] == contract._build["deployedBytecode"][:-96] ) project.close()
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()