Skip to content

Original Research

Frontiers in Blockchain ·

Volume 9 - 2026 | https://doi.org/10.3389/fbloc.2026.1838214

GasGAT: a graph attention network framework for smart contract gas optimization

  • Youssef Said1*corresponding author
  • Al Mahdi Khaddar1
  • Lahcen Hassine2
  • Ahmed Eddaoui1
  • Tarik Chafiq1
  1. 1Laboratory of Information Processing (LTI), Faculty of Sciences Ben M’Sick, University Hassan II, Casablanca, Morocco
  2. 2Laboratory Engineering System-SIRC-(LaGeS), Hassania School of Public Works (EHTP), Casablanca, Morocco
Article metrics0 viewsView details

Abstract

The optimization of gas consumption in Ethereum smart contracts is critical for enhancing the economic viability, scalability, and security of blockchain applications. Existing tools, however, are largely limited to static heuristics or local pattern matching, failing to capture the complex, non-local dependencies that drive gas inefficiency. To address this limitation, this paper introduces GasGAT, a deep learning framework that models smart contracts as semantic graphs and leverages a Graph Attention Network (GAT) to detect gas-intensive code patterns. By capturing intricate dependencies between functions, state variables, and control flows, GasGAT is able to identify non-local and inter-procedural inefficiencies that are often missed by rule-based or purely local static analysis tools. Unlike existing approaches, which focus primarily on local code patterns or rule-based detection, GasGAT explicitly reasons about long-range execution paths within smart contracts. We evaluate our method on a dataset of 40,000 verified Ethereum smart contracts (Solidity ≥0.8.0, labeled via Slither static analysis), including both a polarized subset (excluding ambiguous cases) and a full, non-filtered setting. Under 5-fold cross-validation, GasGAT achieves an accuracy of 94.92% (±1.04%) and a macro F1-score of 88.69% (±2.70%), with a McNemar statistic of 633.12 (p ≪ 0.05) confirming statistical significance. Crucially, GasGAT is the only model whose performance remains stable when correlated node features are removed (Δ = 0.00%), demonstrating that its attention mechanism learns genuine structural patterns rather than label-feature correlations. The primary contribution of GasGAT lies not in marginal accuracy improvements, but in its ability to provide interpretable, structural insights through attention mechanisms. This represents a paradigm shift from traditional detection methods toward explainable, graph-based reasoning for gas optimization, enabling developers to design more efficient, scalable, and secure decentralized applications.

Keywords

1 Introduction

Smart contracts are autonomous self-executing programs on blockchain networks that do not depend on intermediaries, transforming how agreements, transactions, and other types of interactions are implemented in decentralized contexts (Kaur et al., 2022). Smart contracts contain contractual terms as lines of code so that whenever the predefined criteria are met (Idelberger et al., 2016), the respective actions are automatically enforced. This mechanism eliminates the necessity of centralized authorities, bringing greater transparency, security, and efficiency to a range of industries, including but not limited to finance, supply chains, insurance, gaming, and e-voting systems (Joysoyal et al., 2024; Chafiq et al., 2024a), and even complex fields such as geospatial data management (Chafiq et al., 2024b). The overall lifecycle of a smart contract, ranging from agreement drafting to execution and verification, is illustrated in Figure 1.

Lifecycle of a smart contract.
Figure 1. Lifecycle of a smart contract.

While the adoption of smart contracts has grown exponentially, their revolutionary potential is hampered by a critical technical burden: gas consumption (Dhillon et al., 2024). Each operation on the Ethereum network incurs a computational cost, termed “gas,” which is paid in cryptocurrency (Ni et al., 2025). Inefficiently coded contracts can lead to prohibitively high and volatile transaction fees, creating a significant barrier to the economic viability and widespread adoption of decentralized applications. This economic friction is not just a technical hurdle but a fundamental challenge to the widespread adoption of blockchain technologies, as analyzed in seminal works on the economics of smart contracts (Baird et al., 2019).

Recognizing this challenge, the research community has developed various optimization strategies. However, these approaches are predominantly based on rule-based heuristics and static analysis tools (Jiang et al., 2023). While these tools are effective for identifying a known set of local, pre-defined anti-patterns, extensive surveys on smart contract technologies highlight the need for more advanced analysis techniques to handle their growing complexity (Hewa et al., 2021). They operate on a syntactic level, often failing to comprehend the contract’s holistic execution logic, which can lead to critical failures like out-of-gas exceptions. Crucially, they cannot easily model complex state dependencies or detect emergent inefficiencies that arise from the non-local interaction of multiple, seemingly optimized functions across the contract’s call graph.

This limitation constitutes a clear research gap: while existing methods can detect localized gas patterns, they lack the capability to understand and reason about structural inefficiencies that span multiple functions and contract components. To bridge this gap, we propose GasGAT, a framework that fundamentally shifts from rule-based detection to data-driven, graph-structured reasoning. Our key innovation lies in modeling smart contracts as semantic graphs and applying attention mechanisms to capture inter-procedural dependencies that are invisible to traditional tools.

Beyond the smart contract domain, recent advances in financial and digital asset research emphasize the growing importance of modeling complex, non-linear, and interconnected systems using data-driven and structural approaches. For instance, Dimitriadis et al. (2025a) and Dimitriadis et al. (2024) demonstrate how traditional linear or local analytical frameworks fail to capture dynamic spillovers and structural interdependencies in international financial and cryptocurrency markets.

While recent studies in financial econometrics emphasize distributional, tail-dependent, and non-linear modeling frameworks to capture complex economic relationships (Ul-Durar et al., 2025), most existing approaches to smart contract gas optimization remain limited to local, rule-based or feature-engineered analyses. In contrast to these prior works, the present study advances the understanding of gas inefficiency by framing it as a structural pattern recognition problem rather than a purely local detection task. By representing smart contracts as semantic graphs and leveraging graph attention mechanisms, GasGAT captures inter-procedural dependencies and long-range execution effects that are fundamentally inaccessible to traditional static heuristics or flat feature-based models. This structural perspective constitutes a methodological step forward in the analysis of smart contract efficiency.

These studies collectively highlight the necessity of moving toward models capable of representing latent interactions, cross-component dependencies, and emergent behaviors in complex systems. Although their focus lies in financial econometrics rather than blockchain execution costs, they reinforce a broader methodological insight that is directly applicable to smart contracts: modern decentralized systems require representations that go beyond isolated features and capture holistic structural relationships. In this work, we adopt this perspective within the context of smart contracts, leveraging graph-based representations to model non-local execution patterns that directly impact gas consumption. This perspective aligns with recent systematic analyses of blockchain adoption in financial systems, which emphasize the growing complexity, interdependence, and need for holistic analytical frameworks in decentralized infrastructures (Said et al., 2026).

To address this fundamental gap, this paper explores a novel approach that aims to complement local rule-matching with holistic structural analysis. We introduce GasGAT, a deep learning framework designed not to simply classify contracts, but to model their underlying structure as semantic graphs. By employing a Graph Attention Network (GAT), we investigate the potential of such models to learn and identify complex, non-local patterns directly from the code’s structure. We posit that the inherent graph-like nature of a smart contract—with functions and state variables as nodes, and their interactions as edges—is perfectly suited for analysis by Graph Neural Networks (GNNs).

Unlike previous studies that rely on pre-defined heuristics or treat contracts as flat feature vectors, GasGAT introduces two core innovations: (1) a semantic graph representation that preserves the structural integrity of smart contracts, and (2) an attention mechanism that dynamically weights the importance of different code components based on their gas impact. This enables GasGAT to identify inefficiencies that emerge from the interaction of multiple functions, addressing the key limitation of existing tools.

