Paper deep dive
RAGas: Retrieval-Augmented Gas Optimization for Smart Contracts with Continuous Knowledge Integration
Yishun Wang, Wenjin Yi, Wenkai Li, Zongwei Li, Xiaoqi Li
Intelligence
Status: succeeded | Model: Gemma-4-26B-A4B | Prompt: intel-v1 | Confidence: 94%
Last extracted: 8/22/2026, 3:10:07 AM
Summary
The paper introduces RAGas, a three-stage retrieval-augmented generation framework designed to optimize Gas usage in Ethereum smart contracts. It addresses limitations of static analyzers and standalone LLMs by using a dual-model hypothesis generation stage (LLaMA 3.3 and DeepSeek-R1) with confidence calibration, a self-updating vectorized knowledge base of Gas antipatterns, and a final reasoning stage to generate audit reports. Experiments show RAGas reduces Gas usage by up to 11% with high precision and recall.
Entities (10)
Relation Signals (8)
RAGas → optimizes → Gas
confidence 100% · RAGas reduces Gas usage by up to 11%
RAGas → targets → Ethereum
confidence 100% · Smart contracts on Ethereum incur execution fees, known as Gas... We operationalize these insights with RAGas
RAGas → detects → High Gas Consumption (HGC)
confidence 95% · RAGas... achieves high precision and recall in detecting code snippets exhibiting Gas wastage.
RAGas → uses → Llama 3.3
confidence 95% · we selected two models LLaMA-3.3 ... and DeepSeek-R1 ... for preliminary detection.
RAGas → uses → DeepSeek-R1
confidence 95% · we selected two models LLaMA-3.3 ... and DeepSeek-R1 ... for preliminary detection.
RAGas → utilizes → Knowledge Base
confidence 95% · Next, these patterns are aligned with a knowledge base... The resulting conceptual signatures query a specialized vector database
Slither → istypeof → Static Analyzer
confidence 90% · Conventional static analyzers like Slither and Solhint depend on predefined rules
Solhint → istypeof → Static Analyzer
confidence 90% · Conventional static analyzers like Slither and Solhint depend on predefined rules
Cypher Suggestions (0)
No Cypher suggestions yet.
Abstract
Abstract:Ethereum is now integral to mission-critical sectors, including finance, healthcare, and supply chain management. Execution fees, commonly referred to as Gas, scale with the computational complexity of their functions. Smart contracts on Ethereum incur execution fees, known as Gas, which increase with computational complexity. Thus, optimizing Gas-intensive code while preserving functional equivalence significantly lowers deployment costs. No existing system continuously exploits evolving Gas usage patterns. We systematically analyze syntactic and semantic constructs that drive excessive Gas use. This yields six high-level categories covering twelve fine-grained antipatterns underpinning a curated knowledge base. We operationalize these insights with RAGas, a three-stage retrieval-augmented generation framework that uses a large language model to pinpoint and automatically fix Gas inefficiencies. Experiments on deployed contracts demonstrate that RAGas reduces Gas usage by up to 11% and achieves high precision and recall in detecting code snippets exhibiting Gas wastage.
Tags
Links
- Source: https://arxiv.org/abs/2608.15857v1
- Canonical: https://arxiv.org/abs/2608.15857v1
Trouble viewing inline? Open PDF directly →
Full Text
49,130 characters extracted from source content.
Expand or collapse full text
RAGas: Retrieval-Augmented Gas Optimization for Smart Contracts with Continuous Knowledge IntegrationThanks: Corresponding author. Yishun Wang Affiliation: [4pt] School of Cyberspace Security, Hainan Universityyishunwang, wjyi0915, cswkli, lizw1017@hainanu.edu.cn,csxqli@ieee.org Wenjin Yi Affiliation: [4pt] School of Cyberspace Security, Hainan Universityyishunwang, wjyi0915, cswkli, lizw1017@hainanu.edu.cn,csxqli@ieee.org Wenkai Li Affiliation: [4pt] School of Cyberspace Security, Hainan Universityyishunwang, wjyi0915, cswkli, lizw1017@hainanu.edu.cn,csxqli@ieee.org Zongwei Li Affiliation: [4pt] School of Cyberspace Security, Hainan Universityyishunwang, wjyi0915, cswkli, lizw1017@hainanu.edu.cn,csxqli@ieee.org Xiaoqi Li Affiliation: [4pt] School of Cyberspace Security, Hainan Universityyishunwang, wjyi0915, cswkli, lizw1017@hainanu.edu.cn,csxqli@ieee.org Abstract Ethereum is now integral to mission-critical sectors, including finance, healthcare, and supply chain management. Execution fees, commonly referred to as Gas, scale with the computational complexity of their functions. Smart contracts on Ethereum incur execution fees, known as Gas, which increase with computational complexity. Thus, optimizing Gas-intensive code while preserving functional equivalence significantly lowers deployment costs. No existing system continuously exploits evolving Gas usage patterns. We systematically analyze syntactic and semantic constructs that drive excessive Gas use. This yields six high-level categories covering twelve fine-grained antipatterns underpinning a curated knowledge base. We operationalize these insights with RAGas, a three-stage retrieval-augmented generation framework that uses a large language model to pinpoint and automatically fix Gas inefficiencies. Experiments on deployed contracts demonstrate that RAGas reduces Gas usage by up to 11% and achieves high precision and recall in detecting code snippets exhibiting Gas wastage. 1 Introduction Ethereum is an open-source, decentralized computing platform built on the blockchain model pioneered by Bitcoin (Gao et al. 2025; Zhang et al. 2025a). While Bitcoin was designed for peer-to-peer token transfer via an immutable ledger (Song et al. 2024), Ethereum serves as a general-purpose global computational infrastructure. Its key innovation enables developers to deploy and execute decentralized applications (dApps) (Aufiero et al. 2024) on a blockchain that maintains a unified, globally consistent cryptographic state (Long et al. 2025; Zhou et al. 2025). This state is updated through transactions from two types of accounts: externally owned accounts (EOAs), which hold and transfer the native cryptocurrency Ether (ETH) (Destefanis 2024), and smart contract accounts, which store code typically written in high-level Turing-complete languages like Solidity and executed as Ethereum Virtual Machine bytecode (Wang et al. 2026). Along with other smart contract platforms, Ethereum has spurred the growth of a decentralized application ecosystem. A core feature of such platforms is Gas, a measure of computational resources consumed by on-chain operations. Although Gas consumption underpins network security and resource management, it directly correlates to transaction fees for users (Kim & Kim 2024; Ante & Saggu 2024). Therefore, the economic efficiency of a dApp depends critically on the Gas optimization of its smart contracts (Wahab et al. 2026); inefficient code can increase execution costs, hinder user adoption, and threaten the viability of the project (Tharammal & Nitnaware 2024; Sipos & Szénási 2025). Conventional static analyzers like Slither and Solhint depend on predefined rules (Nemati et al. 2025). While effective at identifying known anti-patterns, these tools face inherent limitations. Their rigid heuristic sets cannot detect novel or compositionally complex gas wastage patterns beyond their encoded rules (Alhayani et al. 2025; Huang et al. 2024a). Furthermore, their diagnostics are often superficial, typically providing generic warnings lacking contextual explanation or actionable fixes, placing the burden on developers to interpret and resolve issues independently (Kim et al. 2024; Li et al. 2024b). The emergence of LLMs presents a promising alternative. State-of-the-art models such as GPT-4o and DeepSeek-R1 exhibit strong code comprehension and generation abilities (Ren & Wei 2024; Ma et al. 2024), suggesting considerable potential for advanced code analysis. Their flexibility supports reasoning beyond fixed rules (Ding et al. 2025a). However, their use in specialized domains like gas optimization remains hindered by two key shortcomings: Challenge 1 (C1): Internal knowledge is frozen at the time of the last training cutoff (Tang et al. 2026), rendering the models oblivious to recently emerging community best-practices and optimization techniques (Pearlson et al. 2024); Challenge 2 (C2): When operating outside their training distribution, LLMs are prone to generating plausible-sounding yet factually incorrect or non-existent vulnerabilities and fixes (Li et al. 2026h), thereby undermining trust and reliability (Zhang et al. 2025b). Our Solution: We propose RAGas, a three-stage pipeline that reframes Gas optimization as a reasoning task augmented by knowledge retrieval, combining the strengths of static analyzers and LLMs. First, a large language model (LLM) acts as a hypothesis generator: guided by specialized prompts, it performs a logic and semantic analysis of the target contract and produces a set of abstract gas-related code patterns. Next, these patterns are aligned with a knowledge base; unrecognized patterns are dynamically incorporated, enabling real-time knowledge-base evolution. The resulting conceptual signatures query a specialized vector database containing structured gas-pattern knowledge. Finally, a second LLM synthesizes verified knowledge with the source code to generate a context-aware audit report. Solution for C1: Pre-trained weights are frozen, RAGas maintains model currency by continuously aligning the LLM-generated pattern set with a rigorously curated, domain-specific vector database in real time. New patterns are added on the fly, keeping the knowledge base’s working memory aligned with the latest best practices. Solution for C2: To mitigate hallucinations arising when the model operates beyond its training distribution, RAGas deploys a dual-model detector with confidence feedback: instead of naïve pattern matching, an LLM serves as a hypothesis generator. LLaMA 3 and ChatGPT-4o, strong in code comprehension and logic, independently analyze the same contract, rank plausible Gas issues, and attach a calibrated confidence score with a brief justification. The main contributions of this paper are as follows: • A Novel Three-Stage RAG Architecture for Code Analysis: We propose and implement an innovative approach that recasts code analysis as a knowledge retrieval task. Our architecture decouples hypothesis generation from final diagnosis, leveraging the broad reasoning capabilities of LLMs while grounding them in authoritative external knowledge bases to ensure accuracy and counteract hallucinations. • Self-Updating Knowledge Base for Gas Optimization: We constructed a high-quality, structured knowledge base of Gas patterns based on academic literature and expert knowledge. This knowledge base is processed and vectorized to serve as the foundational source of truth for our RAG system. Furthermore, a verification mechanism incorporating both multi-model verification and confidence scoring is employed to mitigate LLM hallucinations and ensure the accuracy of newly identified Gas problem patterns. • We have uploaded the related codes and experimental data of RAGas, and we will open-source them after the paper’s publication. 2 Background 2.1 Smart Contract and High Gas Consumption (HGC) Smart contracts (Wu et al. 2025; Li et al. 2026f; Li et al. 2025) are deterministic, on-chain programs that digitally encode and autonomously enforce agreements. Yet immutability and asset custody make contracts prime targets, necessitating rigorous audits (Ding et al. 2025b; Li et al. 2026d). All contract code is ultimately executed by the EVM (Dxo et al. 2024). The EVM is Turing-complete (Yaish et al. 2024; Wu et al. 2022), so it could run unbounded loops. Absent safeguards, a malicious or poorly programmed contract might execute indefinitely, exhausting the network’s computational resources. Because miners must expend real-world resources like CPU cycles, memory, and storage to process bytecode, Ethereum introduces the gas mechanism to pre-empt infinite loops, deter resource abuse, and compensate nodes for their expenditure (Rao et al. 2026; Li et al. 2026a). Gas is a dimensionless unit that quantifies the computational work required for each operation (Barakbayeva et al. 2025). The HGC defect denotes a systematic excess in the amount of gas expended by a single transaction or state transition relative to the current industry optimum or to a user-acceptable threshold, even though the contract’s functional correctness is preserved. 2.2 LLMs and RAG LLMs (Zhou et al. 2024) are deep learning architectures grounded in the Transformer paradigm. Pre-trained on web-scale corpora, they distill statistical regularities, syntactic constraints, and world knowledge (Li et al. 2026e). Their core capability is to probabilistically extend a given context with the most plausible continuation, yielding strong performance in language understanding, content generation, and code synthesis (Gu et al. 2024). However, an LLM’s knowledge is strictly confined to its training data: the corpus has a cut-off date (Luo et al. 2026; Li et al. 2026b), barring any post-training information, and the encoded knowledge is static, compressed, and distributed across parameters (Li et al. 2026c). Consequently, recall is unreliable for fine-grained or highly specialized domains that are underrepresented in the training distribution (Li et al. 2024a; Kandpal et al. 2023). This limitation precipitates a critical failure mode hallucination (Anh-Hoang et al. 2025), where the model produces text that is fluent yet conflicts with the prompt, violates real-world facts, or lacks verifiable support (Sahoo et al. 2024). To counteract this deficiency, retrieval-augmented generation (RAG) has been introduced (Arslan et al. 2024; Fan et al. 2024). RAG dynamically fuses parametric knowledge with external sources by retrieving relevant, authoritative, and up-to-date evidence from knowledge bases, document collections, or the open web before generating a response (Li et al. 2026g; Sui et al. 2025). By coupling a parametric model with a precise expert system and an instantly updatable knowledge store, RAG substantially mitigates hallucination and enables continual refreshment and specialization of knowledge (Zhang & Zhang 2025). 3 Preliminaries In this section, we elaborate on the various potential HGC patterns in smart contract development and management. These HGC patterns are categorized into 6 major groups encompassing 12 subcategories, which were extracted from multiple authoritative literature sources in the field (Ta & Do 2024; Liu & Song 2024; He et al. 2025; Huang et al. 2024b). We have consolidated them as the primary data source for this paper. Table 1 provides a concise summary of all HGC patterns, including their names and corresponding major categories. Due to space constraints, detailed descriptions of the 12 HGC patterns are not presented here. They will be separately elaborated in the open-source code and experimental data. Table 1: HGC Patterns in Smart Contracts ID Pattern Name Category 1.1 Suboptimal Storage Slot Packing Storage-Related Waste Patterns 1.2 Redundant Storage Reads Storage-Related Waste Patterns 1.3 Costly State Transitions Storage-Related Waste Patterns 2.1 Unchecked Safe Arithmetic Computational Waste Patterns 2.2 Loop Inefficiencies Computational Waste Patterns 3.1 Calldata-Memory Mismatch Data Handling Waste Patterns 3.2 Type Conversion Overheads Data Handling Waste Patterns 4.1 Visibility Specification Errors Function Design Waste Patterns 4.2 Redundant Code Execution Function Design Waste Patterns 5.1 Proxy Overhead Contract Architecture Issues 6.1 Disabled Compiler Optimizations Compiler Suboptimization 6.2 Misconfigured Optimizer Runs Compiler Suboptimization 4 METHOD In this section, we elaborate on the primary workflow of RAGas. As illustrated in Figure 1, RAGas is designed as a three-stage process. By leveraging different LLM models at each stage and executing distinct practical tasks, it ultimately achieves the detection and optimization of HGC patterns in the input contract code. In the first stage, we perform an initial LLM-based detection on the input contract. Moving beyond traditional code matching methods, we fully utilize the LLM’s capabilities in code comprehension and logical reasoning to conceptually understand the semantics of the target contract. This stage outputs a list containing potential HGC patterns and related information identified in the target contract. This list then proceeds to the second stage, where it is matched and used to update a vectorized knowledge base. This knowledge base incorporates empirically investigated and refined information on currently prevalent HGC patterns. Finally, the third stage employs an LLM to perform retrieval and logical reasoning based on the updated knowledge base, outputting the final results in a pre-defined JSON format. Figure 1: A Brief Architecture of RAGas: Integrating a three-stage design, the stage 1 performs initial LLM-based logical reasoning to output a list of potential HGC patterns. Stage 2 updates the knowledge base, addressing the latency issues inherent in traditional RAG systems. The stage 3 conducts final LLM-driven logical reasoning and knowledge base matching 4.1 On the Construction of the HGC Knowledge Base We conducted systematic manual screening and organization based on existing specialized literature and the empirical data described in Section 3. The HGC patterns, comprising 6 major categories and 12 subcategories, were represented in a structured JSON format. Each JSON object includes the pattern name, corresponding scenario description, and relevant code snippets. For patterns lacking typical code examples, to mitigate the risk of hallucinations during language model generation, the code snippet fields were left unfilled. Instead, enhanced scenario descriptions were provided to guide the model in relying on logical reasoning for judgment, thereby reducing dependence on fixed code examples. 4.2 Stage 1: Hypothesis Generation In this stage, we primarily leverage the logical reasoning and code comprehension capabilities of LLMs to identify potential HGC patterns in the target contract. Balancing economic cost and model performance, we selected two models LLaMA-3.3 (Dubey et al. 2024) and DeepSeek-R1 (Deng et al. 2025), for preliminary detection. The objective is to parse the semantics of the input contract code and abstractly determine whether it encompasses any HGC patterns. Guided by the Auto-CoT Think step by step strategy (Zhang et al. 2022), we systematically designed prompts to enhance the model’s logical reasoning ability and reduce its reliance on simple code pattern matching, as illustrated in Figure 2. Specifically, the model is first prompted to reason independently of the knowledge base, enumerating code scenarios that may lead to high gas consumption in smart contracts, followed by a semantic understanding of the input contract. To mitigate the risk of hallucinations during model generation, we require the model to provide three outputs for each identified HGC pattern: the corresponding original code snippet, a confidence score quantifying the certainty of the judgment, and a detailed rationale supporting the decision. This multi-dimensional output constraint enhances the interpretability and reliability of the detection process. Figure 2: Prompt of Stage 1 for identifying potential HGC patterns in the target contract 4.2.1 Dual-Model Hypothesis Generation with Confidence Calibration We employ a dual-model voting mechanism coupled with a consistency-based confidence calibration strategy to mitigate potential hallucinations that may arise from relying on a single LLM. LLaMa-3.3 and DeepSeek-R1 are utilized concurrently in the first evaluation stage using the same prompt. This process takes preprocessed contract code as input and outputs a verified list of patterns, referred to as the VettedPatternsList, along with calibrated confidence scores. Specific steps are as follows: The carefully designed prompt template, PromptHypothesisPrompt_Hypothesis, is concatenated with the preprocessedcodepreprocessed_code and fed into two independent LLMs. The raw responses from both models are parsed to extract pattern names, code snippets, confidence scores, and explanations, forming two separate pattern lists: PatternListLPatternList_L and PatternListDPatternList_D. Any response that does not adhere to the specified format is logged as an error and excluded from further analysis. The core of this process lies in determining whether the patterns output by the two models refer to the same issue. We define a matching function, is_match(patternx,patterny)is\_match(pattern_x,pattern_y) as follows: Name Similarity Calculation: The string similarity between pattern names is computed using the normalized Levenshtein distance, scaled to the interval [0, 1]. The formula is given by: namesim(patternx,patterny)=1−levenshtein_distance(namex,namey)max(len(namex),len(namey))name_sim(pattern_x,pattern_y)=1- levenshtein\_distance(name_x,name_y)max(len(name_x),len(name_y)) (1) A preliminary match is considered if the name similarity exceeds a threshold θname _name, empirically set to 0.7. Explanation Semantic Similarity Calculation: An embedding model (Tao et al. 2024) is used to obtain vector representations of the explanations explanationxexplanation_x and explanationyexplanation_y. The cosine similarity between these two vectors is computed: semantic_sim=cosinesimilarity(embed(explanationx),embed(explanationy))semantic\_sim=cosine_similarity(embed(explanation_x),embed(explanation_y)) (2) A semantic match is confirmed if the semantic similarity exceeds a threshold θsemantic _semantic, empirically set to 0.75. Final Matching Decision: Patterns patternxpattern_x and patternypattern_y are considered matched if both of the following conditions are met: is_match(patternx,patterny)=Trueifname_sim>θnameandsemantic_sim>θsemanticFalseotherwiseis\_match(pattern_x,pattern_y)= casesTrue if\ name\_sim> _name\ and\ semantic\_sim> _semantic\\ False otherwise cases (3) This indicates that the two models have independently identified the same issue. Confidence Calibration: For each pattern plp_l in PatternListLPatternList_L, we search for a matching pattern pdp_d in PatternListDPatternList_D. • Case 1: Agreed Patterns If a pattern pdp_d is found such that ismatch(pl,pd)is_match(p_l,p_d) = True, the pattern is considered to have dual-model consensus. Its final confidence score is computed as a weighted average of the two confidence values, amplified by a reward factor α(α>1)α(α>1): pfinal.confidence=α.(w1.pl.confidence+w2.pd.confidence)p_final.confidence=α.(w_1.p_l.confidence+w_2.p_d.confidence) where w1w_1 and w2w_2 are weights (initially set to 0.5), and α is set to 1.1 to moderately enhance the confidence of consensus patterns. • Case 2: Disagreed Patterns If no matching pattern is found in the other model’s list for plp_l, the pattern hypothesis is retained, but its confidence is penalized by a factor β(β<1)β(β<1) to reflect the lack of cross-validation: pfinal.confidence=β.pl.confidencep_final.confidence=β.p_l.confidence where β is set between 0.5 and 0.7 to significantly reduce the confidence of patterns identified by only one model, which are more likely to be hallucinations. The same process is repeated for patterns in PatternListDPatternList_D. 4.3 Stage 2: Knowledge Base Matching and Updating This stage enables the self-evolution of the knowledge base (KB) (Kosaka 2024). It processes the VettedPatternsList through a two-step gating mechanism to decide if a candidate pattern should be added to the KB. • Candidate Filtering: A candidate pattern must meet two criteria to proceed: (a) it must be a consensus pattern from both models in Stage 1, and (b) its calibrated confidence score must exceed a high threshold (θconfidence _confidence = 0.7). • Semantic Redundancy Check: Candidates passing the filter are encoded into vectors. We perform an approximate nearest neighbor (ANN) (Liu et al. 2004) search against the existing KB. If the cosine similarity between the candidate and its closest existing pattern exceeds a redundancy threshold (θredundancy _redundancy = 0.85), the candidate is deemed a duplicate and discarded. Otherwise, it is incorporated into the KB. This automated process ensures the KB continuously integrates novel, high-confidence patterns while maintaining its authority by rigorously avoiding duplicates and low-quality entries. 4.4 Stage 3: Logic Thinking and Analysis This module follows the standard RAG workflow but innovates by extending retrieval from unstructured text to structured knowledge patterns. Instruction fine-tuning is used to enforce output structure and traceability. The specific procedure includes: Precision Retrieval: For each candidate in VettedPatternsList, a query derived from its name and description is encoded and used to retrieve the top-K (K=3) most relevant entries (retrieved_knowledge) from the vector database, supplying the LLM with verified reference knowledge (Vaswani et al. 2017). LLM-Guided Contextual Synthesis and Formatting: The retrieved knowledge, first-stage hypotheses, and strict formatting instructions (as in Sec. 4.2) are integrated into a structured prompt to guide final reasoning. Output Parsing: Responses are parsed and validated against a predefined JSON schema. Valid outputs are retained; invalid or null ones are discarded. This dual verification, through hypothesis generation and retrieval augmentation, ensures reliable, actionable results for gas optimization while minimizing hallucinations. 5 Evaluation 5.1 Experimental Settings All experiments are executed on a Ubuntu server 22.04 LTS equipped with NVIDIA GeForce GTX 4070Ti GPU, Intel(R) Core(TM) i9-13900KF CPU, and 128G RAM. The software environment includes Python 3.9, PyTorch 2.0.1, and LangChain 0.2.0. DataSet: To evaluate the usability and efficiency of the RAGas system, this study constructed two test datasets. Dataset A comprises 300 real-world smart contracts, used to evaluate practical gas optimization performance. Quantitative analysis was conducted based on two metrics: Gas Reduction Percentage (GRP), quantifying the relative reduction in gas consumption after optimization, and Optimization Success Rate (OSR), measuring the proportion of successfully addressed gas issues. Dataset B contains 300 smart contracts generated by ChatGPT-4o (Pang et al. 2024) from instructions. These contracts are fully compilable, functionally sound, and uniformly cover diverse gas-related patterns, serving to assess the system’s accuracy in problem identification and quality of optimized code generation. 5.2 Research Questions (RQs) RAGas integrates existing systematic Gas optimization patterns, mechanisms for identifying and discovering novel patterns, and a verification structure based on a multi-agent framework. To systematically evaluate its practical effectiveness, architectural rationality, and usability, we conducted a series of experiments centered around the following research questions: RQ1:How is the retrieval quality and generation quality of RAGas? RQ2:How effective is RAGas in optimizing Gas for smart contracts? RQ3:Is the overall architectural design of RAGas reasonable, i.e., are the functions and roles of all its modules indispensable? 5.2.1 answer to RQ1 To comprehensively evaluate the retrieval and generation quality of RAGas, we conducted a systematic assessment using Dataset B, which consists of 300 synthetically generated yet fully functional smart contracts that uniformly encompass the 12 predefined HGC patterns. The evaluation focuses on four key metrics: Precision, Recall, F1-Score, and Compilation Pass Rate. These metrics collectively reflect the system’s capability to accurately identify gas-inefficient patterns and generate correct, compilable optimized code. We first executed RAGas on each contract in Dataset B and collected the output recommendations. Each recommended optimization was manually verified against the ground truth patterns embedded in the dataset. The results are summarized in Table 2. Table 2: Performance Metrics by HGC Category Category Precision Recall F1-Score Compilation (%) Storage-Related Waste 0.72 0.71 0.71 99.3 Computational Waste 0.76 0.75 0.75 100 Data Handling Waste 0.77 0.81 0.79 99.5 Function Design Waste 0.78 0.72 0.75 100 Contract Architecture Issues 0.82 0.73 0.77 97 Compiler Suboptimization 0.75 0.79 0.77 100 Overall Average 0.75 0.74 0.74 99.3 The results demonstrate that RAGas has a high level of accuracy in both detecting and diagnosing gas-inefficient code segments. Furthermore, the Compilation Pass Rate of 99.3% confirms that the vast majority of code transformations suggested by RAGas are syntactically correct and directly integrable into the original contract without introducing compilation errors. This underscores the practical applicability of the generated optimizations. 5.2.2 answer to RQ2 To evaluate the practical effectiveness of RAGas in reducing gas consumption, we applied the system to Dataset B. We measured gas usage before and after optimization using a local Ethereum testnet (Hardhat) under consistent transaction parameters (e.g., equivalent gas price and block conditions). The degree of optimization is quantified via two primary metrics: GRP=Gasorigina−GasoptimizedGasorigina×100%GRP= Gas_origina-Gas_optimizedGas_origina× 100\%, representing the relative decrease in gas consumed per transaction. OSR, the proportion of successfully patched contracts among all contracts where at least one HGC pattern was identified. Figure 3 summarizes the gas optimization performance of RAGas across each HGC pattern category: Figure 3: HGC Pattern Performance: Avg GRP and OSR RAGas achieved an average gas reduction of 11.2% across all optimized contracts, with particularly significant savings observed in patterns such as Costly State Transitions (1.3), Loop Inefficiencies (2.2), and Misconfigured Optimizer Runs (6.2), each contributing over 12% reduction. These patterns often involve repeated storage operations or subcompiler configurations, whose optimization directly translates into substantial gas savings. Architectural patterns like Proxy Overhead (5.1) showed more modest gains due to the inherent overhead of delegatecall mechanics, which cannot be fully eliminated without structural redesign. The overall Optimization Success Rate of 99.4% confirms that RAGas not accurately identifies gas-inefficient code but also reliably produces syntactically correct and semantically equivalent optimized versions that compile without error and preserve functional behavior. 5.2.3 answer to RQ3 To evaluate the rationality and necessity of the overall architectural design of RAGas, we conducted a series of ablation experiments. The core objective was to determine whether each of the three core stages, Hypothesis Generation (stage 1), Knowledge Base Matching and Updating (stage 2), and Logic Thinking and Analysis (stage 3), plays an indispensable role in the system’s overall performance and effectiveness. We designed three degraded variants of the RAGas system for comparison: • Variant A (w/o Continuous Knowledge Updating): This variant uses a static knowledge base, disabling the dynamic pattern assimilation and update mechanism in Stage 2. • Variant B (w/o Dual-Model Verification): This variant removes the dual-model hypothesis generation with confidence calibration in Stage 1, relying solely on a single model (LLaMA-3.3) for initial detection. • Variant C (w/o Retrieval-Augmented Synthesis): This variant bypasses the final RAG-based reasoning in Stage 3. It directly outputs the results from Stage 1 after a simple keyword-based lookup in the knowledge base, without the contextual synthesis performed by the LLM. Each variant was evaluated on Dataset B, and its performance was compared against the complete RAGas system using the F1-Score for detection accuracy and GRP for optimization effectiveness as the primary metrics. The results are summarized in Table 3. Experimental results confirm that each module in RAGas’ three-stage architecture is essential: (a) Without dynamic knowledge base updates (Stage 2), the system’s missed detection rate for new patterns rises significantly. (b) Absent dual-model verification (Stage 1), false positives and hallucinations increase, undermining result reliability. (c) Removing retrieval augmentation and context synthesis (Stage 3) reduces suggestion quality, yielding impractical outputs. This study empirically validates a three-stage architecture wherein each module executes critical functions, hypothesis generation, knowledge update, and semantic synthesis, which collaborate to ensure system performance, forming an integral entity. Table 3: Performance Comparison of RAGas Variants System Variant F1-Score Avg. GRP (%) Complete RAGas 0.74 11.2 Variant A (Static KB) 0.55 9.5 Variant B (Single Model) 0.68 10.1 Variant C (No RAG Synthesis) 0.71 8.7 5.3 Comparative Analysis with State-of-the-Art Tools To further evaluate the effectiveness of RAGas, we conducted a comparative analysis against two widely recognized tools in the smart contract analysis domain: Slither and GPTScan. The evaluation focused on three critical metrics: Precision, F1-Score, and GRP. The experiments were performed on Dataset B, ensuring a fair and reproducible benchmark. The results, summarized in Table 4, demonstrate RAGas’ superior performance across all evaluated metrics. Table 4: Performance Comparison of RAGas, Slither, and GPTScan on Dataset B Tool Precision Recall F1-Score Avg. GRP (%) Slither 0.66 0.58 0.62 6.8 GPTScan 0.50 0.61 0.55 9.1 RAGas 0.75 0.74 0.74 11.2 A comprehensive analysis of the experimental results above indicates that, as the understanding of most HGC patterns relies on contextual code semantic reasoning, traditional tools like Slither (Feist et al. 2019) are limited by their rule-based approach, exhibiting significant deficiencies in semantic comprehension and logical inference. In contrast, GPTScan (Sun et al. 2024), due to its lack of a RAG mechanism, is prone to generating hallucinations when encountering patterns outside its training data or low-frequency patterns, thereby reducing its reliability. RAGas, by integrating retrieval augmentation and a multi-stage reasoning mechanism, effectively suppresses hallucination generation while maintaining high precision, demonstrating more comprehensive optimization capabilities. 6 Conclusion This paper presents RAGas, a novel three-stage retrieval-augmented generation framework for gas optimization in Ethereum smart contracts. By reformulating gas inefficiency detection as a knowledge retrieval and reasoning task, RAGas integrates the abstract reasoning capabilities of large language models with a continuously updated structured knowledge base. Evaluations on both real-world and synthetic contracts demonstrate that RAGas reduces gas consumption by up to 11.2% on average while maintaining high precision, recall, and compilation reliability. Ablation studies confirm the necessity and complementary roles of each architectural stage, highlighting the importance of dual-model verification, dynamic knowledge integration, and context-aware synthesis. RAGas provides both a practical tool for reducing transaction costs and a scalable framework for code optimization in dynamic environments. Future work will expand the knowledge base to include additional optimization patterns and explore integration with formal verification methods to further improve code reliability. 7 Acknowledgment AI was used for linguistic refinement of this paper to improve clarity and readability. References Alhayani et al. (2025) Mohammed Yaseen Alhayani, Wisam Hazim Gwad, Shahab Wahhab Kareem, and Moustafa Fayad. A comparative study of machine and deep learning approaches for smart contract vulnerability detection. Technologies, 13(12):592, 2025. Anh-Hoang et al. (2025) D Anh-Hoang, V Tran, and LM Nguyen. Survey and analysis of hallucinations in large language models: Attribution to prompting strategies or model behavior. frontiers in artificial intelligence, 8, 1622292, 2025. Ante & Saggu (2024) Lennart Ante and Aman Saggu. Time-varying bidirectional causal relationships between transaction fees and economic activity of subsystems utilizing the ethereum blockchain network. Journal of Risk and Financial Management, 17(1):19, 2024. doi: 10.3390/jrfm17010019. Arslan et al. (2024) Muhammad Arslan, Hussam Ghanem, Saba Munawar, and Christophe Cruz. A survey on rag with llms. Procedia computer science, 246:3781–3790, 2024. Aufiero et al. (2024) Sabrina Aufiero, Giacomo Ibba, Silvia Bartolucci, Giuseppe Destefanis, Rumyana Neykova, and Marco Ortu. Dapps ecosystems: Mapping the network structure of smart contract interactions. EPJ Data Science, 13(1):60, 2024. Barakbayeva et al. (2025) Togzhan Barakbayeva, Soroush Farokhnia, Amir Kafshdar Goharshady, Pingjiang Li, and Zhaorun Lin. Improved gas optimization of smart contracts. In International Conference on Fundamentals of Software Engineering, p. 1–10. Springer, 2025. Deng et al. (2025) Zehang Deng, Wanlun Ma, Qing-Long Han, Wei Zhou, Xiaogang Zhu, Sheng Wen, and Yang Xiang. Exploring deepseek: A survey on advances, applications, challenges and future directions. IEEE/CAA Journal of Automatica Sinica, 12(5):872–893, 2025. Destefanis (2024) Giuseppe Destefanis. Complex systems oriented approach for dapps analysis. In 2024 IEEE International Conference on Pervasive Computing and Communications Workshops and other Affiliated Events (PerCom Workshops), p. 757–762. IEEE, 2024. Ding et al. (2025a) Hao Ding, Yizhou Liu, Xuefeng Piao, Huihui Song, and Zhenzhou Ji. Smartguard: An llm-enhanced framework for smart contract vulnerability detection. Expert Systems with Applications, 269:126479, 2025a. Ding et al. (2025b) Yuchen Ding, Hongli Peng, and Xiaoqi Li. A comprehensive study of exploitable patterns in smart contracts: From vulnerability to defense. arXiv, 2025b. Dubey et al. (2024) Abhimanyu Dubey, Abhinav Jauhri, Abhinav Pandey, Abhishek Kadian, Ahmad Al-Dahle, Aiesha Letman, Akhil Mathur, Alan Schelten, Amy Yang, Angela Fan, et al. The llama 3 herd of models. arXiv e-prints, p. arXiv–2407, 2024. Dxo et al. (2024) Dxo, Mate Soos, Zoe Paraskevopoulou, Martin Lundfall, and Mikael Brockman. Hevm, a fast symbolic execution framework for evm bytecode. In International Conference on Computer Aided Verification, p. 453–465. Springer, 2024. Fan et al. (2024) Wenqi Fan, Yujuan Ding, Liangbo Ning, Shijie Wang, Hengyun Li, Dawei Yin, Tat-Seng Chua, and Qing Li. A survey on rag meeting llms: Towards retrieval-augmented large language models. In Proceedings of the 30th ACM SIGKDD conference on knowledge discovery and data mining, p. 6491–6501, 2024. Feist et al. (2019) Josselin Feist, Gustavo Grieco, and Alex Groce. Slither: a static analysis framework for smart contracts. In 2019 IEEE/ACM 2nd International Workshop on Emerging Trends in Software Engineering for Blockchain (WETSEB), p. 8–15. IEEE, 2019. Gao et al. (2025) Pengfei Gao, Dechao Kong, and Xiaoqi Li. Implementation and security analysis of cryptocurrencies based on ethereum. arXiv, 2025. Gu et al. (2024) Jiawei Gu, Xuhui Jiang, Zhichao Shi, Hexiang Tan, Xuehao Zhai, Chengjin Xu, Wei Li, Yinghan Shen, Shengjie Ma, Honghao Liu, et al. A survey on llm-as-a-judge. arXiv preprint arXiv:2411.15594, 2024. He et al. (2025) Mengting He, Shihao Xia, Boqin Qin, Nobuko Yoshida, Tingting Yu, Yiying Zhang, and Linhai Song. How to save my gas fees: Understanding and detecting real-world gas issues in solidity programs. IEEE Transactions on Software Engineering, 2025. Huang et al. (2024a) Qing Huang, Renxiong Chen, Zhenchang Xing, Jinshan Zeng, Qinghua Lu, and Xiwei Xu. Guessgas: Tell me fine-grained gas consumption of my smart contract and why. IEEE Transactions on Reliability, 74(1):2348–2362, 2024a. Huang et al. (2024b) Ruiyao Huang, Qingni Shen, Yuchen Wang, Yiqi Wu, Zhonghai Wu, Xiapu Luo, and Anbang Ruan. Reenrepair: Automatic and semantic equivalent repair of reentrancy in smart contracts. Journal of Systems and Software, 216:112107, 2024b. Kandpal et al. (2023) Nikhil Kandpal, Haikang Deng, Adam Roberts, Eric Wallace, and Colin Raffel. Large language models struggle to learn long-tail knowledge. In International conference on machine learning, p. 15696–15707. PMLR, 2023. Kim & Kim (2024) Heesang Kim and Dohoon Kim. Optimal gas fee minimization in defi: Enhancing efficiency and security on the ethereum blockchain. IEEE Access, 12:173810–173823, 2024. Kim et al. (2024) Jaehyun Kim, Sangmyeong Lee, Howon Kim, et al. Robust vulnerability detection in solidity-based ethereum smart contracts using fine-tuned transformer encoder models. IEEE Access, 12:154700–154717, 2024. Kosaka (2024) Takumi Kosaka. The effects of chunk reading strategy training on the word chunking skills of l1-japanese english learners. System, 126:103495, 2024. Li et al. (2024a) Huihan Li, Yuting Ning, Zeyi Liao, Siyuan Wang, Xiang Lorraine Li, Ximing Lu, Wenting Zhao, Faeze Brahman, Yejin Choi, and Xiang Ren. In search of the long-tail: Systematic generation of long-tail inferential knowledge via logical rule guided search. In Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing, p. 2348–2370, 2024a. Li et al. (2024b) Kaixuan Li, Yue Xue, Sen Chen, Han Liu, Kairan Sun, Ming Hu, Haijun Wang, Yang Liu, and Yixiang Chen. Static application security testing (sast) tools for smart contracts: How far are we? Proceedings of the ACM on Software Engineering, 1(FSE):1447–1470, 2024b. Li et al. (2026a) Wenkai Li, Xiaoqi Li, Yingjie Mao, and Yuqing Zhang. Interaction-aware vulnerability detection in smart contract bytecodes. IEEE Transactions on Dependable and Secure Computing, p. 298–315, 2026a. Li et al. (2025) Xiaoqi Li, Wenkai Li, Zhiquan Liu, Yuqing Zhang, and Yingjie Mao. Penetrating the hostile: Detecting defi protocol exploits through cross-contract analysis. IEEE Transactions on Information Forensics and Security, p. 1, 2025. Li et al. (2026b) Xiaoqi Li, Hailu Kuang, Wenkai Li, Zongwei Li, and Shipeng Ye. Ckg-llm: Llm-assisted detection of smart contract access control vulnerabilities based on knowledge graphs. In Proceedings of the IEEE/ACM 48th International Conference on Software Engineering, p. 91–95. Association for Computing Machinery, 2026b. Li et al. (2026c) Xiaoqi Li, Zongwei Li, Wenkai Li, and Yuqing Zhang. A systematic survey of defi composability: From code correctness to protocol robustness. Blockchain: Research and Applications, p. 100554, 2026c. Li et al. (2026d) Xiaoqi Li, Zongwei Li, Wenkai Li, Zeng Zhang, and Lei Xie. Atomgraph: Tackling atomicity violation in smart contracts using multimodal gcns. In Proceedings of the IEEE/ACM 48th International Conference on Software Engineering, p. 86–90. Association for Computing Machinery, 2026d. Li et al. (2026e) Xiaoqi Li, Xin Wang, Wenkai Li, and Zongwei Li. Psr2: A phase-based semantic reasoning framework for atomicity violation detection via contract refinement. In Proceedings of the 34th ACM International Conference on the Foundations of Software Engineering, p. 1297–1301, 2026e. Li et al. (2026f) Xiaoqi Li, Lei Xie, Wenkai Li, and Zongwei Li. Uscsa: Evolution-aware security analysis for proxy-based upgradeable smart contracts. In Proceedings of the IEEE/ACM 48th International Conference on Software Engineering, ICSE-NIER ’26, p. 126–130. Association for Computing Machinery, 2026f. ISBN 9798400724251. Li et al. (2026g) Xiaoqi Li, Shipeng Ye, Wenkai Li, and Zongwei Li. Scpatcher: Automated smart contract code repair via retrieval-augmented generation and knowledge graph. In Proceedings of the 34th ACM International Conference on the Foundations of Software Engineering, p. 1212–1216, 2026g. Li et al. (2026h) Zongwei Li, Wenkai Li, and Xiaoqi Li. Defensible design for openclaw: Securing autonomous tool-invoking agents. arXiv preprint arXiv:2603.13151, 2026h. Liu et al. (2004) Ting Liu, Andrew Moore, Ke Yang, and Alexander Gray. An investigation of practical approximate nearest neighbor algorithms. Advances in neural information processing systems, 17, 2004. Liu & Song (2024) Yunqi Liu and Wei Song. Funredisp: Reordering function dispatch in smart contract to reduce invocation gas fees. In Proceedings of the 33rd ACM SIGSOFT International Symposium on Software Testing and Analysis, p. 516–527, 2024. Long et al. (2025) Xu Long, Yishun Wang, and Xiaoqi Li. From fomo3d to lottery dapp: Analysis of ethereum-based gambling applications. arXiv, 2025. Luo et al. (2026) Haitong Luo, Fali Wang, Weiyao Zhang, Xianren Zhang, Zhiwei Zhang, Tianxiang Zhao, Minhua Lin, Jiahao Zhang, Hui Liu, Xianfeng Tang, et al. Graph-assisted large language models: A perspective on mitigating intrinsic limitations. In Findings of the Association for Computational Linguistics: ACL 2026, p. 18936–18955, 2026. Ma et al. (2024) Jiarun Ma, Shiling Feng, Jiahao Zeng, Jia Lu, and Jie Chen. Smart contract vulnerability detection based on prompt-guided chatgpt. In 2024 International Conference on Networking and Network Applications (NaNA), p. 321–326. IEEE, 2024. Nemati et al. (2025) Nasrin Nemati, Nasr Abosata, and Usman Javed Butt. Enhancing ethereum smart contract security: A novel slither-based static analysis framework. In 2025 IEEE International Conference on Distributed Ledger Technologies (ICDLT), p. 1–7, 2025. Pang et al. (2024) Samarnh Pang, Engheang Nol, and Kimkong Heng. Chatgpt-4o for english language teaching and learning: Features, applications, and future prospects. Available at SSRN 4837988, 2024. Pearlson et al. (2024) Joshua Carter Pearlson, Xiaoyuan Liu, Chengsong Huang, Kripa Ann George, Dawn Song, and Chenguang Wang. Evaluating large language models in an emerging domain: a pilot study in decentralized finance. In ICLR 2024 Workshop on Navigating and Addressing Data Problems for Foundation Models, 2024. Rao et al. (2026) Ruicheng Rao, Mostafizur Rahman, and Md Showaib Sarker. Evaluating ethereum gas fee dynamics. In SoutheastCon 2026, p. 1–6. IEEE, 2026. Ren & Wei (2024) Xiaolei Ren and Qiping Wei. Sligpt: A large language model-based approach for data dependency analysis on solidity smart contracts. Software, 3(3):345–367, 2024. Sahoo et al. (2024) Pranab Sahoo, Prabhash Meharia, Akash Ghosh, Sriparna Saha, Vinija Jain, and Aman Chadha. A comprehensive survey of hallucination in large language, image, video and audio foundation models. Findings of the association for computational linguistics: EMNLP 2024, p. 11709–11724, 2024. Sipos & Szénási (2025) Miklós Sipos and Sándor Szénási. Optimal gas consumption in ethereum smart contracts: A targeted review of empirical results, design patterns and formal methods. In 2025 IEEE 25th International Symposium on Computational Intelligence and Informatics (CINTI), p. 517–522, 2025. Song et al. (2024) Han Song, Yihao Wei, Zhongche Qu, and Weihan Wang. Unveiling decentralization: A comprehensive review of technologies, comparison, challenges in bitcoin, ethereum, and solana blockchain. In 2024 IEEE 6th Advanced Information Management, Communicates, Electronic and Automation Control Conference (IMCEC), volume 6, p. 1896–1901. IEEE, 2024. Sui et al. (2025) Yi Sui, Chaozhuo Li, Chen Zhang, Dawei Song, and Qiuchi Li. Bridging external and parametric knowledge: Mitigating hallucination of llms with shared-private semantic synergy in dual-stream knowledge. In Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, p. 10845–10869, 2025. Sun et al. (2024) Yuqiang Sun, Daoyuan Wu, Yue Xue, Han Liu, Haijun Wang, Zhengzi Xu, Xiaofei Xie, and Yang Liu. Gptscan: Detecting logic vulnerabilities in smart contracts by combining gpt with program analysis. In Proceedings of the IEEE/ACM 46th International Conference on Software Engineering, p. 1–13, 2024. Ta & Do (2024) Minh Thanh Ta and Tien Quyet Do. A study on gas cost of ethereum smart contracts and performance of blockchain on simulation tool. Peer-to-Peer Networking and Applications, 17(1):200–212, 2024. Tang et al. (2026) Pingzhi Tang, Yiding Wang, and Muhan Zhang. Knowledge is not enough: Injecting RL skills for continual adaptation. In Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics, volume 1, p. 11969–11997. Association for Computational Linguistics, 2026. Tao et al. (2024) Chongyang Tao, Tao Shen, Shen Gao, Junshuo Zhang, Zhen Li, Kai Hua, Wenpeng Hu, Zhengwei Tao, and Shuai Ma. Llms are also effective embedding models: An in-depth overview. arXiv preprint arXiv:2412.12591, 2024. Tharammal & Nitnaware (2024) Rahul Raghavan Tharammal and Prashant Nitnaware. Maximizing efficiency in smart contract execution costs: Techniques for cost optimization on blockchain networks. In 2024 International Conference on Integration of Emerging Technologies for the Digital World (ICIETDW), p. 1–6, 2024. Vaswani et al. (2017) Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017. Wahab et al. (2026) Nur Haliza Abdul Wahab, Juniardi Nur Fadila, Nur Faszha Razali, and Keng Yinn Wong. Gas-efficient smart contract design: Quantifying refactoring impact on EVM execution costs. International Journal of Advanced Computer Science and Applications (IJACSA), 17(5), 2026. Wang et al. (2026) Yishun Wang, Wenkai Li, Xiaoqi Li, Zongwei Li, Lei Xie, and Yuqing Zhang. Libscan: Smart contract library misuse detection with iterative feedback and static verification. Blockchain: Research and Applications, p. 100521, 2026. Wu et al. (2025) Xiangfan Wu, Ju Xing, and Xiaoqi Li. Exploring vulnerabilities and concerns in solana smart contracts. arXiv, 2025. Wu et al. (2022) Zhendong Wu, Shan Li, Bin Wang, Tianjian Liu, Yongsheng Zhu, Chenming Zhu, and Mingqing Hu. Detecting vulnerabilities in ethereum smart contracts with deep learning. In 2022 4th International Conference on Data Intelligence and Security (ICDIS), p. 55–60, 2022. Yaish et al. (2024) Aviv Yaish, Kaihua Qin, Liyi Zhou, Aviv Zohar, and Arthur Gervais. Speculative \Denial-of-Service\ attacks in ethereum. In 33rd USENIX security symposium (USENIX Security 24), p. 3531–3548, 2024. Zhang et al. (2025a) Chunyi Zhang, Fengjiao Dou, and Xiaoqi Li. Dos attacks and defense technologies in blockchain systems: A hierarchical analysis. arXiv, 2025a. Zhang & Zhang (2025) Wan Zhang and Jing Zhang. Hallucination mitigation for retrieval-augmented large language models: A review. Mathematics (2227-7390), 13(5):856, 2025. Zhang et al. (2025b) Yue Zhang, Yafu Li, Leyang Cui, Deng Cai, Lemao Liu, Tingchen Fu, Xinting Huang, Enbo Zhao, Yu Zhang, Yulong Chen, et al. Siren’s song in the ai ocean: A survey on hallucination in large language models. Computational Linguistics, 51(4):1373–1418, 2025b. Zhang et al. (2022) Zhuosheng Zhang, Aston Zhang, Mu Li, and Alex Smola. Automatic chain of thought prompting in large language models. arXiv preprint arXiv:2210.03493, 2022. Zhou et al. (2024) Hao Zhou, Chengming Hu, Ye Yuan, Yufei Cui, Yili Jin, Can Chen, Haolun Wu, Dun Yuan, Li Jiang, Di Wu, et al. Large language model (llm) for telecommunications: A comprehensive survey on principles, key techniques, and opportunities. IEEE Communications Surveys & Tutorials, 2024. Zhou et al. (2025) Wenwen Zhou, Dongyang Lyu, and Xiaoqi Li. Blockchain security based on cryptography: a review. arXiv preprint arXiv:2508.01280, 2025.