AI
New Training Method Combines Retrieval and Preference Learning to Improve AI-Generated Solidity Smart Contract Code
Researchers introduce RAPO-Sol, a two-stage framework that augments training with code examples and semantic-aware preference optimization to generate more secure and consistent blockchain smart contracts.
Smart contract code generation presents a unique challenge: since these programs on blockchains handle money, permissions, and permanent data changes, mistakes carry real consequences. Generating complete Solidity contracts at the repository level—maintaining alignment across state variables, modifiers, events, inheritance patterns, and access controls—requires models to grasp intricate code relationships and security patterns.
Two-Stage Training Approach#
Researchers from arXiv have developed RAPO-Sol, a training framework combining two complementary techniques. The first stage, Retrieval-Augmented Fine-Tuning (RAFT), feeds the model similar Solidity examples alongside training data, enabling it to internalize recurring contract patterns. Importantly, the model operates without retrieval assistance during actual use, keeping inference costs low.
The second stage applies Direct Preference Optimization (DPO), teaching the model to favor correct reference contracts over nearly-identical but semantically broken versions. This preference-learning approach steers the AI toward safer, more reliable outputs.
Semantic-Aware Error Generation#
Creating meaningful wrong answers is critical to preference optimization. The team built Solidity Semantic-Anchor Perturbation (SAP), which deliberately introduces realistic flaws—altered validation checks, visibility settings, data-location keywords, variable references, payment handling, and low-level calls. By training on these challenging contrasts, the model learns to avoid genuine security pitfalls rather than just pattern-matching.
Results Across Multiple Models#
Testing on SolidityBench with three different base models (CodeLlama-7B-Instruct, DeepSeek-Coder-6.7B-Instruct, and Qwen2.5-Coder-7B-Instruct) showed consistent improvements. RAFT alone outperformed standard fine-tuning, while SAP-based DPO pushed performance further on both BLEU scores and SolidityScore metrics. The combined RAFT+DPO pipeline achieved the strongest results across all three models, proving the two techniques reinforce each other without introducing retrieval overhead at inference time.

