Unit 2 / 11

Smart Contract Writing Support: Solidity/Vyper Draft and Secure Code Generation

Gains:

  • Ability to use artificial intelligence to produce frameworks, tests and review drafts based on proven libraries (e.g. OpenZeppelin) and understand that humans guarantee production security
  • Ability to verify the code version, pattern and access control produced by artificial intelligence through compilation, testing and testnet
  • Being able to distinguish that compilation does not mean being secure and that testnet and auditing are essential.

Writing a smart contract is different from ordinary software: the code you write is public, immutable, and a program that directly moves money. In this unit, you will learn how to use AI as a smart contract development assistant; We will learn from draft production to test writing, from pattern recall to gas (transaction fee) optimization. But let's be clear from the start: AI produces blueprints; Humans ensure secure code that goes into production.

Ground first: language and environment

The most common smart contract language is Solidity (the language of Ethereum and EVM — Ethereum Virtual Machine, the virtual machine on which contracts run — compatible chains). The alternative is Vyper (a Python-like language that aims to be more constrained and readable). Your code consumes gas (the cost of each transaction to the blockchain); Inefficient code is expensive. Keeping these terms clear in the context you give it to the AI ​​is key to getting accurate output.

Where AI is most valuable is not in "writing from scratch" but in producing the framework + good mold: a standards-compliant start, a blueprint on which to add your expertise.

Layers of using AI in coding

1. Generating skeletons. AI quickly mines the skeleton of a standard token (ERC-20) or NFT (ERC-721 — a unique digital asset standard). But be sure to make the AI ​​use a proven library: for example, OpenZeppelin (the community's trusted, audited standard contracting library). The rule is to use the tested block rather than writing security from scratch.

2. Function description and review. Explaining an existing function to AI allows you to spot logic errors early.

3. Test generation. AI is good at generating test cases for edge cases: zero input, very large number, unauthorized caller, repeated call. This reminds one of the scenarios one skips.

4. Gas and readability. AI flags expensive patterns such as unnecessary storage writes and suggests alternatives.

Hint: Instruct the AI ​​to "Build on OpenZeppelin's audited contracts, rewrite security from scratch." It is much riskier for an AI to write original security code than to use a tested library.

Weak prompt / Strong prompt

Weak prompt:

Write me a token contract.

This prompt is dangerous: it is not clear which standard, which chain, which library, which security requirement. The AI ​​generates random, possibly outdated or insecure code.

Powerful prompt:

Your role: senior Solidity developer. Generate an ERC-20 token draft for an EVM compatible chain. Rules:- Based on OpenZeppelin's audited ERC20 and Ownable contracts.- Write the Solidity version and license (SPDX) line explicitly.- Only the owner has permission to mint; add a cap against infinite pressing. - Add NatSpec comment to each function. - Write security from scratch; Use the standard block. - Add a warning at the end: "This is a draft; auditing and testing is required". Mark the areas you are not sure about with // TODO.

Difference: strong prompt gives clear role, standard, library, security boundary, documentation and validation expectations.

Four copyable templates

1) Standards based skeleton:

Your role: Solidity developer. Generate [ERC-20 / ERC-721 / staking]contract framework based on OpenZeppelin audited library. Write SPDX license and pragma version. Add access control (who can call) to each external function. Reinventing security; Use standard blocks. This is a draft.

2) Function review:

Examine the following function like a senior developer: what does it do, what states does it change, who can call it? Mark possible logic errors and security risks as HYPOTHESIS, linking each to a line in the code. Don't say "safe" outright; just list the points of attention.

3) Test scenario draft:

Propose test cases for this contract (could be a draft for Foundry/Hardhat). Specifically cover limit cases: zero input, very large number, unauthorized call, reentrant call, insufficient funds. Write WHAT each test confirms.

4) Gas and readability review:

In this contract, mark the patterns that can reduce the gas cost: unnecessary storage writing, external call in the loop, repetitive calculation. Explain the before/after difference in each suggestion. Recommend security-breaking optimizations; If it's not clear, say "ask the auditor".

Three mini cases (in numbers)

