AI-Generated Smart Contract Code: How to Protect the Bottom Line of Fund Security

    Large language models can now generate complete smart contract functions, tests, and templates, but responsibility for on-chain fund losses still rests with whoever merges the code. This article explains why DeFi code—especially oracle price feed logic—demands stricter review, walks through a typical incident path where a formula error led to fund losses, breaks down five common oracle calculation mistakes with a worked precision-conversion example, analyzes the specific risks of AI-generated code, and presents a five-layer defense system plus a pre-launch security audit checklist.

    1. Background: AI Can Write Code, but Responsibility Still Lies with the Merger

    Large language models can already generate complete business functions, test cases, and contract templates, significantly accelerating development. But the boundary of responsibility has not changed. The person who merges the code remains accountable for any fund losses after deployment.

    In decentralized finance (DeFi), contracts directly control user assets. Once logic such as lending, liquidation, or collateral ratio calculation goes wrong, losses occur the moment a transaction is confirmed—and they are usually unrecoverable. This type of code therefore demands a much higher review intensity than ordinary business code.

    2. Incident Review: How a Formula Error Becomes a Fund Loss

    The typical path of such incidents looks roughly like this:

    1. A developer uses an AI tool to generate part of a lending protocol’s contract logic.
    2. The code compiles and the main flow runs normally, so it enters the submission pipeline.
    3. The calculation formula for the oracle price feed is configured incorrectly—the meaning of the price is inverted or miscalculated.
    4. An attacker exploits the distorted price to borrow assets, and the protocol suffers losses.

    According to public reports, losses from this type of incident can reach the million-dollar scale. This article does not point to any specific protocol; refer to the original reports for exact amounts and details.

    The key to this kind of incident is not simply that “AI wrote the wrong code.” More importantly, a mathematical-level configuration error went undetected. Such errors pass compilation and run normally; routine checks rarely expose them. A dedicated review step is required to find them.

    3. Why Oracle Price Feeds Are Error-Prone

    Oracles supply external asset prices to contracts. Lending protocols use these prices to calculate collateral value, borrowing limits, and liquidation thresholds. Once a price is distorted, an attacker can borrow high-value assets at an undervalued price, or trigger improper liquidations at an overvalued price.

    There are five common categories of errors, each identifiable with a small example:

    1. Inconsistent precision. Prices typically use a fixed number of decimals, while token amounts use another. For example, if a token amount is stored with 18 decimals and the price with 8 decimals, multiplying them directly without conversion produces a result off by a factor of 10^10.
    2. Inverted direction. Does the quote mean “how many USD one token is worth” or “how many tokens one USD is worth”? If the formula uses it the wrong way, the result is completely reversed.
    3. Operation order and integer truncation. Dividing before multiplying loses precision, and unsigned integer division rounds down. With small amounts, truncation can reduce collateral value directly to zero.
    4. Unvalidated boundaries. Prices that are zero, negative, long unupdated, or abnormally volatile in a single update all require explicit handling.
    5. Misused default values. Constants or default parameters from a template get applied to mismatched assets—for example, using a stablecoin’s decimal count for another token.

    The following pseudocode illustrates precision conversion. It is for explaining the idea only and does not correspond to any specific protocol. A real implementation must be checked item by item against the target system’s interface documentation.

    Incorrect example:

    1. # Wrong: price precision and token precision are not unified; the unit of the result is unclear
    2. collateral_value = amount * price / 10**8

    Corrected approach:

    1. # Variable definitions
    2. # amount: collateral amount, as an integer in the token's smallest unit
    3. # token_decimals: token precision, e.g., 18
    4. # price_raw: integer price returned by the oracle, representing how much USD one whole token is worth
    5. # price_decimals: price precision, e.g., 8
    6. # USD_DECIMALS: precision of the output amount, set to 8 in this article
    7. # Multiply before dividing to reduce truncation; output unit is fixed as USD * 10**USD_DECIMALS
    8. # where // denotes integer division
    9. collateral_value_usd = amount * price_raw * 10**USD_DECIMALS // (10**token_decimals * 10**price_decimals)

    Verification example: 2 tokens (18 decimals), unit price of 3,000 USD (price precision 8), output precision 8. The result should be 6000 × 10^8. If the result doesn’t match, check direction and precision first, then the logic.

    In fixed-width integer environments such as Solidity, multiplication can overflow. Use an audited mulDiv-style library and perform range checks on intermediate results.

    The way to validate direction is: find an externally verifiable price—such as a public quote from an exchange—and compare it against the contract’s computed result. When the magnitude is off, suspect direction and precision first, then business logic.

    4. Risks Specific to AI-Generated Code

    AI-generated code shares the same types of defects as human-written code, but the following risks are more pronounced.

    Semantic errors are hard to spot. Models are good at producing well-structured, properly named code, but their understanding of business meaning can be off. The more professional the code looks, the more easily reviewers let their guard down.

    Missing context. Models generally don’t know a protocol’s risk parameters—such as collateral ratio caps, liquidation discounts, or price deviation tolerance. If the prompt doesn’t spell these out, the model fills them in on its own, and the result may not match the design intent.

    Unstable output. The same requirement can produce different code at different times. A version that passes review once says nothing about the reliability of the next generated version.

    Fabricated dependencies. Models sometimes call interfaces or parameter names that don’t exist. The way to check: for every external interface name, function signature, and parameter, find its source in the official documentation or source code. ABI files, compiler warnings, and static analysis tools can assist this check. The compiler catches some problems, but business assumptions still require manual verification.

    Therefore, AI-generated code should be treated as a draft pending review, not a finished product ready to merge.

    5. The Defense System: Five Gates from Requirements to Audit

    Gate 1: Specification first. Before asking a model to generate code, the team should clearly write down the price source, maximum allowed deviation, price expiry time, precision conventions, and liquidation thresholds. The clearer the specification, the easier it is to spot deviations in the generated code.

    Gate 2: Line-by-line manual review. The review focus should be on mathematics and units. Every amount-related expression should be annotated with its precision and unit, and the reviewer should be able to verify at least one typical input by hand calculation.

    Gate 3: Multi-layer testing.

    • Unit tests: cover boundary values, including zero, extreme values, the smallest precision unit, and the case where the price is zero.
    • Property-based tests: generate large numbers of random inputs and check whether invariants—such as “collateral value is proportional to price”—always hold.
    • State replay: simulate key operations on historical data consistent with the production environment and observe whether results match expectations.

    Gate 4: Static analysis and formal verification. For fund-related invariants—such as “total borrowed never exceeds collateral value times the collateral ratio”—formal methods or specialized analysis tools can be used. These techniques can find paths that manual testing easily misses.

    Gate 5: Independent audit. The audit scope should cover all AI-generated code; it must not be narrowed just because “it was only a small piece generated as an assist.” Every finding in the audit report needs a clear remediation record.

    Smart Contract Security Audit Checklist

    Before merging and going live, confirm each of the following:

    • Every amount variable is annotated with precision and unit
    • Price direction has been verified against external quotes
    • Price expiry time and deviation thresholds are implemented in code, with corresponding tests
    • Scenarios where the price is zero, negative, or long unupdated have explicit handling
    • Unit tests and property-based tests cover boundary values
    • All external interface names and parameters can be found in the official documentation
    • Admin privileges and parameter changes are controlled by multisig
    • Every finding in the audit report has a remediation record

    6. Production Safeguards: Assume Errors Will Happen

    No matter how thorough the defenses are, zero defects cannot be guaranteed. The goal of production safeguards is: even if an error reaches production, the loss can be contained, detected, and blocked. It is recommended to implement