---
title: 'GasAgent: Multi-Agent Smart Contract Optimizer'
url: https://www.emergentmind.com/topics/gasagent
type: topic
---

# GasAgent: Multi-Agent Smart Contract Optimizer

GasAgent is a multi-agent framework for automated gas optimization of Solidity smart contracts. It was introduced as the first multi-agent system for smart contract Gas optimization that combines compatibility with existing patterns and automated discovery and validation of new patterns, enabling end-to-end optimization [2507.15761]. In its original formulation, GasAgent addresses gas waste patterns caused by non-optimal coding practices, compiler limitations, and incomplete coverage by manually defined rule libraries. It organizes optimization as a closed-loop workflow among four specialized agents—Seeker, Innovator, Executor, and Manager—that identify inefficiencies, refactor code, verify security and behavioral consistency, and measure actual gas savings. Subsequent literature also uses “GasAgent-like” to denote a broader class of gas-aware or guarded agent architectures, especially in decentralized coordination and secure tool-using multi-agent systems; this later usage is related, but distinct from the original smart-contract optimizer [2511.22924] [2605.28914] [2512.20973].

## 1. Problem domain and design objective

On Ethereum and similar blockchains, every operation executed by a smart contract consumes Gas, which quantifies computation and storage usage, and users pay for gas in `wei`, where \(1\) wei \(= 10^{-18}\) Ether. Two gas components are central: deployment gas, which is the cost to deploy contract bytecode, and execution gas, which is the cost for each transaction invoking contract functions. Because execution is fully replicated across nodes, inefficient Solidity code is financially costly and can also worsen resource pressure at the protocol level [2507.15761].

GasAgent targets gas waste patterns: code structures known to unnecessarily increase gas consumption. The documented causes include redundant storage reads and writes such as multiple `SLOAD` or `SSTORE` operations to the same slot, unnecessary mappings or arrays instead of more compact representations, and use of storage instead of `immutable` or `calldata`. The framework is positioned against two earlier solution families. The first comprises manually defined pattern libraries and rule-based static analyzers, which are hard to maintain and difficult to scale because new patterns must be encoded by experts. The second comprises single-LLM approaches, which may discover new code smells but struggle with compatibility with existing patterns, often produce redundant patterns, may hallucinate invalid suggestions, and typically do not provide an automated pipeline for judgement, refactoring, testing, and deployment-level gas measurement [2507.15761].

The design objective is therefore not merely suggestion generation. GasAgent is structured as an optimization system that integrates prior gas-optimization knowledge, proposes additional refactorings when necessary, and accepts a transformation only if security, behavioral consistency, and empirical gas reduction all hold. This makes gas optimization an end-to-end verification problem rather than a prompt-response task.

## 2. Closed-loop multi-agent architecture

GasAgent decomposes the optimization workflow into four specialized roles coordinated in a closed loop. The architecture is implemented with LangGraph, uses GPT-4o-2024-11-20 for all LLM tasks, represents known patterns through a library of JSON descriptions plus Python detection modules, and relies on external toolchains for testing and gas measurement [2507.15761].

| Agent | Core function |
|---|---|
| Seeker | Finds known gas-waste instances using dual retrieval over the pattern library |
| Innovator | Proposes new or refined patterns beyond the library |
| Executor | Applies refactorings and runs security, equivalence, and gas checks |
| Manager | Orchestrates iterations and decides when to stop |

Seeker is the compatibility-oriented component. It retrieves known gas-waste patterns through a dual mechanism. On the code side, it embeds contract code and pattern examples using `jina-v2` embeddings, computes cosine similarity, and selects patterns whose example similarity exceeds a threshold, with default \(0.7\). On the natural-language side, it prompts the model with the contract source code plus natural-language descriptions of known patterns and asks it to return only the relevant pattern IDs. The merged candidate set is then checked by invoking the corresponding Python detection tools, which confirm whether the pattern truly matches and extract detailed information such as locations and suggested transformations. The output is an Existing Pattern Report [2507.15761].

