Source-linked AI summary

RAGas: Retrieval-Augmented Gas Optimization for Smart Contracts with Continuous Knowledge Integration

Yishun Wang, Wenjin Yi, Wenkai Li, Zongwei Li, Xiaoqi Li

arXiv:2608.15857v1cs.AI

TL;DR

Existing gas-optimization tools struggle with novel patterns and limited contextual guidance, while language models may lack current knowledge and produce unreliable fixes. RAGas combines LLM reasoning with a continuously updated knowledge base and reduces gas consumption by 11.2% on average while maintaining high precision, recall, and compilation reliability.

  • Problem

    Existing static analyzers rely on fixed rules that miss novel or compositionally complex gas-wastage patterns and provide limited contextual guidance.

  • Method

    RAGas uses a three-stage retrieval-augmented framework combining LLM-generated hypotheses, a curated evolving gas-pattern knowledge base, and context-aware synthesis.

  • Results

    RAGas reduces gas consumption by 11.2% on average while maintaining high precision, recall, and compilation reliability.

  • Takeaways & Limitations

    RAGas provides a practical tool for reducing transaction costs and a scalable framework for code optimization in dynamic environments.

Abstract

from arXiv · show

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

RAGas addresses the limitations of rule-based analyzers and standalone LLMs in specialized Gas optimization by combining LLM reasoning with retrieval from an authoritative, continuously updated knowledge base. Its three-stage pipeline uses pattern generation, knowledge alignment, and verification to improve diagnosis reliability and mitigate hallucinations.

  • Motivation: Static analyzers rely on predefined rules, limiting their ability to detect novel or compositionally complex Gas-wastage patterns and provide actionable explanations.Their diagnostics are often superficial and generic.
  • Motivation: LLMs offer flexible code comprehension and generation but remain vulnerable to frozen knowledge and plausible yet incorrect vulnerabilities or fixes outside their training distribution.These shortcomings undermine their reliability for specialized Gas optimization.
  • RAGas: RAGas proposes a three-stage pipeline in which an LLM generates abstract Gas-related patterns, aligns them with a knowledge base, and uses retrieved knowledge for diagnosis.The approach reframes Gas optimization as reasoning augmented by knowledge retrieval while combining static-analysis and LLM strengths.
  • RAGas: RAGas continuously aligns generated patterns with a curated domain-specific vector database, adding newly identified patterns in real time to track evolving best practices.This mechanism addresses the problem of frozen pretrained weights without modifying them.
  • RAGas: A dual-model detector has LLaMA 3 and ChatGPT-4o independently rank plausible Gas issues and attach calibrated confidence scores with brief justifications.Multi-model verification and confidence scoring are used to mitigate hallucinations and improve the accuracy of newly identified patterns.

2 BACKGROUND

Smart contracts are deterministic on-chain programs executed by the EVM, but their immutability and asset custody make rigorous audits necessary. Ethereum’s gas mechanism quantifies computational work, limits resource abuse, and compensates nodes, while LLMs support code synthesis but have confined knowledge.

  • Smart Contracts and the EVM: Smart contracts deterministically encode and autonomously enforce agreements on-chain, with all contract code ultimately executed by the EVM.Their immutability and asset custody make them prime targets requiring rigorous audits.
  • Gas: Gas quantifies the computational work required for each operation and helps prevent infinite loops, deter resource abuse, and compensate processing nodes.Ethereum introduced gas because miners expend CPU, memory, and storage resources processing bytecode.
  • Large Language Models: LLMs are Transformer-based deep learning architectures pretrained on web-scale corpora that perform language understanding, content generation, and code synthesis.Their core capability is probabilistically extending context with plausible continuations, but their knowledge is strictly confined.

3 PRELIMINARIES

This section establishes a taxonomy of high-Gas-consumption patterns in smart contracts, organized into six major groups and twelve subcategories drawn from authoritative literature. These patterns form the paper’s primary data source.

  • HGC pattern taxonomy: Six major groups encompass twelve HGC-pattern subcategories extracted from multiple authoritative literature sources.The patterns are consolidated as the primary data source for the paper.

4 METHOD

