Method and system for solving compiling error in version evolution of smart contract
By building a version migration knowledge base and a large language model, we can automatically repair compilation errors of Solidity smart contracts, resolve the semantic differences between different versions, and achieve efficient and accurate contract migration and repair.
Patent Information
- Application Number
- CN202510670355.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-23
- Publication Date
- 2025-09-05
AI Technical Summary
The semantic changes between different versions of Solidity smart contracts lead to frequent compilation errors. Traditional manual repair methods are inefficient and error-prone, especially difficult to deal with during large-scale code migration.
Build a version migration knowledge base, use static analysis tools to locate erroneous code snippets, combine large language models to generate repair patches, perform automated repairs through code slicing, error information and expert domain knowledge, and introduce an iterative mechanism to ensure repair accuracy.
It significantly improves the accuracy of automated repairs and development efficiency of smart contract version migration, improves the reliability and compatibility of contract code, and reduces developers' debugging and maintenance costs.
Smart Images

Figure CN120596142A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer program analysis based on large language models, and in particular to a method and system for resolving compilation errors in smart contract version evolution. Background Art
[0002] Solidity is a high-level, contract-oriented programming language specifically designed for writing and deploying smart contracts on blockchain platforms, particularly Ethereum (Tikhomirov S. Ethereum: state of knowledge and research perspectives [C] / / International symposium on foundations and practice of security. Cham: Springer International Publishing, 2017: 206-221.). Smart contracts, as a key component for automated protocol execution in blockchain ecosystems (Wood G. Ethereum: A secure decentralized generalized transaction ledger [J]. Ethereum project yellow paper, 2014, 151 (2014): 1-32.), can automatically execute transaction logic based on predefined conditions without third-party intervention. These characteristics make it widely used in various blockchain application scenarios such as decentralized finance (DeFi), digital asset issuance and management, DAO (decentralized autonomous organization), NFT (non-fungible token) (Sillaber C, Waltl B. Lifecycle of smart contracts in blockchain ecosystems [J]. Datenschutz und Datensicherheit-DuD, 2017, 41 (8): 497-500.).
[0003] As blockchain technology continues to evolve, the Solidity language itself is also undergoing continuous development and iteration. From v0.4.1 to v0.8.23, Solidity has undergone over 80 significant version updates. These updates include significant changes in syntax, type system, memory model, function calling methods, exception handling mechanisms, security checks (such as integer overflow checks), access control semantics, ABI encoding format, and more. For example, the default integer overflow check mechanism introduced in v0.8.x significantly improves the security of smart contracts; and certain syntax and type constraints in earlier versions have been removed or refactored in subsequent versions to enhance readability and modularity.
[0004] However, this continuous and frequent language evolution also presents numerous challenges. First, semantic changes between versions directly impact the compilability and runnability of contracts. When migrating or reusing code, developers often encounter issues such as incompatible syntax, type mismatches, and changes in function behavior, leading to frequent compilation errors. Second, Solidity contracts are often componentized. A single project may consist of multiple interdependent contracts, even requiring the invocation of external contracts already deployed on the blockchain. When different contracts are written using different versions of Solidity, incompatibility between versions may cause the construction of the entire system to fail, increasing debugging and maintenance costs (Wang Y, He J, Zhu N, et al. Security enhancement technologies for smart contracts in the blockchain: Asurvey[J]. Transactions on Emerging Telecommunications Technologies, 2021, 32(12): e4341.)(Chen J, Xia X, Lo D, et al. Maintenance-related concerns for post-deployed Ethereum smart contract development: issues, techniques, and future challenges[J]. Empirical Software Engineering, 2021, 26(6): 117.). In addition, some development tool chains, testing frameworks, deployment tools, or security analysis tools have limited support for Solidity versions (DiAngeloM, SalzerGA survey of tools for analyzing ethereum smart contracts[C] / / 2019IEEE international conference on decentralized applications and infrastructures(DAPPCON).IEEE,2019:69-78.), which further exacerbates the complexity of cross-version development.
[0005] In practice, developers may choose a specific version of Solidity for different purposes. For example, some projects prefer older versions for stability and audit maturity, while others rely on the latest version to leverage new features or optimize performance. This multi-version ecosystem forces developers to constantly adapt to the pace of language evolution and master the subtle differences between versions to ensure contract compatibility and security.
[0006] Therefore, effectively resolving compilation errors and semantic differences between different versions of Solidity smart contracts has become a critical issue for ensuring the efficiency and quality of blockchain smart contract development. Manual document comparison and code debugging are inefficient and prone to missing key changes, especially when working with complex contract systems or large-scale code migrations. Therefore, an intelligent solution is urgently needed that can systematically analyze the impact of version evolution, understand code semantics, and automatically assist in fixing compilation errors. This approach can lower the barrier to cross-version development and improve development efficiency and code reliability. Summary of the Invention
[0007] The purpose of the present invention is to provide a method and system for resolving compilation errors in smart contract version evolution, in view of the difficulties existing in the prior art in repairing smart contract compilation errors caused by the frequent evolution of Solidit language versions.
[0008] To achieve the above objectives, the present invention provides a method for resolving compilation errors in smart contract version evolution, comprising the following steps:
[0009] (1) Based on the official Solidity website, we collect and catalog all breaking changes recorded, and filter out breaking changes that cause compilation problems to build a knowledge base for version migration.
[0010] (2) Use static analysis tools to perform context-aware code slicing on the error code with compilation problems, locate and extract code fragments that have a call relationship or the same structure as the compilation error content;
[0011] (3) according to the error information obtained after the error code is compiled on the Solidity compiler, based on the knowledge base, retrieving expert domain knowledge associated with the error;
[0012] (4) Construct refined prompts, taking code slices, error information, and expert domain knowledge as input, and iteratively generate code patches for fixing compilation errors through a large language model;
[0013] (5) Recompile the generated code patch. If the compilation still fails, repeat steps (3) and (4) until the patch is compiled successfully or the set number of iterations is reached.
[0014] Furthermore, the step (1) includes the following sub-steps:
[0015] (1.1) Use a crawler to automatically collect HTML pages containing all version change information from the Solidity official website to obtain a comprehensive version evolution data source;
[0016] (1.2) During the crawling process, retain the code block content in HTML tags to preserve the original code sample information; remove other useless HTML tags and only retain the natural language description part in the page body;
[0017] (1.3) Use natural language processing tools to structure the retained text descriptions and convert unstructured text into structured knowledge entries; this is used to support subsequent error repair tasks.
[0018] Furthermore, the step (2) includes the following sub-steps:
[0019] (2.1) Use the python-solidity-parser tool to convert the Solidity source code into an abstract syntax tree for structural analysis of the various components of the code;
[0020] (2.2) Extract the error line number from the compiler error message and locate the corresponding node in the leaf node of the AST; match the node containing the error keyword and expand it one level outward to obtain its context dependencies (such as variable declaration, assignment, etc.);
[0021] (2.3) According to the located AST node, the corresponding code snippet is extracted from the source code to subsequently construct the prompt words of the high-quality large-scale language model.
[0022] Furthermore, the step (3) includes the following sub-steps:
[0023] (3.1) Preprocessing the compiler error message, extracting key fields (such as error type, variable name, location, etc.), and converting the key fields into a text representation suitable for calculation;
[0024] (3.2) Vectorize each migration rule (including change descriptions and error examples) in the version migration knowledge base to build a unified semantic space;
[0025] (3.3) Calculate the similarity scores between the error message and each transfer rule in the knowledge base, including cosine similarity and text similarity based on the language model;
[0026] (3.4) Select the top-k transfer rules with the highest similarity scores as candidate transfer knowledge.
[0027] Furthermore, the step (4) includes:
[0028] The code slices, error messages, and expert domain knowledge are organized into a clearly structured and semantically coherent prompt word template, which is then input into the LLM to guide it in generating semantically reasonable and version-compliant repair patches. The prompt words include task descriptions, original code snippets that failed to compile, compiler error prompt information, and retrieved migration knowledge entries.
[0029] Furthermore, in step (5), the maximum number of iterations is preferably 5.
[0030] The present invention also provides a system for resolving compilation errors in smart contract version evolution, including:
[0031] The code slicer module is used to obtain Solidity smart contracts, identify compilation errors and slice the code into code snippets;
[0032] A knowledge retriever module is used to retrieve the migration knowledge entry with the highest relevance to the current error information from the version migration knowledge base;
[0033] The patch generator module is used to accept code snippets, error messages and retrieved transfer knowledge entries, and input them into the large language model to generate code patches.
[0034] Furthermore, the patch generator module includes: in the process of inputting the code snippet, error message and retrieved migration knowledge entry into the large language model, generating a code patch based on a structured prompt word template, the prompt word including the task description, the original code snippet that failed to compile, the compiler error prompt information and the retrieved migration knowledge entry.
[0035] Furthermore, the patch generator module includes: introducing an iterative mechanism in the process of generating code patches; recompiling new code after each round of patch generation, and automatically updating the prompt if error information still exists, and entering the next round of repair generation process.
[0036] Furthermore, the knowledge retriever module includes an encoder module, which includes a multi-head attention mechanism, a GELU activation function and a two-layer linear mapping, for generating an embedding vector to enhance the representation capability of code terms and error context.
[0037] The present invention has the following beneficial effects: existing methods have significant limitations in addressing compilation errors caused by the frequent evolution of the Solidity language, particularly lacking intelligent support for version migration and automatic repair. By combining the contextual understanding and generation capabilities of a large language model with structured version migration knowledge and static analysis results, this invention achieves efficient repair of smart contract compilation errors, significantly improving the accuracy and development efficiency of automated migration, and helping developers quickly address the compilation challenges brought about by Solidity version upgrades. BRIEF DESCRIPTION OF THE DRAWINGS
[0038] Figure 1 This is a diagram of the types of compilation errors that may be caused by Solidity version migration;
[0039] Figure 2 It is the overall framework diagram of the method of the present invention;
[0040] Figure 3 It is a structural diagram of the retriever of the method of the present invention. DETAILED DESCRIPTION
[0041] The following is a clear and complete description of the technical solutions in the embodiments of the present invention, in conjunction with the accompanying drawings. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. All other embodiments obtained by ordinary technicians in this field based on the embodiments of the present invention without making any creative efforts shall fall within the scope of protection of the present invention.
[0042] The present invention proposes a method for solving compilation errors in the evolution of Solidity smart contract versions based on the Large Language Model (LLM), which aims to solve a large number of version migration problems and compilation errors caused by the frequent evolution of the Solidity language. As the most mainstream smart contract development language in the Ethereum ecosystem, Solidity's syntax and semantics have changed significantly in multiple versions. Although this frequent language evolution enhances functionality and security, it also makes it impossible for historical versions of contracts to be compiled smoothly under the new version, seriously hindering the reuse and migration of contract code. Traditional manual repair is not only inefficient, but also has the risk of misjudgment and misrepair, which is especially difficult to deal with when faced with a large-scale historical code base.
[0043] This paper first built a comprehensive and clearly structured version migration knowledge base. This knowledge base was systematically constructed based on the official Solidity documentation (https: / / docs.soliditylang.org / ). Using programmatic crawling techniques, it extracted 131 semantically significant language changes from Solidity versions 0.4 to 0.8. This crawling process preserved code blocks, prompts, and version change identifiers, while removing redundant information such as style tags and navigation bars to ensure concise and accurate content.
[0044] like Figure 1 As shown, to facilitate knowledge classification and efficient retrieval, the present invention divides all change items according to the types of compilation errors they may cause, and ultimately summarizes them into six major error types: parser error (Parser Error), declaration error (Declaration Error), syntax error (Syntax Error), type error (Type Error), JSON error (JSON Error) and IO error (Input / Output Error). Among them, parser errors usually arise from unsupported grammatical structures of the code, such as incorrect use of new keywords, unclosed structures, etc.; declaration errors often occur in situations such as duplicate variable names, scope conflicts, and undeclared uses; syntax errors manifest as missing semicolons, mismatched brackets, and incorrect function formats; type errors are the most common, reflected in data type changes, function parameter type upgrades, and tightened implicit conversion restrictions; JSON and IO errors involve format and path issues in deployment and compilation configuration.
[0045] To verify the coverage and practical application value of the constructed knowledge base, the present invention further conducted a large-scale empirical migration study, constructing 2,050 Solidity contract migration samples covering multiple version spans, and statistically analyzing the changes in their compilability when migrating between different versions. The results show that 81.68% of contracts experienced at least one compilation failure during the migration process, of which a whopping 86.92% of failures could be directly attributed to compiler errors. This finding further confirms the breadth and depth of semantic changes in the Solidity language during version iteration, and also clearly points out the key role of automated knowledge acquisition and precise matching in migration and repair.
[0046] To address the two core challenges mentioned above—(1) how to accurately obtain the knowledge points triggered by version migration; and (2) how to make LLM understand this knowledge and correctly generate patches—the present invention designs and implements the SMCFIXER framework. The overall structure of the framework is as follows: Figure 2As shown in the figure, it is mainly composed of three core modules: code slicer module, knowledge retriever module and patch generator module. The three modules work together to complete the whole process from error identification, knowledge matching to repair suggestion generation.
[0047] In the first stage, the code slicer module first receives the input Solidity smart contract, and calls the compiler to compile it to obtain accurate compiler error information. Subsequently, the abstract syntax tree (AST) of the contract is constructed with the help of the python-solidity-parser tool, and the AST structure is aligned with the error information to accurately locate the AST node where the error occurs. Based on the positioning, the present invention further introduces a context-aware extension mechanism, which traces back semantically related information such as variable declarations, function definitions, call chains, etc. around the error node, and associates it with the statement blocks that may be affected, thereby extracting the smallest but semantically complete code slice. The mechanism not only effectively compresses the input scale required to be processed by LLM (reduces noise), but also enhances the reasoning ability of the model.
[0048] In the second stage, the knowledge retriever module is responsible for retrieving the migration knowledge items with the highest relevance to the current error from the version migration knowledge base. To improve the retrieval accuracy and semantic matching ability, this paper performs structural level fine-tuning based on the all-MiniLM-L6-v2 model and constructs a vector space indexing tool SOCR dedicated to code-knowledge semantic mapping. Specifically, Figure 3 As shown, the fine-tuned model takes sentence pairs consisting of (error message text, knowledge item text) as input and generates corresponding embedding vectors through the Transformer encoder module. The encoder architecture incorporates a multi-head attention mechanism, GELU activation function, and two linear mapping layers (Linear-1 and Linear-2), enhancing the model's representation of code terminology and error context. The error message is aggregated using a pooling layer, while the knowledge item uses a self-attention mechanism to extract key semantic features. Finally, the embedding vectors generated from the sentence pairs are concatenated and fed into a linear classification layer for relevance judgment. CosineSimilarityLoss is used as the loss function during training, and supervised learning is performed on constructed triples (error message, knowledge item, relevance label). This results in a vector space index system with strong semantic consistency. Experiments demonstrate that this module achieves a top-5 retrieval accuracy of 94.5%, significantly outperforming the original untuned model and providing high-quality knowledge input for subsequent LLM generation.
[0049] In the third stage, the patch generator module receives the sliced code snippets, error prompt text, and retrieved transfer knowledge items, and integrates the three into a prompt, which is input into a large language model (supporting multiple models such as GPT-4o, GPT-3.5, LLaMA3-8B, DeepSeek-7B, etc.) to generate repair suggestions. To improve the readability and controllability of the prompt, the present invention designs a structured prompt template, which is divided into four areas: (1) Task description: clearly informing the model that its goal is to "repair a piece of Solidity code that cannot be compiled"; (2) The original code snippet that failed to compile; (3) Compiler error prompt information; (4) Retrieved transfer knowledge items. This structure encourages the model to focus on the core semantic interval, effectively reducing the deviation and redundancy of the generated content. The output result is formatted in a "search / replace" patch format, which is convenient for subsequent automatic repair through tools such as git apply or script systems.
[0050] To further improve the robustness of the repair suggestions, the present invention also introduces an iterative repair mechanism: after each round of patch generation, the system immediately recompiles the new code. If errors still occur, the prompt is automatically updated (adding the previous round of errors and patch information) and entering the next round of repair generation process. This iterative process is carried out for up to five rounds to ensure that the correct repair suggestions can be converged in most cases. Experiments have shown that the iterative mechanism significantly improves its stability and accuracy, especially for LLMs with smaller parameter counts (such as 7B-13B scale).
[0051] In order to systematically evaluate the effectiveness and practicality of the SMCFIXER framework, the present invention designed a number of experimental tasks. First, an end-to-end test was conducted on a synthetic dataset, and compared with baselines such as the original completion capability of GPT-4o. The results showed that SMCFIXER improved the compilation pass rate by 24.24%, and the average repair accuracy reached 95.20%. It was significantly better than the control group in multiple indicators such as BLEU-4 and edit similarity. Subsequently, its practicality was verified on a real dataset (historical contract versions collected from GitHub and Stack Overflow). The experimental results showed that SMCFIXER successfully repaired 96.97% of the compilation failed contracts, especially when dealing with complex migration problems such as type changes, inconsistent ABI signatures, and keyword replacements. It showed extremely strong adaptability, verifying its actual deployability and expansion value.
[0052] In addition, the present invention conducted a series of ablation experiments to analyze the impact of each module on overall performance. The results showed that removing the code slicer module, retaining only the original code input, reduced the overall repair rate by approximately 2.8%. Removing the knowledge retriever module, and leaving only the LLM to freely generate repair suggestions based on error information, reduced the accuracy by over 14.9%. Parameter adjustment experiments further demonstrated that five rounds is the optimal number of rounds for the iterative repair mechanism, achieving the best repair results while ensuring time efficiency.
[0053] In summary, the present invention proposes for the first time a fully automatic compilation error repair system for the evolution of the Solidity language by combining code static analysis, structured semantic knowledge modeling, embedded vector retrieval and large language model reasoning generation. This system can not only accurately identify compilation problems at the syntax and type levels, but also generate patches at the semantic level through knowledge understanding of language changes, filling the gap in the current tool ecosystem in contract migration and repair. Compared with traditional rule-based tools or simple text matching methods, SMCFIXER exhibits higher generalization, adaptability and intelligence levels, and has extremely high engineering implementation potential.
[0054] This invention has achieved a breakthrough in the technical path by combining the capabilities of large language models with Solidity semantic knowledge, providing an end-to-end fully automatic solution to the version migration problem in blockchain contract development and maintenance. It not only has important theoretical research value, but also has broad industrial application prospects.
[0055] The above embodiments are intended only to illustrate the design concepts and features of the present invention. Their purpose is to enable those skilled in the art to understand the contents of the present invention and implement them accordingly. The scope of protection of the present invention is not limited to the above embodiments. Therefore, any equivalent changes or modifications made based on the principles and design concepts disclosed in the present invention are within the scope of protection of the present invention.
Claims
1. A method for resolving compilation errors in smart contract version evolution, characterized in that: The steps include: (1) Based on the official Solidity website, we collect and catalog all recorded major changes, filter out the major changes that cause compilation problems, and build a knowledge base for version migration; (2) Use static analysis tools to perform context-aware code slicing on the error code with compilation problems, locate and extract code fragments that have a call relationship or the same structure as the compilation error content; (3) according to the error information obtained after the error code is compiled on the Solidity compiler, based on the knowledge base, retrieving expert domain knowledge associated with the error; (4) constructing refined prompts, taking the code snippet, error information, and expert domain knowledge as input, and iteratively generating code patches for fixing compilation errors through a large language model; (5) Recompile the generated code patch. If the compilation still fails, repeat steps (3) and (4) until the patch is compiled successfully or the set number of iterations is reached.
2. The method according to claim 1, characterized in that The step (1) includes the following sub-steps: (1.1) Use a crawler to automatically collect HTML pages containing all version change information from the Solidity official website to obtain a comprehensive version evolution data source; (1.2) During the crawling process, the code block content in HTML tags is retained to preserve the original code sample information; Remove other useless HTML tags and only keep the natural language description part in the page body; (1.3) Use natural language processing tools to structure the retained text descriptions and convert unstructured text into structured knowledge items; Used to support subsequent bug fixing tasks.
3. The method according to claim 1, characterized in that The step (2) includes the following sub-steps: (2.1) Use the python-solidity-parser tool to convert the Solidity source code into an abstract syntax tree for structural analysis of the various components of the code; (2.2) Extract the error line number from the compiler error message and locate the corresponding node in the leaf node of the AST; match the node containing the error keyword and expand it one level outward to obtain its context dependency; (2.3) According to the located AST node, the corresponding code fragment is extracted from the source code.
4. The method according to claim 1, wherein The step (3) includes the following sub-steps: (3.1) Preprocessing the compiler error message, extracting key fields therein, and converting the key fields into a text representation suitable for calculation; (3.2) Vectorize each migration rule in the version migration knowledge base and build a unified semantic space; (3.3) Calculate the similarity scores between the error message and each transfer rule in the knowledge base, including cosine similarity and text similarity based on the language model; (3.4) Select the top-k transfer rules with the highest similarity scores as candidate transfer knowledge.
5. The method according to claim 1, wherein The step (4) includes: organizing the code snippet, error message and expert domain knowledge into a prompt word template, inputting it into the LLM to guide it to generate a code patch that complies with the version specification, the prompt word includes the task description, the original code snippet that failed to compile, the compiler error prompt information and the retrieved migration knowledge entry.
6. The method according to claim 1, wherein: In step (5), the maximum number of iterations is 5.
7. A system for resolving compilation errors in smart contract version evolution, characterized in that: include: The code slicer module is used to obtain Solidity smart contracts, identify compilation errors and slice the code into code snippets; A knowledge retriever module is used to retrieve the migration knowledge items with the highest relevance to the current error information from the version migration knowledge base; The patch generator module is used to accept code snippets, error messages and retrieved transfer knowledge entries, and input them into the large language model to generate code patches.
8. The system according to claim 7, characterized in that The patch generator module includes: when the code snippet, error message and retrieved migration knowledge entry are input into the large language model, a code patch is generated based on a structured prompt word template, where the prompt word includes a task description, the original code snippet that failed to compile, the compiler error prompt message and the retrieved migration knowledge entry.
9. The system according to claim 7, wherein: The patch generator module includes: introducing an iterative mechanism in the process of generating code patches; recompiling new code after each round of patch generation, and automatically updating the prompt if error information still exists, and entering the next round of repair generation process.
10. The system according to claim 7, wherein: The knowledge retriever module includes an encoder module, which includes a multi-head attention mechanism, a GELU activation function and a two-layer linear mapping, and is used to generate an embedding vector to enhance the representation capability of code terms and error context.
Citation Information
Cited By
Code adaptation method and related device for version upgrading of Android system
CN120892088A
Patch round system based on AI
CN121326378A