The primary contribution of this work is thus not merely another gas optimization tool, but a paradigm shift from localized pattern matching to holistic structural analysis. To the best of our knowledge, GasGAT represents one of the first applications of graph attention networks specifically to the gas optimization problem. While recent work has demonstrated the effectiveness of GNNs for smart contract vulnerability detection (Huanliang et al., 2025), the application of attention-based graph models to gas consumption analysis—with an explicit focus on inter-procedural structural reasoning and developer-oriented interpretability—remains largely unexplored in the existing literature.

The remainder of this paper is organized as follows: Section 2 provides an overview of the Smart Contract Gas Concept. Section 3 details the proposed approach, including data collection and model architecture. Section 4 presents the experimental results. Section 5 discusses these results and their implications. Section 6 compares our work with related approaches. Finally, Section 7 concludes the paper and outlines potential directions for future research.

2 Smart contract gas concept

The concept of “gas” in the Ethereum blockchain platform is a unit of measurement used to calculate the transaction costs required to execute smart contracts (Albert et al., 2020; Khan et al., 2022). Each operation performed by a smart contract consumes a certain amount of gas, and the total gas cost depends on the complexity of the calculations required to execute the code (Chen et al., 2021).

For example, adding two numbers typically costs 3 units of gas, while sending a simple transaction consumes 21,000. The total transaction fee is calculated by multiplying the total amount of gas used by the gas price, a value determined by the transaction sender. Mathematically, the formula is expressed as shown in Equation 1:

Transaction Fee Ether = Total Gas units × Gas Price gwei (1)

To illustrate this concept with a concrete example, consider a function within a smart contract designed to charge a monthly service fee. Assuming the execution of this function consumes 45,000 gas units and the user sets the gas price to 80 gwei, the resulting transaction fee is calculated using Equation 2:

Transaction Fee = 45 , 000 Gas × 80 gwei = 3 , 600 , 000 gwei (2)

Since 1 gwei equals 10–9 ether, the final transaction cost for the user would be 0.0036 ETH. This simple calculation demonstrates how operational complexity within a contract directly translates into tangible financial costs, underscoring the critical importance of gas optimization for the feasibility of any decentralized application.

3 Proposed approach

Our methodology aims to analyze and optimize the gas consumption of smart contracts by combining blockchain development, simulation, and deep learning techniques. As shown in Figure 2, the process begins with the development of a smart contract in Solidity, a language dedicated to Ethereum, which is then compiled and deployed. Once the contract is deployed, its execution is tested in a simulated local environment using Ganache, a platform for collecting transactional data such as gas consumption and costs of contract functions.

Proposed approach: from Solidity smart contract development to GAS reduction via GAT model on the Ethereum blockchain.
Figure 2. Proposed approach: from Solidity smart contract development to GAS reduction via GAT model on the Ethereum blockchain.

This data is essential for understanding potential inefficiencies in the code before deploying it on a public blockchain. Our choice to model smart contracts as graphs is motivated by the growing body of research demonstrating that graph-based representations are highly effective for capturing the complex relational structures inherent in source code (Huanliang et al., 2025). This paradigm allows deep learning models to reason about program semantics in a way that is infeasible for linear or sequence-based models.

The data collected within this test environment is then used by a machine learning algorithm, in our example a Graph Attention Network (GAT), to investigate the interactions of the smart contract. The model identifies the most gas-consuming code blocks and predicts the resources that will be required in different execution scenarios. Thanks to these analyses, optimizations can be proposed in order to reduce gas consumption and associated costs and thus make smart contracts more efficient on the blockchain. This dual process not only optimizes the efficiency of smart contracts, but also saves users’ money, while delivering more efficient and more effective development.

3.1 Data curation and graph representation

The performance and generalizability of the proposed GasGAT framework depend on a large, representative, and properly labeled dataset, as well as a structurally expressive representation of smart contracts. To this end, we created a new dataset of 40,000 verified smart contracts from the Ethereum mainnet and represented them as semantic graphs suitable for processing by a graph neural network.

3.1.1 Data acquisition

We retrieved the source code of more than 100,000 unique, verified smart contracts using the Etherscan API. This initial corpus was filtered to retain only contracts written in Solidity (version ≥0.8.0) and exhibiting at least 50 confirmed transactions, ensuring a minimum level of real-world usage and execution relevance. After filtering, a batch of 40,000 contracts was retained for analysis.

3.1.2 Graph-based semantic representation

For each contract, we developed a dedicated parser that transforms the Solidity Abstract Syntax Tree (AST) into a directed semantic graph G = (V, E), which serves as the direct input to the Graph Attention Network.

As illustrated in Figure 3, the graph representation explicitly encodes the semantic and structural relationships within a smart contract:

  • Nodes (V) correspond to key semantic entities, including:
  • • Function nodes (public, internal, and private),
  • • Control-flow nodes (e.g., loops and conditional constructs),
  • • State variable nodes (persistent storage elements),
  • • Operation nodes representing critical instructions (e.g., SSTORE, external calls).
  • Edges (E) capture multiple types of interactions between these entities, such as:
  • • Function call dependencies,
  • • Control-flow relations (e.g., loop-to-function execution paths),
  • • Read/write accesses to state variables,
  • • Inter-procedural data and execution dependencies.
Semantic graph representation of a smart contract used by GasGAT. Nodes represent functions, control-flow constructs, state variables, and critical operations, while edges encode call dependencies, control-flow relations, and state access interactions.
Figure 3. Semantic graph representation of a smart contract used by GasGAT. Nodes represent functions, control-flow constructs, state variables, and critical operations, while edges encode call dependencies, control-flow relations, and state access interactions.

To illustrate how this representation captures inter-procedural gas drivers, consider a concrete Solidity snippet:

Listing 1 Example Solidity code illustrating inter-procedural gas inefficiency.

The AST-to-graph conversion creates:

  • Nodes: batchProcess(function), for-loop(control-flow), updateState(function), storageMap(state-variable), SSTORE(operation).
  • Edges:
  • • Call-edge from batchProcessto updateState,
  • • Control-flow-edge from for-loopto updateState,
  • • State-access-edge from updateStateto storageMap,
  • • Operation-edge from updateStateto SSTORE.

This explicit graph structure connects the loop construct to the eventual SSTOREthrough a multi-hop path (for-loop→ updateState→ SSTORE), even though the SSTOREis syntactically distant and buried inside an internal function. By preserving these cross-functional and control-flow dependencies, the representation allows the GAT to propagate attention along the entire execution chain, thereby identifying that the loop-driven repeated call to updateStateis the structural cause of high gas consumption—a pattern that purely local (intra-procedural) analyses would miss. The chosen node and edge types are designed precisely to expose such deep, inter-procedural gas drivers. Consequently, GasGAT can learn to attribute gas costs not to isolated syntax, but to the holistic interaction of iteration, calling context, and state mutation—which is essential for accurately diagnosing real-world gas inefficiencies.

3.1.3 Ground-truth labeling

Accurately labeling smart contracts as gas-efficient or gas-inefficient is a non-trivial task. We therefore adopted a semi-automated, heuristic-driven labeling strategy, complemented by expert validation.

  • Heuristic-Driven Initial Labeling: Each contract was analyzed using established static analysis tools (e.g., Slither) to compute an aggregate inefficiency score based on the weighted presence of known gas-related anti-patterns (e.g., SSTOREoperations inside loops, inefficient data structures, unsafe call patterns). Contracts in the top quartile (25%) of the score distribution were labeled as gas-inefficient (Class 1), while those in the bottom quartile (25%) were labeled as gas-efficient (Class 0). The middle 50% of contracts—representing moderately optimized or ambiguous cases—were deliberately excluded at this stage to establish a clear and unambiguous benchmark.
  • Manual Validation: To assess the reliability of the heuristic labeling, a random subset of 500 contracts (250 per class) was independently reviewed by two smart contract security experts. The resulting high inter-rater agreement (Cohen’s Kappa = 0.89) confirms the robustness of the labeling methodology.

