### Serve and View Arbiter Book Documentation Locally Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Command to serve the comprehensive book documentation locally and open it in the browser. The book includes detailed explanations of mathematical concepts, examples, and usage guides. ```bash just book ``` -------------------------------- ### Run Arbiter Project Simulation Example Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/getting_started/examples.md This command executes a minimal counter-simulation within an Arbiter project. It demonstrates how Arbiter uses a main macro to define agent behaviors and a TOML configuration, where the incrementer behavior deploys a counter on startup and increments it on an event. ```bash cargo run --example project simulate examples/project/configs/example.toml ``` -------------------------------- ### Install Arbiter Command-Line Binary Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Install the Arbiter command-line interface (CLI) tool globally on your machine. After installation, you can verify it by running `arbiter --help` to see the available commands. ```bash cargo install arbiter ``` -------------------------------- ### Run Arbiter Mainnet State Forking Example Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/getting_started/examples.md This command initiates an Arbiter fork, loading the specified mainnet state from `weth_config.toml`. Users can modify this configuration file to include additional Ethereum Owned Accounts (EOAs) or contract storage for custom forking scenarios. ```bash arbiter fork examples/fork/weth_config.toml ``` -------------------------------- ### Run Arbiter Template Example CLI Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Execute the basic template example to interact with its command-line interface. This command provides an overview of available commands and flags for the template project. ```bash cargo run --example template ``` -------------------------------- ### Rust Example: Setting Up and Running a Single `World` Simulation Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/worlds_and_universes.md This example demonstrates how to initialize a `World` instance and add `Agent`s with defined behaviors. It shows the `setup_world` function for creating a `World` and populating it with agents, and the `run` function for executing the simulation within that single `World`. ```Rust use arbiter_engine::{agent::Agent, world::World}; use crate::Replier; fn setup_world(id: &str) -> World { let ping_replier = Replier::new("ping", "pong", 5, None); let pong_replier = Replier::new("pong", "ping", 5, Some("ping")); let agent = Agent::new("my_agent") .with_behavior(ping_replier) .with_behavior(pong_replier); let mut world = World::new(id); world.add_agent(agent); } async fn run() { let world = setup_world("my_world"); world.run().await; } ``` -------------------------------- ### Rust Example: Implementing a Replier Behavior Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/behaviors.md This Rust example demonstrates how to implement a custom `Behavior` called `Replier`. The `Replier` sends a startup message, then listens for specific incoming messages, replies to them, and halts after a predefined number of replies. It showcases the `startup` method for initialization and stream setup, and the `process` method for event handling and state management. ```Rust use std::sync::Arc; use arbiter_core::middleware::RevmMiddleware; use arbiter_engine::{ machine::{Behavior, ControlFlow}, messager::{Messager, To}, EventStream}; pub struct Replier { receive_data: String, send_data: String, max_count: u64, startup_message: Option, count: u64, messager: Option, } impl Replier { pub fn new( receive_data: String, send_data: String, max_count: u64, startup_message: Option, ) -> Self { Self { receive_data, send_data, startup_message, max_count, count: 0, messager: None, } } } impl Behavior for Replier { async fn startup( &mut self, client: Arc, messager: Messager, ) -> Result, ArbiterEngineError> { if let Some(startup_message) = &self.startup_message { messager.send(To::All, startup_message).await; } self.messager = Some(messager.clone()); messager.stream() } async fn process(&mut self, event: Message) -> Result { if event.data == self.receive_data { self.messager.unwrap().messager.send(To::All, send_data).await; self.count += 1; } if self.count == self.max_count { return Ok(ControlFlow::Halt); } Ok(ControlFlow::Continue) } } ``` -------------------------------- ### Add Arbiter Crates as Project Dependencies Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/getting_started/index.md This TOML configuration block demonstrates how to add the `arbiter-core`, `arbiter-bindings`, and `arbiter-engine` crates to your Rust project's `Cargo.toml` file. Wildcard `*` is used for the version, but specific versions can be specified for production environments. ```TOML [dependencies] arbiter-core = "*" # You can specify a version here if you'd like arbiter-bindings = "*" # You can specify a version here if you'd like arbiter-engine = "*" # You can specify a version here if you'd like ``` -------------------------------- ### Install Rust and Development Tools for Arbiter Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Commands to install the Rust programming language and essential development components like 'rustfmt' for code formatting and 'clippy' for linting. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustup component add rustfmt clippy ``` -------------------------------- ### Rust Example: Creating an Agent with Multiple Behaviors Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/agents_and_engines.md Illustrates how to instantiate an `Agent` using the builder pattern and attach multiple `Replier` behaviors. This example demonstrates a 'ping-pong' message chain initiated by a startup message, showcasing how behaviors can interact and drive agent activity. ```rust use arbiter_engine::agent::Agent; use crate::Replier; fn setup() { let ping_replier = Replier::new("ping", "pong", 5, None); let pong_replier = Replier::new("pong", "ping", 5, Some("ping")); let agent = Agent::builder("my_agent") .with_behavior(ping_replier) .with_behavior(pong_replier); } ``` -------------------------------- ### Loading and Running Simulation from Configuration File Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/configuration.md Provides a Rust example demonstrating how to load a simulation configuration from a TOML file using `World::from_config` and then execute the simulation using `world.run().await`. This shows the final step of integrating the configuration into the simulation runtime. ```Rust fn main() { let world = World::from_config("./path/to/config.toml")?; world.run().await; } ``` -------------------------------- ### Initialize Simulation Runtime and Start Loop (JavaScript) Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html Initializes the simulation environment by creating the runtime, setting up event listeners, and starting the main simulation loop using `requestAnimationFrame`. Includes error handling for the initialization process. ```JavaScript function initialize() { try { createSimulation(1000, 680); console.log("Runtime created"); setupEventListeners(); console.log("Event listeners set up"); simulationRunning = true; console.log("Starting simulation loop"); requestAnimationFrame(simulationLoop); console.log("Initialization complete!"); } catch (error) { console.error('Initialization failed:', error); } } ``` -------------------------------- ### Load Arbiter Forked State into Environment (Rust) Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/getting_started/examples.md This Rust code snippet illustrates how to load a previously saved forked state from a JSON file into an Arbiter `Environment`. It then demonstrates the creation of an `ArbiterMiddleware` client, enabling subsequent simulations to operate on the loaded mainnet state. ```rust use arbiter_core::{database::Fork::*, Environment, ArbiterMiddleware}; let fork = Fork::from_disk("tests/fork.json").unwrap(); // Get the environment going let environment = Environment::builder().with_db(fork.db).build(); // Create a client let client = ArbiterMiddleware::new(&environment, Some("name")).unwrap(); ``` -------------------------------- ### Deploy Contract with ArbiterMiddleware Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/middleware.md This example illustrates how to deploy a contract, specifically an `ArbiterToken`, into the `Environment`'s world state using an `ArbiterMiddleware` client. It showcases the asynchronous deployment process, allowing the client to interact with deployed contracts. ```rust use arbiter_core::{middleware::ArbiterMiddleware, environment::Environment}; use arbiter_bindings::bindings::arbiter_token::ArbiterToken; #[tokio::main] async fn main() { let env = Environment::builder().build(); let client = ArbiterMiddleware::new(&env, None).unwrap(); // Deploy a contract let contract = ArbiterToken::deploy(client, ("ARBT".to_owned(), "Arbiter Token".to_owned(), 18u8)).unwrap().send().await().unwrap(); } ``` -------------------------------- ### Install cargo-generate for Arbiter Development Source: https://github.com/harnesslabs/arbiter/blob/main/README.md To facilitate development with the Arbiter framework, it is helpful to install the `cargo-generate` package. This command uses Cargo, Rust's package manager, to install the utility globally, which can then be used to generate new Arbiter projects. ```Bash cargo install cargo-generate ``` -------------------------------- ### Rust Example: Running Multiple `World` Simulations with `Universe` Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/worlds_and_universes.md This example illustrates how to leverage the `Universe` struct to manage and concurrently execute multiple `World` simulations. It demonstrates creating a `Universe`, adding several pre-configured `World` instances to it, and then initiating their parallel execution using `universe.run_worlds().await`. ```Rust use arbiter_engine::{agent::Agent, world::World}; use crate::Replier; fn setup_world(id: &str) -> World { let ping_replier = Replier::new("ping", "pong", 5, None); let pong_replier = Replier::new("pong", "ping", 5, Some("ping")); let agent = Agent::new("my_agent") .with_behavior(ping_replier) .with_behavior(pong_replier); let mut world = World::new(id); world.add_agent(agent); } fn main() { let mut universe = Universe::new(); universe.add_world(setup_world("my_world")); universe.add_world(setup_world("my_other_world")); universe.run_worlds().await; } ``` -------------------------------- ### Simulate ModifiedCounter Example with Debug Logging Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Run a simulation of the `ModifiedCounter.sol` example, enabling verbose debug logging. The `-vvv` flag sets the log level to debug, providing detailed internal execution insights. ```bash cargo run --example template simulate examples/template/configs/example.toml -vvv ``` -------------------------------- ### Configure Arbiter Environment with Inspector Features Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/environment.md This example shows how to enable inspection features for the `revm` instance within the `Environment`. `with_console_logs()` allows printing Solidity `console2.log` outputs, while `with_pay_gas()` enables realistic gas payment for transactions, aiding debugging and realism. ```Rust use arbiter_core::environment::Environment; fn main() { let env = Environment::builder() .with_console_logs() .with_pay_gas() .build(); } ``` -------------------------------- ### Customize Gas and Contract Size Limits for Arbiter Environment Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/environment.md This example demonstrates how to set custom `gas_limit` and `contract_size_limit` for the `revm` instance managed by the `Environment`. This provides fine-grained control over transaction execution and contract deployment constraints. ```Rust use arbiter_core::environment::Environment; fn main() { let env = Environment::builder() .with_gas_limit(revm_primitives::U256::from(12_345_678)) .with_contract_size_limit(111_111) .build(); } ``` -------------------------------- ### Initialize New Arbiter Project from Arbiter-Template Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Create a new Arbiter project based on the `arbiter-template` repository. This command prompts for a project name and sets up the basic project structure, simplifying new project creation. ```bash cd cargo generate https://github.com/anthias-labs/arbiter-template.git ``` -------------------------------- ### Configure Arbiter Environment with a Forked Database Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/environment.md This snippet illustrates how to initialize an `Environment` with a database that has been forked from a live network and serialized to disk. It loads the `Fork` from a specified path, allowing the `Environment` to operate on a pre-existing state. ```Rust use arbiter_core::environment::Environment; use arbiter_core::database::fork::Fork; fn main() { let path_to_fork = "path/to/fork"; let fork = Fork::from_disk(path_to_fork).unwrap(); let env = Environment::builder().with_db(fork).build(); } ``` -------------------------------- ### Create a Default Arbiter Environment Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/environment.md This snippet demonstrates how to create a basic `Environment` instance using its builder pattern. The call to `.build()` initializes the `Environment`'s dedicated thread, preparing it to process incoming `Instruction`s. ```Rust use arbiter_core::environment::Environment; fn main() { let env = Environment::builder().build(); } ``` -------------------------------- ### Clone Arbiter Repository and Initialize Submodules Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Instructions to clone the Arbiter repository from GitHub and ensure all necessary submodules are initialized and updated. This is the first step to setting up the development environment. ```bash git clone https://github.com/anthias-labs/arbiter.git cd arbiter git submodule update --init --recursive ``` -------------------------------- ### Run Arbiter-core Benchmarks Source: https://github.com/harnesslabs/arbiter/blob/main/README.md This command executes the benchmarking suite for the `arbiter-core` package. It compares the performance of `ArbiterMiddleware` against Anvil for various EVM operations, providing insights into execution speed and efficiency. ```bash cargo bench --package arbiter-core ``` -------------------------------- ### Clone Arbiter Repository Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Instructions to clone the forked Arbiter repository using Git and navigate into its directory. ```bash git clone https://github.com/yourusername/arbiter.git cd arbiter ``` -------------------------------- ### Run Tests and Code Checks for Arbiter Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Commands to execute tests, format code using 'rustfmt', and run 'clippy' for linting, ensuring code quality and adherence to style guidelines before committing changes. ```bash cargo test cargo fmt --all -- --check cargo clippy --all-targets --all-features -- -D warnings ``` -------------------------------- ### Importing WASM Module and Initializing Global State Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html This snippet imports essential functions and classes from the WebAssembly module ('./pkg/leader.js') and sets up global variables. These variables manage the WASM module instance, runtime state, simulation status, and timing parameters for the UI. ```JavaScript import init, { Runtime, create_leader_follower_simulation, simulation_tick, add_simulation_agent, get_agent_positions, clear_all_agents, remove_single_agent } from './pkg/leader.js'; // Global state let wasmModule = null; let runtime = null; let placementMode = null; let simulationRunning = false; let lastTickTime = 0; const TICK_INTERVAL = 50; // 20 FPS for simulation, but 60 FPS for rendering ``` -------------------------------- ### Initialize a New Arbiter Project Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_cli.md This command initializes a new Arbiter project with a template. The `--no-git` flag can be used to remove the `.git` directory from the template upon initialization. ```bash arbiter init your-new-project cd your-new-project ``` -------------------------------- ### Build and View Rust API Documentation for Arbiter Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Command to build and open the automatically generated Rust API documentation in the browser. This documentation is derived directly from code comments and should be kept up to date. ```bash just docs ``` -------------------------------- ### Create ArbiterMiddleware Instances Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/middleware.md This snippet demonstrates how to initialize `ArbiterMiddleware` clients, either with a specific ID or without one, by associating them with an `Environment` instance. These clients then facilitate interactions with contracts deployed in the `Environment`'s world state. ```rust use arbiter_core::{middleware::ArbiterMiddleware, environment::Environment}; fn main() { let env = Environment::builder().build(); // Create a client for the above `Environment` with an ID let id = "alice"; let alice = ArbiterMiddleware::new(&env, Some(id)); // Create a client without an ID let client = ArbiterMiddleware::new(&env, None); } ``` -------------------------------- ### Run an Arbiter Project Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_cli.md This command executes the Arbiter project template. Ensure all dependencies are resolved before running. ```bash cargo run ``` -------------------------------- ### Run All Arbiter-core Tests Source: https://github.com/harnesslabs/arbiter/blob/main/README.md This command executes all tests within the `arbiter-core` project, including those for all features. It is essential for verifying new code contributions and ensuring the stability and correctness of the codebase. ```bash cargo test --all --all-features ``` -------------------------------- ### Arbiter Environment Instructions API Reference Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_core/environment.md This section details the various `Instruction` types that can be sent to the `Environment` to control its behavior and query its state. It includes nested `Cheatcodes` for state manipulation and `EnvironmentData` options for querying environment parameters. ```APIDOC Instruction Enum: Instruction::AddAccount: Add an account to the Environment's world state. This is usually called by the RevmMiddleware when a new client is created. Instruction::BlockUpdate: Update the Environment's block number and block timestamp. This can be handled by an external agent in a simulation, if desired. Instruction::Cheatcode: Execute one of the Cheatcodes on the Environment's world state. Cheatcodes Enum: Cheatcodes::Deal: Used to set the raw ETH balance of a user. Useful when you need to pay gas fees in a transaction. Cheatcodes::Load: Gets the value of a storage slot of an account. Cheatcodes::Store: Sets the value of a storage slot of an account. Cheatcodes::Access: Gets the account at an address. Instruction::Query: Allows for querying the Environment's world state and current configuration. Anything in the EnvironmentData enum is accessible via this instruction. EnvironmentData Enum: EnvironmentData::BlockNumber: Gets the current block number of the Environment. EnvironmentData::BlockTimestamp: Gets the current block timestamp of the Environment. EnvironmentData::GasPrice: Gets the current gas price of the Environment. EnvironmentData::Balance: Gets the current ETH balance of an account. EnvironmentData::TransactionCount: Gets the current nonce of an account. Instruction::Stop: Stops the Environment's thread and echos out to any listeners to shut down their event streams. This can be used when handling errors or reverts, or just when you're done with the Environment. Instruction::Transaction: Executes a transaction on the Environment's world state. This is usually called by the RevmMiddleware when a client sends a ETH-call or state-changing transaction. ``` -------------------------------- ### Fork EVM Network State using Arbiter Source: https://github.com/harnesslabs/arbiter/blob/main/README.md Create a local fork of an EVM network's state using a specified configuration file. This command stores the network data locally, allowing simulations to run without a constant RPC connection. An optional `--overwrite` flag can be used to replace an existing fork. ```bash arbiter fork ``` -------------------------------- ### Configure CLI with #[main] Macro for Arbiter Simulations in Rust Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_macros.md The `#[arbiter_macros::main]` macro simplifies CLI creation for simulations by automatically generating a `main` function that sets up command-line parsing, logging, async execution, and world creation. It takes custom attributes to configure application metadata and integrates with `clap` for CLI arguments and `tracing` for logging. This macro requires an object that has the `CreateStateMachine` trait implemented, often achieved using the `#[derive(Behaviors)]` macro. ```Rust use arbiter_macros::main; use Behaviors; // From the Behaviors example above #[main( name = "ExampleArbiterProject", about = "Our example to get you started.", behaviors = Behaviors )] pub async fn main() {} ``` -------------------------------- ### Set Up UI Event Listeners for Agent Placement and Control (JavaScript) Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html Attaches event listeners to the canvas for agent placement and to control buttons (Add Leader, Add Follower, Clear All). It handles adding new agents based on click coordinates and the active placement mode, and provides functionality to clear all agents from the simulation. ```JavaScript function setupEventListeners() { const canvas = document.getElementById('canvas'); const addLeaderBtn = document.getElementById('addLeaderBtn'); const addFollowerBtn = document.getElementById('addFollowerBtn'); const clearAllBtn = document.getElementById('clearAllBtn'); canvas.addEventListener('click', (event) => { if (!runtime || !placementMode) return; const rect = canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; try { const isLeader = placementMode === 'leader'; const agentId = add_simulation_agent(runtime, x, y, isLeader); if (agentId) { console.log(`Added ${isLeader ? 'leader' : 'follower'} "${agentId}" at (${x}, ${y})`); placementMode = null; updateButtonStates(); updateAgentList(); } else { console.log(`Failed to add ${isLeader ? 'leader' : 'follower'} at (${x}, ${y})`); } } catch (error) { console.error('Error adding agent:', error.message); } }); addLeaderBtn.addEventListener('click', () => { placementMode = 'leader'; updateButtonStates(); console.log("Leader placement mode activated"); }); addFollowerBtn.addEventListener('click', () => { placementMode = 'follower'; updateButtonStates(); console.log("Follower placement mode activated"); }); clearAllBtn.addEventListener('click', () => { if (!runtime) return; try { const removed = runtime.removeAllAgents(); clear_all_agents(); console.log(`Cleared ${removed} agents and reset state`); placementMode = null; updateButtonStates(); updateAgentList(); } catch (error) { console.error('Error clearing agents:', error.message); } }); } ``` -------------------------------- ### Leader-Follower Simulation UI Stylesheet Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html This comprehensive CSS block defines the entire visual presentation for the Leader-Follower Simulation interface. It includes global resets, body styling, container layouts, header elements, demo and control panel structures, button styles, agent list rendering, and responsive adjustments for various screen sizes. ```CSS * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); color: #1e293b; line-height: 1.6; } .container { max-width: 1400px; margin: 0 auto; padding: 40px 20px; } .header { text-align: center; margin-bottom: 60px; border-bottom: 1px solid #e2e8f0; padding-bottom: 40px; } .header .brand { font-size: 11px; font-weight: 600; letter-spacing: 3px; text-transform: uppercase; color: #64748b; margin-bottom: 16px; } .header h1 { font-size: 42px; font-weight: 200; color: #0f172a; margin-bottom: 20px; letter-spacing: -0.5px; } .header p { font-size: 16px; color: #475569; max-width: 600px; margin: 0 auto; font-weight: 400; } .demo-container { display: grid; grid-template-columns: 1fr 340px; gap: 32px; align-items: start; } .canvas-container { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); } #canvas { display: block; cursor: crosshair; border: none; width: 100%; height: auto; } .controls { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 24px; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); } .control-group { margin-bottom: 24px; } .control-group:last-child { margin-bottom: 0; } .control-group h3 { font-size: 12px; font-weight: 600; color: #374151; margin-bottom: 12px; text-transform: uppercase; letter-spacing: 1px; } .instructions { background: #f8fafc; border: 1px solid #e2e8f0; padding: 16px; border-radius: 8px; margin-bottom: 24px; } .instructions h4 { margin-bottom: 10px; color: #1e293b; font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; } .instructions ul { list-style: none; color: #64748b; font-size: 13px; line-height: 1.5; } .instructions li { margin-bottom: 6px; padding-left: 12px; position: relative; } .instructions li::before { content: "·"; position: absolute; left: 0; color: #94a3b8; font-weight: 600; font-size: 16px; } .btn { background: linear-gradient(135deg, #1e293b 0%, #334155 100%); color: #ffffff; border: none; padding: 12px 16px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.2s ease; text-transform: uppercase; letter-spacing: 0.5px; border-radius: 6px; margin-bottom: 6px; width: 100%; box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); } .btn:hover { background: linear-gradient(135deg, #334155 0%, #475569 100%); transform: translateY(-1px); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); } .btn:active { transform: translateY(0); } .btn.danger { background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%); } .btn.danger:hover { background: linear-gradient(135deg, #b91c1c 0%, #dc2626 100%); } .agent-list-container { max-height: 320px; min-height: 320px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; } .agent-list-container::-webkit-scrollbar { width: 6px; } .agent-list-container::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 3px; } .agent-list-container::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; } .agent-list-container::-webkit-scrollbar-thumb:hover { background: #94a3b8; } .agent-item { background-color: #ffffff; margin: 0; padding: 12px 16px; border-bottom: 1px solid #e2e8f0; transition: all 0.15s ease; } .agent-item:last-child { border-bottom: none; } .agent-item:hover { background-color: #f8fafc; } .agent-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; } .agent-id { font-weight: 600; color: #1e293b; font-size: 13px; } .agent-state { font-size: 10px; padding: 3px 6px; border-radius: 4px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; } .agent-state.running { background-color: #10b981; color: white; } .agent-state.paused { background-color: #f59e0b; color: white; } .agent-state.stopped { background-color: #ef4444; color: white; } .agent-controls { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 3px; } .agent-btn { padding: 4px 6px; font-size: 9px; border: none; border-radius: 3px; cursor: pointer; transition: all 0.15s ease; font-weight: 500; text-transform: uppercase; letter-spacing: 0.3px; } .agent-btn.start { background-color: #10b981; color: white; } .agent-btn.pause { background-color: #f59e0b; color: white; } .agent-btn.stop { background-color: #ef4444; color: white; } .agent-btn.remove { background-color: #64748b; color: white; } .agent-btn:hover { opacity: 0.8; transform: scale(1.02); } .agent-btn:disabled { opacity: 0.4; cursor: not-allowed; transform: none; } .empty-state { text-align: center; color: #94a3b8; font-style: italic; font-size: 13px; padding: 20px; } @media (max-width: 1024px) { .demo-container { grid-template-columns: 1fr; gap: 24 ``` -------------------------------- ### Create an EVM Network Fork Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_cli.md This command creates a fork of an EVM network based on a provided configuration file. The fork data is stored locally, allowing emulation without a constant RPC connection. The `--overwrite` flag can be used to overwrite an existing fork. ```bash arbiter fork ``` -------------------------------- ### Generate Smart Contract Bindings Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_cli.md This command wraps Foundry's `forge bind` to generate Rust smart-contract bindings to `src/bindings` as a Rust module. It can be configured via `cargo.toml`. ```bash arbiter bind ``` -------------------------------- ### Configuring Agents with Replier Behavior Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/configuration.md Demonstrates how to define a `Replier` behavior in Rust, including its struct definition and enum wrapping. It then shows two ways to configure agents using this `Replier` behavior in a TOML file: first, by specifying anonymous agents, and second, by assigning specific names like 'Alice' and 'Bob' to agents. ```Rust #[derive(Behaviors)] pub enum Behaviors { Replier(Replier), } pub struct Replier { receive_data: String, send_data: String, max_count: u64, startup_message: Option, count: u64, messager: Option, } ``` ```TOML [[my_agent]] Replier = { send_data = "ping", receive_data = "pong", max_count = 5, startup_message = "ping" } [[my_agent]] Replier = { send_data = "pong", receive_data = "ping", max_count = 5 } ``` ```TOML [[alice]] Replier = { send_data = "ping", receive_data = "pong", max_count = 5, startup_message = "ping" } [[bob]] Replier = { send_data = "pong", receive_data = "ping", max_count = 5 } ``` -------------------------------- ### Reproducing Portfolio Rebalancing Vulnerability with Arbiter Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/vulnerability_corpus.md This snippet provides steps to reproduce a critical vulnerability found in Primitive Finance's Portfolio Contracts using Arbiter. The bug, which was not caught by prior audits, allowed swappers to exploit mispriced funds due to an invariant jump at liquidity distribution tails. The reproduction involves cloning a specific repository, checking out a bug-found branch, and running a Rust project. ```bash git clone https://github.com/primitivefinance/portfolio_simulations.git cd portfolio_simulations git checkout (bug-found)-invariant-pre-post-swap cargo run --release ``` -------------------------------- ### CSS Layout for Simulation UI Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html A fragment of CSS defining layout properties for UI elements such as controls and the agent list container within the leader-follower simulation interface. ```CSS px; } .controls { order: -1; } .agent-list-container { max-height: 300px; } } ``` -------------------------------- ### Clearing Canvas and Drawing Grid Background Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html The `clearCanvas` function prepares the HTML canvas for rendering. It fills the canvas with a white background and then draws a subtle grid pattern across its full extent, providing visual reference points for agent positions. ```JavaScript function clearCanvas() { const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Clear with white background ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Add a subtle grid that covers the FULL canvas ctx.strokeStyle = '#f1f5f9'; ctx.lineWidth = 1; // Vertical lines - cover full width for (let x = 0; x <= canvas.width; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height); ctx.stroke(); } // Horizontal lines - cover full height for (let y = 0; y <= canvas.height; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(canvas.width, y); ctx.stroke(); } } ``` -------------------------------- ### Update UI Button States Based on Placement Mode (JavaScript) Source: https://github.com/harnesslabs/arbiter/blob/main/examples/leader/index.html Modifies the text content and background style of the 'Add Leader' and 'Add Follower' buttons. When a placement mode is active, the corresponding button's text changes to 'Click Canvas' and its background color is updated, providing visual feedback to the user. ```JavaScript function updateButtonStates() { const addLeaderBtn = document.getElementById('addLeaderBtn'); const addFollowerBtn = document.getElementById('addFollowerBtn'); if (placementMode === 'leader') { addLeaderBtn.textContent = 'Click Canvas'; addLeaderBtn.style.background = '#10b981'; } else { addLeaderBtn.textContent = 'Add Leader'; addLeaderBtn.style.background = ''; } if (placementMode === 'follower') { addFollowerBtn.textContent = 'Click Canvas'; addFollowerBtn.style.background = '#10b981'; } else { addFollowerBtn.textContent = 'Add Follower'; addFollowerBtn.style.background = ''; } } ``` -------------------------------- ### Create New Feature Branch for Arbiter Development Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Command to create a new Git branch for a feature or fix, following a specific naming convention (type/area/description) to maintain consistency. ```bash git checkout -b type/area/description # Example: git checkout -b feat/algebra/vector-spaces ``` -------------------------------- ### Defining Behaviors Enum with arbiter_macros Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/configuration.md Illustrates how to wrap custom `Behavior` structs (like `Maker` and `Taker`) into a single `enum` using the `arbiter_macros::Behaviors` derive macro. This simplifies configuration by allowing the enum to represent all possible behaviors in a simulation. ```Rust use arbiter_macros::Behaviors; #[derive(Behaviors)] pub enum Behaviors { Maker(Maker), Taker(Taker), } ``` -------------------------------- ### Rust Behavior Trait Definition Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/behaviors.md This snippet defines the core `Behavior` trait in Rust, which is essential for creating event-driven logic in `arbiter-engine` simulations. It requires implementing `startup` for initialization and `process` for handling events, allowing for control flow within the simulation. ```Rust pub trait Behavior { fn startup(&mut self, client: Arc, messager: Messager) -> Result, ArbiterEngineError>; fn process(&mut self, event: E) -> Result; } ``` -------------------------------- ### Rust `Universe` Struct Definition Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/worlds_and_universes.md Defines the `Universe` struct, the top-level component for managing and running multiple `World` simulations in parallel. It contains an optional map of `World`s, identified by their IDs, and a vector of tasks representing the concurrently running `World`s. ```Rust pub struct Universe { worlds: Option>, world_tasks: Option>>, } ``` -------------------------------- ### Configure Arbiter Bindings in Cargo.toml Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_cli.md Optional fields to configure `arbiter bind` in your `cargo.toml`. `bindings_workspace` specifies a valid workspace member, `submodules` controls submodule binding generation, and `ignore_interfaces` ignores interface contracts. ```toml [arbiter] bindings_workspace = "simulation" # must be a valid workspace member submodules = false # change to true if you want the submodule bindings to be generated ignore_interfaces = false # change to true if you want to ignore interfaces contracts ``` -------------------------------- ### Arbiter Commit Message Format Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Specifies the structured format for commit messages, including 'type', 'area', a brief description, and optional body and footer for additional context or issue references. ```APIDOC type(area): description [optional body] [optional footer] ``` -------------------------------- ### Arbiter Issue Title Format Source: https://github.com/harnesslabs/arbiter/blob/main/CONTRIBUTING.md Defines the required format for issue titles, specifying the 'type' (e.g., 'feat', 'fix', 'refactor') and 'area' (e.g., 'core', 'engine') of the issue for clear categorization. ```APIDOC type(area): brief description ``` -------------------------------- ### Rust Agent Struct Definition Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/agents_and_engines.md Defines the `Agent` struct, the primary component for interacting with the Arbiter `Environment`. It includes an ID, a client for sending calls and transactions, a `Messager`, and a vector of `StateMachine`s representing its behaviors. ```rust pub struct Agent { pub id: String, pub messager: Messager, pub client: Arc, pub(crate) behavior_engines: Vec>, } ``` -------------------------------- ### Implement CreateStateMachine with #[derive(Behaviors)] Macro in Rust Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_macros.md This Rust procedural macro automatically implements the `CreateStateMachine` trait for an enum, generating a `create_state_machine` method. It's designed for enums where each variant contains a single unnamed field representing state data, simplifying state machine creation and reducing boilerplate. ```Rust use arbiter_macros::Behaviors; use arbiter_engine::machine::Behavior; struct MyBehavior1 {} impl Behavior for MyBehavior1 { // ... } struct MyBehavior2 {} } impl Behavior for MyBehavior2 { // ... } #[derive(Behaviors)] enum Behaviors { MyBehavior1(MyBehavior1), MyBehavior2(MyBehavior2), } ``` -------------------------------- ### Rust `World` Struct Definition Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/arbiter_engine/worlds_and_universes.md Defines the `World` struct, which encapsulates a single simulation environment. It includes a unique ID, an Arbiter `Environment`, a collection of `Agent`s, and a `Messager` for inter-agent communication. The `World` is responsible for integrating agents into the simulation environment. ```Rust pub struct World { pub id: String, pub agents: Option>, pub environment: Environment, pub messager: Messager, } ``` -------------------------------- ### Calculate Exploitation Likelihood in Rust Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/techniques/measuring_risk.md This Rust function determines the likelihood of exploitation based on four factors: historical frequency, threat capability, control effectiveness, and environmental factors. All input parameters are `f64` values between zero and one. The function returns a single `f64` representing the calculated likelihood. ```rust fn calculate_likelihood(historical_frequency: f64, threat_capability: f64, control_effectiveness: f64, environment_factor: f64) -> f64 { historical_frequency * threat_capability * (1.0 - control_effectiveness) * environment_factor } fn main() { // Example: High historical frequency (e.g., 0.8), high threat capability (e.g., 0.9), medium control effectiveness (e.g., 0.5), high environment factor (e.g., 1.0) let likelihood = calculate_likelihood(0.8, 0.9, 0.5, 1.0); println!("{}", likelihood); // Outputs: 0.36 } ``` -------------------------------- ### Geometric Brownian Motion Stochastic Differential Equation Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/techniques/measuring_risk.md This equation models asset price paths in financial markets, describing the change in asset price over an infinitesimally small period. The first term represents the deterministic trend (drift, μ), and the second term represents the random fluctuation (volatility, σ) influenced by a Wiener process (Wt). ```Mathematical Formula $$dS_t = \mu S_t dt + \sigma S_t dW_t$$ ``` -------------------------------- ### Calculate Security Incident Impact in Rust Source: https://github.com/harnesslabs/arbiter/blob/main/docs/src/usage/techniques/measuring_risk.md This Rust function calculates the total impact of a security incident by summing weighted consequences. It takes a vector of `f64` consequences and an optional vector of `f64` weights. If weights are not provided, equal importance is assumed. The function returns a single `f64` representing the aggregated impact. ```rust pub fn calculate_impact(consequences: Vec, weights: Option>) -> f64 { let weights = match weights { Some(w) => w, None => vec![1.0; consequences.len()], // If no weights are provided, assume equal importance }; consequences.iter().zip(weights.iter()).map(|(c, w)| c * w).sum() } // Example: Data loss (e.g., $5000), downtime (e.g., 10 hours), reputational damage (e.g., 7 on a scale of 10) let consequences = vec![5000.0, 10.0, 7.0]; let weights = Some(vec![0.5, 0.3, 0.2]); // Weights reflecting the relative importance of each consequence let impact = calculate_impact(consequences, weights); println!("{}", impact); // Outputs: 2535.0 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.