Innovator is the novelty-oriented component. It receives the original contract and Seeker’s Existing Pattern Report and is instructed to summarize at most one new gas optimization pattern, explicitly avoiding repetition of existing suggestions. Its output includes the proposed pattern name, description, relevant code locations, and an explanation of how the transformation reduces gas. To suppress repeated hallucinations, GasAgent maintains a New Pattern Blacklist containing previously proposed but falsified patterns; proposals matching blacklisted entries are discarded [2507.15761].

Executor is the safety gate. It applies Seeker’s suggested changes to obtain a Seeker-optimized contract, then runs Slither for security auditing, auto-generates unit tests, boundary-value tests, and fuzzing with Foundry, and measures deployment gas with `solc 0.8.20`, Ganache, and Hardhat. Foundry fuzzing is configured with up to 5 parameter combinations and 100 fuzz runs per function. Only if the transformed contract is secure, behaviorally equivalent, and strictly lower in gas than the baseline does Executor accept it. If the Seeker-derived version passes, Executor may then apply Innovator’s refactoring on top of it and repeat the same validation procedure. Failed innovative patterns are blacklisted; successful ones are added to a Verified New Pattern pool [2507.15761].

Manager is the controller and external interface. It receives the input contract, initiates the Seeker → Innovator → Executor pipeline, collects outcomes from each loop, and decides whether additional optimization is likely beneficial. If further effective patterns are not found, or if gains become marginal or negative, Manager terminates and returns the last validated optimized contract together with a report of applied patterns, gas savings, number of iterations, and patterns that failed validation [2507.15761].

## 3. Pattern library, retrieval mechanics, and pattern discovery

GasAgent’s pattern library is a directory of JSON files, each describing one verified gas-waste pattern. The schema includes `name`, `description`, `summary`, `tags`, `applicableScenarios`, and `examples`; each example includes `id`, `title`, `description`, `codeBefore`, `codeAfter`, `codeIssueTags`, and `codeImprovements`. Patterns are also implemented as Python modules that can automatically detect, and in some cases propose refactoring for, given Solidity code [2507.15761].

Compatibility with existing work is based on 24 patterns extracted from six representative tools or papers. The reported sources include Unearth, GASaVER, Gasaver, GasMet, Gassaver, and DPGOE. Four PhD students read the original works and implemented each pattern as a Python detection module. This library gives Seeker a curated prior over known inefficiencies while keeping the detection step executable rather than purely descriptive [2507.15761].

The retrieval pipeline balances recall and cost. Exhaustively running all 24 pattern tools on 100 real-world contracts yields 557 ground-truth pattern instances. Under the default cosine-similarity threshold \(0.7\), Seeker retrieves 515 of 557 instances, corresponding to 92.5% recall, while reducing pattern-tool calls from 2400 to 1722, a 28.25% reduction. The paper notes that lowering the threshold to \(0\) would yield 100% recall at the cost of more tool calls. This establishes GasAgent’s central trade-off in pattern incorporation: selective invocation of known detectors rather than universal execution [2507.15761].

Pattern discovery operates in context rather than in isolation. GasAgent discovered 68 new patterns during experiments on 100 real-world contracts: 38 original patterns and 30 sub-patterns. The new patterns are categorized by optimization method into batch or consolidation with 28 patterns, mapping and struct data layout with 22 patterns, bitwise operations and packing or unchecked arithmetic with 10 patterns, and miscellaneous safe compute and storage optimizations with 8 patterns [2507.15761].

Two examples illustrate the discovery logic. “Bitmap Role Management” replaces separate role mappings such as `mapping(address => bool) public isAdmin;` and `mapping(address => bool) public isMinter;` with a single `mapping(address => uint256) private _roles;` plus bitmask constants, reducing storage slots per address and lowering deployment gas; the example reports 96,516 gas saved. “Immutable Metadata Fields” refines an existing immutable-variable pattern by recognizing that deployment-time constant metadata such as `chainId` or `launchTimestamp` should be `immutable`, thereby avoiding constructor `SSTORE` operations and reducing deployment gas; the example reports 36,084 gas saved [2507.15761].

