Manuscript Offprint

arXiv:2610.08429

RAPO-Sol: Retrieval-Augmented Preference Optimization for Repository-Level Solidity Code Generation

Rongcun Wang, Shi Chen

Rongcun Wang, Shi Chen

School of Computer Science and Technology (School of Artificial Intelligence), China University of Mining and Technology, Xuzhou, Jiangsu Province, China

Email: rcwang@cumt.edu.cn, ts24170102p31@cumt.edu.cn

Abstract—Smart contracts, predominantly written in Solidity on Ethereum and other EVM-compatible blockchains, govern on-chain assets, permissions, and irreversible state changes. Writing them correctly is both labor-intensive and security-critical, making automated generation an appealing direction. The realistic target is not an isolated function but repository-level Solidity code generation: synthesizing a complete contract or library that a developer can ship directly. This task is challenging because a correct output requires cross-function consistency among state variables, modifiers, events, inheritance relations, external calls, and access-control logic. Moreover, small deviations in these constructs can change contract behavior even when the code remains syntactically plausible. To address these challenges, we present RAPO-Sol, a two-stage framework for repository-level Solidity code generation. First, Retrieval-Augmented Fine-Tuning (RAFT) augments each training input with similar Solidity examples, allowing the model to learn recurring contract-level patterns while remaining retrieval-free at inference time. Second, Direct Preference Optimization (DPO) trains the model to prefer the reference contract over close but semantically flawed alternatives. To construct such rejected samples, we introduce Solidity Semantic-Anchor Perturbation (SAP), which perturbs validation statements, visibility modifiers, data-location keywords, context variables, payment operations, and low-level calls. We evaluate the framework on SolidityBench using CodeLlama-7B-Instruct, DeepSeek-Coder-6.7B-Instruct, and Qwen2.5-Coder-7B-Instruct. RAFT consistently outperforms standard supervised fine-tuning; SAP-based DPO further improves both BLEU and SolidityScore, a Solidity-aware embedding similarity metric, and the full RAFT+DPO pipeline achieves the best performance across all three models. These results indicate that retrieval during training and Solidity-aware preference data offer distinct, additive benefits for repository-level smart contract generation.

I. INTRODUCTION

Smart contracts are a cornerstone of blockchain applications, especially in decentralized finance (DeFi). On Ethereum, smart contracts are most commonly written in Solidity, whose code defines application logic that directly manages on-chain assets, enforces access control, and triggers irreversible state transitions [1], [2]. Consequently, errors in Solidity code can have severe financial repercussions: mistakes in access control, handling of external calls, exception management, or state updates frequently lead to loss of funds or unsafe contract behavior [3], [4]. Prior studies [5]–[7] further reveal that smart contract defects are predominantly semantic rather than merely syntactic. These characteristics make semantic correctness a central requirement for Solidity code generation, as even small semantic errors can compromise contract security or lead to financial loss.

Large language models (LLMs) have substantially advanced code generation. Code-oriented models such as CodeLlama [8], DeepSeek-Coder [9], and Qwen2.5-Coder [10] perform well on many programming tasks, and benchmarks such as HumanEval, CodeXGLUE, and MultiPL-E have driven progress in program synthesis and code understanding [11]–[13]. These benchmarks, however, primarily focus on single-function or single-file scenarios in general-purpose languages. They reveal little about whether a model can produce a complete, internally consistent smart contract, where long-range dependencies and Solidity-specific semantic constraints make correctness a whole-contract property. In this paper, we study repository-level Solidity generation at the contract-unit granularity: the task is to generate a complete contract or library unit from a natural-language requirement, covering imports, inheritance relations, interfaces, library usage, state declarations, and cross-function logic, rather than completing an isolated function. A correct output requires consistency across state variables, modifiers, events, inheritance, access checks, and cross-function behavior. This need for long-range consistency aligns with findings from repository-level code generation, where project-level context remains difficult for current models [14]–[16].