Case 1 — Skeleton saved 4 hours. One team mined the skeleton of a audited library-based vesting contract with AI in 30 minutes; It took ~4 hours manually. The team devoted time to security and testing. The gain came not from transferring security, but from speeding up the tedious framework.

Case 2 — Outdated version trap. The AI ​​produced a pattern that sends raw Ether by transfer, which is no longer recommended because the training data is outdated. The developer noticed this and changed it to the current call-based and reentrancy-protected pattern. Lesson: The AI's library/pattern is always confirmed to be up to date; AI does not know beyond the training cutoff date.

Case 3 — Test draft popped hidden bug. The "unauthorized caller" test that the AI ​​produced revealed that the developer had forgotten access control in a function. onlyOwner missing 1 line, caught in 5 minutes on testnet; There could have been a loss of funds on the mainnet. Lesson: AI covers human blind spot in testing.

Remembering security patterns with AI

AI is good at reminding you of known vulnerability patterns like a checklist. The most common patterns:

  • Reentrancy: Making an external call without updating the status. Solution: checks-effects-interactions order, reentrancy guard.
  • Lack of access control: Anyone can call the critical function.
  • Integer overflow/underfall: Modern Solidity catches most of them, but still a risk in low-level code.
  • Inadequate input validation: Zero address, zero quantity control.
  • Oracle dependency: Blind trust in external data (such as price).
Attention: AI can recall this list, but it cannot guarantee whether an item in the list is in your specific code. The checklist is a start; It is not a replacement for container control.

Getting the context right: The secret to good code from AI

The quality of the code the AI produces depends directly on the quality of the context you give it. In Web3 this is especially critical because one small detail (which chain, which Solidity version, which token standard) changes the entire output. A good context includes:

  • Target chain and environment: Ethereum mainnet or a Layer 2 (cheaper sidechain that runs on top of the mainchain)? Gas cost and some features vary by chain.
  • Version and library: Which Solidity version, which OpenZeppelin version? If no version is specified, AI may produce outdated, deprecated patterns.
  • Security requirements: Is there a cap, can it be paused, can it be increased? These should be said from the very beginning.
  • Constraints: Clear limits like "don't use assembly", "avoid external call", "optimize gas but maintain readability".

Another powerful technique is to ask the AI ​​for the plan first, then the code: "First list the functions of this contract and what each will do; write the code once I approve it." This catches the AI ​​going in the wrong direction early and allows you to retain the architectural decision.

Hint: Ask the AI ​​"why did you write this code like this?" ask. Explaining the rationale will both speed up your learning and bring to the surface any logical errors (e.g. a false security assumption). Don't trust the output of an AI that can't defend its own code.

Common mistakes

  • Putting security in AI from scratch. Use a tested library.
  • Not confirming the version/pattern produced by the AI. Training data may be old.
  • Bypassing testnet. Every draft should run on the test network before going live.
  • Not adding NatSpec/documentation. Inspection and maintenance become difficult.
  • "It's compiled, so it's safe" misconception. Being compiled does not mean being safe.
  • Forgetting access control. It is one of the most common and expensive mistakes.

In summary

  • In smart contract writing, AI produces frameworks, tests and review drafts; Human guarantees production safety.
  • Build security not from scratch but based on proven libraries (e.g. OpenZeppelin).
  • The up-to-dateness of the versions and patterns produced by YZ is always confirmed.
  • Test stubs are valuable in capturing human blind spots (limit cases, access control).
  • Being compiled does not mean being safe; testnet and auditing are a must.

Application task

For a simple ERC-20 token, generate a draft using the "standards-based skeleton" prompt above. Then: (1) check if it uses a checked library, (2) check the access controls, (3) generate tests with the "test case draft" prompt and actually run at least one rogue-caller test. Find and note at least one security point that the AI ​​missed.

checklist

  • [ ] I have clearly stated the standard and chain in the prompt.
  • [ ] I wanted proven library-based production.
  • [ ] SPDX license and pragma version available.
  • [ ] There is access control in every critical function.
  • [ ] I created and ran tests for limit cases.
  • [ ] I confirmed that the library/pattern is up to date.
  • [ ] I marked the code for auditing and testing; I didn't get it unsupervised on mainnet.