## 4. Validation criteria and optimization semantics

GasAgent accepts an optimization only under three conditions: no new vulnerabilities are introduced, the refactored contract remains behaviorally consistent with the original, and measured deployment gas is strictly lower. This makes Executor the decisive component of the framework, because both Seeker and Innovator can propose transformations, but neither can validate them [2507.15761].

Behavioral consistency is tested comparatively between versions. The generated Foundry suite checks function outputs and behavior equivalence, deployment initialization consistency, and allows structural tolerance for minor differences that do not affect semantics. Security is checked with Slither under compatible compiler settings. Gas is measured by compiling and deploying the original and transformed contracts using `solc 0.8.20`, with Ganache and Hardhat used to cross-validate deployment gas estimates [2507.15761].

The optimization objective is defined as percentage deployment gas savings. If \(G_{orig}\) is the deployment gas of the original contract and \(G_{opt}\) is the deployment gas of the optimized contract, the saving ratio is

$$
\text{Saving (\%)} = \frac{G_{orig} - G_{opt}}{G_{orig}} \times 100\%.
$$

Three outcomes are distinguished. Positive saving, where \(G_{opt} < G_{orig}\), is accepted. No change, where \(G_{opt} = G_{orig}\), is treated as ineffective and the system reverts to the original. Negative saving, where \(G_{opt} > G_{orig}\), is rejected and the original contract is preserved. This strict acceptance rule is the main mechanism by which GasAgent filters LLM-generated but economically unhelpful refactorings [2507.15761].

This validation regime also structures GasAgent’s self-updating behavior. A new pattern that survives security analysis, behavioral testing, and strict gas comparison is considered empirically validated and added to the Verified New Pattern pool. A failed new pattern is added to the blacklist. This suggests a gradual transition from exploratory pattern proposal to curated reusable knowledge, although the paper still assumes manual creation of a corresponding Python detection tool before a validated new pattern joins the main library [2507.15761].

## 5. Experimental results and ablation evidence

The main evaluation uses two datasets. The first contains 100 real-world contracts, randomly sampled from Etherscan, required to be verified, compiled with 0.8.20, deployed after June 2025, and not restricted by category. The second contains 500 LLM-generated contracts focused on DeFi, constructed from the 10 most prevalent DeFi protocol categories from DefiLlama, two difficulty levels per category, five LLMs, and manually verified test cases designed by two PhD students [2507.15761].

On the 100 real-world contracts, GasAgent successfully optimizes 82 contracts, achieving an average deployment Gas savings of 9.97%. The outcome breakdown is 82% with actual gas savings, 7% unchanged because the contracts were already efficient, and 11% with negative-savings proposals that were rejected. Most contracts fall into the 5–20% savings range, and the best case exceeds 30% reduction. In terms of iteration structure, 52% of contracts are optimized in a single cycle using only existing patterns, while 48% require additional rounds involving Innovator, with up to 4 new patterns discovered in some contracts [2507.15761].

On the 500 LLM-generated contracts, GasAgent optimizes 79.8% of them. Reported deployment gas savings range from 4.79% to 13.93% across models and difficulty levels. The model-wise results include 13.93% savings for Llama-4-Maverick-17B-128E-Instruct on fundamental contracts and 4.79% savings for Gemini-2.5-Flash on advanced contracts. The paper notes that savings and success rates generally drop from fundamental to advanced contracts, which it attributes to more complex control flows and data dependencies [2507.15761].

