### Generate Example Project Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Generates an example Wake project in the current empty working directory. This command is useful for quickly setting up a boilerplate project to follow along with the guide's examples. ```bash wake up --example counter ``` -------------------------------- ### Setup Config and Generate Pytypes Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Configures Wake's compilation settings by creating a `wake.toml` file and then generates pytypes for Solidity contracts. This is an alternative to the full `wake up` command if only configuration and pytype generation are needed. ```bash wake up config wake up pytypes -w ``` -------------------------------- ### Install Foundry Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Installs the latest version of Anvil, a component of the Foundry development chain, which is crucial for Wake development. Ensure you have the latest version installed as it's under active development. ```bash foundryup ``` -------------------------------- ### Wake CLI: Detectors and Printers with Path Specification Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started This example shows how to specify paths for detectors and printers when running Wake from the command line. It demonstrates passing source code file and directory paths as arguments. ```bash wake detect my-detector contracts/utils ``` -------------------------------- ### Python: Printer CLI with Arguments and Options Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Shows how to define a command-line interface for a Wake printer using the Click library. This example includes defining a required string argument and a boolean flag option, demonstrating how to add custom parameters to printers. ```python import click from wake.cli import @printer @printer.command(name="my-printer") @click.argument( "modifier", type=str, required=True, help="Name of the modifier to analyze.", ) @click.option( "--follow-function-calls/--no-follow-function-calls", is_flag=True, default=False, help="Follow function calls in the modifier.", ) def cli(modifier: str, follow_function_calls: bool) -> None: # Printer logic here pass ``` -------------------------------- ### Python: Create Printer Template using Wake CLI Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Generates a template for a new printer using the Wake command-line interface. This command initializes a basic printer structure in the `./printers` directory, facilitating the creation of custom analysis output formats. The `--global` flag can be used for global installation. ```bash wake up printer printer-name ``` -------------------------------- ### Python: Create Detector Template using Wake CLI Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Generates a template for a new detector using the Wake command-line interface. This command initializes a basic detector structure in the `./detectors` directory, serving as a starting point for custom implementations. The `--global` flag can be used to create it in a global directory. ```bash wake up detector detector-name ``` -------------------------------- ### Python: Visiting AST Nodes in Wake Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Illustrates how to implement visitor methods for Solidity Abstract Syntax Tree (AST) nodes within a Wake detector or printer. The example shows a `visit_function_definition` method that processes a function definition node from the Wake IR. ```python from wake.ir import FunctionDefinition from wake.detectors import Detector class MyDetectorDetector(Detector): # ... other methods ... def visit_function_definition(self, node: FunctionDefinition) -> None: # Process the function definition node pass ``` -------------------------------- ### Install eth-wake using pip Source: https://ackee.xyz/wake/docs/latest/installation Installs the eth-wake Python package using pip. Ensure you have Python 3.8 or higher installed. This is the primary method for integrating Wake into your Python projects. ```bash pip3 install eth-wake ``` -------------------------------- ### Pull and run Wake Docker image Source: https://ackee.xyz/wake/docs/latest/installation Pulls the official Wake Docker image and runs it interactively, displaying the help message. This is useful for testing Wake without a local Python installation or for isolated environments. ```bash docker pull ackeeblockchain/wake docker run -it ackeeblockchain/wake wake --help ``` -------------------------------- ### Generate Pytypes Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Generates Python-native equivalents ('pytypes') of Solidity types from Solidity source files. This command also prepares the `wake.toml` configuration file, updates `.gitignore`, and sets up a basic project directory structure. ```bash wake up ``` -------------------------------- ### Deploy Solidity Contract using Wake Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Shows how to deploy a Solidity contract using Wake's generated Python types. The `Counter.deploy()` method is used, which takes constructor arguments and optional keyword arguments to configure the deployment transaction. This assumes `pytypes.contracts.Counter` has been generated. ```python from wake.testing import * from pytypes.contracts.Counter import Counter @chain.connect() def test_example(): counter = Counter.deploy() print(counter) ``` -------------------------------- ### Wake Printer: Override visit_mode to 'all' with Path Filtering Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started This Python example shows a printer overriding the visit_mode to 'all' and implementing custom logic to filter detections based on specified paths. This ensures that only relevant information from the provided paths is processed. ```python class MyPrinterPrinter(Printer): ... @property def visit_mode(self): return "all" def visit_contract_definition(self, node: ir.ContractDefinition) -> None: from wake.utils import is_relative_to if not any(is_relative_to(node.source_unit.file, p) for p in self.paths): return ... ``` -------------------------------- ### Connect to Blockchain Chain using Wake Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Demonstrates how to use the `chain.connect()` decorator in Wake to either launch a new development chain or connect to an existing one via HTTP, WebSocket, or IPC socket. This is essential for running tests in a controlled environment. ```python from wake.testing import * # launch a new development chain @chain.connect() # or connect to an existing chain # @chain.connect("ws://localhost:8545") def test_counter(): print(chain.chain_id) ``` -------------------------------- ### Python: Basic Detector Class Structure Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Illustrates the fundamental structure of a custom detector in Python for Wake. It includes the necessary inheritance from the `Detector` class, initialization of a detections list, and the implementation of the `detect` method to return findings. A Click-based CLI command is also defined. ```python from typing import List from wake.detectors import Detector, DetectorResult from wake.cli import @detector class MyDetectorDetector(Detector): _detections: List[DetectorResult] def __init__(self) -> None: self._detections = [] def detect(self) -> List[DetectorResult]: return self._detections @detector.command(name="my-detector") def cli(self) -> None: pass ``` -------------------------------- ### Python: Basic Printer Class Structure Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Demonstrates the basic structure of a custom printer in Python for Wake. It inherits from the `Printer` class and implements the `print` method for outputting analysis results. A Click-based CLI command is also included. ```python from wake.printers import Printer from wake.cli import @printer class MyPrinterPrinter(Printer): def print(self) -> None: pass @printer.command(name="my-printer") def cli(self) -> None: pass ``` -------------------------------- ### Configure Fish shell completion for Wake Source: https://ackee.xyz/wake/docs/latest/installation Enables shell completions for the `wake` command in Fish by adding a command to your `~/.config/fish/completions/wake.fish` file. This integrates Wake's command suggestions into the Fish shell's completion system. ```fish eval (env _WAKE_COMPLETE=fish_source wake) ``` -------------------------------- ### Wake Detector: Override visit_mode to 'all' Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started This Python snippet illustrates how a detector can override the default 'paths' visit mode to 'all', enabling it to process all IR nodes in the project. This is useful for detectors that require a project-wide view. ```python class MyDetectorDetector(Detector): ... @property def visit_mode(self) -> str: return "all" ``` -------------------------------- ### Interact with Deployed Contract using Wake Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started Illustrates how to interact with a deployed Solidity contract through Wake's generated Python methods. This includes calling functions like `increment` and `setCount`, managing transaction senders (`from_`), and asserting contract state changes. It also shows how to test for reverted transactions using `must_revert`. ```python from wake.testing import * from pytypes.contracts.Counter import Counter @chain.connect() def test_counter(): owner = chain.accounts[0] other = chain.accounts[1] counter = Counter.deploy(from_=owner) counter.increment(from_=other) assert counter.count() == 1 # setCount can only be called by the owner counter.setCount(10, from_=owner) assert counter.count() == 10 # this will fail because the sender account is not the owner with must_revert(): counter.setCount(20, from_=other) assert counter.count() == 10 ``` -------------------------------- ### Python: Generating Links from IR Nodes Source: https://ackee.xyz/wake/docs/latest/static-analysis/getting-started Demonstrates the use of the `generate_link` method within a Wake detector or printer to create console links pointing to specific IR nodes. This is useful for providing interactive references to code elements in the analysis output. ```python from wake.ir import FunctionDefinition from wake.detectors import Detector class MyDetectorDetector(Detector): # ... other methods ... def visit_function_definition(self, node: FunctionDefinition) -> None: link = f"[link={self.generate_link(node)}]{node.canonical_name}[/link]" print(link) # Example usage ``` -------------------------------- ### Setup Git Hooks Source: https://ackee.xyz/wake/docs/latest/contributing Makes the git hook setup script executable and then runs it. These hooks automate checks like code formatting and testing before commits. ```shell chmod +x ./setup-githooks.sh ./setup-githooks.sh ``` -------------------------------- ### Complete FuzzTest Example for Counter Contract Source: https://ackee.xyz/wake/docs/latest/testing-framework/fuzzing This comprehensive example integrates flows, invariants, and execution hooks to test a Counter contract. It includes setup in `pre_sequence`, increment/decrement flows with error handling, and an invariant to check the counter's state. The test is run with specific sequence and flow counts. ```Python from wake.testing import * from wake.testing.fuzzing import * from pytypes.contracts.Counter import Counter class CounterTest(FuzzTest): counter: Counter count: int def pre_sequence(self) -> None: self.counter = Counter.deploy() self.count = 0 @flow() def flow_increment(self) -> None: self.counter.increment() self.count += 1 @flow() def flow_decrement(self) -> None: with may_revert(PanicCodeEnum.UNDERFLOW_OVERFLOW) as e: self.counter.decrement() if e.value is None: self.count -= 1 else: assert self.count == 0 @invariant(period=10) def invariant_count(self) -> None: assert self.counter.count() == self.count @chain.connect() def test_counter(): CounterTest().run(sequences_count=30, flows_count=100) ``` -------------------------------- ### Configure Bash shell completion for Wake Source: https://ackee.xyz/wake/docs/latest/installation Enables shell completions for the `wake` command in Bash by adding a command to your `~/.bashrc` file. This enhances command-line usability by providing autocompletion suggestions. ```bash eval "$(_WAKE_COMPLETE=bash_source wake)" ``` -------------------------------- ### Install Project with Poetry Source: https://ackee.xyz/wake/docs/latest/contributing Installs the project dependencies using Poetry, including optional development and testing extras. This command ensures all necessary packages are available. ```shell poetry install -E tests -E dev ``` -------------------------------- ### List Installed Solc Versions using SVM Source: https://ackee.xyz/wake/docs/latest/solc-version-manager Lists the solc compiler versions currently installed by SVM. The '--all' option can be used to list all available versions, not just the installed ones. ```bash wake svm list wake svm list --all ``` -------------------------------- ### Solidity Contract Layout Specification Example Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/meta/storage-layout-specifier Demonstrates how to specify a storage layout at a particular slot within a Solidity contract. This example shows the syntax used in Solidity code. ```solidity contract C layout at (10 + 20) {} ``` -------------------------------- ### Install Solc Version using SVM Source: https://ackee.xyz/wake/docs/latest/solc-version-manager Installs a specific version or a range of versions of the solc compiler using the 'wake svm install' command. The '--force' option can be used to reinstall an already installed version. ```bash wake svm install wake svm install wake svm install --force wake svm install --all ``` -------------------------------- ### Install Project with pip Source: https://ackee.xyz/wake/docs/latest/contributing Installs the project in editable mode using pip, including development and testing dependencies. The `-e` flag allows for direct modification of installed files. ```shell pip install -e ".[tests,dev]" ``` -------------------------------- ### Solidity Do-While Loop Example Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/statements/do-while-statement An example of a do-while loop in Solidity, demonstrating its syntax for repeating a block of code until a condition is met. This snippet is used for illustrating the DoWhileStatement class. ```solidity function foo(uint x) public { do { x += 1; } while (x < 10); } ``` -------------------------------- ### Get Mapping Value Name Location in Python Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/type-names/mapping Python code to get the source code location (start and end byte offsets) of the mapping's value name. This is available for mappings in Solidity 0.8.18 and later. ```python return self._value_name_location ``` -------------------------------- ### Get Mapping Key Name Location in Python Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/type-names/mapping Python code to get the source code location (start and end byte offsets) of the mapping's key name. This is available for mappings in Solidity 0.8.18 and later. ```python return self._key_name_location ``` -------------------------------- ### List Detector Help and Configuration Options Source: https://ackee.xyz/wake/docs/latest/static-analysis/using-detectors This command displays detailed help information for a specific detector, including available arguments, options, and environment variables for configuration. It's a crucial step for understanding how to customize detector behavior. ```bash wake detect detector-name --help ``` -------------------------------- ### Wake Accounts CLI Help Source: https://ackee.xyz/wake/docs/latest/testing-framework/deployment This displays the help information for the `wake accounts` command, outlining available subcommands for managing accounts, such as importing, exporting, listing, creating new accounts, and removing existing ones. ```bash $ wake accounts --help Usage: wake accounts [OPTIONS] COMMAND [ARGS]... Run Wake accounts manager. ╭─ Options ──────────────────────────────────────────────────────────────╮ │ --help Show this message and exit. │ ╰─────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ──────────────────────────────────────────────────────────────╮ │ export Export an account's private key. │ │ import Import an account from a private key or mnemonic. │ │ list List all accounts. │ │ new Create a new account. │ │ remove Remove an account. │ ╰─────────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Solidity String Slicing Example Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/types This Solidity code snippet demonstrates how to create a string slice using the slicing syntax `[start:end]`. String slices are a way to reference a portion of a string. ```solidity function foo(string calldata s) public pure { s[0:5]; // s[0:5] is a string slice } ``` -------------------------------- ### Configure Zsh shell completion for Wake Source: https://ackee.xyz/wake/docs/latest/installation Enables shell completions for the `wake` command in Zsh by adding a command to your `~/.zshrc` file. This provides autocompletion features for the `wake` command within the Zsh shell. ```bash eval "$(_WAKE_COMPLETE=zsh_source wake)" ``` -------------------------------- ### Pytest Fixture for Chain Connection Source: https://ackee.xyz/wake/docs/latest/testing-framework/getting-started A pytest fixture that establishes a connection to a blockchain. It checks if a connection already exists before attempting to connect, ensuring efficient use of resources when interacting with smart contracts in tests. ```python @fixture def chain(): if chain.connected: return chain else: with chain.connect(): yield chain ``` -------------------------------- ### Wake Plugins Configuration Example (TOML) Source: https://ackee.xyz/wake/docs/latest/configuration This TOML snippet demonstrates how to configure plugin loading priorities for Wake detectors and printers. It allows specifying preferred modules for specific plugins or a default for all. ```toml [detector_loading_priorities] reentrancy = "my_detectors" # prefer my_detectors module if present unused-import = ["my_detectors", "wake_detectors"] # prefer my_detectors, then wake_detectors "*" = "wake_detectors" # prefer wake_detectors for all other detectors [printer_loading_priorities] # follows the same structure ``` -------------------------------- ### Get Byte Offsets of External Reference - Python Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/statements/inline-assembly Calculates and returns the byte offsets (start and end) of an identifier representing an external reference within a Solidity source file. It handles stripping comments and adjusting offsets based on stripped content. ```python source = bytearray(self._source) _, stripped_sums = SoliditySourceParser.strip_comments(source) match = IDENTIFIER_RE.match(source) assert match if len(stripped_sums) == 0: stripped = 0 else: index = bisect([s[0] for s in stripped_sums], match.start()) if index == 0: stripped = 0 else: stripped = stripped_sums[index - 1][1] start = self.byte_location[0] + match.start() + stripped end = self.byte_location[0] + match.end() + stripped return start, end ``` -------------------------------- ### Python: Deploy Contract From Creation Code Source: https://ackee.xyz/wake/docs/latest/testing-framework/accounts-and-addresses Shows how to deploy a contract by providing its raw creation bytecode to the `chain.deploy` method. This is useful when you have the contract's creation code and need to instantiate it on the blockchain. ```python chain.deploy(Counter.get_creation_code()) ``` -------------------------------- ### Access Accounts with Wake Testing Source: https://ackee.xyz/wake/docs/latest/testing-framework/migrating-from-ape-and-brownie Demonstrates how to access and print the available accounts provided by the Wake testing framework. Accounts are managed by the default `chain` instance. ```python from wake.testing import * @chain.connect() def test_accounts(): print(chain.accounts) ``` -------------------------------- ### ProjectBuild Class Initialization and Properties (Python) Source: https://ackee.xyz/wake/docs/latest/api-reference/compiler/build-data-model Defines the ProjectBuild class, responsible for holding a single project build. It initializes with interval trees, a reference resolver, and source units, and provides properties to access these components. The interval trees allow querying IR nodes by byte offsets, the reference resolver handles AST node ID to IR node resolution, and source units map file paths to top-level IR nodes. ```python class ProjectBuild: """ Class holding a single project build. """ _interval_trees: Dict[Path, IntervalTree] _reference_resolver: ReferenceResolver _source_units: Dict[Path, SourceUnit] def __init__( self, interval_trees: Dict[Path, IntervalTree], reference_resolver: ReferenceResolver, source_units: Dict[Path, SourceUnit], ): self._interval_trees = interval_trees self._reference_resolver = reference_resolver self._source_units = source_units @property def interval_trees(self) -> Dict[Path, IntervalTree]: """ Returns: Mapping of source file paths to [interval trees](https://github.com/chaimleib/intervaltree) that can be used to query IR nodes by byte offsets in the source code. """ return MappingProxyType( self._interval_trees ) # pyright: ignore reportGeneralTypeIssues @property def reference_resolver(self) -> ReferenceResolver: """ Returns: Reference resolver responsible for resolving AST node IDs to IR nodes. Useful especially for resolving references across different compilation units. """ return self._reference_resolver @property def source_units(self) -> Dict[Path, SourceUnit]: """ Returns: Mapping of source file paths to top-level [SourceUnit][wake.ir.meta.source_unit.SourceUnit] IR nodes. """ return MappingProxyType( self._source_units ) # pyright: ignore reportGeneralTypeIssues ``` -------------------------------- ### Get Type Name String Representation Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/type-names/abc This property returns a user-friendly string representation of the type name. It is useful for displaying complex types like mappings or arrays in a human-readable format, as demonstrated by the example `mapping(uint256 => int24[])`. An assertion ensures the 'type_string' attribute is available. ```python class TypeNameAbc(SolidityAbc, ABC): ... @property def type_string(self) -> str: """ !!! example `:::solidity mapping(uint256 => int24[])` in the case of the `:::solidity mapping(uint => int24[])` type name in the following declaration: ```solidity mapping(uint => int24[]) map; ``` Returns: User-friendly string describing the type name type. """ assert self._type_descriptions.type_string is not None return self._type_descriptions.type_string ``` -------------------------------- ### List Available Detector Sources Source: https://ackee.xyz/wake/docs/latest/static-analysis/using-detectors This command lists all available sources for detectors, including local project-specific directories, global detector directories, and installed detector packages (plugins). This helps in understanding where detectors are being loaded from and their respective priorities. ```bash wake detect list ``` -------------------------------- ### Get Byte Location of IR Node in wake/ir/abc.py Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/abc This property returns the start and end byte offsets of an IR node within its source file. It's useful for pinpointing the exact location of code segments. Note that structured documentation has a different location logic. ```python @property def byte_location(self) -> Tuple[int, int]: """ Returns: Tuple of the start and end byte offsets of this node in the source file. """ return ( self._ast_node.src.byte_offset, self._ast_node.src.byte_offset + self._ast_node.src.byte_length, ) ``` -------------------------------- ### Get User-Friendly Type String for Expression (Python & Solidity) Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/expressions/abc Returns a user-friendly string representing the type of the expression. This can be particularly useful for Solidity expressions, providing a readable format for function signatures or type names. It can return None for identifiers within import directives, as demonstrated in the Solidity example. ```python @property def type_string(self) -> Optional[str]: """ !!! example `:::solidity function (uint256,uint256) returns (uint256)` in the case of the `foo` [Identifier][wake.ir.expressions.identifier.Identifier] in the `:::solidity foo(1, 2)` expression for the following function: ```solidity function foo(uint a, uint b) public onlyOwner payable virtual onlyOwner returns(uint) { return a + b; } ``` Can be `None` in case of an [Identifier][wake.ir.expressions.identifier.Identifier] in an [ImportDirective][wake.ir.meta.import_directive.ImportDirective]. !!! example `Ownable` in the following example has no type information: ```solidity import { Ownable } from './Ownable.sol'; ``` Returns: User-friendly string describing the expression type. """ return self._type_descriptions.type_string ``` -------------------------------- ### Creating a New Random Account in Python Source: https://ackee.xyz/wake/docs/latest/testing-framework/accounts-and-addresses Provides an example of creating a new Account instance with a randomly generated private key. This is useful for setting up fresh accounts for testing. ```python from wake.testing import Account Account.new() ``` -------------------------------- ### Python: Deploy and Interact with Contracts via Proxy Source: https://ackee.xyz/wake/docs/latest/testing-framework/accounts-and-addresses Demonstrates deploying an implementation contract (`Counter`) and then deploying a proxy (`ERC1967Proxy`) that points to the implementation. It shows how to interact with the contract through the proxy's address, treating it as the actual contract instance. ```python from wake.testing import * from pytypes.contracts.Counter import Counter from pytypes.openzeppelin.contracts.proxy.ERC1967.ERC1967Proxy import ERC1967Proxy @chain.connect() def test_proxy(): impl = Counter.deploy() proxy = ERC1967Proxy.deploy(impl, b"") # behave as if Counter was deployed at proxy.address counter = Counter(proxy.address) counter.increment() assert counter.count() == 1 ``` -------------------------------- ### Solidity Factory Contract for Initialization Strategies Source: https://ackee.xyz/wake/docs/latest/cookbook/testing-infrastructure/initialization-strategies This Solidity contract defines a factory with different strategy types for deployment. It includes structs for parameters specific to each strategy and a deploy function. It requires specific parameter types for each strategy, and invalid strategy types or parameters will result in errors. ```solidity contract Factory { enum StrategyType { BASIC, ADVANCED, UPGRADEABLE, PROXY } error InvalidStrategy(); error InvalidParams(); struct BasicParams { address admin; uint256 value; } struct AdvancedParams { address admin; string name; uint8 version; uint256 config; } struct UpgradeableParams { address admin; address implementation; bytes initData; } struct ProxyParams { address admin; address logic; address proxy; } function deploy( bytes32 salt, StrategyType strategyType, bytes memory params ) external returns (address) { // Deploy contract based on strategy } } ``` -------------------------------- ### Python Cross-Chain Message Passing Fuzz Test Source: https://ackee.xyz/wake/docs/latest/cookbook/specialized-use-cases/cross-chain-message-passing This Python script defines a cross-chain fuzz test. It sets up two chains and services, then simulates sending a message from chain1 to chain2 and executing it on the destination chain. Dependencies include a fuzz testing framework (like Brownie or a similar setup) with Chain and Service abstractions. ```python class CrossChainFuzzTest(FuzzTest): chain1: Chain chain2: Chain service1: Service service2: Service def pre_sequence(self) -> None: self.chain1 = Chain() self.chain2 = Chain() self.service1 = Service.deploy(chain=self.chain1) self.service2 = Service.deploy(chain=self.chain2) @flow() def flow_cross_chain_send(self) -> None: amount = random_int(0, 2**256 - 1) sender = random_account(chain=self.chain1) recipient = random_account(chain=self.chain2) # Send on source chain tx1 = self.service1.sendMessage( "chain2", recipient.address, amount, from_=sender ) # Execute on destination chain self.service2.executeMessage( "chain1", sender.address, amount, tx1.events[0].messageHash, from_=random_account(chain=self.chain2) ) ``` -------------------------------- ### Get Named Arguments from Function Call (Solidity) Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/expressions/function-call This snippet demonstrates how to extract the names of named arguments used in a function call. It is applicable when a function call utilizes named arguments, such as in the example `token.transfer({to: msg.sender, value: 100})`. The 'names' property returns a tuple of strings representing the argument names in their source code order. ```Solidity token.transfer({to: msg.sender, value: 100}); ``` -------------------------------- ### List Printer Loading Sources (Wake CLI) Source: https://ackee.xyz/wake/docs/latest/static-analysis/using-printers Shows all available sources for each printer, including local directories (project-specific and global) and installed packages. This helps understand printer precedence. ```bash wake print list ``` -------------------------------- ### Importing Wake Modules for Testing and Deployment Source: https://ackee.xyz/wake/docs/latest/testing-framework/deployment This snippet shows how to import the appropriate Wake modules based on the environment. `wake.deployment` is used for live chains (testnet/mainnet), while `wake.testing` is for local development chains. ```python # use wake.deployment when interacting with a live chain from wake.deployment import * # use wake.testing when interacting with a local development chain from wake.testing import * ``` -------------------------------- ### List All Available Detectors (Wake CLI) Source: https://ackee.xyz/wake/docs/latest/static-analysis/using-detectors This command lists all the available detectors within the wake_detectors module. It's a foundational step to understand the analysis capabilities. ```bash wake detect --help ``` -------------------------------- ### Configure Wake Development Chains Source: https://ackee.xyz/wake/docs/latest/testing-framework/migrating-from-ape-and-brownie Shows how to configure Wake to launch a new development chain or connect to an existing one. This involves using the `@chain.connect()` decorator with or without a URI, and can be further customized in the `wake.toml` configuration file. ```python @chain.connect() ``` ```python @chain.connect("http://localhost:8545") ``` -------------------------------- ### Run Wake LSP Server Source: https://ackee.xyz/wake/docs/latest/language-server Launches the Wake LSP server. It can be run with default settings or a specified port. The server facilitates communication between the IDE and the Wake toolset for Solidity development. Multi-root workspaces are not supported. ```shell wake lsp ``` ```shell wake lsp --port 1234 ``` -------------------------------- ### Solidity Unused Modifier Detection Example Source: https://ackee.xyz/wake/docs/latest/static-analysis/detectors/unused-modifier This example demonstrates the 'unused-modifier' detector by showing a Solidity contract with an unused modifier. The detector would flag the 'onlyOwner' modifier as unused in this specific example. ```solidity pragma solidity ^0.8; contract C { address public owner; modifier onlyOwner() { require(msg.sender == owner, "Not owner."); _; } constructor() { owner = msg.sender; } function withdraw() external /*onlyOwner*/ { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } } ``` -------------------------------- ### Solidity Struct Example - Solidity Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/declarations/struct-definition An example of how to define a struct in Solidity. This syntax is used within the StructDefinition class to illustrate its purpose. ```solidity struct S { uint a; uint b; } ``` -------------------------------- ### Python Deployment Script using wake.deployment Source: https://ackee.xyz/wake/docs/latest/testing-framework/deployment This Python script demonstrates deploying a Counter smart contract and interacting with it using the `wake.deployment` module. It connects to the Ethereum mainnet via Alchemy, sets default accounts, deploys the contract, increments its count, and asserts the new count. It requires an Alchemy API key and an account aliased as 'deployment'. ```python from wake.deployment import * from pytypes.contracts.Counter import Counter ALCHEMY_API_KEY = "YOUR_ALCHEMY_API_KEY" @chain.connect(f"wss://eth-mainnet.g.alchemy.com/v2/{ALCHEMY_API_KEY}") def main(): acc = Account.from_alias("deployment") chain.set_default_accounts(acc) counter = Counter.deploy() print(counter) counter.increment() assert counter.count() == 1 ``` -------------------------------- ### Account Creation and Chain Association in Python Source: https://ackee.xyz/wake/docs/latest/testing-framework/accounts-and-addresses Shows how to create Account instances, associating them with a specific Chain or the global chain. It highlights that Accounts from different chains are not directly comparable. ```python from wake.testing import Account, Chain, chain other_chain = Chain() assert Account(0) == Account(0, chain) assert Account(0) != Account(0, other_chain) ``` -------------------------------- ### Enum Value Example (Solidity) Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/declarations/enum-value Illustrates the syntax for defining an enum with multiple named values in Solidity. This is used in the documentation example for the EnumValue class. ```solidity enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } ``` -------------------------------- ### Install Pyright with npm Source: https://ackee.xyz/wake/docs/latest/contributing Installs Pyright, a static type checker for Python, globally using npm. This tool helps catch type errors before runtime. ```shell npm i -g pyright ``` -------------------------------- ### Import Optimization for Shell Completions Source: https://ackee.xyz/wake/docs/latest/static-analysis/command-line-interface Illustrates recommended practices for managing imports to ensure fast shell completions in Wake projects. It highlights avoiding unnecessary top-level imports and delaying imports until they are needed within functions or methods. Lazy-loaded modules like `networkx` and `wake.ir` should not be accessed at the top level. ```python from __future__ import annotations from pathlib import Path from typing import Set, Tuple, Union import graphviz import networkx as nx import rich_click as click from rich import print import wake.ir as ir import wake.ir.types as types from wake.cli import SolidityName from wake.printers import Printer, printer class MyPrinter(Printer): restricted_nodes = ( ir.Identifier, ir.IndexAccess, ir.IndexRangeAccess, ir.Literal, ir.MemberAccess, ) ... ``` -------------------------------- ### Execute wake-solc Wrapper Source: https://ackee.xyz/wake/docs/latest/solc-version-manager Demonstrates how to execute the 'wake-solc' wrapper to check the installed solc version. This wrapper points to the currently selected solc executable managed by SVM. ```bash $ wake-solc --version solc, the solidity compiler commandline interface Version: 0.8.15+commit.e14f2714.Linux.g++ ``` -------------------------------- ### Solidity Function with Conditional Return Example Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/statements/return-statement Illustrates a Solidity function where a return statement is used conditionally. This example highlights scenarios where a function might return early. ```solidity function f(uint x) public { if (x > 0) { return; } doSomething(x); } ``` -------------------------------- ### Solidity Modifier Definition Example Source: https://ackee.xyz/wake/docs/latest/api-reference/ir/declarations/modifier-definition An example demonstrating the syntax and usage of a custom modifier in Solidity. This 'onlyOwner' modifier restricts execution to the contract's owner. ```solidity modifier onlyOwner { require(msg.sender == owner); _; } ```