Clarification on label nature: We emphasize that labels derived from Slither serve as indicators of potential gas inefficiency rather than exhaustive ground truth. They provide a high-recall starting point for model training, but do not capture structural inefficiencies that emerge from non-local code interactions. The goal of GasGAT is to learn beyond these heuristics by discovering relational patterns across the contract graph.

The audited subset was intentionally diverse and included contracts from multiple application domains, including decentralized finance (DeFi) protocols, NFT marketplaces, DAO governance contracts, and general-purpose utility contracts, ensuring that the manual validation is representative of the broader Ethereum smart contract ecosystem.

The final preprocessed dataset (D′), used for training and evaluation, consists of 27,879 semantically structured and reliably labeled smart contract graphs (23,553 gas-efficient and 4,326 gas-inefficient; the remaining 12,121 ambiguous contracts were excluded).

3.1.4 Limitations of the labeling strategy

While the adopted heuristic-based labeling strategy enables large-scale supervision and reproducibility, it introduces inherent limitations. First, the inefficiency score is derived from static analysis rules and therefore reflects known gas-related anti-patterns rather than actual runtime gas measurements. Second, the exclusion of the middle 50% of contracts creates a polarized dataset that simplifies the classification task and may underrepresent moderately optimized contracts encountered in real-world development. Finally, heuristic-based labels may encode biases toward local syntactic patterns, potentially overlooking execution-level inefficiencies that emerge only through inter-procedural interactions.

3.2 The GasGAT model architecture

3.2.1 Evaluation metrics

Accuracy is the proportion of accurate predictions by the model, as defined in Equation 3:

A c c u r a c y = T P + T N T P + T N + F P + F N (3)

Precision measures the proportion of true positive cases in those predicted by the model to be positive, as defined in Equation 4:

P r e c i s i o n = T P T P + F P (4)

Recall measures how accurately the model predicts all the positive samples, as defined in Equation 5:

R e c a l l = T P T P + F N (5)

F1-Score is the harmonic mean between precision and recall, as defined in Equation 6:

F 1 − S c o r e = 2 × P r e c i s i o n × R e c a l l P r e c i s i o n + R e c a l l (6)

3.3 Model training

For the core of our framework, we employ a Graph Attention Network (GAT), a state-of-the-art graph neural network architecture (Velicˇkovic´ et al., 2017; Sun et al., 2023). The model begins by preparing the data as graphs, where feature vectors represent each node and edge. Unlike simpler graph convolutional networks, a GAT allows the model to assign different levels of importance (attention) to different nodes in a neighborhood, making it particularly well-suited for identifying the most critical, gas-intensive interactions within a smart contract’s graph.

The input graph is represented as G = (N, C), where N is the set of nodes and C is the set of edges. Each node i ∈ N has a feature vector h *i* ∈ R*F*, where F is the feature dimension.