The ablation study shows the contribution of the full multi-agent design. On the same 100 real-world contracts, a direct LLM baseline optimizes 71 contracts with 5.93% average savings; GasAgent without Innovator optimizes 72 contracts with 5.52% average savings; GasAgent without Seeker optimizes 70 contracts with 5.74% average savings; full GasAgent optimizes 82 contracts with 9.97% average savings. The reported implication is that Seeker-only and Innovator-only variants are roughly comparable to or slightly worse than the direct LLM baseline, while the combination of compatibility-oriented retrieval and novelty-oriented discovery yields substantially better performance [2507.15761].

The authors also present GasAgent as an optimization layer for LLM-assisted smart contract development. In that role, a coding model generates initial Solidity code, and GasAgent identifies known patterns, discovers additional opportunities, applies and validates refactorings, and returns an optimized contract plus a report of changes and measured gas savings. The paper explicitly connects this usage to “vibe-coding” workflows [2507.15761].

## 6. Limitations, later reinterpretations, and related agent systems

The original GasAgent paper identifies several limitations. Some contracts are already well optimized, leaving Seeker with no matches and Innovator with no valid safe transformation. Advanced LLM-generated contracts with deep nesting, dynamic control flow, and complex state interactions are harder to refactor safely. Runtime overhead remains nontrivial because the system combines LLM calls, tool invocations, and automated test generation. The paper also notes that Innovator’s effectiveness depends on the underlying model’s gas and programming knowledge, and suggests dynamic execution traces or deeper semantic flow analysis as future directions [2507.15761].

In later work, “GasAgent-like” no longer refers only to Solidity optimization. In AgentShield, the term denotes a modular LLM multi-agent system with specialized agents and routing, into which topology-aware auditing, sentry agents, and two-round consensus can be integrated. AgentShield models the MAS as a directed graph \(G=(V,E)\), prioritizes auditing by centrality and task contribution, uses a strict unanimity trigger for lightweight sentries, and reports a 92.5% recovery rate while reducing auditing overhead by over 70% compared to existing methods. The paper explicitly states that AgentShield is designed precisely for the kind of setting a framework like GasAgent targets and describes concrete integration hooks for a GasAgent-like system [2511.22924].

AIRGuard uses “GasAgent” in yet another sense: as a guarded agent framework controlling tool use and side effects. It argues that a GasAgent-style system should normalize heterogeneous tool calls into a runtime action form \(\bar{a} = (\kappa, y, e, s)\), maintain an authority context \(\alpha = (\mathrm{issuer}, \mathrm{subject}, \mathrm{scope}, \mathrm{ttl}, A, G)\), track source and target trust \(\rho=(r,t)\), and enforce a monotone decision function over \(\{\text{allow}, \text{audit}, \text{ask}, \text{inspect}, \text{sandbox}, \text{quarantine}, \text{block}\}\). AIRGuard reports that on AgentTrap it reduces Sonnet 4.6 attack success from 36.3% without defense to 5.5%, and on DTAP-150 it preserves 76.0% benign utility with Haiku 4.5, compared with 52.0% for ARGUS and 42.0% for MELON [2605.28914].

DAO-Agent extends the term into decentralized coordination. Its authors explicitly frame DAO-Agent as “GasAgent”: a blueprint for gas-aware agent systems in which heavy computation is off-chain, blockchain is limited to commitments, proof verification, and settlement, and verification complexity and gas cost are independent of the number of agents. In its crypto-trading case study, the chain performs constant-cost Groth16 verification at about 27k gas, with proof size about 1.4–1.8 KB, and reports up to 99.9% reduction in verification gas costs relative to naive on-chain alternatives as coalition size increases to 10 agents [2512.20973].

This broader usage suggests that GasAgent has become both a specific optimizer for smart contracts and an editor’s term for a family of gas-aware, verification-oriented agent architectures. In the original sense, however, GasAgent remains the four-agent Solidity optimization framework defined by pattern reuse, constrained innovation, external-tool validation, and measured deployment gas reduction [2507.15761].

Source: https://www.emergentmind.com/topics/gasagent