### Setup Virtual Environment and Install Dependencies Source: https://github.com/vyperlang/titanoboa/blob/master/CONTRIBUTING.md Create a Python virtual environment, activate it, and install development and production dependencies using pip. ```bash python -m venv venv source venv/bin/activate # Install dev requirements pip install -r dev-requirements.txt # Install prod requirements (in the pyproject.tom) pip install . ``` -------------------------------- ### Contract Deployment Example Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/_BaseEVMContract.md An example demonstrating how to deploy an EVM contract using the `boa` library and the `_BaseEVMContract` functionality. ```APIDOC ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> type(contract) ``` ``` -------------------------------- ### Basic Usage Example Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Demonstrates how to deploy a contract and then connect to it using the `at()` method to interact with its state. ```APIDOC ## Basic Usage ```python import boa # Deploy a contract first original = boa.loads(""" value: public(uint256) @external def set_value(v: uint256): self.value = v """) original.set_value(42) # Connect to the same contract using at() contract = boa.loads(""" value: public(uint256) @external def set_value(v: uint256): self.value = v """).at(original.address) # Verify it's the same contract assert contract.value() == 42 ``` ``` -------------------------------- ### Forge Contract Setup Pattern Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Define contract state and initialize it within the `setUp` function for Forge tests. Use `vm.deal` to set account balances. ```solidity contract TestContract is Test { MyContract contract; address alice = address(0x1); function setUp() public { contract = new MyContract(); vm.deal(alice, 100 ether); } } ``` -------------------------------- ### Install Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Install the latest stable version of Titanoboa using pip. ```bash pip install titanoboa ``` -------------------------------- ### Run Vyper Project Setup Source: https://github.com/vyperlang/titanoboa/blob/master/README.md If encountering 'ModuleNotFoundError: No module named 'vyper.version'' when running Titanoboa on a local Vyper project, run 'python setup.py install' within the Vyper project directory. ```bash python setup.py install ``` -------------------------------- ### Install Titanoboa with Forking Extras Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Install Titanoboa with the 'forking-recommended' extra for performance improvements in mainnet forking, including caching and faster JSON parsing. ```bash pip install "git+https://github.com/vyperlang/titanoboa#egg=titanoboa[forking-recommended]" ``` ```bash pip install titanoboa[forking-recommended] ``` -------------------------------- ### Example Usage Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/overview.md Demonstrates how to load, deploy, and interact with a Vyper contract using the boa library. ```APIDOC ## Example Usage ### Description Demonstrates how to load, deploy, and interact with a Vyper contract using the boa library. ### Code ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... ... @internal ... def foo() -> uint256: ... return 123 ... """ >>> contract = boa.loads_partial(src, name="Foo").deploy() >>> type(contract.main) >>> type(contract.internal.foo) >>> contract.internal.foo() 123 ``` ``` -------------------------------- ### Load Environment Variables from File Source: https://github.com/vyperlang/titanoboa/blob/master/CONTRIBUTING.md Optionally, copy the example environment file and source it to load all necessary environment variables for integration tests. ```bash source .env.unsafe ``` -------------------------------- ### Initialize Project: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Compares project initialization commands for Forge and Titanoboa. Titanoboa does not require a separate install command after project creation. ```bash forge init my-project cd my-project forge install ``` ```bash mkdir my-project cd my-project pip install titanoboa # No separate install needed - dependencies managed via pip ``` -------------------------------- ### Script Deployment: Forge Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Example of a Forge deployment script using `Script` and `vm.startBroadcast`/`vm.stopBroadcast`. ```solidity // script/Deploy.s.sol contract DeployScript is Script { function run() external { vm.startBroadcast(); new MyContract(); vm.stopBroadcast(); } } ``` -------------------------------- ### Install Titanoboa Source: https://context7.com/vyperlang/titanoboa/llms.txt Install the latest stable release of Titanoboa. For mainnet forking capabilities, install with the 'forking-recommended' extras. The development version can be installed directly from GitHub. ```bash pip install titanoboa ``` ```bash pip install "titanoboa[forking-recommended]" ``` ```bash pip install git+https://github.com/vyperlang/titanoboa ``` -------------------------------- ### Install Latest Dev Version of Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Install the most recent development version directly from GitHub. ```bash pip install git+https://github.com/vyperlang/titanoboa ``` -------------------------------- ### BrowserEnv Usage Example Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/browser_env.md Demonstrates how to set up and use the BrowserEnv for deploying and interacting with smart contracts, including automatic wallet connection and transaction signing. ```APIDOC ## BrowserEnv Usage ### Description Demonstrates how to set up and use the BrowserEnv for deploying and interacting with smart contracts, including automatic wallet connection and transaction signing. ### Code Example ```python import boa # Set up browser environment boa.set_browser_env() # Deploy and interact with contracts contract = boa.loads_partial("@external\ndef get() -> uint256: return 42").deploy() ``` ### Notes The environment automatically handles wallet connection and transaction signing through the browser. ``` -------------------------------- ### Basic Contract Deployment and Connection Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Load a contract partially to get a deployer object, then deploy new instances with constructor arguments or connect to an existing contract at a specific address. ```python import boa # Load contract source without deploying deployer = boa.load_partial("MyToken.vy") # Deploy with constructor arguments token = deployer.deploy("My Token", "MTK", 18, 1000000) # Deploy at specific address token2 = deployer.at("0x1234567890123456789012345678901234567890") ``` -------------------------------- ### Set up Browser Environment and Deploy Contract Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/browser_env.md Initializes the browser environment for interacting with web3 wallets and deploys a simple contract. This is the primary setup for using `BrowserEnv`. ```python import boa # Set up browser environment boa.set_browser_env() # Deploy and interact with contracts contract = boa.loads_partial("@external\ndef get() -> uint256: return 42").deploy() ``` -------------------------------- ### Output of CREATE Opcode Tracing Example Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/pyevm/patch_opcode.md This bash output shows the list of contract addresses traced by the `CreateTracer` after executing the example contract. ```bash $ python example.py [ "0xd130b7e7f212ecadcfcca3cecc89f85ce6465896", "0x37fdb059bf647b88dbe172619f00b8e8b1cf9338", "0x40bcd509b3c1f42d535d1a8f57982729d4b52adb", "0xaa35545ac7a733600d658c3f516ce2bb2be99866", "0x29e303d13a16ea18c6b0e081eb566b55a74b42d6", "0x3f69d814da1ebde421fe7dc99e24902b15af960b", "0x719c0dc21639008a2855fdd13d0d6d89be53f991", "0xf6086a85f5433f6fbdcdcf4f2ace7915086a5130", "0x097dec6ea6b9eb5fc04db59c0d343f0e3b4097a0", "0x905794c5566184e642ef14fb0e72cf68ff8c79bf" ] ``` -------------------------------- ### Install Titanoboa in Colab Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Installs the Titanoboa plugin and loads the IPython extension for use in Google Colab notebooks. ```jupyter !pip install titanoboa %load_ext boa.ipython ``` -------------------------------- ### Install and Enable Titanoboa JupyterLab Extension Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Provides instructions for installing the Titanoboa JupyterLab extension via pip and enabling it for use within JupyterLab. This is a prerequisite for using Titanoboa's IPython magic commands in a Jupyter environment. ```bash pip install titanoboa jupyter lab extension enable boa ``` -------------------------------- ### Titanoboa Contract Setup Pattern Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Utilize pytest fixtures to load contracts and set up accounts with balances using `boa.env.generate_address` and `boa.env.set_balance`. ```python import pytest import boa @pytest.fixture def contract(): return boa.load("MyContract.vy") @pytest.fixture def alice(): addr = boa.env.generate_address() boa.env.set_balance(addr, 100 * 10**18) return addr ``` -------------------------------- ### Running Pytest Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/pytest.md Example output of running pytest on the test file. Shows a single test passing. ```bash > pytest test_example.py ============================= test session starts ============================== ... collected 1 item test_example.py::test_set_foo PASSED ============================== 1 passed in 0.01s =============================== ``` -------------------------------- ### Implement CREATE Opcode Tracing with `patch_opcode` Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/pyevm/patch_opcode.md This example demonstrates how to patch the `CREATE` opcode (0xf0) to trace newly created contract addresses. It defines a `CreateTracer` class that wraps the original opcode implementation and appends the address of each created contract to a list. This approach is useful for monitoring contract deployments. ```python import boa class CreateTracer: def __init__(self, super_fn): """Track addresses of contracts created via the CREATE opcode. Parameters: super_fn: The original opcode implementation. """ self.super_fn = super_fn self.trace = [] def __call__(self, computation): # first, dispatch to the original opcode implementation provided by py-evm self.super_fn(computation) # then, store the output of the CREATE opcode in our `trace` list for later self.trace.append("0x" + computation._stack.values[-1][-1].hex()) if __name__ == "__main__": create_tracer = CreateTracer(boa.env.vm.state.computation_class.opcodes[0xf0]) boa.patch_opcode(0xf0, create_tracer) source = """ @external def main(): for _ in range(10): addr: address = create_minimal_proxy_to(self) """ contract = boa.loads(source) contract.main() # execute the contract function print(create_tracer.trace) ``` -------------------------------- ### Using Special Addresses Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/address.md Provides examples of commonly used special addresses like the zero address and precompile addresses. ```python # Zero address ZERO_ADDRESS = Address("0x0000000000000000000000000000000000000000") # Common precompiles ECRECOVER = Address("0x0000000000000000000000000000000000000001") SHA256 = Address("0x0000000000000000000000000000000000000002") RIPEMD160 = Address("0x0000000000000000000000000000000000000003") IDENTITY = Address("0x0000000000000000000000000000000000000004") MODEXP = Address("0x0000000000000000000000000000000000000005") ``` -------------------------------- ### Install Development Version with uv Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/install.md Add the latest development version of Titanoboa from its GitHub repository to your project using uv. Replace `` with the desired commit hash. ```console uv add https://github.com/vyperlang/titanoboa.git --rev ``` -------------------------------- ### Deterministic Deployment with CREATE2 Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Shows how to set up a factory contract for deterministic deployment using CREATE2, including calculating the salt and preparing the bytecode. ```python # Using a factory with CREATE2 factory = boa.loads(""" @external def deploy_deterministic(salt: bytes32, bytecode: Bytes[24576]) -> address: return create2(bytecode, salt=salt) ") # Calculate expected address salt = b"my_unique_salt".ljust(32, b'\0') # Deploy deterministically ``` -------------------------------- ### Install Titanoboa with Brownie Source: https://github.com/vyperlang/titanoboa/blob/master/README.md When installing from Git alongside Brownie, ensure Titanoboa is installed after Brownie to avoid potential conflicts. ```bash pip install brownie pip install git+https://github.com/vyperlang/titanoboa ``` -------------------------------- ### Using at() with Deployers Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Shows how to load a contract's ABI using `load_partial` and then connect to an existing deployment at a specific address using `at()`. This is useful when you have the contract's ABI but not its deployment transaction. ```python # Load contract without deploying deployer = boa.load_partial("MyContract.vy") # Connect to existing deployment existing_address = "0x1234567890123456789012345678901234567890" contract = deployer.at(existing_address) # Interact with the contract result = contract.some_function() ``` -------------------------------- ### Install Development Version with poetry Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/install.md Add the latest development version of Titanoboa from its GitHub repository to your project using poetry. Replace `` with the desired commit hash. ```console poetry add git+https://github.com/vyperlang/titanoboa.git@ ``` -------------------------------- ### Custom Admonition Examples Source: https://github.com/vyperlang/titanoboa/blob/master/docs/template.md Examples of custom admonition blocks used for different purposes within the documentation. ```text !!!vyper lorem ipsum dolor sit amet ``` ```text !!!titanoboa lorem ipsum dolor sit amet ``` ```text !!!moccasin lorem ipsum dolor sit amet ``` ```text !!!python lorem ipsum dolor sit amet ``` -------------------------------- ### Snapshots/Checkpoints: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Illustrates creating and reverting to a state snapshot using Forge's `vm.snapshot`/`vm.revertTo` and Titanoboa's `boa.env.anchor` context manager. ```solidity uint256 snapshot = vm.snapshot(); // Do some operations vm.revertTo(snapshot); ``` ```python with boa.env.anchor(): # Do some operations pass # Automatically reverts after context ``` -------------------------------- ### Basic Usage: Connect to a Deployed Contract Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Demonstrates deploying a contract and then connecting to it using `at()` to verify state. This ensures that the `at()` method correctly instantiates a contract at a given address. ```python import boa # Deploy a contract first original = boa.loads(""" value: public(uint256) @external def set_value(v: uint256): self.value = v """) original.set_value(42) # Connect to the same contract using at() contract = boa.loads(""" value: public(uint256) @external def set_value(v: uint256): self.value = v """).at(original.address) # Verify it's the same contract assert contract.value() == 42 ``` -------------------------------- ### Get Contract Factory from VVMDeployer Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vvm_deployer/factory.md Instantiate VVMDeployer and access its factory property to get a contract factory. This is useful for deploying new instances of a contract. ```python >>> deployer = VVMDeployer(abi, bytecode, filename) >>> factory = deployer.factory ``` -------------------------------- ### Basic Contract Deployment and Logging Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/deployments.md Set up persistent deployment tracking and network environment, then deploy contracts. All deployments are automatically logged. ```python import boa from boa.deployments import DeploymentsDB, set_deployments_db # Set up deployment tracking with persistent storage set_deployments_db(DeploymentsDB("./deployments.db")) # Set up network connection boa.set_network_env("http://localhost:8545") # Deploy a contract - automatically logged contract = boa.load("contracts/MyContract.vy", arg1, arg2) # All deployments are tracked another_contract = boa.loads(""" @external def hello() -> String[32]: return "Hello, World!" """) ``` -------------------------------- ### Install Development Version with pip Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/install.md Install the latest development version of Titanoboa directly from its GitHub repository using pip. Replace `` with the desired commit hash. ```console pip install git+https://github.com/vyperlang/titanoboa.git@ ``` -------------------------------- ### Get Contract Logs Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/get_logs.md Retrieves logs from a Vyper contract computation. Use `None` for computation to get logs from the last computation. Set `include_child_logs` to `False` to exclude logs from child computations. ```python >>> import boa >>> src = """ ... @external ... def main(): ... log MyEvent() ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> contract.main() >>> contract.get_logs() [] ``` -------------------------------- ### get_balance Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Get the ether balance of an account. ```APIDOC ## `get_balance` ### Description Get the ether balance of an account. ### Parameters - `address`: The address to retrieve the balance from. ``` -------------------------------- ### Setting Account Balances: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Shows how to set the balance of an address using Forge's `vm.deal` and Titanoboa's `boa.env.set_balance`. ```solidity vm.deal(alice, 100 ether); ``` ```python boa.env.set_balance(alice, 100 * 10**18) ``` -------------------------------- ### Upgradeable Proxy Pattern Deployment Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Illustrates the deployment process for an upgradeable proxy pattern, involving deploying the implementation contract first, then the proxy pointing to it. ```python # Deploy implementation implementation_deployer = boa.load_partial("ImplementationV1.vy") impl = implementation_deployer.deploy() # Deploy proxy pointing to implementation proxy_deployer = boa.load_partial("Proxy.vy") proxy = proxy_deployer.deploy(impl.address) # Interact through proxy contract = implementation_deployer.at(proxy.address) ``` -------------------------------- ### get_gas_price Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Get the current gas price used for transactions in the environment. ```APIDOC ## `get_gas_price` ### Description Get the current gas price used for transactions in the environment. ### Returns The current gas price as an integer. ### Example ```python >>> import boa >>> boa.env.get_gas_price() 0 # Default gas price is 0 ``` ``` -------------------------------- ### Enable Deployment Logging with Default In-Memory Database Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/deployments.md Initialize a deployments database for in-memory storage. Data is lost when the program exits. ```python import boa from boa.deployments import DeploymentsDB, set_deployments_db # Enable with default in-memory database (data lost when program exits) set_deployments_db(DeploymentsDB()) ``` -------------------------------- ### Working with Proxies Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Demonstrates how to use `at()` to interact with proxy contracts, ensuring calls are routed to the correct implementation. ```APIDOC ## Working with Proxies Use `at()` to interact with proxy contracts: ```python # Implementation ABI implementation_deployer = boa.load_partial("ImplementationV2.vy") # Connect to proxy address with implementation ABI proxy_address = "0x1234567890123456789012345678901234567890" contract = implementation_deployer.at(proxy_address) # Calls go through proxy to implementation contract.upgradedFunction() ``` ``` -------------------------------- ### Get ETH Balance Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/network_env.md Retrieves the ETH balance of a given address in wei. ```python import boa >>> balance = boa.env.get_balance("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") >>> print(f"Balance: {balance / 10**18:.4f} ETH") ``` -------------------------------- ### Run Tests: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Shows how to run tests using Forge and Titanoboa, including options for matching specific tests or contracts and adjusting verbosity. ```bash forge test forge test --match-test testFoo forge test --match-contract TestContract forge test -vvvv # Max verbosity ``` ```bash pytest tests/ pytest tests/test_file.py::test_foo pytest tests/test_contract.py pytest tests/ -v # Verbose output ``` -------------------------------- ### Example Vyper Contract Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/pytest.md A simple Vyper contract with a public variable and a function to set it. ```vyper foo: public(uint256) @external def set_foo(foo: uint256): self.foo = foo ``` -------------------------------- ### Get Contract Verifier Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/verify/get_verifier.md Retrieves the current contract verifier instance. Defaults to Blockscout. ```APIDOC ## get_verifier ### Description Returns the current contract verifier instance. ### Signature ```python def get_verifier() -> ContractVerifier ``` ### Returns The current `ContractVerifier` instance (defaults to `Blockscout()`) ### Example ```python import boa verifier = boa.get_verifier() print(type(verifier)) # ``` ``` -------------------------------- ### Enable Deployment Logging with Persistent Database File Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/deployments.md Initialize a deployments database with a specified file path for persistent storage. The default database is ':memory:' if no path is provided. ```python import boa from boa.deployments import DeploymentsDB, set_deployments_db # Enable with persistent database file set_deployments_db(DeploymentsDB("./deployments.db")) ``` -------------------------------- ### Working with Storage Keys Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/address.md Demonstrates how Address objects are used as keys when interacting with contract storage, particularly with HashMaps. ```python contract = boa.loads(""" owner: public(address) admins: public(HashMap[address, bool]) """) # Set owner owner_addr = boa.env.generate_address(alias="owner") contract.eval(f"self.owner = {owner_addr}") # Access storage print(contract._storage.owner) # Returns Address object print(contract._storage.admins) # Returns dict with Address keys ``` -------------------------------- ### Deploying Contract Instances Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Use the `deploy` method on a deployer object to instantiate a contract, optionally providing constructor arguments, ETH value, or a custom gas limit. ```python # Deploy with constructor args contract = deployer.deploy(arg1, arg2) # Deploy with ETH value contract = deployer.deploy(arg1, arg2, value=10**18) # Deploy with custom gas limit contract = deployer.deploy(arg1, arg2, gas=3000000) ``` -------------------------------- ### Comparison: `simulate=True` vs `anchor()` Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/function_calls.md Explains the differences between using the `simulate=True` parameter and the `boa.env.anchor()` context manager for preventing state changes. ```APIDOC ## `simulate=True` vs `anchor()` ### `simulate=True` - Works in both local and network modes. - In network mode, uses `eth_call` - no transaction is created. - Only affects the specific function call. - Returns the function result directly. - `boa.env.anchor()` may not be available in network mode. - More efficient in network mode (no state changes to revert). ### `anchor()` - Only works in local mode (PyEVM). - Creates a snapshot of entire EVM state. - Can wrap multiple operations. - Reverts all state changes within the context. ### Example (`simulate=True`) ```python # Using simulate result = contract.calculate_amount(100, simulate=True) # State unchanged, result returned ``` ### Example (`anchor()`) ```python # Using anchor with boa.env.anchor(): contract.increment() contract.increment() result = contract.counter() # All changes reverted when exiting context # State unchanged ``` ``` -------------------------------- ### String Representation of Address Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/address.md Shows how to get the checksum address string representation and its lowercase equivalent. ```python addr = Address("0x5B38Da6a701c568545dCfcB03FcB875f56beddC4") # Checksum address (default string representation) print(str(addr)) # 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 # Lowercase hex print(str(addr).lower()) # 0x5b38da6a701c568545dcfcb03fcb875f56beddc4 ``` -------------------------------- ### Creating Address Objects Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/address.md Demonstrates various ways to instantiate an Address object, including from hex strings, checksum addresses, bytes, integers, and by generating a new address via the environment. ```python import boa from boa.util.abi import Address # From hex string addr1 = Address("0x0000000000000000000000000000000000000001") # From checksum address addr2 = Address("0x5B38Da6a701c568545dCfcB03FcB875f56beddC4") # From bytes addr3 = Address(b"\x00" * 20) # From integer addr4 = Address(1) # Generate new address addr5 = boa.env.generate_address() ``` -------------------------------- ### Get Call Trace Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/call_trace.md Use this function to retrieve the call trace of a computation. It returns a TraceFrame instance. ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> contract.main() >>> contract.call_trace() ``` -------------------------------- ### Deploy Contract as Blueprint Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_blueprint/overview.md Demonstrates how to load a Vyper contract partially and deploy it as a blueprint using boa. ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> blueprint = deployer.deploy_as_blueprint() >>> type(blueprint) ``` -------------------------------- ### Forking Mainnet: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Demonstrates how to fork a live network for testing in Forge (using `--fork-url`) and Titanoboa (`boa.fork`). Includes options for specifying a block number. ```bash forge test --fork-url https://eth-mainnet.g.alchemy.com/v2/KEY forge test --fork-url https://eth-mainnet.g.alchemy.com/v2/KEY --fork-block-number 12345678 ``` ```python boa.fork("https://eth-mainnet.g.alchemy.com/v2/KEY") boa.fork("https://eth-mainnet.g.alchemy.com/v2/KEY", block_identifier=12345678) ``` -------------------------------- ### Get Vyper Trace Source Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/trace_source.md Use trace_source to retrieve the VyperTraceSource for a computation. This is useful for debugging failed transactions. ```python >>> import boa >>> src = """ ... @external ... def main(): ... assert False, "error" ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> try: ... contract.main() ... except: ... pass >>> contract.trace_source(contract._computation) ``` -------------------------------- ### Get Contract Bytecode Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/network_env.md Retrieves the bytecode stored at a specific address. Returns bytes or None if the address is an EOA. ```python import boa >>> code = boa.env.get_code("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") >>> if code: ... print(f"Contract has {len(code)} bytes of code") ... else: ... print("No code at address (EOA)") ``` -------------------------------- ### Creating Addresses Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/address.md Demonstrates various ways to instantiate an Address object, including from hex strings, checksum addresses, bytes, and integers. It also shows how to generate new addresses using the Boa environment. ```APIDOC ## Creating Addresses The `Address` class can be instantiated in several ways: ### From Hex String ```python from boa.util.abi import Address addr1 = Address("0x0000000000000000000000000000000000000001") ``` ### From Checksum Address ```python addr2 = Address("0x5B38Da6a701c568545dCfcB03FcB875f56beddC4") ``` ### From Bytes ```python addr3 = Address(b"\x00" * 20) ``` ### From Integer ```python addr4 = Address(1) ``` ### Generate New Address ```python import boa addr5 = boa.env.generate_address() ``` ``` -------------------------------- ### Deploying a Vyper Contract with Boa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/_BaseEVMContract.md Demonstrates how to load a partial Vyper contract source and deploy it using the boa library. This is useful for setting up contract instances for testing or interaction. ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> type(contract) ``` -------------------------------- ### get_singleton Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Get or create the singleton instance of the `Env` class. This is typically used internally to ensure a single environment instance. ```APIDOC ## `get_singleton` ### Description Get or create the singleton instance of the `Env` class. This is typically used internally to ensure a single environment instance. ### Returns The singleton instance of the `Env` class. ### Example ```python >>> import boa >>> env = boa.env.get_singleton() >>> # Use env for environment operations ``` ``` -------------------------------- ### Get Current Gas Price Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Fetches the current gas price configured for the environment. This is important for estimating transaction costs. ```python import boa boa.env.get_gas_price() ``` -------------------------------- ### Get VVMDeployer Constructor Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vvm_deployer/constructor.md Instantiate VVMDeployer and access its constructor property to retrieve the contract's constructor function from the ABI. ```python >>> deployer = VVMDeployer(abi, bytecode, filename) >>> constructor = deployer.constructor ``` -------------------------------- ### reset_gas_used Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Reset the gas usage counter to zero and reset access counters. Useful for starting a fresh gas measurement. ```APIDOC ## `reset_gas_used` ### Description Reset the gas usage counter to zero and reset access counters. ### Example ```python >>> import boa >>> boa.env.reset_gas_used() >>> # Gas usage is now reset to 0 ``` ### Note This is useful when you want to start a fresh gas measurement. ``` -------------------------------- ### Contract Deployment: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Illustrates contract deployment syntax in Forge (Solidity) and Titanoboa (Python), including passing constructor arguments and value. ```solidity contract = new MyContract(); contract = new MyContract{value: 1 ether}(arg1, arg2); ``` ```python contract = boa.load("MyContract.vy") contract = boa.load("MyContract.vy", arg1, arg2, value=10**18) ``` -------------------------------- ### get_gas_used Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Get the total amount of gas used in the current environment. This is useful for tracking gas consumption across multiple operations. ```APIDOC ## `get_gas_used` ### Description Get the total amount of gas used in the current environment. This is useful for tracking gas consumption across multiple operations. ### Returns The total gas used as an integer. ### Example ```python >>> import boa >>> gas_used = boa.env.get_gas_used() >>> print(f"Total gas used: {gas_used}") ``` ``` -------------------------------- ### Get Account Balance Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Retrieves the Ether balance of a given account address. This function is essential for checking account funds during simulations. ```python import boa boa.env.get_balance("0x...") ``` -------------------------------- ### Network Deployment with Custom Transaction Settings Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Deploy contracts on a live network by setting the network environment and customizing transaction settings like gas price before deployment. ```python # Connect to network boa.set_network_env("https://eth-mainnet.g.alchemy.com/v2/YOUR-KEY") # Load deployer deployer = boa.load_partial("MyContract.vy") # Deploy with network-specific settings from boa.network import NetworkEnv boa.env.tx_settings.gas_price = 30 * 10**9 # 30 gwei contract = deployer.deploy(constructor_arg) print(f"Deployed at: {contract.address}") print(f"Transaction: {contract.receipt.transactionHash.hex()}") ``` -------------------------------- ### Network Mode: Interacting with Mainnet Contracts Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Illustrates connecting to a contract on a live network (e.g., Ethereum mainnet) using `at()`. This requires setting the network environment and providing the contract's address. ```python # Connect to mainnet boa.set_network_env("https://eth-mainnet.g.alchemy.com/v2/YOUR-KEY") # Connect to USDC contract usdc_address = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" usdc = boa.load_partial("USDC.vy").at(usdc_address) # Query contract total_supply = usdc.totalSupply() print(f"USDC Total Supply: {total_supply / 10**6:,.0f}") ``` -------------------------------- ### Get VyperContract Instance at Address Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_deployer/at.md Instantiate a `VyperContract` object at a given address. This is useful for interacting with contracts that have already been deployed to the blockchain. ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, "Foo") >>> contract = deployer.deploy() >>> contract_at_address = deployer.at(contract.address) >>> type(contract_at_address) ``` -------------------------------- ### Working with Proxy Contracts Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Explains how to use `at()` with the implementation ABI to interact with a proxy contract. Calls made to the contract instance will be routed through the proxy to the underlying implementation. ```python # Implementation ABI implementation_deployer = boa.load_partial("ImplementationV2.vy") # Connect to proxy address with implementation ABI proxy_address = "0x1234567890123456789012345678901234567890" contract = implementation_deployer.at(proxy_address) # Calls go through proxy to implementation contract.upgradedFunction() ``` -------------------------------- ### Get Stack Trace of Last Computation Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/stack_trace.md Retrieves the stack trace for the most recent computation. Useful for debugging failed transactions or assertions. ```python import boa src = """ @external def main(): assert False, "error" """ deployer = boa.loads_partial(src, name="Foo") contract = deployer.deploy() try: contract.main() except: pass contract.stack_trace() ``` -------------------------------- ### Get Contract Verifier Instance Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/verify/get_verifier.md Call `boa.get_verifier()` to obtain the current contract verifier. This is useful for interacting with contract verification services. ```python import boa verifier = boa.get_verifier() print(type(verifier)) # ``` -------------------------------- ### Creating Mock Contracts: Forge vs. Titanoboa Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/forge.md Illustrates creating mock ERC20 contracts. Forge uses standard Solidity inheritance, while Titanoboa uses `boa.loads` with a Vyper string. ```solidity contract MockToken is ERC20 { function mint(address to, uint256 amount) public { _mint(to, amount); } } ``` ```python mock_token = boa.loads(""" @external def mint(to: address, amount: uint256): self.balances[to] += amount self.totalSupply += amount @external def balanceOf(account: address) -> uint256: return self.balances[account] """) ``` -------------------------------- ### Set up Deployment Tracking Database Source: https://context7.com/vyperlang/titanoboa/llms.txt Configures a persistent SQLite database to log contract deployments. Ensure the database file path is correctly specified. ```python import boa from boa.deployments import DeploymentsDB, set_deployments_db # Persistent deployment log set_deployments_db(DeploymentsDB("./deployments.db")) boa.set_network_env("http://localhost:8545") from eth_account import Account boa.env.add_account(Account.from_key("0x")) erc20 = boa.load("examples/ERC20.vy", "LoggedToken", "LT", 18, 10**18) # Query all deployments (most recent first) db = DeploymentsDB("./deployments.db") for dep in db.get_deployments(): print(f"[{dep.deployment_id}] {dep.contract_name} @ {dep.contract_address}") print(f" tx: {dep.tx_hash}") print(f" deployer: {dep.deployer}") print(f" timestamp: {dep.broadcast_ts}") # Export to JSON for CI artifacts first = next(db.get_deployments()) print(first.to_json(indent=2)) ``` -------------------------------- ### Get Contract ABI Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/abi.md Retrieve the ABI of a deployed Vyper contract. This property returns a dictionary representing the contract's ABI. ```python >>> import boa >>> src = """ ... @external ... def main(): ... pass ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> contract_abi = contract.abi >>> type(contract_abi) ``` -------------------------------- ### Debugging with Source Mapping Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/advanced_features.md Illustrates how to use `boa.env.anchor` and exception handling to trace contract execution with source mapping. Stack traces will include Vyper source lines for debugging. ```python contract = boa.loads(""" @external def complex_function(x: uint256) -> uint256: if x > 100: return x * 2 else: return x + 50 """) try: with boa.env.anchor(): result = contract.complex_function(150) # Source maps track which lines were executed except Exception as e: # Stack traces include Vyper source lines print(contract.stack_trace(e)) ``` -------------------------------- ### Install Latest Release with uv Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/install.md Use this command to add the latest stable version of Titanoboa to your project's dependencies using uv. ```console uv add titanoboa ``` -------------------------------- ### Configure IPython for Titanoboa Extension Source: https://github.com/vyperlang/titanoboa/blob/master/README.md Demonstrates how to automatically load the Titanoboa IPython extension and import the `boa` library on every IPython session startup by modifying the `ipython_config.py` file. ```python c.InteractiveShellApp.extensions = ["boa.ipython"] c.InteractiveShellApp.exec_lines = ['import boa'] ``` -------------------------------- ### Install Latest Release with poetry Source: https://github.com/vyperlang/titanoboa/blob/master/docs/tutorials/install.md Use this command to add the latest stable version of Titanoboa to your project's dependencies using poetry. ```console poetry add titanoboa ``` -------------------------------- ### Hypothesis Integration for Property-Based Testing Source: https://github.com/vyperlang/titanoboa/blob/master/docs/guides/advanced_features.md Integrate Hypothesis for property-based testing. The Titanoboa pytest plugin ensures state isolation between test examples. ```python from hypothesis import given, strategies as st @given(value=st.integers(min_value=0, max_value=10**18)) def test_property(value): contract = boa.loads(""" total: uint256 @external def add(amount: uint256): self.total += amount """) contract.add(value) assert contract.eval("self.total") == value # State automatically isolated between examples ``` -------------------------------- ### load Source: https://github.com/vyperlang/titanoboa/blob/master/docs/template.md Compiles source code from a specified file path and returns a deployed instance of the contract. ```APIDOC ## `load` ### Description Compile source from disk and return a deployed instance of the contract. ### Signature ```python load( fp: str, *args: Any, **kwargs: Any ) -> VyperContract | VyperBlueprint ``` ### Parameters - `fp` (str): The contract source code file path. - `args` (Any): Contract constructor arguments. - `kwargs` (Any): Keyword arguments to pass to the [`boa.loads`](api/load_contracts.md#loads) function. ### Returns A [`VyperContract`](api/vyper_contract/overview.md) or [`VyperBlueprint`](api/vyper_blueprint/overview.md) instance. ### Examples === "Deployment" ```python >>> import boa >>> boa.load("Foo.vy") ``` ```python >>> import boa >>> from vyper.compiler.settings import OptimizationLevel, Settings >>> boa.load("Foo.vy", compiler_args={"settings": Settings(optimize=OptimizationLevel.CODESIZE)}) ``` === "Foo.vy" ```vyper # Foo.vy @external def addition(a: uint256, b: uint256) -> uint256: return a + b ``` ``` -------------------------------- ### get_gas_meter_class Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Get the current gas meter class used in the environment. This method is useful for inspecting the current gas metering behavior in the environment. ```APIDOC ## `get_gas_meter_class` ### Description Get the current gas meter class used in the environment. This method is useful for inspecting the current gas metering behavior in the environment. ### Returns The current gas meter class. ### Example ```python >>> import boa >>> gas_meter_class = boa.env.get_gas_meter_class() >>> print(gas_meter_class.__name__) 'GasMeter' # Default gas meter class ``` ``` -------------------------------- ### loads_partial Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/load_contracts.md Compiles Vyper source code provided as a string and returns a deployer instance. ```APIDOC ## `boa.loads_partial(source)` ### Description The `loads_partial` function compiles Vyper source code provided as a string and returns a deployer instance. This function is useful for preparing contracts for deployment in environments where the source code is dynamically generated or modified. ### Parameters - `source`: The Vyper source code. - `name`: The name of the contract (optional). - `dedent`: If `True`, remove any common leading whitespace from every line in `source`. - `compiler_args`: Argument to be passed to the Vyper compiler (optional). ### Returns A [`VyperDeployer`](vyper_deployer/overview.md) or [`VVMDeployer`](vvm_deployer/overview.md) instance. If a legacy Vyper version is detected, a `VVMDeployer` may be returned due to VVM usage. See [Legacy Vyper Contracts](../explain/vvm_contracts.md) for more details. ### Examples SOON ``` -------------------------------- ### Creating Multiple Contract Instances Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Shows how to create multiple contract instances by iterating over a dictionary of token addresses and using `at()` for each. This is useful for managing multiple ERC20 tokens or other contracts. ```python # Token addresses on mainnet addresses = { "USDC": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "USDT": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F", } # Create instances for each erc20_deployer = boa.load_partial("ERC20.vy") tokens = {} for name, addr in addresses.items(): tokens[name] = erc20_deployer.at(addr) print(f"{name}: {tokens[name].symbol()}") ``` -------------------------------- ### Get Singleton Environment Instance Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/env/env.md Retrieves the singleton instance of the environment. This is typically used internally to manage a single, consistent environment state. ```python import boa env = boa.env.get_singleton() # Use env for environment operations ``` -------------------------------- ### Testing Pattern: Verifying Contract Upgrades Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vyper_contract/at.md Demonstrates using `at()` in tests to simulate a contract upgrade. By connecting a new contract version's ABI to the old contract's address, you can verify state persistence and new functionality. ```python def test_contract_upgrade(): # Deploy V1 v1 = boa.load("ContractV1.vy") v1.initialize(100) # Store address contract_address = v1.address # Simulate upgrade by connecting V2 ABI to same address v2_deployer = boa.load_partial("ContractV2.vy") v2 = v2_deployer.at(contract_address) # Verify state persisted assert v2.get_value() == 100 # Use new functionality v2.new_function() ``` -------------------------------- ### Get Contract Instance at Address Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/vvm_deployer/at.md Use this method to obtain a contract instance at a given address after deployment. Requires a pre-existing VVMDeployer instance. ```python >>> deployer = VVMDeployer(abi, bytecode, filename) >>> contract = deployer.deploy() >>> contract_at_address = deployer.at(contract.address) ``` -------------------------------- ### Connecting to Existing Contracts Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/deployer.md Use the `at` method to create a contract instance connected to an already deployed contract at a given address. This works with both string addresses and `Address` objects. ```python # Connect to existing contract existing = deployer.at("0x1234567890123456789012345678901234567890") # Works with Address objects too from boa.util.abi import Address addr = Address("0x1234567890123456789012345678901234567890") existing = deployer.at(addr) ``` -------------------------------- ### Get Computation Stack Trace Source: https://github.com/vyperlang/titanoboa/blob/master/docs/api/common_classes/stack_trace.md Use this function to retrieve the stack trace of a computation after an error has occurred. Ensure the computation object is available. ```python >>> import boa >>> src = """ ... @external ... def main(): ... assert False, "error" ... """ >>> deployer = boa.loads_partial(src, name="Foo") >>> contract = deployer.deploy() >>> try: ... contract.main() ... except: ... pass >>> contract.stack_trace(contract._computation) ```