RAGas uses a three-stage workflow combining LLM-based detection, knowledge-base updating, and final reasoning with knowledge-pattern matching to detect and optimize high-gas-consumption patterns. Its method structures curated patterns, validates detections through dual-model agreement and calibrated confidence, and retrieves relevant knowledge for candidate analysis.

  • Overall workflow: RAGas’s three-stage workflow performs initial LLM reasoning, updates the knowledge base, and conducts final LLM reasoning with knowledge-base matching.The workflow is designed to detect and optimize high-gas-consumption patterns in input contract code.
  • Knowledge-base construction: The curated knowledge base represents 6 major categories and 12 subcategories as structured JSON objects containing pattern names, scenarios, and code snippets.Manual screening draws on specialized literature and empirical data; examples are included to reduce hallucination risk during generation.
  • Stage 1: Initial detection: For each detected pattern, the models provide the original code snippet, a confidence score, and a detailed rationale to improve interpretability and reliability.The outputs are constrained to mitigate hallucinations during model generation.
  • Stage 2: Knowledge-base updating: The knowledge base admits candidates only when both models agree and calibrated confidence exceeds θconfidence = 0.7, then uses ANN retrieval to avoid semantic duplicates.This gating mechanism supports continuous integration of novel, high-confidence patterns while preserving knowledge-base authority.
  • Stage 3: Knowledge retrieval: For each vetted candidate, RAGas encodes its name and description to retrieve the top-K (K=3) relevant structured knowledge entries from the vector database.This extends standard RAG retrieval from unstructured text to structured knowledge patterns and supports traceable output structure.

5 EVALUATION

RAGas was evaluated for retrieval and generation quality, gas-optimization effectiveness, and architectural necessity using synthetic smart-contract datasets and targeted ablation experiments. It achieved high-quality code detection and transformation, an average 11.2% gas reduction, and evidence that all three architectural stages are essential.

  • Retrieval and Generation Quality: Dataset B contains 300 fully functional synthetic smart contracts covering all 12 predefined HGC patterns and supports Precision, Recall, F1-Score, and Compilation Pass Rate evaluation.Recommendations were manually verified against the embedded ground-truth patterns.
  • Retrieval and Generation Quality: 99.3% Compilation Pass Rate confirms that nearly all generated transformations are syntactically correct and directly integrable without compilation errors.The results also demonstrate high accuracy in detecting and diagnosing gas-inefficient code segments.
  • Gas Optimization Effectiveness: 11.2% average gas reduction was achieved across all optimized contracts, with Costly State Transitions, Loop Inefficiencies, and Misconfigured Optimizer Runs each exceeding 12% reduction.Gas usage was measured before and after optimization on a local Hardhat Ethereum testnet under consistent transaction parameters.
  • Architectural Ablation: Each of RAGas’s three stages—Hypothesis Generation, Knowledge Base Matching and Updating, and Logic Thinking and Analysis—was tested through degraded variants on Dataset B using F1-Score and GRP.The experiments confirmed that each module is essential, including dynamic knowledge updates, dual-model verification, and retrieval-augmented synthesis.
  • Comparative Evaluation: RAGas was benchmarked against Slither and GPTScan on Dataset B using Precision, F1-Score, and GRP, with the reported results demonstrating superior performance across all evaluated metrics.The paper attributes traditional tools’ deficiencies to limited semantic reasoning and GPTScan’s hallucinations outside its training patterns.

6 CONCLUSION

RAGas is a three-stage retrieval-augmented generation framework for optimizing gas use in Ethereum smart contracts through knowledge retrieval, reasoning, and a continuously updated structured knowledge base. Evaluations show reduced gas consumption, while future work targets broader optimization knowledge and formal verification integration.

  • Framework: RAGas reformulates gas inefficiency detection as a knowledge retrieval and reasoning task using large language models and a continuously updated structured knowledge base.The framework combines large language models’ abstract reasoning capabilities with structured knowledge integration.
  • Evaluation: 11.2% average gas-consumption reduction was demonstrated on real-world and synthetic contracts.The passage reports the reduction as reaching up to 11.2% on average.
  • Implications: RAGas offers a practical tool for reducing transaction costs and a scalable framework for code optimization in dynamic environments.These roles position RAGas for practical cost reduction and scalable optimization.
  • Future work: Future work will expand the knowledge base with additional optimization patterns and investigate formal verification integration to improve code reliability.The proposed extensions target broader optimization coverage and stronger reliability assurances.
Loading 2608.15857v1…