Recent Solidity benchmarks consider more realistic development settings. SolEval [17], for example, evaluates repository-level Solidity generation by prompting the model with a function signature, a natural-language requirement, and surrounding repository context. The generated function is then injected back into the original repository for execution-based scoring using Pass@k. Because the contract structure, including imports, inheritance, interfaces, and state declarations, is already fixed by the surrounding scaffold, this setting evaluates local function synthesis rather than structural synthesis itself. In contrast, generating a complete contract or library directly from a short requirement raises two coupled challenges: (1) inferring a coherent, multi-component contract structure, and (2) producing Solidity code that is not only syntactically plausible but semantically correct in its handling of access control, data locations, and payment-sensitive operations. SolidityBench [18] directly matches this setting, and we therefore adopt it as our evaluation benchmark.

For this task, supervised fine-tuning (SFT) achieves promising results [18]. On its own, however, SFT faces two primary limitations in this setting, each motivating a distinct form of supplementary supervision. First, SFT imitates reference contracts, but a natural-language requirement rarely specifies the full contract structure. Although such patterns may exist in the training corpus, standard SFT does not explicitly condition each training instance on similar contracts that capture reusable contract-level structures. Retrieval-augmented generation (RAG) can surface such patterns during inference [19], yet this ties inference to retriever quality and lengthens the prompt. Retrieval-Augmented Fine-Tuning (RAFT) instead supplies retrieved examples during training only, so the model learns from related contracts while remaining retrieval-free during inference [20]. Second, SFT offers only positive demonstrations and never contrasts a correct contract with a nearby variant that appears syntactically plausible but behaves differently. In Solidity, such near misses are common: a one-line change to an access-control guard, a visibility modifier, a data-location keyword, or a payment-sensitive call can preserve syntactic plausibility while silently changing contract semantics. Preference optimization can provide this contrast, and Direct Preference Optimization (DPO) learns directly from chosen and rejected responses without training a separate reward model [21]. The central design challenge is not merely applying DPO, but constructing rejected contracts that stay close to the reference while being wrong in Solidity-specific ways.

To provide the complementary supervision required by these two limitations, we propose RAPO-Sol (Retrieval-Augmented Preference Optimization for Repository-Level Solidity Code Generation) 1^{1}, a novel two-stage framework. In the first stage, RAFT incorporates retrieved requirement-code examples during fine-tuning, enabling the model to learn reusable contract-level structures while retaining requirement-only inference. In the second stage, DPO refines the RAFT-trained model by contrasting each reference contract with a structurally close but semantically flawed alternative. These rejected contracts are constructed using our Solidity Semantic-Anchor Perturbation (SAP), which perturbs condition, visibility, data/context, and call/payment anchors.

We evaluate RAPO-Sol on SolidityBench [18], a dataset of 5,470 repository-level requirement–contract pairs, using CodeLlama-7B-Instruct-HF [8], DeepSeek-Coder-6.7B-Instruct [9], and Qwen2.5-Coder-7B-Instruct [10]. We report BLEU [22] and SolidityScore [18], where SolidityScore is a Solidity-aware embedding-based similarity metric that complements surface-level overlap by measuring contextual alignment between generated and reference contracts. Experimental results show that RAFT consistently outperforms standard SFT, and SAP-based DPO brings further improvements across all three models. RAPO-Sol achieves the best results on both metrics. For example, on Qwen2.5-Coder, RAPO-Sol improves BLEU from 35.962 to 41.263 and SolidityScore from 0.653 to 0.707 over SFT. These results suggest that retrieval during training and SAP-based preference data provide complementary supervision for complete-contract Solidity generation.

Overall, the paper makes the following contributions:

• We propose RAPO-Sol, a two-stage framework that integrates RAFT with DPO while keeping inference retrieval-free.

• We introduce Solidity SAP, a domain-aware hard-negative construction strategy that perturbs condition, visibility, data/context, and call/payment anchors to create close but semantically flawed rejected contracts, enabling DPO to learn fine-grained Solidity semantics.

• We conduct a systematic empirical study on SolidityBench, a dataset containing 5,470 requirement-contract pairs across three code models, demonstrating complementary gains from the two-stage pipeline and isolating the effects of each component through controlled ablations.

The remainder of this paper is organized as follows. Section II describes the research motivation. Section III presents the proposed framework. The experimental setup and results are detailed in Section IV and Section V, respectively. Section VI discusses the threats to validity. Section VII summarizes related work, followed by the conclusion in Section VIII.

References (44)