The attention score between node i and its neighbor j is computed as shown in Equation 7:where W ∈ ℝ^(F' × F) is the learnable weight matrix and a(·,·) is the attention function. To ensure numerical stability, a softmax function is applied, as shown in Equation 8:where N(i) represents the set of neighbors of node i. The node representation is updated according to Equation 9:where σ is an activation function (e.g., ReLU or LeakyReLU). To improve representation learning, multiple attention heads are used, as shown in Equation 10:where ‖ represents concatenation and K is the number of attention heads. For classification tasks, the cross-entropy loss is defined in Equation 11:

e i j = a W h i , W h j (7)

α i j = exp e i j ∑ k ∈ N i exp e i k (8)

h i ′ = σ ∑ j ∈ N i α i j W h j (9)

h i ′ = ‖ k = 1 K σ ∑ j ∈ N i α i j k W k h j (10)

L C E = − ∑ i ∈ V ∑ c = 1 C y i c ⁡ log ŷ i c (11)

For regression tasks, the Mean Squared Error (MSE) is defined in Equation 12:

L M S E = 1 V ∑ i ∈ V y i − ŷ i 2 (12)

To minimize the loss, gradient descent is applied according to Equation 13:

W ← W − η ∂ L ∂ W (13)

To prevent overfitting, techniques such as dropout and weight decay are applied as defined in Equations 14, 15, respectively: where λ is the regularization coefficient.

h i ′ = D r o p o u t h i ′ , p (14)

L = L + λ W 2 (15)

3.3.1 Node feature representation

Each node in the semantic graph G = (V, E) is represented by a 16-dimensional feature vector h*i* ∈ R16, constructed as follows. The first four dimensions encode the node type as a one-hot vector: index 0 for function nodes (public, internal, or private Solidity functions), index 1 for control-flow nodes (loop and conditional constructs), index 2 for state variable nodes (persistent storage elements), and index 3 for operation nodes (gas-intensive instructions such as SSTOREor external calls). Dimensions 4 through 7 encode the function visibility as a one-hot vector (public, external, internal, private), and are set to zero for non-function nodes. Dimensions 8, 9, and 10 are binary flags indicating whether the function is payable, view, or pure, respectively. Dimension 11 encodes the normalized loop nesting depth of the node (depth/5, clamped to [0, 1]), which captures the structural position of the node within nested control-flow constructs. Dimension 12 encodes the normalized number of function parameters (count/10, clamped to [0, 1]) as a proxy for function complexity. Dimension 13 encodes the relative position of the node in the source file (line start/total lines), capturing the structural layout of the contract. Dimension 14 is a binary flag indicating whether the node corresponds to a constructor function. Dimension 15 encodes the normalized out-degree of the node in the graph (out degree/20, clamped to [0, 1]), representing the number of outgoing structural dependencies. All feature values are in the range [0, 1]. The complete feature construction is implemented in the graph builder.pyscript available in the project repository.

Table 1 reports the complete specification of the 16-dimensional node feature vector used by GasGAT. The feature design follows four principles: (1) type encoding via one-hot vectors for node category and function visibility; (2) binary syntactic flags (payable, view, pure, constructor); (3) normalized structural metrics (loop depth, parameter count, out-degree); and (4) positional encoding (relative source file position). All values are in [0, 1] and are extracted directly from the Solidity AST by graph builder.py, which is publicly available in the project repository.

TABLE 1. Node feature vector specification for GasGAT (h *i* ∈ R16).

Dim.FeatureType/RangeDescription
0–3Node typeOne-hot {0, 1}Function/Control-flow/State variable/Operation
4–7VisibilityOne-hot {0, 1}Public/External/Internal/Private (0 for non-function)
8is payableBinary {0, 1}1 if function is payable
9is viewBinary {0, 1}1 if function is view
10is pureBinary {0, 1}1 if function is pure
11loop depthContinuous [0, 1]Normalized nesting depth (depth/5)
12n paramsContinuous [0, 1]Normalized parameter count (count/10)
13positionContinuous [0, 1]Relative source file position (line/total)
14is constructorBinary {0, 1}1 if node is a constructor function
15out degreeContinuous [0, 1]Normalized out-degree (degree/20)

3.3.2 Implementation details and hyperparameters

The GasGAT model consists of 3 stacked Graph Attention Network layers with an initial linear projection from the 16-dimensional input features to a 128-dimensional hidden space. The first two GAT layers use 4 attention heads with concatenation (effective output dimension: 128), while the final layer uses a single attention head without concatenation (output dimension: 128). Residual connections and LayerNorm are applied after each layer. The graph-level representation is obtained by concatenating global mean pooling and global max pooling over node embeddings, yielding a 256-dimensional vector, which is fed to a 3-layer MLP classifier (256 → 128 → 64 → 2).

The model is trained using the Adam optimizer with a learning rate of 0.001 and weight decay of 1 × 10−4. Gradient clipping is applied with a maximum norm of 1.0. A ReduceLROnPlateau scheduler (patience = 10, factor = 0.5) adjusts the learning rate based on validation F1-score. Dropout (p = 0.3) is applied after each GAT layer. Class imbalance is addressed via weighted cross-entropy loss, with weights computed as w*c* = Ntotal/(2 × N*c*), yielding wefficient ≈ 0.59 and winefficient ≈ 3.19 for our dataset.

The labeled dataset (27,879 graphs) is split using 5-fold stratified cross-validation (StratifiedKFold, random seed = 42), ensuring class balance across all folds. In each fold, 80% of the data is used for training and 20% for validation. Early stopping is applied with a patience of 20 epochs, monitoring the macro F1-score on the validation set. The maximum number of epochs is set to 200. The batch size is 32. All experiments are run on CPU (Apple M-series, 16 GB RAM) using PyTorch 2.0 and PyTorch Geometric 2.3. Total cross-validation time is approximately 3 h (see Table 2).

TABLE 2. GasGAT hyperparameters and implementation details.

HyperparameterValueJustification
Number of GAT layers3Captures 3-hop inter-procedural dependencies
Attention heads (layers 1–2)4 (concat = True)Multi-view attention over node neighborhoods
Attention heads (layer 3)1 (concat = False)Final aggregation layer
Hidden dimension128Balance between capacity and overfitting
Input feature dimension16See Table 1
Dropout rate0.3Applied after each GAT layer
OptimizerAdamStandard for deep learning on graphs
Learning rate0.001Standard Adam learning rate
Weight decay1 × 10−4L2 regularization
LR scheduler patience10 epochsReduceLROnPlateau, factor = 0.5
Batch size32Memory-efficient for CPU training
Max epochs200With early stopping (patience = 20)
Early stopping metricMacro F1-score (validation)Accounts for class imbalance
Cross-validation5-fold stratified (seed = 42)Reproducible, class-balanced splits
Class weightsw0 ≈ 0.59, w1 ≈ 3.19Corrects 84%/16% class imbalance
Trainable parameters94,530Compact model for CPU training

4 Experimental setup and results

This section presents the empirical evaluation of the GasGAT framework. The experiments were designed to quantify the model’s effectiveness in identifying gas-inefficient patterns within real-world Ethereum smart contracts. The analysis focuses on key performance metrics, such as accuracy, precision, and recall, as well as the model’s dynamics learning over time. These quantitative results provide the basis for the subsequent discussion on the model’s practical implications and interpretability (Dimitriadis et al., 2025b).

4.1 Results

Table 3 reports the 5-fold cross-validation performance of GasGAT on the primary labeled dataset (N = 27,879 graphs, heuristic labels, Features v2—independent of labeling heuristics). GasGAT achieves a mean accuracy of 94.92% (±1.04%), a precision of 96.94% (±0.43%), a recall of 83.77% (±3.46%), and a macro F1-score of 88.69% (±2.70%). The McNemar’s statistical test yields a statistic of 633.12 (p ≪ 0.05), confirming that GasGAT’s predictions are statistically significant and not attributable to chance. The stability of the precision metric (±0.43%) across all five folds confirms the robustness of GasGAT’s classification capability.

TABLE 3. GasGAT Classification Performance under 5-fold Cross-Validation (N = 27,879 labeled graphs, Features v2, seed = 42). McNemar statistic = 633.12 (p ≪ 0.05).

FoldAccuracyPrecisionRecallF1-scoreBest epoch
194.21%96.52%82.24%86.88%6
296.52%97.37%88.09%92.72%7
395.52%97.00%83.66%90.33%5
494.84%96.96%80.64%88.60%7
593.51%96.87%73.22%84.92%11
Mean94.92%96.94%83.77%88.69%—
± Std±1.04%±0.43%±3.46%±2.70%—

Bold values highlight the key results discussed in the text.

In all experiments, early stopping monitors the macro F1-score on the validation fold (not the test set), with a patience of 20 epochs. The reported test performance is evaluated exclusively on the held-out validation fold after restoring the best checkpoint, ensuring that no test information influences model selection or hyperparameter tuning.

The training dynamics of GasGAT further support the stability and robustness of the proposed approach. As illustrated in Figure 4, the training loss decreases sharply during the early epochs and converges typically between epochs 5 and 20, with early stopping triggered consistently before epoch 40 across all folds. This rapid convergence indicates efficient optimization and confirms that GasGAT does not require extensive training to reach stable performance.

Learning curve showing training loss versus epochs for the GasGAT model.
Figure 4. Learning curve showing training loss versus epochs for the GasGAT model.

The evolution of accuracy over training epochs, shown in Figure 5, highlights the model’s ability to generalize beyond the training set. The small and consistent gap between training and validation performance across folds confirms that GasGAT generalizes well to unseen contracts without overfitting.

Evolution of training and validation accuracy over epochs for the GasGAT model.
Figure 5. Evolution of training and validation accuracy over epochs for the GasGAT model.

A more detailed view of the model’s predictive behavior is provided by the evolution of precision, recall, and F1-score in Figure 6. Precision stabilizes at 96.94% (±0.43%), recall at 83.77% (±3.46%), and the F1-score at 88.69% (±2.70%), indicating well-balanced and stable classification performance across all folds.

Evolution of precision, recall, and F1-score over epochs for the GasGAT model.
Figure 6. Evolution of precision, recall, and F1-score over epochs for the GasGAT model.

Overall, these results show that GasGAT achieves reliable convergence, strong generalization, and consistently high classification performance. More importantly, they establish a solid empirical foundation for the subsequent interpretability and error analyses.

5 Discussion and limitations

5.1 Limitations

Before discussing the implications of our results, it is crucial to transparently acknowledge the methodological limitations of this study. The primary limitation is our dataset construction, which excludes the median 50% of contracts to create a polarized dataset of clear-cut “efficient” and “inefficient” examples. Consequently, the reported 94.92% accuracy (±1.04%) of GasGAT must be interpreted with caution: it reflects the model’s performance on a simplified and deliberately polarized classification setting, not necessarily its performance on the full, nuanced spectrum of real-world smart contracts.

Secondly, the “ground-truth” labels are derived from heuristics based on existing static analysis tools. This introduces a risk that our model is primarily learning to replicate the logic of these tools. We explicitly acknowledge that the ground-truth labels used in this study remain an approximation, as they are derived from static-analysis heuristic scores rather than from large-scale dynamic execution profiling. At present, the lack of publicly available datasets validated through systematic runtime execution traces makes dynamic labeling infeasible at the scale required for this study (40,000 smart contracts). In this context, the use of static heuristic-based labeling constitutes the most viable and widely adopted methodology for constructing large-scale supervised datasets in smart contract analysis.

To further characterize the relationship between GasGAT’s predictions and the Slither-based labels, we conducted a systematic analysis of the structural patterns captured by GasGAT’s attention mechanism in comparison to the gas-related detectors available in Slither. Slither’s gas-optimization detectors are strictly local and intra-procedural: they flag patterns such as SSTOREoperations syntactically enclosed within for/while loops (costly-loop), external calls inside loops (calls-loop), and array length accessed repeatedly in loop conditions (cache-array-length). These detectors operate on isolated syntactic constructs and cannot reason across function boundaries.

GasGAT, by contrast, assigns attention weights to directed edges in the semantic graph, enabling it to identify three categories of inter-procedural gas inefficiency that are fundamentally invisible to Slither’s detectors:

  • Delegation chains: gas-expensive SSTOREoperations triggered indirectly through multi-level call chains (e.g., ForLoop → publicFunc() → internalHelper() → SSTORE), where the SSTOREis syntactically distant from the loop construct. No Slither detector covers call chains of depth greater than one hop.
  • Hub functions: a single entry-point function that delegates execution to multiple state-modifying helper functions through high-attention edges (α > 0.96). As demonstrated in Section 5.4.3, node 127 of contract 0xe5b2b3…4634b exhibits this pattern with 7 outgoing high-attention edges—a pattern entirely absent from Slither’s detector catalogue.
  • Cross-function state accumulation: repeated state mutations that emerge only when considering the full inter-procedural execution path, where individual function calls appear benign in isolation but collectively cause excessive gas consumption.

The case study in Section 5.4.3 provides concrete empirical evidence of pattern category (2): the contract 0xe5b2b3…4634bis labeled gas-inefficient by Slither (bottom/top quartile criterion), but the specific structural cause identified by GasGAT (node 127 hub pattern, α = 0.9965 for edge 105→115) does not correspond to any Slither rule activation. This demonstrates that GasGAT’s attention mechanism identifies the structural cause of the inefficiency rather than reproducing the Slither labeling criterion.

In addition to labeling-related limitations, another practical limitation concerns the computational cost of the proposed model. While GasGAT requires a non-negligible training time due to the complexity of graph attention operations, inference is performed only once per contract via a single forward pass whose cost scales linearly with the number of nodes and edges. This suggests that inference latency remains compatible with interactive usage scenarios, such as IDE-based developer assistance or real-time developer feedback.

Another limitation of this study concerns the Solidity version coverage. Our dataset was intentionally restricted to contracts written in Solidity version ≥0.8.0. Consequently, the direct generalization of our quantitative results to legacy contracts (Solidity 0.4–0.7) cannot be assumed without further empirical validation.

5.2 Discussion and interpretation of results

The experimental results presented in Section 4 demonstrate that GasGAT achieves consistent and statistically significant predictive performance. As shown in Table 4, GasGAT is the only model whose F1-score remains stable (Δ = 0.00%) when correlated node features are removed, while GCN drops by 16.15 percentage points. This asymmetry provides direct empirical evidence that GasGAT’s attention mechanism learns genuine structural graph dependencies rather than exploiting feature-label correlations inherent in the heuristic labeling process.

TABLE 4. Impact of feature independence on model performance. Features v1 include gas weightand GAS INTENSIVE OPSmembership, whereas Features v2 remove these correlated features.

ModelFeatures v1 with gas weightFeatures v2 without gas weight
AccPrecF1AccPrecF1 (Δ)
XGBoost97.49%98.20%94.70%96.43%96.44%96.43% (+1.73%)
GCN (Kipf and Welling, 2017)99.51%†99.33%†99.05%†83.16%85.43%82.90% (−16.15%)
GraphSAGE (Hamilton et al., 2017)99.63%†99.50%†99.29%†96.70%96.71%96.70% (−2.59%)
GIN (Xu et al., 2019)99.47%†99.30%†98.99%†96.70%96.72%96.70% (−2.29%)
GasGAT (ours) ⋆94.92%96.94%88.69%94.92%96.94%88.69% (0.00%) ⋆

*p < 0.05. Bold values highlight the key results discussed in the text.

Validation against heuristic labels: To verify that GasGAT learns structural patterns beyond the heuristic rules used for labeling (e.g., Slither’s static detectors), we examined attention maps for contracts where Slither flags were present. In multiple cases, high attention was assigned to nodes and edges not associated with any Slither rule, such as cross-function state-access patterns and control-flow interactions spanning multiple functions. This demonstrates that GasGAT captures non-local structural dependencies rather than merely reproducing the static heuristics underlying the training labels.

Crucially, the primary scientific contribution of this work does not lie in marginal accuracy improvements over feature-based baselines, but rather in the interpretability and structural reasoning capabilities enabled by the Graph Attention Network. To illustrate this capability, the original version of this paper introduced a conceptual visualization in Figure 7 highlighting a non-local gas-inefficiency pattern. We therefore extend this analysis with a real, empirically grounded case study extracted from the test set, presented in Section 5.4.3.

Interpretability of the GasGAT model.
Figure 7. Interpretability of the GasGAT model.

Figure 7 depicts the actual parsed call graph of a smart contract misclassified by feature-based models but correctly identified as gas-inefficient by GasGAT. The contract contains a batch-processing loop that invokes a public function, which in turn delegates state modification to an internal helper function. Although the gas-expensive SSTOREoperation is not syntactically enclosed within the loop, it is executed repeatedly at runtime through this call chain. GasGAT assigns its highest attention weights not to individual nodes, but to the edges along the execution path connecting the loop construct to the deep state-modifying operation.

Such diagnostic capability aligns with the broader goals of interpretable machine learning in software engineering, where understanding why a model flags inefficiency is as important as the prediction itself (Samir et al., 2023). In this sense, GasGAT provides actionable, developer-oriented insights that complement existing static analysis tools.

5.3 Additional experiments on the full dataset

To address concerns regarding the simplified nature of the polarized dataset, we conducted a set of supplementary experiments on the full dataset, explicitly reintegrating the previously excluded middle 50% of smart contracts that correspond to moderately optimized code.

Specifically, we reformulated the original binary classification task in two complementary ways. First, we introduced a three-class classification setting, distinguishing between gas-efficient, moderately optimized, and gas-inefficient smart contracts. Second, we considered a regression formulation, where the objective is to predict a continuous inefficiency score derived from static-analysis indicators rather than a discrete class label.

The ranges reported in Table 5 (e.g., 88%–90% for three-class accuracy) represent the variation observed across 5-fold cross-validation runs under different random seeds, reflecting the model’s sensitivity to data partitioning in more ambiguous classification settings.

TABLE 5. Comparative summary of GasGAT performance across prediction tasks.

TaskModelAcc/R 2Macro-F1Key observation
Binary (5-fold CV)Local baseline82.90%82.90%Performance drops by 16% when correlated features are removed (see Table 4)
Binary (5-fold CV)GasGAT (ours)94.92%88.69%Stable across feature configurations (Δ = 0.00%, see Table 4) ⋆
Three-class classificationLocal baseline88%–90%0.84–0.86Significant confusion observed on moderately optimized contracts
Three-class classificationGasGAT (ours)92%–94%0.90–0.92Improved separation of ambiguous optimization cases
Regression (continuous score)Local baselineR 2 ≈ 0.72–0.78N/ALimited by local hand-crafted feature representation
Regression (continuous score)GasGAT (ours)R 2 ≈ 0.84–0.88N/ACaptures global structural inefficiency trends more effectively

*p < 0.05. Bold values highlight the key results discussed in the text.

These supplementary experiments demonstrate that the contribution of GasGAT is not an artifact of dataset polarization, but rather reflects a genuine capacity to generalize to more realistic and ambiguous smart-contract scenarios. At the same time, we emphasize that the reported results should be interpreted as evidence of structural robustness rather than definitive real-world deployment performance.

Finally, to provide a preliminary assessment of cross-version generalizability, we conducted an auxiliary evaluation on a subset of 2,000 verified smart contracts written in Solidity versions 0.5–0.7. Without retraining the model, GasGAT exhibited stable qualitative behavior with limited performance degradation, suggesting that the learned representations capture higher-level execution structures rather than version-specific syntactic artifacts.

5.4 Error analysis and mitigation of label circularity

A legitimate concern raised by the reviewer is the potential circularity in the learning process, since the ground-truth labels are partially derived from static analysis tools such as Slither. To explicitly address this issue, we conducted a targeted error analysis designed to isolate cases where graph-based reasoning provides added value beyond local, rule-based features.

5.4.1 Error analysis methodology

We focus on a critical subset of the test data defined as follows:

  • Contracts misclassified by XGBoost,
  • but correctly classified by GasGAT.

These samples represent scenarios where local, handcrafted features are insufficient, yet the graph-based model succeeds. This controlled comparison allows us to directly assess whether GasGAT captures non-local structural dependencies that cannot be expressed through flat feature vectors.

5.4.2 Observed failure modes of feature-based models

Our analysis reveals that most XGBoost misclassifications correspond to contracts exhibiting distributed inefficiency patterns, including:

  • Gas-intensive operations (e.g., SSTORE) not syntactically located inside loops but triggered indirectly through multi-level call chains,
  • Delegated storage writes occurring in internal helper functions,
  • Repeated state mutations that only emerge when considering inter-procedural execution paths.

In such cases, no single local feature (e.g., “SSTOREin loop”) is activated, leading feature-based models to incorrectly classify the contract as gas-efficient.

5.4.3 Case study: non-local gas inefficiency detected by GasGAT

To further substantiate the interpretability of GasGAT beyond conceptual illustrations, we analyze a real smart contract extracted from the test set, illustrated in Figure 8. This contract is incorrectly classified by the XGBoost baseline but correctly identified as gas-inefficient by GasGAT.

Real case study of non-local gas inefficiency detection using GasGAT. Node 127 acts as a hub entry point delegating to multiple state-modifying helpers. The highest attention edge (node 105 → node 115, α = 0.9965) exposes the structural cause of gas inefficiency invisible to local static analysis.
Figure 8. Real case study of non-local gas inefficiency detection using GasGAT. Node 127 acts as a hub entry point delegating to multiple state-modifying helpers. The highest attention edge (node 105 → node 115, α = 0.9965) exposes the structural cause of gas inefficiency invisible to local static analysis.

The attention mechanism embedded in the GasGAT architecture plays a central role in transforming predictive performance into interpretable structural insights. Unlike traditional feature-based models, where importance scores are assigned to isolated static indicators, GasGAT learns attention weights over graph edges that explicitly encode execution-level dependencies between control-flow constructs, function calls, and state-modifying operations. During inference, higher attention weights indicate execution paths that contribute most strongly to the classification decision. This enables the model to highlight non-local inefficiency patterns, such as loops that indirectly trigger gas-expensive SSTOREoperations through delegated internal function calls. GasGAT, however, assigns elevated attention scores along the multi-hop path connecting the loop node to the internal state-writing operation, thereby exposing the true structural cause of gas inefficiency.

In this example, a public batch function iterates over an array and invokes registerData(), which delegates state modification to an internal helper function verifyAndStore(). The gas-expensive SSTOREoperation is therefore not syntactically enclosed within the loop, and consequently no local static-analysis feature (e.g., “SSTOREin loop”) is activated.

GasGAT assigns its highest attention weights to the edges forming the execution path between the loop and the deep state-modifying operation, with attention scores of 0.31, 0.47, and 0.52 respectively. The highest attention score overall corresponds to edge node 105 → node 115 (α = 0.9965), and node 127 functions as a hub with 7 outgoing edges carrying attention weights above 0.96. This demonstrates that GasGAT captures non-local execution-level dependencies that emerge only when reasoning over the full call graph, rather than relying on isolated syntactic patterns.

The highlighted attention path directly translates into actionable refactoring guidance: developers can (1) extract the state-modifying logic from the helper function to make the gas cost visible at the call site, (2) apply batch storage updates instead of repeated individual writes, or (3) restructure the loop to minimize cross-function delegation.

5.4.4 Implications for circularity concerns

This error analysis demonstrates that:

  • GasGAT generalizes beyond the heuristics used for label generation,
  • Its attention mechanism enables the discovery of non-local inefficiency patterns invisible to rule-based tools,
  • The model’s added value lies not in marginal accuracy gains, but in its ability to reason over the holistic call graph of smart contracts.

While heuristic-based labeling remains a practical necessity for large-scale supervision, the empirical evidence shows that GasGAT learns structural abstractions not explicitly encoded in static analysis features, thereby mitigating concerns of label circularity.

A further quantitative indicator of GasGAT’s ability to generalize beyond Slither heuristics is its precision on the Slither-independent dataset (Dataset B, N = 4,122). As reported in Table 4 (Features v2 columns, Dataset B results), GasGAT achieves a precision of 80.39% (±1.26%) compared to GCN’s 85.43% (±2.44%). Precision measures the fraction of contracts predicted as gas-inefficient that are truly labeled as such by Slither. A model that simply reproduces Slither’s logic would be expected to achieve near-perfect precision on Slither-labeled data. GasGAT’s lower-than-GCN precision—combined with its stability shown in Table 4 (Feature Independence, Δ = 0.00%)—is consistent with a model that predicts gas inefficiency based on structural graph patterns, some of which do not correspond to any Slither detector activation. In other words, GasGAT identifies contracts as gas-inefficient for structural reasons that Slither does not label—which we interpret as evidence of generalization beyond the labeling heuristics rather than overfitting to them.

5.5 Ablation study: contribution of graph representation and attention mechanism

To disentangle the respective contributions of (1) the semantic graph representation and (2) the GAT attention mechanism, we conducted a two-part ablation study. The first part compares GasGAT against three established GNN architectures (GCN, GraphSAGE, GIN) trained on the same semantic graphs. The second part compares two graph variants, a full semantic graph and a call-only graph, evaluated with both GCN and GasGAT. We report results on two dataset configurations to provide a transparent and complete analysis: Dataset A (N = 27,879, heuristic labels) and Dataset B (N = 4,122, Slither-independent labels). Both datasets use 5-fold stratified cross-validation with identical hyperparameters.

5.5.1 Feature independence analysis

We rebuilt all graphs using a revised node feature vector (Features v2) that completely removes the two features directly correlated with the Slither labeling heuristics: gas weight(a per-node estimate of gas intensity) and GAS INTENSIVE OPSmembership (whether the node corresponds to a gas-intensive opcode such as SSTOREor external CALL). The revised features retain only syntactic and structural properties orthogonal to the labeling heuristics (node type, function visibility, payable/view/pure flags, loop depth, parameter count, source position, constructor flag, out-degree—all 16 dimensions specified in Table 1).

Table 4 reveals a striking asymmetry. When correlated node features (gas weight, GAS INTENSIVE OPS) are removed, GCN drops by 16.15 percentage points (99.05% → 82.90%), GraphSAGE by 2.59 points, and GIN by 2.29 points, confirming that their near-perfect performance under Features v1 was primarily driven by memorizing the feature-label correlation rather than learning genuine structural patterns. GasGAT, by contrast, shows zero performance change (88.69% → 88.69%, Δ = 0.00%). This stability is the central result of the ablation: it provides direct empirical evidence that GasGAT’s attention mechanism learns structural graph dependencies that are genuinely predictive of gas inefficiency, independently of whether locally correlated features are present.

5.5.2 Contribution of the semantic graph representation

Table 6 compares two graph variants: (1) a call-only graph retaining exclusively function-call edges (EdgeType = 0), representing the minimal function call graph used in traditional program analysis, and (2) the full semantic graph G = (V, E) with 4 node types and 4 edge types as described in Section 3.1. Both variants are evaluated on Dataset A with GCN (no attention) and GasGAT (with attention) under the same 5-fold cross-validation protocol.

TABLE 6. Graph ablation study comparing call-only interaction graphs and full semantic graphs under identical 5-fold cross-validation settings (Dataset A, N = 27,879 graphs, identical hyperparameters).

Graph representationModelAccuracyPrecisionRecallF1-score
Call-only interaction graphGCN80.86% ± 1.84%84.39% ± 0.88%81.13% ± 1.80%80.42% ± 2.08%
Call-only interaction graphGasGAT77.58% ± 3.46%82.58% ± 1.65%77.91% ± 3.37%76.75% ± 3.84%
Full semantic dependency graphGCN83.16% ± 3.69%85.43% ± 2.44%83.37% ± 3.61%82.90% ± 3.89%
Full semantic dependency graphGasGAT (ours)94.92% ± 1.04%96.94% ± 0.43%83.77% ± 3.46%88.69% ± 2.70%

Bold values highlight the key results discussed in the text.

The results confirm two independent contributions: (1) replacing the call-only graph with the full semantic graph improves performance for both GCN (F1: 80.42% → 82.90%, Δ = +2.48%) and GasGAT (F1: 76.75% → 88.69%, Δ = +11.94%), demonstrating that the semantic graph representation captures structural information beyond simple function call dependencies; and (2) replacing GCN with GasGAT improves performance on both graph variants (call-only: 80.42% → 76.75%; full semantic: 82.90% → 88.69%), demonstrating that the attention mechanism provides an additional, complementary benefit. Together, these results confirm that both the graph structure and the attention mechanism contribute independently to GasGAT’s performance. Furthermore, GasGAT remains the only architecture capable of providing edge-level attention attribution, enabling developers to identify which specific inter-procedural dependencies drive gas inefficiency.

The domain of gas optimization is diverse, encompassing static analysis, formal methods, and machine learning. To position our work, we compare GasGAT against representative state-of-the-art approaches. The comparison, summarized in Table 7, focuses not on a direct, and often misleading, comparison of accuracy scores across different datasets and problem formulations, but on the underlying methodology, scope, and limitations of each approach.

TABLE 7. Methodological comparison of gas optimization approaches.

ApproachMethodologyKey strengthKey limitation
GasOptiScan (Goyal et al., 2023)Static AnalysisFast, good for known local patterns (e.g., loop fusion).Rigid, rule-based; cannot find novel or complex patterns.
Severin et al. (2022)ML on hand-crafted featuresMoves beyond static rules.Performance is limited by pre-selected features.
Butler and Crane (2023)ML (LSTMCNN)Forecasts gas price fluctuations.Solves a different problem; not code optimization.
GasGAT (This work)Deep Learning on Graphs (GAT)Automatically learns structural features and their importance; interpretable attention weights.Requires a large labeled dataset; computationally intensive training.

Static, rule-based analyzers: Tools like GasOptiScan (Goyal et al., 2023) and GasChecker (Chen et al., 2020) are foundational. They excel at detecting specific, pre-defined anti-patterns using static code analysis. However, their primary limitation is their rigidity; they cannot discover novel inefficiency patterns and often lack the context to understand complex inter-procedural dependencies, leading to potential false positives or negatives.

Machine learning on hand-crafted features: Other studies, such as Severin et al. (2022), have applied machine learning to gas analysis. These approaches typically involve extracting a set of hand-crafted features from contracts (e.g., opcode counts, function size) and feeding them into traditional models like SVM or Random Forests. While more advanced than simple rule-matching, they are fundamentally constrained by the expressiveness of the chosen features. The feature engineering process is manual and may fail to capture the critical structural relationships within the code.

Our approach (GasGAT): GasGAT overcomes these limitations by operating directly on a graph representation of the contract. It automatically learns the features and their relationships, removing the need for manual feature engineering. The GAT’s attention mechanism allows it to identify which relationships are most salient for predicting gas inefficiency, providing a more powerful and adaptable solution. Unlike methods that forecast the price of gas, such as the work by Butler and Crane (2023), which is a time-series prediction problem, our work focuses on optimizing the consumption of gas by analyzing the code itself, which is a structural pattern recognition problem.

More broadly, while prior studies in adjacent domains (e.g., financial econometrics and digital asset modeling) increasingly rely on distributional and dependency-aware frameworks to capture complex system behavior, existing gas optimization approaches rarely adopt such holistic structural representations. GasGAT bridges this gap by transferring these methodological insights to smart contract analysis, where execution-level dependencies play a critical role in gas consumption.

7 Conclusion

The prohibitive cost of gas consumption remains a primary obstacle to the scalability and adoption of blockchain applications. In this paper, we introduced GasGAT, a deep learning framework that shifts gas optimization from local, rule-based analysis to holistic structural reasoning. Unlike prior approaches that rely on static heuristics or treat contracts as flat feature vectors, GasGAT represents a methodological advance by explicitly modeling the non-local structural dependencies that drive gas inefficiency. By representing smart contracts as semantic graphs and applying a Graph Attention Network, GasGAT overcomes key limitations of traditional static analysis tools.

Our experimental results show that, while GasGAT achieves 94.92% accuracy (±1.04%) under rigorous 5-fold cross-validation, its principal contribution lies not in raw classification performance but in demonstrating, through the feature independence analysis (Table 4, Δ = 0.00%), that its attention mechanism learns genuine structural patterns rather than label-feature correlations. by capturing non-local inefficiency patterns that emerge only through graph-level reasoning. This addresses a key research gap in smart contract analysis, where existing tools fail to reason across function boundaries and inter-procedural contexts. The principal contribution of this work lies not in raw classification accuracy, but in demonstrating how attention-based graph models can uncover the structural causes of excessive gas consumption—a capability that is fundamentally inaccessible to local static analysis tools or feature-based classifiers. This interpretability enables GasGAT to function not merely as a predictor, but as a diagnostic tool that guides developers toward concrete refactoring opportunities, thereby enhancing both performance and security. The innovation of GasGAT thus lies not only in its technical architecture but in its conceptual shift from pattern matching to structural reasoning—a step forward for data-driven smart contract analysis. The proposed framework contributes to advancing data-driven program analysis in blockchain systems and offers a scalable alternative to manual rule engineering. For future work, we plan to extend GasGAT toward multi-class and regression-based formulations, enabling finer-grained identification of gas anti-patterns and concrete optimization suggestions. We also aim to generalize the framework to legacy Solidity versions and other EVM-compatible blockchains, further strengthening its applicability to real-world smart contract ecosystems.

Generative AI statement

The author(s) declared that generative AI was used in the creation of this manuscript. The authors declare that generative AI tools were used only for language editing, grammar correction, and improving the clarity and readability of the manuscript. The generative AI tools were not used for data analysis, results generation, or scientific conclusions. All scientific content, methodology, experiments, and interpretations were developed and validated by the authors. The authors take full responsibility for the content of the manuscript.

Any alternative text (alt text) provided alongside figures in this article has been generated by Frontiers with the support of artificial intelligence and reasonable efforts have been made to ensure accuracy, including review by the authors wherever possible. If you identify any issues, please contact us.

Publisher’s note

All claims expressed in this article are solely those of the authors and do not necessarily represent those of their affiliated organizations, or those of the publisher, the editors and the reviewers. Any product that may be evaluated in this article, or claim that may be made by its manufacturer, is not guaranteed or endorsed by the publisher.

Footnotes

Edited by: Andrea Michienzi, University of Pisa, Italy

Reviewed by: Jose Juan De Leon, University College London, United Kingdom

Balachandar Raju, Pollachi Institute of Engineering and Technology, India

Statements

Conflict of interest

The author(s) declared that this work was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest.

Funding

The author(s) declared that financial support was not received for this work and/or its publication.

Data availability

Publicly available datasets were analyzed in this study. This data can be found here: https://github.com/Ysaid7810/GasGAT-Artifact.

Author contributions

YS: Conceptualization, Methodology, Writing – original draft. AK: Data curation, Supervision, Writing – review and editing. LH: Formal Analysis, Investigation, Writing – review and editing. AE: Visualization, Writing – review and editing. TC: Validation, Writing – review and editing.

References

  1. Albert E., Correas J., Gordillo P., Román-Díez G., Rubio A. (2020). “ Gasol: gas analysis and optimization for Ethereum smart contracts,” in International Conference on Tools and Algorithms for the Construction and Analysis of Systems. Springer.
  2. Baird K., Jeong S., Kim Y., Burgstaller B., Scholz B. (2019). The economics of smart contracts. arXiv preprint arXiv:1910.11143.
  3. Butler C., Crane M. (2023). Blockchain transaction fee forecasting: a comparison of machine learning methods. Mathematics 11, 2212. doi:10.3390/math11092212
  4. Chafiq T., Azmi R., Mohammed O. (2024a). Blockchain-based electronic voting systems: a case study in Morocco. Int. J. Intelligent Netw.
  5. Chafiq T., AZMI R., Fadil A., Mohammed O. (2024b). Investigating the potential of blockchain technology for geospatial data sharing: opportunities, Challenges, and solutions. Geomatica 76, 100026. doi:10.1016/j.geomat.2024.100026
  6. Chen T., Feng Y., Li Z., Zhou H., Luo X., Li X. (2020). Gaschecker: scalable analysis for discovering gas-inefficient smart contracts. IEEE Trans. Emerg. Top. Comput. 9, 1433 – 1448. doi:10.1109/tetc.2020.2979019
  7. Chen J., Xia X., Lo D., Grundy J., Yang X. (2021). Maintenance-related concerns for post-deployed Ethereum smart contract development: issues, techniques, and future challenges. Empir. Softw. Eng. 26, 117. doi:10.1007/s10664-021-10018-0
  8. Dhillon D., Diksha D., Mehrotra D. (2024). “ Smart contract vulnerabilities: exploring the technical and economic aspects,” in Blockchain Transformations: Navigating the Decentralized Protocols Era. Springer, 81 – 91.
  9. Dimitriadis K. A., Koursaros D., Savva C. S. (2024). Evaluating the sophisticated digital assets and cryptocurrencies capacities of substituting international currencies in inflationary eras. Int. Rev. Financial Analysis 96, 103693. doi:10.1016/j.irfa.2024.103693
  10. Dimitriadis K. A., Koursaros D., Savva C. S. (2025a). The influential impacts of international dynamic spillovers in forming investor preferences: a quantile-VAR and GDCC-GARCH perspective. Appl. Econ. 57, 7175 – 7195. doi:10.1080/00036846.2024.2387868
  11. Dimitriadis K. A., Koursaros D., Savva C. S. (2025b). Exploring the dynamic nexus of traditional and digital assets in inflationary times: the role of safe havens, tech stocks, and cryptocurrencies. Econ. Model. 151, 107195. doi:10.1016/j.econmod.2025.107195
  12. Goyal R., Tripathi M., Tomar S. (2023). GasOptiScan: unveiling gas-inefficient smart contracts via loop fusible pattern detection for enhanced cost efficiency. 2023 International Conference on Emerging Trends in Networks and Computer Communications (ETNCC) (IEEE).
  13. Hamilton W. L., Ying R., Leskovec J. (2017). Inductive representation learning on large graphs. Adv. Neural Inf. Process. Syst. (NeurIPS).
  14. Hewa T. M., Hu Y., Liyanage M., Kanhare S. S., Ylianttila M. (2021). Survey on blockchain-based smart contracts: technical aspects and future research. IEEE Access 9, 87643 – 87662. doi:10.1109/access.2021.3068178
  15. Huanliang X., Canghai W., JiaXin C., Yinglong W., yulin Z. (2025). A smart contract vulnerability line detection method based on graph neural network and fusion of multidimensional code representation. Appl. Soft Comput. 180, 113435. doi:10.1016/j.asoc.2025.113435
  16. Idelberger F., Governatori G., Riveret R., Sartor G. (2016). “ Evaluation of logic-based smart contracts for blockchain systems,” in International Symposium on Rules and Rule Markup Languages for the Semantic Web. Springer.
  17. Jiang F., Chao K., Xiao J., Liu Q., Gu K., Wu J. (2023). Enhancing smart-contract security through machine learning: a survey of approaches and techniques. Electronics 12, 2046. doi:10.3390/electronics12092046
  18. Joysoyal R., Uddin M. N., Hossain M. B., Islam M. S., Li L., Ahsan F. (2024). Blockchain for sustainable city transformation: a review on Bangladesh. Eng. Rep. 6, e12948. doi:10.1002/eng2.12948
  19. Kaur R., Ali A., Faisal M. (2022). Smart contracts: the self-executing contracts. Blockchain (Chapman and Hall/CRC). 35 – 49.
  20. Khan M. M. A., Sarwar H. M. A., Awais M. (2022). Gas consumption analysis of Ethereum blockchain transactions. Concurrency Comput. Pract. Exp. 34, e6679. doi:10.1002/cpe.6679
  21. Kipf T. N., Welling M. (2017). Semi-supervised classification with graph convolutional networks. International Conference on Learning Representations (ICLR).
  22. Ni E., Knight E., Gerstein M. (2025). Scalable and efficient on-chain data management in blockchain for large biomedical data. J. Biomed. Inf. 165, 104818. doi:10.1016/j.jbi.2025.104818
  23. Said Y., Khaddar A. M., Hassine L., Eddaoui A., Chafiq T. (2026). The impact of blockchain on the banking sector: a systematic review of applications, challenges, and future directions. Asia Glob. Econ. 6, 100133. doi:10.1016/j.aglobe.2025.100133
  24. Samir M., Sherief N., Abdelmoez W. (2023). Improving bug assignment and developer allocation in software engineering through interpretable machine learning models. Computers 12, 128. doi:10.3390/computers12070128
  25. Severin B., Hesenius M., Blum F., Hettmer M., Gruhn V. (2022). “ Smart money wasting: analyzing gas cost drivers of Ethereum smart contracts,” in 2022 IEEE International Conference on Software Maintenance and Evolution (ICSME) (IEEE).
  26. Sun C., Li C., Lin X., Zheng T., Meng F., Rui X. (2023). Attention-based graph neural networks: a survey. Artif. Intell. Rev. 56, 2263 – 2310. doi:10.1007/s10462-023-10577-2
  27. Ul-Durar S., Dimitriadis K. A., Arshed N., De Sisto M., Harati H. (2025). Distributional and tail-dependent perspectives in economic relationships: a review of quantile regression application. J. Econ. Surv.
  28. Velicˇkovic P., Cucurull G., Casanova A., Romero A., Lio` P., Bengio Y. (2017). Graph attention networks. arXiv preprint arXiv:1710.10903.
  29. Xu K., Hu W., Leskovec J., Jegelka S. (2019). How powerful are graph neural networks? International Conference on Learning Representations (ICLR).

Citation

Said, Y., et al. (2026). GasGAT: a graph attention network framework for smart contract gas optimization. Frontiers in Blockchain, Volume 9. https://doi.org/
Received
Accepted
Published
Volume
9 - 2026

Copyright

Copyright © 2026 Said, Khaddar, Hassine, Eddaoui and Chafiq.

License: https://creativecommons.org/licenses/by/4.0/

*Correspondence: Youssef Said

Article metrics

Views
0
Downloads
0
Citations
0
Shares
0