### Start Bob Node for Multi-node Testnet Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command starts the 'bob' validator node, connecting it to the 'alice' node. It uses different ports than 'alice' and specifies 'alice's multiaddress as a bootnode. This allows 'bob' to discover and connect to 'alice' to form a two-node network. ```bash gear \ --bob \ --chain=local \ --base-path ./tmp/bob \ --port 30334 \ --rpc-port 9945 \ --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWMar4rG4kfoCZA1sqaY8FqtPDgpBPfDnQ7Md9x6Sdkgw5 \ --validator ``` -------------------------------- ### Start Alice Node for Multi-node Testnet Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command starts the 'alice' validator node for a local multi-node testnet. It specifies the chain, base path, ports for P2P and RPC, and marks it as a validator. Ensure unique ports if running multiple nodes on the same machine. ```bash gear --alice --chain=local --base-path ./tmp/alice --port 30333 --rpc-port 9944 --validator ``` -------------------------------- ### Replay Block on Live Chain with Gear CLI Source: https://github.com/gear-tech/gear/blob/master/utils/gear-replay-cli/README.md Demonstrates how to replay a block from a live Gear chain using the `gear-replay-cli`. It shows examples with and without the `--force-run` option, specifying the WebSocket URI and block hash or number. ```bash gear-replay-cli -lgear,syscalls,pallet replay-block live -u wss://archive-rpc.vara.network:443 -b 0x8dc1e32576c1ad4e28dc141769576efdbc19d0170d427b69edb2261cfc36e905 gear-replay-cli -lgear,syscalls,pallet replay-block --force-run live -u wss://archive-rpc.vara.network:443 -b 2000000 ``` -------------------------------- ### Connect to Vara Testnet Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command connects a Gear node to the default chain, which is the Vara testnet. It's the simplest way to get a node running and synced with the test network. ```bash gear ``` -------------------------------- ### Run Gear Node in Development Mode Source: https://context7.com/gear-tech/gear/llms.txt Instructions to download a pre-built Gear binary and run a single-node development network. This setup uses the Alice account and can be configured with a custom database path using the --base-path argument. ```bash # Download pre-built binary wget https://get.gear.rs/gear-nightly-x86_64-unknown-linux-gnu.tar.xz tar xf gear-nightly-x86_64-unknown-linux-gnu.tar.xz # Run in dev mode ./gear --dev # With custom database path ./gear --dev --base-path /tmp/vara ``` -------------------------------- ### Build Gear Node from Source Source: https://context7.com/gear-tech/gear/llms.txt Compiles the Gear node from its source code. This process involves installing dependencies, Rust, and then cloning and building the repository. ```bash # Install dependencies (Ubuntu/Debian) sudo apt update sudo apt install -y git clang curl libssl-dev llvm libudev-dev cmake protobuf-compiler # Install Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source ~/.cargo/env # Install nightly toolchain rustup toolchain install nightly-2025-10-20 # Add Wasm target rustup target add wasm32v1-none --toolchain nightly-2025-10-20 # Clone and build git clone https://github.com/gear-tech/gear.git cd gear make node-release # Binary located at ./target/release/gear ``` -------------------------------- ### Rust: End-to-End Testing with gclient and Gear API Source: https://context7.com/gear-tech/gear/llms.txt Shows how to perform end-to-end integration testing against a running Gear node using the gclient library. This example connects to a local dev node, calculates gas, uploads a Wasm program, and sends messages to it. ```rust use gclient::{EventProcessor, GearApi, Result}; #[tokio::test] async fn test_upload_and_send() -> Result<()> { // Connect to local dev node let api = GearApi::dev().await?; let mut listener = api.subscribe().await?; // Calculate gas for upload let gas_info = api .calculate_upload_gas( None, gclient::code_from_os("./target/wasm32v1-none/release/app.opt.wasm")?, vec![], 0, true ) .await?; // Upload program let (message_id, program_id, _hash) = api .upload_program_bytes_by_path( "./target/wasm32v1-none/release/app.opt.wasm", gclient::now_micros().to_le_bytes(), vec![], gas_info.min_limit * 2, 0 ) .await?; assert!(listener.message_processed(message_id).await?.succeeded()); // Send message to program let gas_info = api.calculate_handle_gas(None, program_id, b"PING".to_vec(), 0, true).await?; let (message_id, _) = api .send_message_bytes(program_id, b"PING", gas_info.min_limit * 2, 0) .await?; assert!(listener.message_processed(message_id).await?.succeeded()); Ok(()) } ``` -------------------------------- ### Start Two-Validator Local Network Source: https://context7.com/gear-tech/gear/llms.txt Sets up and runs a local test network with two validators, Alice and Bob. Requires two separate terminal instances to run. ```bash # Terminal 1 - Start Alice node gear --alice \ --chain=local \ --base-path ./tmp/alice \ --port 30333 \ --rpc-port 9944 \ --validator # Get the node identity (e.g., 12D3KooWMar4rG4kfoCZA1sqaY8FqtPDgpBPfDnQ7Md9x6Sdkgw5) # Terminal 2 - Start Bob node gear --bob \ --chain=local \ --base-path ./tmp/bob \ --port 30334 \ --rpc-port 9945 \ --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWMar4rG4kfoCZA1sqaY8FqtPDgpBPfDnQ7Md9x6Sdkgw5 \ --validator ``` -------------------------------- ### Connect to Vara, Get Balance, Upload Program with gsdk Source: https://context7.com/gear-tech/gear/llms.txt Demonstrates connecting to the Vara testnet using gsdk, retrieving an account's balance, and uploading a WASM program to the blockchain. Requires a 'program.wasm' file and utilizes tokio for asynchronous operations. ```rust use gsdk::{Api, Result}; use sp_core::sr25519::Pair; #[tokio::main] async fn main() -> Result<()> { // Connect to Vara testnet let api = Api::new(Some("wss://testnet.vara.network")).await?; // Create account from seed let signer = Pair::from_string("//Alice", None).unwrap(); // Get account balance let account_id = signer.public(); let account_info = api.free_balance(account_id.into()).await?; println!("Balance: {} VARA", account_info); // Submit upload_program extrinsic let code = std::fs::read("program.wasm")?; let salt = b"unique_salt"; let init_payload = vec![]; let gas_limit = 10_000_000_000; let value = 0; let tx = api.upload_program(code, salt.to_vec(), init_payload, gas_limit, value)?; let (message_id, program_id) = tx .sign_and_submit_then_watch(&signer) .await? .wait_for_success() .await?; println!("Program ID: {:?}", program_id); println!("Init message ID: {:?}", message_id); Ok(()) } ``` -------------------------------- ### Run Node as Validator Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command starts a Gear node with the `--validator` flag, enabling it to participate as a validator in the network. Additional steps are required for mainnet validation, including registration, token bonding, and session key configuration, as detailed in the Vara Network Wiki. ```bash gear --validator ``` -------------------------------- ### Ethexe-Enabled Gear Program Source: https://context7.com/gear-tech/gear/llms.txt Example of a Gear program configured with the 'ethexe' feature flag for Ethereum integration. It includes a basic message handling function. ```rust #![no_std] #[cfg(feature = "ethexe")] use gstd::msg; #[unsafe(no_mangle)] extern "C" fn handle() { #[cfg(feature = "ethexe")] { let payload = msg::load_bytes().expect("Failed to load payload"); msg::reply_bytes(b"Response from ethexe", 0).expect("Failed to reply"); } } ``` -------------------------------- ### Rust: Unit Testing Gear Programs with gtest Source: https://context7.com/gear-tech/gear/llms.txt Illustrates how to write unit tests for Gear programs using the gtest framework. This example simulates a blockchain environment to test program initialization and message handling, specifically checking a PING/PONG interaction. ```rust use gtest::{Program, System}; #[test] fn test_ping_pong() { // Initialize testing environment let sys = System::new(); sys.init_logger(); // Load and initialize program let program = Program::current(&sys); let result = program.send_bytes(2, b"PING"); assert!(!result.main_failed()); // Check the reply let mailbox = sys.get_mailbox(2); let log = mailbox.first().expect("Should have reply"); assert_eq!(log.payload_bytes(), b"PONG"); // Run to next block sys.run_next_next_block(); assert_eq!(sys.block_height(), 1); } ``` -------------------------------- ### Run Archive Node Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command starts a Gear node configured to run as an archive node, storing all historical data. It uses specific pruning settings for blocks and state. Be aware that this significantly increases disk space usage and can impact performance. ```bash gear --chain=vara --blocks-pruning=archive --state-pruning=512 ``` -------------------------------- ### Connect to Custom Chain Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command connects a Gear node to a custom chain using a provided chain specification JSON file. The node will attempt to connect to the bootnodes defined in the specification and start syncing blocks. ```bash gear --chain=/path/to/your/chain/spec.json ``` -------------------------------- ### Install Dependencies Source: https://github.com/gear-tech/gear/blob/master/galloc/optimization/fungible_token.ipynb Installs necessary Python libraries for data analysis and visualization, including pandas, numpy, and matplotlib. ```python %pip install pandas numpy matplotlib tabulate ``` -------------------------------- ### Gear Replay Block CLI Help Source: https://github.com/gear-tech/gear/blob/master/utils/gear-replay-cli/README.md Displays the help message for the `gear-replay-cli replay-block` command, outlining its subcommands (snap, live, help) and available options. ```bash $ gear-replay-cli replay-block -h Replay block subcommand Usage: gear-replay-cli replay-block [OPTIONS] Commands: snap Use a state snapshot as the source of runtime state live Use a live chain as the source of runtime state help Print this message or the help of the given subcommand(s) Options: --block-ws-uri The ws uri from which to fetch the block -f, --force-run Forces `Gear::run()` inherent to be placed in the block -h, --help Print help (see more with '--help') ``` -------------------------------- ### Purge Chain Data Source: https://context7.com/gear-tech/gear/llms.txt Removes all chain data for the local development network. This is useful for starting with a clean state. ```bash ./gear purge-chain --dev ``` -------------------------------- ### Deploy Ethereum Contracts for Ethexe Source: https://context7.com/gear-tech/gear/llms.txt Builds and deploys Gear-compatible smart contracts to an Ethereum network using Foundry. Includes steps for local deployment with Anvil and testnet deployment. ```bash cd ethexe/contracts # Build contracts forge build # Deploy to local Ethereum node anvil & forge script script/Deploy.s.sol --rpc-url http://localhost:8545 --broadcast # Deploy to testnet forge script script/Deploy.s.sol --rpc-url $TESTNET_RPC_URL --broadcast --verify ``` -------------------------------- ### Connect to Vara Mainnet Source: https://github.com/gear-tech/gear/blob/master/node/README.md This command connects a Gear node to the Vara mainnet. By default, it syncs with the mainnet chain. Additional CLI arguments can be used to customize parameters like database location and RPC ports. ```bash gear --chain=vara ``` -------------------------------- ### Build Gear Program with Ethexe Feature Source: https://context7.com/gear-tech/gear/llms.txt Compiles a Gear program with the 'ethexe' feature enabled, preparing it for deployment on Ethereum or EVM-compatible chains. ```bash cargo build --release --features ethexe ``` -------------------------------- ### Replay Block from State Snapshot with Gear CLI Source: https://github.com/gear-tech/gear/blob/master/utils/gear-replay-cli/README.md Illustrates replaying a block using a local state snapshot as the source. This command utilizes the `--force-run` option and specifies the path to the snapshot file and the target block. ```bash gear-replay-cli -lgear,syscalls,pallet replay-block -f --block-ws-uri wss://archive-rpc.vara.network:443 snap -p ./vara-1200@1999999 -b 2000000 ``` -------------------------------- ### Calculate Gas for Program Upload Source: https://context7.com/gear-tech/gear/llms.txt Estimates the gas required for uploading and initializing a new program. This is useful for planning deployment costs. ```APIDOC ## POST /rpc ### Description Estimates the gas required for uploading and initializing a new program. ### Method POST ### Endpoint http://localhost:9944 ### Parameters #### Request Body - **jsonrpc** (string) - Required - JSON-RPC protocol version. - **method** (string) - Required - The method name, should be `gear_calculateInitUploadGas`. - **params** (object) - Required - Parameters for the `gear_calculateInitUploadGas` method. - **source** (string) - Required - The source account address. - **code** (string) - Required - The WASM code of the program (hex encoded). - **payload** (string) - Required - The initialization payload for the program (hex encoded). - **value** (number) - Required - The amount of tokens to send with the initialization. - **allow_other_panics** (boolean) - Required - Whether to allow panics from other origins. - **at** (string|null) - Optional - The block hash to query state at. - **id** (number) - Required - The request ID. ### Request Example ```json { "jsonrpc": "2.0", "method": "gear_calculateInitUploadGas", "params": { "source": "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "code": "0x0061736d0100000001...", "payload": "0x", "value": 0, "allow_other_panics": true, "at": null }, "id": 1 } ``` ### Response #### Success Response (200) - **jsonrpc** (string) - The JSON-RPC protocol version. - **result** (object) - The gas calculation result. - **min_limit** (number) - The minimum gas limit required. - **reserved** (number) - The reserved gas. - **burned** (number) - The burned gas. - **may_be_returned** (number) - The gas that may be returned. - **id** (number) - The request ID. ``` -------------------------------- ### Build Script for Wasm Binary Source: https://context7.com/gear-tech/gear/llms.txt Creates a build.rs file to compile Wasm binaries for Gear programs using gear-wasm-builder. ```rust fn main() { gear_wasm_builder::build(); } ``` -------------------------------- ### Implement build.rs for Gear WASM Building Source: https://github.com/gear-tech/gear/blob/master/utils/wasm-builder/README.md Demonstrates the minimal `build.rs` file required to integrate the `gear-wasm-builder`. The `gear_wasm_builder::build()` function is called to initiate the build process for Gear WASM. ```rust fn main() { gear_wasm_builder::build(); } ``` -------------------------------- ### Configure Cargo.toml for Gear Programs Source: https://context7.com/gear-tech/gear/llms.txt Sets up the Cargo.toml file for building Gear programs, including dependencies for gstd, parity-scale-codec, scale-info, and gear-wasm-builder. ```toml [package] name = "my-gear-program" version = "0.1.0" edition = "2024" [dependencies] gstd = { git = "https://github.com/gear-tech/gear.git", tag = "v1.10.0" } parity-scale-codec = { version = "3.7", default-features = false } scale-info = { version = "2.11", default-features = false } [build-dependencies] gear-wasm-builder = { git = "https://github.com/gear-tech/gear.git", tag = "v1.10.0" } [dev-dependencies] gtest = { git = "https://github.com/gear-tech/gear.git", tag = "v1.10.0" } [profile.release] opt-level = "s" lto = true [profile.dev] opt-level = 0 ``` -------------------------------- ### Rust: Initialize and Handle Messages with gstd Source: https://context7.com/gear-tech/gear/llms.txt Demonstrates how to define a struct for message payloads and implement init and handle functions for a Gear smart contract using the gstd library. It includes encoding/decoding and basic message reply logic. ```rust #![no_std] use gstd::{msg, prelude::*}; #[derive(Debug, Decode, Encode, TypeInfo)] #[codec(crate = gstd::codec)] #[scale_info(crate = gstd::scale_info)] pub struct Payload { question: String, answer: u8, } #[unsafe(no_mangle)] extern "C" fn init() { gstd::debug!("Program initialized"); msg::reply_bytes("Ready", 0).expect("Failed to reply"); } #[unsafe(no_mangle)] extern "C" fn handle() { let payload: Payload = msg::load().expect("Unable to decode"); if payload.question == "life-universe-everything" { msg::reply(payload.answer, 0).expect("Unable to reply"); } } ``` -------------------------------- ### Rust: Gas-Efficient Message Handling with gcore Source: https://context7.com/gear-tech/gear/llms.txt Provides a minimal implementation for handling messages in a gas-efficient manner using the gcore library. It includes manual panic and OOM handlers suitable for WASM environments and demonstrates reading and replying to byte messages. ```rust #![no_std] #![feature(alloc_error_handler)] extern crate galloc; use gcore::msg; #[unsafe(no_mangle)] extern "C" fn handle() { let mut bytes = [0; 64]; msg::read(&mut bytes).expect("Unable to read"); if let Ok(payload) = core::str::from_utf8(&bytes) { if payload == "PING" { msg::reply(b"PONG", 0).expect("Unable to reply"); } } } #[cfg(target_arch = "wasm32")] #[alloc_error_handler] pub fn oom(_: core::alloc::Layout) -> ! { core::arch::wasm32::unreachable() } #[cfg(target_arch = "wasm32")] #[panic_handler] fn panic(_: &core::panic::PanicInfo) -> ! { core::arch::wasm32::unreachable() } ``` -------------------------------- ### Rust Async Program for Concurrent Message Handling Source: https://context7.com/gear-tech/gear/llms.txt A Rust program utilizing async/await for concurrent message handling. It initializes with a list of approvers and handles 'PING' messages by sending requests to approvers and replying 'PONG' upon receiving the first approval. Dependencies include gstd, msg, prelude, and ActorId. ```rust #![no_std] use gstd::{msg, prelude::*, ActorId}; static mut APPROVERS: [ActorId; 3] = [ActorId::zero(); 3]; #[derive(Decode, TypeInfo)] #[codec(crate = gstd::codec)] #[scale_info(crate = gstd::scale_info)] pub struct InitInput { pub approvers: [ActorId; 3], } #[gstd::async_init] async fn init() { let input: InitInput = msg::load().expect("Failed to decode"); unsafe { APPROVERS = input.approvers }; // Send to all approvers and wait for at least 2 replies let mut requests: Vec<_> = unsafe { APPROVERS } .iter() .map(|addr| msg::send_bytes_for_reply(*addr, b"", 0, 0)) .collect::>() .expect("Failed to send messages"); let mut count = 0; while let Some(result) = requests.next().await { if result.is_ok() { count += 1; if count >= 2 { break; } } } } #[gstd::async_main] async fn main() { let payload = msg::load_bytes().expect("Failed to load"); if payload == b"PING" { // Send approval requests let mut requests: Vec<_> = unsafe { APPROVERS } .iter() .map(|addr| msg::send_bytes_for_reply(*addr, b"", 0, 0)) .collect::>() .expect("Failed to send"); // Wait for first approval if let Some(Ok(_)) = requests.next().await { msg::reply_bytes("PONG", 0).expect("Failed to reply"); } } } ``` -------------------------------- ### Generate Initialization and Relative Difference Bar Charts (Python) Source: https://github.com/gear-tech/gear/blob/master/galloc/optimization/fungible_token.ipynb Generates two horizontal bar charts: one showing absolute gas units and another showing percentage difference relative to a baseline. It configures axis labels, formats, grids, and highlights the baseline bar. The output is saved as 'init_entrypoint.png'. ```python ax1.set_xlabel("Gas units") ax1.xaxis.set_major_formatter(fmt_int) ax1.grid(axis="x", linestyle="--", alpha=0.5) ax1.invert_yaxis() # smallest at top # absolute values ax1.bar_label( bars1, labels=[fmt_int(v) for v in vals.values], padding=3, # gap from bar end clip_on=False, ) # highlight baseline bar for b, lab in zip(bars1, labels): if lab == BASELINE: b.set_alpha(1.0) b.set_linewidth(2.0) break # ========== Relative (% vs baseline) ========== bars2 = ax2.barh(labels, rel_pct.values, edgecolor="black", alpha=0.85) ax2.set_title(f"Δ vs baseline [{BASELINE}]") ax2.set_xlabel("Percent difference") ax2.xaxis.set_major_formatter(fmt_pct) ax2.grid(axis="x", linestyle="--", alpha=0.5) ax2.axvline(0, color="black", linewidth=1) ax2.invert_yaxis() # percentages ax2.bar_label( bars2, labels=[f"{p:+.2f}%" for p in rel_pct.values], padding=3, clip_on=False, ) plt.savefig("init_entrypoint.png", dpi=200, bbox_inches="tight") plt.show() ``` -------------------------------- ### Use Cargo Commands for Gear WASM Build Source: https://github.com/gear-tech/gear/blob/master/utils/wasm-builder/README.md Lists the standard `cargo` commands used after setting up the `gear-wasm-builder`. These commands trigger the build process, including clean, build (debug and release), and test (debug and release). ```bash cargo clean cargo build cargo build --release cargo test cargo test --release ``` -------------------------------- ### Connect and Sign Transaction with GSDK (Rust) Source: https://github.com/gear-tech/gear/blob/master/gsdk/README.md Demonstrates how to connect to a Gear network RPC node using GSDK, create a signer, and perform a transfer transaction. It also shows how to fetch events related to the transaction. Requires the 'gsdk' and 'tokio' crates. ```rust use gsdk::signer::Signer; #[tokio::main] async fn main() { // Connect to "wss://rpc-node.gear-tech.io:443" by default. let signer = Api::new(None).signer("//Alice", None); // Transaction with block details. let tx = signer.transfer_keep_alive("//Bob", 42).await.expect("Transfer value failed."); // Fetch all of the events associated with this transaction. for events in tx.fetch_events().await { // ... } } ``` -------------------------------- ### Calculate Gas for Gear Program Upload (RPC API) Source: https://context7.com/gear-tech/gear/llms.txt Estimates the gas required for uploading and initializing a new Gear program. This RPC method requires the sender's address, the program's WASM code, and an initialization payload. It also allows specifying value and whether other panics are allowed. ```bash curl -X POST \ http://localhost:9944 \ -H 'Content-Type: application/json' \ -d '{ "jsonrpc": "2.0", "method": "gear_calculateInitUploadGas", "params": { "source": "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "code": "0x0061736d0100000001...", "payload": "0x", "value": 0, "allow_other_panics": true, "at": null }, "id": 1 }' ``` -------------------------------- ### Connect to Vara Network Source: https://context7.com/gear-tech/gear/llms.txt Connects to the Vara network, supporting mainnet, testnet, and archive nodes. Specify chain and pruning options as needed. ```bash # Mainnet gear --chain=vara # Testnet (default) gear # Archive node with full history gear --chain=vara \ --blocks-pruning=archive \ --state-pruning=512 ``` -------------------------------- ### Generate Entrypoint Gas Consumption Graph Source: https://github.com/gear-tech/gear/blob/master/galloc/optimization/fungible_token.ipynb Visualizes the initial gas consumption for program uploads, sorted by absolute value. It displays the gas units and the percentage difference relative to a baseline. This provides insight into the efficiency of different program uploads. ```python def init_entrypoint_graph(): first_values = df.iloc[0] # Series baseline = first_values[BASELINE] # --- order by absolute value (ascending) --- vals = first_values.sort_values() labels = vals.index rel_pct = (vals / baseline - 1.0) * 100.0 # % vs baseline # formatters fmt_int = FuncFormatter(lambda x, _: f"{int(x):,}".replace(",", " ")) fmt_pct = FuncFormatter(lambda x, _: f"{x:+.1f}%") fig, (ax1, ax2) = plt.subplots( 2, 1, figsize=(14, 8), gridspec_kw={"height_ratios": [2.0, 1.2], "hspace": 0.25}, ) # ========== Absolute (gas units) ========== bars1 = ax1.barh(labels, vals.values, edgecolor="black", alpha=0.85) ax1.set_title("Program upload gas consumption (sorted)") ``` -------------------------------- ### Run Runtime Fuzzer with Corpus Source: https://github.com/gear-tech/gear/blob/master/utils/runtime-fuzzer/README.md Executes the runtime fuzzer with a specified corpus and runtime logs. It requires a minimum input size of 350 KiB for the corpus. The command sets various runtime parameters like RSS limit and maximum input length. ```bash cd utils/runtime-fuzzer # Fuzzer expects a minimal input size of 350 KiB. Without providing a corpus of the same or larger # size fuzzer will stuck for a long time with trying to test the target using 0..100 bytes. mkdir -p fuzz/corpus/main dd if=/dev/urandom of=fuzz/corpus/main/fuzzer-seed-corpus bs=1 count=350000 # Run fuzzer for at least 20 minutes and then press Ctrl-C to stop fuzzing. # You can also remove RUST_LOG to avoid printing tons of logs on terminal. RUST_LOG=debug,syscalls,runtime::sandbox=trace,gear_wasm_gen=trace,runtime_fuzzer=trace,gear_core_backend=trace \ cargo fuzz run \ --release \ --sanitizer=none \ main \ fuzz/corpus/main \ -- \ -rss_limit_mb=8192 \ -max_len=450000 \ -len_control=0 ``` -------------------------------- ### Simple Ping-Pong Program with gstd Source: https://context7.com/gear-tech/gear/llms.txt A basic Gear smart contract that replies 'PONG' when it receives a 'PING' message. It implements the `init` and `handle` entry points for message processing. No external dependencies beyond `gstd`. ```rust #![no_std] use gstd::{msg, prelude::*}; #[unsafe(no_mangle)] extern "C" fn init() { let payload = msg::load_bytes().expect("Failed to load payload"); if payload == b"PING" { msg::reply_bytes("PONG", 0).expect("Failed to reply"); } } #[unsafe(no_mangle)] extern "C" fn handle() { let payload = msg::load_bytes().expect("Failed to load payload"); if payload == b"PING" { msg::reply_bytes("PONG", 0).expect("Failed to reply"); } } ``` -------------------------------- ### Rust: Creating a New Announce as Block Producer Source: https://github.com/gear-tech/gear/wiki/Vara‐eth-consensus When a node acts as the block producer, it creates a new Announce. This involves selecting a parent announce, determining gas allowance, and bundling valid injected transactions. The newly created Announce is then broadcast to other validators. ```rust let new_announce_from_producer = Announce { block_hash: chain_head, parent_announce_hash: chosen_alive_parent_announce_hash, gas_allowance: chosen_gas_allowance, transactions: chosen_valid_injected_transactions, }; ``` -------------------------------- ### Genesis Announce Creation in Rust Source: https://github.com/gear-tech/gear/wiki/Vara‐eth-consensus Demonstrates the creation of a 'genesis announce', which serves as the ancestor for all other announces in a Vara-eth network. This special announce is characterized by having no gas allowance and no transactions, and it is tied to the Ethereum block where the Router contract was deployed. ```rust let genesis_announce = Announce { // Attached to the Vara-eth genesis Ethereum block block_hash: genesis_block_hash, // Since there were no announces before, the parent is zero parent_announce_hash: H256::zero(), // No gas allowance gas_allowance: None, // No injected transactions transactions: vec![], }; ```