{"id":28138625,"url":"https://github.com/blocknative/gas-agent","last_synced_at":"2025-07-23T22:33:28.056Z","repository":{"id":290981058,"uuid":"970309057","full_name":"blocknative/gas-agent","owner":"blocknative","description":"Create gas predictions and publish them for evaluation and submission to the Gas Network","archived":false,"fork":false,"pushed_at":"2025-07-18T15:04:55.000Z","size":91,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-18T19:07:14.486Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/blocknative.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-21T20:14:20.000Z","updated_at":"2025-07-18T15:04:56.000Z","dependencies_parsed_at":"2025-06-11T13:29:47.811Z","dependency_job_id":"be03c65b-e571-4e43-903e-2180073081db","html_url":"https://github.com/blocknative/gas-agent","commit_stats":null,"previous_names":["blocknative/gas-agent"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/blocknative/gas-agent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blocknative%2Fgas-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blocknative%2Fgas-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blocknative%2Fgas-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blocknative%2Fgas-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/blocknative","download_url":"https://codeload.github.com/blocknative/gas-agent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blocknative%2Fgas-agent/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266761346,"owners_count":23980289,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-23T02:00:09.312Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-05-14T17:14:37.436Z","updated_at":"2025-07-23T22:33:28.036Z","avatar_url":"https://github.com/blocknative.png","language":"Rust","readme":"# Gas Agent\n\nA Rust-based agent system that generates and submits gas price predictions for EVM networks to the [Gas Network](https://gas.network/) for evaluation.\n\n## Prerequisites\n\n### Install Rust\n\nYou'll need Rust installed on your system. The recommended way is using `rustup`:\n\n#### macOS and Linux\n\n```bash\ncurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\nsource ~/.cargo/env\n```\n\n#### Windows\n\nDownload and run the installer from [rustup.rs](https://rustup.rs/)\n\nVerify your installation:\n\n```bash\nrustc --version\ncargo --version\n```\n\n## Installation\n\n### Pre-built Binaries (Recommended)\n\nDownload the latest release for your platform:\n\n```bash\n# Install using our shell installer (macOS/Linux)\ncurl --proto '=https' --tlsv1.2 -LsSf https://github.com/blocknative/gas-agent/releases/latest/download/gas-agent-installer.sh | sh\n\n# Or install via Homebrew (macOS/Linux)\nbrew install blocknative/tap/gas-agent\n\n# Or download manually from GitHub releases\n# Visit: https://github.com/blocknative/gas-agent/releases\n```\n\n### From Source\n\nIf you prefer to build from source or need the latest unreleased changes:\n\n```bash\n# Install via cargo (requires Rust toolchain)\ncargo install --git https://github.com/blocknative/gas-agent\n\n# Or clone and build\ngit clone https://github.com/blocknative/gas-agent\ncd gas-agent\ncargo build --release\n```\n\n## Quick Start\n\n1. **Generate signing keys**\n\n   All agent payloads are signed before submission to the Gas Network so that they are verifiable and attributable. Use the private key for the `signer_key` field for each agent.\n\n   ```bash\n   gas-agent generate-keys\n   ```\n\n2. **Configure chains and agents**\n\n   A list of chains and the agents to run for each chain can be configured and will run in parallel with each chain running on it's own thread. Set the `CHAINS` env variable with a JSON string:\n\n   ```json\n   [\n     {\n       \"system\": \"ethereum\",\n       \"network\": \"mainnet\",\n       \"json_rpc_url\": \"https://ethereum-rpc.publicnode.com\",\n       \"agents\": [\n         {\n           \"kind\": \"percentile\",\n           \"signer_key\": \"YOUR-GENERATED-PRIVATE-KEY\",\n           \"prediction_trigger\": \"block\"\n         }\n       ]\n     }\n   ]\n   ```\n\n3. **Run the agent**\n   ```bash\n   gas-agent start\n   ```\n\n## Agent Registration\n\nBefore your agent can submit predictions to the Gas Network, you need to register and get your signing addresses whitelisted.\n\n### How Agent Authentication Works\n\n1. **Signed Predictions**: All agent payloads are cryptographically signed using your private key before submission\n2. **Address Extraction**: The Gas Network collector validates the signature and extracts the corresponding Ethereum address\n3. **Whitelist Validation**: Only predictions from whitelisted addresses are accepted and processed by the network\n\n### Getting Whitelisted\n\nTo register your agent and get your signing addresses whitelisted:\n\n1. **Generate Your Keys**: Use the built-in key generation tool to create your signing keys:\n\n   ```bash\n   gas-agent generate-keys\n   ```\n\n2. **Save Your Keys**: Securely store the private key for your agent configuration and note the corresponding public address\n\n3. **Submit Whitelist Request**: Contact the Blocknative team with your public address(es):\n\n   - **Email**: [support@blocknative.com](mailto:support@blocknative.com)\n   - **Discord**: Join our community at [https://discord.com/invite/KZaBVME](https://discord.com/invite/KZaBVME)\n\n4. **Include in Your Request**:\n   - Your Ethereum address(es) that will be signing predictions\n   - Brief description of your prediction model/strategy\n   - Expected prediction frequency and settlement types\n   - Your intended use case or research goals\n\n### Multiple Agents and Addresses\n\n- **Unique Keys Recommended**: Use different signing keys for different agent types or models\n- **Separate Evaluation**: Each unique combination of address, system, network, and settlement is evaluated independently\n- **All Addresses Need Whitelisting**: Each signing address you plan to use must be individually whitelisted\n\n### Testing Before Whitelisting\n\nWhile waiting for whitelist approval, you can:\n\n- Test your agent locally with mock endpoints\n- Verify your prediction logic and model performance\n- Ensure your signing and payload generation works correctly\n\nOnce whitelisted, your agent can begin submitting predictions that will be evaluated and potentially published to the Gas Network for end users.\n\n## Development\n\n### Prerequisites for Development\n\nBefore starting development, ensure you have:\n\n1. **Rust toolchain** (see Installation section above)\n2. **Git** for version control\n3. **A code editor** with Rust support (VS Code with rust-analyzer recommended)\n\n### Setting Up the Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/blocknative/gas-agent\ncd gas-agent\n\n# Verify everything builds and tests pass\ncargo check\ncargo test\ncargo clippy --workspace --all-targets --all-features\ncargo fmt --check\n```\n\n### Running in Development Mode\n\n```bash\n# Run with debug logging\nRUST_LOG=debug cargo run -- start --chains 'YOUR-CONFIG-JSON'\n\n# Run tests\ncargo test\n\n# Run specific tests\ncargo test test_name\n\n# Run with release optimizations (for performance testing)\ncargo run --release -- start --chains 'YOUR-CONFIG-JSON'\n```\n\n### Development Workflow\n\n1. **Create a feature branch**:\n   ```bash\n   git checkout -b feature/your-feature-name\n   ```\n\n2. **Make your changes** and ensure code quality:\n   ```bash\n   # Check for compilation errors\n   cargo check\n   \n   # Run tests\n   cargo test\n   \n   # Fix linting issues\n   cargo clippy --workspace --all-targets --all-features --fix\n   \n   # Format code\n   cargo fmt\n   ```\n\n3. **Commit your changes**:\n   ```bash\n   git add .\n   git commit -m \"Add your feature description\"\n   ```\n\n4. **Push and create a pull request**:\n   ```bash\n   git push -u origin feature/your-feature-name\n   # Then create a PR on GitHub\n   ```\n\n### Code Quality Standards\n\nThe project enforces strict code quality standards:\n\n- **No warnings**: All code must compile without warnings\n- **Formatted code**: Use `cargo fmt` to format code consistently\n- **Linted code**: Use `cargo clippy` to catch common mistakes and improve code quality\n- **Tested code**: Add tests for new functionality\n- **Documentation**: Document public APIs and complex logic\n\n### Testing\n\n```bash\n# Run all tests\ncargo test\n\n# Run tests with output\ncargo test -- --nocapture\n\n# Run tests for a specific module\ncargo test models::\n\n# Run integration tests only\ncargo test --test '*'\n\n# Generate test coverage report (requires cargo-tarpaulin)\ncargo install cargo-tarpaulin\ncargo tarpaulin --out Html\n```\n\n### Configuration Options\n\nThe agent supports the following command-line arguments and environment variables:\n\n- `--server-address` / `SERVER_ADDRESS`: HTTP server bind address (currently used only for Kubernetes probes) (default: `0.0.0.0:8080`)\n- `--chains` / `CHAINS`: JSON configuration for EVM networks and agents\n- `--collector-endpoint` / `COLLECTOR_ENDPOINT`: The Gas Network endpoint for payload evaluation (default: `https://collector.gas.network`)\n\n### Chain Configuration\n\nThe chain configuration is specified as a JSON array where each object represents an EVM network and its associated agents. Each chain configuration supports the following fields:\n\n#### ChainConfig Fields\n\n- **`system`** (required): The blockchain system to connect to\n\n  - Available options: `\"ethereum\"`, `\"base\"`, `\"polygon\"`\n\n- **`network`** (required): The network within the system\n\n  - Available options: `\"mainnet\"`\n\n- **`json_rpc_url`** (required): The JSON-RPC endpoint URL to poll for new blocks\n\n  - Example: `\"https://ethereum-rpc.publicnode.com\"`\n\n- **`pending_block_data_source`** (optional): Configuration for fetching pending-block (mempool) data\n\n  - See [Pending Block Data Source](#pending-block-data-source) section below\n\n- **`agents`** (required): Array of agent configurations to run on this chain\n  - See [Agent Configuration](#agent-configuration) section below\n\n#### Pending Block Data Source\n\nWhen specified, this configures how to fetch pending block (mempool) data which can be passed to models that can be more reactive to changes in the mempool and to make use of private data to create more accurate predictions:\n\n```json\n{\n  \"pending_block_data_source\": {\n    \"json_rpc\": {\n      \"url\": \"https://api.example.com/pending\",\n      \"method\": \"eth_getPendingBlock\",\n      \"params\": [\"pending\"],\n      \"poll_rate_ms\": 1000\n    }\n  }\n}\n```\n\nA full `CHAINS` configuration for Ethereum with a JSON RPC pending block data source:\n\n```bash\nCHAINS='[{\"system\": \"ethereum\", \"network\": \"mainnet\", \"json_rpc_url\": \"https://ethereum-rpc.publicnode.com\", \"pending_block_data_source\": {\"json_rpc\": {\"url\": \"http://localhost:8545\", \"method\": \"eth_getBlockByNumber\", \"params\": [\"pending\", true], \"poll_rate_ms\": 1000}}, \"agents\": [{\"kind\": \"pending_floor\", \"prediction_trigger\": {\"poll\": {\"rate_ms\": 1000}}, \"signer_key\": \"0xede33830a316e1f3018a50709c54d1f01d6ab3053f4f29ec552ce10bc9f5ef72\"}]}]'\n```\n\n**Fields:**\n\n- **`url`** (required): The JSON-RPC endpoint URL\n- **`method`** (required): The RPC method to call\n- **`params`** (optional): Parameters to pass to the RPC method\n- **`poll_rate_ms`** (required): Polling interval in milliseconds\n\nCurrently, JSON RPC is the only source available, but other sources are coming soon. Please create an issue if there is a specific source that you would like to see supported.\n\n##### Expected RPC Response Structure\n\nThe pending block RPC endpoint must return a JSON-RPC 2.0 response containing a required `transactions` field with an array of transaction objects. Each transaction object has the following requirements:\n\n**Required fields:**\n\n- `hash`: Transaction hash identifier\n\n**Gas price fields (one of the following combinations):**\n\n- `gasPrice`: Legacy gas price (for pre-EIP-1559 transactions)\n- OR `maxFeePerGas` AND `maxPriorityFeePerGas`: EIP-1559 gas price fields (both required together)\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"result\": {\n    \"transactions\": [\n      {\n        \"hash\": \"0x1234567890abcdef...\",\n        \"maxFeePerGas\": \"0x174876e800\",\n        \"maxPriorityFeePerGas\": \"0x59682f00\"\n      },\n      {\n        \"hash\": \"0xabcdef1234567890...\",\n        \"gasPrice\": \"0x165a0bc00\"\n      }\n    ]\n  }\n}\n```\n\n#### Agent Configuration\n\nEach agent in the `agents` array supports the following configuration:\n\n```json\n{\n  \"kind\": \"percentile\",\n  \"signer_key\": \"0x1234567890abcdef...\",\n  \"prediction_trigger\": \"block\"\n}\n```\n\n**Fields:**\n\n- **`kind`** (required): The type of agent to run\n\n  - `\"node\"`: Publishes the standard estimate from the node\n  - `\"target\"`: Publishes the actual minimum price for new blocks\n  - Model-based agents:\n    - `\"adaptive_threshold\"`: Uses adaptive threshold analysis\n    - `\"distribution_analysis\"`: Analyzes gas price distributions\n    - `\"moving_average\"`: Uses moving average calculations\n    - `\"percentile\"`: Uses percentile-based predictions\n    - `\"time_series\"`: Uses time series analysis\n    - `\"last_min\"`: Takes the minimum from the previous block and uses that as the prediction for the next block.\n    - `\"pending_floor\"`: Takes the minimum from the pending-block, adds 1 wei and uses that as the prediction for the next block.\n\n- **`signer_key`** (required): Private key for signing predictions (use `cargo run -- generate-keys` to create)\n\n- **`prediction_trigger`** (required): When to generate predictions\n  - `\"block\"`: Generate prediction when a new block is detected\n  - `{\"poll\": {\"rate_ms\": 5000}}`: Generate predictions at regular intervals (rate in milliseconds)\n\n## Models\n\nThe gas agent includes several built-in prediction models that analyze block data to estimate optimal gas prices. Each model uses different strategies and data sources to predict gas prices. All models now return errors when they lack sufficient data instead of fallback values, providing clear feedback about what's needed for successful predictions.\n\n### Historical Block Models\n\nThese models use historical onchain data to create a prediction for the next block. Since these models can only generate a single prediction per block, the `\"prediction_trigger\": \"block\"` is typically used with these models. All historical models require at least one block with transaction data and will return descriptive errors if insufficient data is provided.\n\n#### `percentile`\n\nAnalyzes the distribution of gas prices across the 5 most recent blocks and selects the 75th percentile to ensure high inclusion probability. This model is particularly effective during periods of high volatility, as it targets a price that would have included 75% of recent transactions. Requires at least one block distribution with transactions.\n\n#### `last_min`\n\nSimply takes the minimum gas price from the most recent block and uses it as the prediction for the next block. This is the most aggressive pricing strategy and works well when gas prices are stable. Requires at least one non-empty block distribution.\n\n#### `moving_average`\n\nCalculates a Simple Weighted Moving Average (SWMA) of recent gas prices, giving more weight to more recent blocks (up to 10 blocks). This approach works well when gas prices are relatively stable and provides smooth price transitions. Requires at least one block with transactions.\n\n#### `adaptive_threshold`\n\nIdentifies the minimum gas price that would have been included in each recent block (up to 50 blocks) and applies an adaptive premium based on price volatility. When prices are stable, it applies a small premium; when volatile, it applies a larger premium (up to 50%). This provides a balance between cost and inclusion probability. Requires at least one block distribution with transactions.\n\n#### `time_series`\n\nUses simple linear regression to identify trends in gas prices and predict the next value based on the median gas price of the last 20 blocks. This model is particularly useful when gas prices show a consistent trend over time (either increasing or decreasing). Requires at least one block with transactions for analysis.\n\n#### `distribution_analysis`\n\nAnalyzes the cumulative distribution function (CDF) of gas prices in the most recent block to find \"sweet spots\" where many transactions are being included. It identifies points where the rate of change in the CDF decreases significantly, representing efficient gas price levels, then applies a 10% premium for higher inclusion probability. Requires at least one block distribution with a non-empty latest block.\n\n### Pending Block Models\n\nThese models use pending (mempool or private) transaction data to make predictions. They are specifically designed for users who have access to pending block information, such as block builders with proprietary transaction flows.\n\n#### `pending_floor`\n\nSpecifically designed for block builders with proprietary private transaction flow who can see what the likely next block will contain. This model analyzes the pending block distribution to find the minimum gas price and adds exactly 1 wei (0.000000001 gwei) to ensure transaction inclusion while paying the absolute minimum. Unlike historical models, this one requires access to pending block data and will return an error if no pending block distribution is provided. Most effective when used with a polling prediction trigger to provide up to date predictions (`\"prediction_trigger\": {\"poll\": {\"rate_ms: \u003cdesired_rate\u003e\"}}`).\n\n### Model Error Handling\n\nAll models will return descriptive errors instead of fallback values when they lack sufficient data. This provides clear feedback about what's needed for successful predictions.\n\n**Common Error Scenarios:**\n\n- **Empty block distributions**: All historical models require at least one block distribution\n- **No transactions**: Models need blocks that contain actual transaction data to analyze\n- **Missing pending data**: The `pending_floor` model specifically requires pending block distribution data\n\n**Error Message Examples:**\n\n- `\"LastMin model requires at least one block distribution\"`\n- `\"Percentile model requires blocks with transactions\"`\n- `\"PendingFloor model requires pending block distribution data\"`\n\nWhen a model returns an error, check that:\n\n1. You're providing the correct type of data for the model\n2. Your block distributions contain actual transaction data\n3. For `pending_floor`, you're providing the `pending_block_distribution` parameter\n\n### Creating Custom Models\n\nTo create a custom prediction model, you'll need to fork the repository and implement your own model logic. Here's how:\n\n#### Step 1: Fork and Clone\n\n```bash\ngit fork https://github.com/blocknative/gas-agent\ngit clone https://github.com/YOUR-USERNAME/gas-agent\ncd gas-agent\n```\n\n#### Step 2: Add Your Model Type\n\nAdd your model to the `ModelKind` enum in `src/types.rs`:\n\n```rust\n#[derive(Debug, Clone, EnumString, Display, Deserialize, Serialize)]\n#[strum(serialize_all = \"snake_case\")]\n#[serde(rename_all = \"snake_case\")]\npub enum ModelKind {\n    AdaptiveThreshold,\n    DistributionAnalysis,\n    MovingAverage,\n    Percentile,\n    TimeSeries,\n    LastMin,\n    PendingFloor,\n    YourCustomModel,  // Add this line\n}\n```\n\n#### Step 3: Create Your Model Implementation\n\nCreate a new file `src/models/your_custom_model.rs`:\n\n```rust\n/*\nYour Custom Model Description\nExplain what your model does and how it works.\n*/\n\nuse crate::types::Settlement;\nuse crate::{distribution::BlockDistribution, utils::round_to_9_places};\n\npub fn get_prediction_your_custom_model(block_distributions: \u0026[BlockDistribution], pending_block_distribution: \u0026Option\u003cBlockDistribution\u003e) -\u003e (f64, Settlement) {\n    // Your model logic here\n    //\n    // block_distributions is a Vec\u003cBlockDistribution\u003e where:\n    // - BlockDistribution = Vec\u003cBucket\u003e\n    // - Bucket { gwei: f64, count: u32 }\n    //\n    // Each BlockDistribution represents gas price buckets from a block\n    // sorted from oldest to newest blocks\n\n    // Example: Get the most recent block\n    let latest_block = block_distributions.last().unwrap();\n\n    // Example: Calculate some prediction logic\n    let mut total_gas_price = 0.0;\n    let mut total_transactions = 0u32;\n\n    for bucket in latest_block {\n        total_gas_price += bucket.gwei * bucket.count as f64;\n        total_transactions += bucket.count;\n    }\n\n    let predicted_price = if total_transactions \u003e 0 {\n        total_gas_price / total_transactions as f64\n    } else {\n        1.0 // fallback price\n    };\n\n    // Return the prediction and settlement time\n    (round_to_9_places(predicted_price), Settlement::Fast)\n}\n```\n\n#### Step 4: Register Your Model\n\nAdd your model to the module system in `src/models/mod.rs`:\n\n```rust\nuse your_custom_model::get_prediction_your_custom_model;\n\nmod your_custom_model;\n\n// In the apply_model function, add your case:\npub async fn apply_model(\n    model: \u0026ModelKind,\n    block_distributions: \u0026[BlockDistribution],\n    pending_block_distribution: Option\u003cBlockDistribution\u003e,\n) -\u003e Result\u003c(f64, Settlement)\u003e {\n    // ... existing code ...\n\n    match model {\n        // ... existing cases ...\n        ModelKind::YourCustomModel =\u003e Ok(get_prediction_your_custom_model(block_distributions, pending_block_distribution)),\n    }\n}\n```\n\n#### Step 5: Build and Test\n\n```bash\ncargo build\ncargo test\n\n# Test your model\ngas-agent start --chains '[{\n  \"system\": \"ethereum\",\n  \"network\": \"mainnet\",\n  \"json_rpc_url\": \"https://ethereum-rpc.publicnode.com\",\n  \"agents\": [{\n    \"kind\": \"your_custom_model\",\n    \"signer_key\": \"YOUR-PRIVATE-KEY\",\n    \"prediction_trigger\": \"block\"\n  }]\n}]'\n```\n\n#### Model Development Tips\n\n1. **Understand the Data Structure**: Each `BlockDistribution` contains buckets of gas prices with transaction counts, representing the gas price distribution for that block.\n\n2. **Handle Edge Cases**: Always check for empty distributions and provide fallback values.\n\n3. **Consider Settlement Times**: Choose appropriate `Settlement` values:\n\n   - `Immediate`: Next block\n   - `Fast`: ~15 seconds\n   - `Medium`: ~15 minutes\n   - `Slow`: ~1 hour\n\n4. **Use Utility Functions**: The `round_to_9_places()` function ensures consistent precision across predictions.\n\n5. **Test with Different Market Conditions**: Test your model during periods of high volatility, network congestion, and normal conditions.\n\n6. **Leverage Pending Block Data**: If available, you can access `pending_block_distribution` parameter in the `apply_model` function for more reactive predictions.\n\n## Settlement Times and Block Windows\n\nAs a prediction provider, you can generate gas price predictions for different settlement times that end users will consume to price their transactions. Each settlement time represents a different urgency level and block window that your predictions target. A settlement `BlockWindow` is derived from the `from_block` parameter and `Settlement` enum. The `from_block` must be a future block number and is typically set to the next block.\n\n### Settlement Options for Prediction Models\n\nYour models can return one of four settlement times, each targeting different end-user needs:\n\n#### `immediate`\n\n- **Target Time**: Next block (0ms)\n- **Block Window**: 0 blocks (next block only)\n- **End User Profile**: Arbitrage bots, MEV strategies, time-critical DeFi operations\n- **Prediction Strategy**: Should predict the minimum gas price needed for immediate inclusion\n\n#### `fast`\n\n- **Target Time**: ~15 seconds (15,000ms)\n- **End User Profile**: Standard DeFi interactions, swaps, NFT minting\n- **Prediction Strategy**: Balance between inclusion probability and cost efficiency\n\n#### `medium`\n\n- **Target Time**: ~15 minutes (900,000ms)\n- **End User Profile**: Regular transfers, non-urgent contract interactions\n- **Prediction Strategy**: Focus on cost optimization while maintaining reasonable inclusion probability\n\n#### `slow`\n\n- **Target Time**: ~1 hour (3,600,000ms)\n- **End User Profile**: Batch operations, low-priority transactions, cost-sensitive users\n- **Prediction Strategy**: Minimize gas costs, accepting longer wait times\n\n### Block Window Calculation\n\nSettlement times are converted to block windows based on each network's block time:\n\n#### Network Block Times\n\n- **Ethereum**: 12 seconds per block (12,000ms)\n- **Base**: 2 seconds per block (2,000ms)\n- **Polygon**: 2 seconds per block (2,000ms)\n\n#### Settlement to Block Window Translation\n\nThe number of blocks for each settlement is calculated as: `floor(settlement_time_ms / network_block_time_ms)`\n\n| Settlement  | Ethereum (12s blocks) | Base (2s blocks)      | Polygon (2s blocks)   |\n| ----------- | --------------------- | --------------------- | --------------------- |\n| `immediate` | 0 blocks (next block) | 0 blocks (next block) | 0 blocks (next block) |\n| `fast`      | ~1 block              | ~8 blocks             | ~8 blocks             |\n| `medium`    | ~75 blocks            | ~450 blocks           | ~450 blocks           |\n| `slow`      | ~300 blocks           | ~1,800 blocks         | ~1,800 blocks         |\n\n### How Your Predictions Are Evaluated\n\nWhen you submit a gas price prediction, the Gas Network evaluates its accuracy within the specified block window:\n\n1. **Prediction Submitted**: Your model predicts 20 gwei with `fast` settlement for Ethereum\n2. **Block Window Calculated**: `fast` on Ethereum = ~1 block window starting from `from_block`\n3. **Evaluation Period**: The system monitors min price for blocks within that window\n4. **Scoring**: Your prediction is scored on:\n   - **Inclusion Rate**: Did your prediction price get onchain within the block window\n   - **Cost Efficiency**: Percentage overpayment\n\n## Building for Production\n\n```bash\n# Optimized release build\ncargo build --release\n\n# The binary will be available at\n./target/release/gas-agent\n```\n\n## Release Process\n\n### Creating a New Release\n\nReleases are automated using [cargo-dist](https://github.com/axodotdev/cargo-dist) and triggered by pushing git tags. Follow these steps:\n\n#### 1. Update Version\n\nUpdate the version in `Cargo.toml`:\n\n```toml\n[package]\nversion = \"0.1.0\"  # Update this\n```\n\n#### 2. Update Changelog\n\nUpdate `CHANGELOG.md` following [Keep a Changelog](https://keepachangelog.com/) format:\n\n```markdown\n## [0.1.0] - 2025-01-22\n\n### Added\n- New feature descriptions\n- New model implementations\n\n### Changed\n- Breaking changes or significant modifications\n- Performance improvements\n\n### Fixed\n- Bug fixes and error handling improvements\n\n### Removed\n- Deprecated features that were removed\n```\n\n**Important**: The GitHub release title and body are automatically generated from the changelog, so ensure your changelog entries are clear and well-formatted.\n\n#### 3. Create and Push Tag\n\n```bash\n# Commit version and changelog changes first\ngit add Cargo.toml CHANGELOG.md\ngit commit -m \"Prepare release v0.1.0\"\n\n# Create and push the tag\ngit tag v0.1.0\ngit push origin v0.1.0\n```\n\n#### 4. Automated Release Process\n\nWhen you push the tag, GitHub Actions will automatically:\n\n1. **Build artifacts** for multiple platforms (Linux, macOS, Windows)\n2. **Run tests** to ensure code quality\n3. **Generate release notes** from your changelog\n4. **Create GitHub release** with:\n   - Auto-generated title from changelog\n   - Auto-generated body from changelog\n   - Platform-specific binaries and installers\n   - Checksums for verification\n\n#### 5. Verify Release\n\nAfter the workflow completes:\n\n1. Check the [GitHub releases page](https://github.com/blocknative/gas-agent/releases)\n2. Verify all platform binaries are present\n3. Test the installer scripts work correctly\n4. Update documentation if needed\n\n### Release Checklist\n\nBefore creating a release:\n\n- [ ] All tests pass: `cargo test`\n- [ ] Code is properly formatted: `cargo fmt --check`\n- [ ] No clippy warnings: `cargo clippy --workspace --all-targets --all-features`\n- [ ] Version updated in `Cargo.toml`\n- [ ] `CHANGELOG.md` updated with new version and changes\n- [ ] All changes committed to main branch\n- [ ] Git tag created and pushed\n\n### Hotfix Releases\n\nFor urgent fixes:\n\n1. Create a hotfix branch from the release tag\n2. Apply minimal fix\n3. Update patch version (e.g., `0.1.0` → `0.1.1`)\n4. Update changelog with hotfix entry\n5. Create new tag and push\n\n### Pre-releases\n\nFor beta or release candidate versions:\n\n1. Use pre-release version format: `v0.1.0-beta.1`\n2. GitHub release will automatically be marked as pre-release\n3. Follow same process as regular releases\n\n## Docker Support\n\nA Dockerfile is included for containerized deployments:\n\n```bash\ndocker build -t gas-agent .\ndocker run -e CHAINS='YOUR-CONFIG' gas-agent start\n```\n\n## Monitoring\n\nThe agent exposes kubernetes probe endpoints:\n\n- Liveness: `GET /internal/probe/liveness`\n- Readiness: `GET /internal/probe/readiness`\n\n## License\n\nSee [LICENSE](LICENSE) file for details.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblocknative%2Fgas-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fblocknative%2Fgas-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblocknative%2Fgas-agent/lists"}