solidity-coding

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Solidity Coding Standards

Solidity编码标准

Language Rule

语言规则

  • Always respond in the same language the user is using. If the user asks in Chinese, respond in Chinese. If in English, respond in English.
  • 始终使用用户使用的语言进行回应。如果用户用中文提问,就用中文回应;如果用英文,则用英文回应。

Coding Principles

编码原则

  • Pragma: Use
    pragma solidity ^0.8.20;
    — keep consistent across all files in the project
  • Dependencies: OpenZeppelin Contracts 4.9.x, manage imports via
    remappings.txt
  • Error Handling: Prefer custom errors over
    require
    strings — saves gas and is more expressive
    • Define:
      error InsufficientBalance(uint256 available, uint256 required);
    • Use:
      if (balance < amount) revert InsufficientBalance(balance, amount);
  • Documentation: All
    public
    /
    external
    functions must have NatSpec (
    @notice
    ,
    @param
    ,
    @return
    )
  • Event Indexing: Only add
    indexed
    to
    address
    type parameters — add comment if indexing other types
  • Special Keywords:
    immutable
    /
    constant
    /
    unchecked
    /
    assembly
    must have inline comment explaining why
  • Pragma:使用
    pragma solidity ^0.8.20;
    — 确保项目中所有文件保持一致
  • 依赖项:OpenZeppelin Contracts 4.9.x,通过
    remappings.txt
    管理导入
  • 错误处理:优先使用自定义错误而非
    require
    字符串 — 节省Gas且表达更清晰
    • 定义:
      error InsufficientBalance(uint256 available, uint256 required);
    • 使用:
      if (balance < amount) revert InsufficientBalance(balance, amount);
  • 文档:所有
    public
    /
    external
    函数必须添加NatSpec注释(
    @notice
    @param
    @return
  • 事件索引:仅对
    address
    类型参数添加
    indexed
    — 若为其他类型添加索引需附上注释说明
  • 特殊关键字
    immutable
    /
    constant
    /
    unchecked
    /
    assembly
    必须添加行内注释解释使用原因

Naming Conventions

命名规范

ElementConventionExample
Contract / LibraryPascalCase
MyToken
,
StakingPool
Interface
I
+ PascalCase
IMyToken
,
IStakingPool
State variable / FunctionlowerCamelCase
totalSupply
,
claimDividend
Constant / ImmutableUPPER_SNAKE_CASE
MAX_SUPPLY
,
ROUTER_ADDRESS
EventPascalCase (past tense)
TokenTransferred
,
PoolCreated
Custom ErrorPascalCase
InsufficientBalance
,
Unauthorized
Function parameterprefix
_
for setter
function setFee(uint256 _fee)
  • Forbidden: Pinyin names, single-letter variables (except
    i/j/k
    in loops), excessive abbreviations
元素规范示例
合约/库PascalCase
MyToken
,
StakingPool
接口
I
+ PascalCase
IMyToken
,
IStakingPool
状态变量/函数lowerCamelCase
totalSupply
,
claimDividend
常量/Immutable变量UPPER_SNAKE_CASE
MAX_SUPPLY
,
ROUTER_ADDRESS
事件PascalCase(过去式)
TokenTransferred
,
PoolCreated
自定义错误PascalCase
InsufficientBalance
,
Unauthorized
函数参数setter方法参数前缀加
_
function setFee(uint256 _fee)
  • 禁止:拼音命名、单字母变量(循环中的
    i/j/k
    除外)、过度缩写

Code Organization Rules

代码组织规则

SituationRule
Cross-contract constantsPlace in
src/common/Const.sol
Interface definitionsPlace in
src/interfaces/I<Name>.sol
, separate from implementation
Simple on-chain queriesUse
cast call
or
cast send
Complex multi-step operationsUse
forge script
Import styleUse named imports:
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
场景规则
跨合约常量放置在
src/common/Const.sol
接口定义放置在
src/interfaces/I<Name>.sol
,与实现代码分离
简单链上查询使用
cast call
cast send
复杂多步操作使用
forge script
导入风格使用命名导入:
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

Project Directory Structure

项目目录结构

src/              — Contract source code
  interfaces/     — Interface definitions (I*.sol)
  common/         — Shared constants, types, errors (Const.sol, Types.sol)
test/             — Test files (*.t.sol)
script/           — Deployment & interaction scripts (*.s.sol)
config/           — Network config, parameters (*.json)
deployments/      — Deployment records (latest.env)
docs/             — Documentation, changelogs
lib/              — Dependencies (managed by forge install)
src/              — 合约源代码
  interfaces/     — 接口定义(I*.sol)
  common/         — 共享常量、类型、错误(Const.sol, Types.sol)
test/             — 测试文件(*.t.sol)
script/           — 部署与交互脚本(*.s.sol)
config/           — 网络配置、参数(*.json)
deployments/      — 部署记录(latest.env)
docs/             — 文档、变更日志
lib/              — 依赖项(由forge install管理)

Configuration Management

配置管理

  • config/*.json
    — network RPC URLs, contract addresses, business parameters
  • deployments/latest.env
    — latest deployed contract addresses, must update after each deployment
  • foundry.toml
    — compiler version, optimizer settings, remappings
  • Important config changes must be documented in the PR description
  • config/*.json
    — 网络RPC地址、合约地址、业务参数
  • deployments/latest.env
    — 最新部署的合约地址,每次部署后必须更新
  • foundry.toml
    — 编译器版本、优化器设置、重映射规则
  • 重要配置变更必须在PR描述中记录

Foundry Quick Reference

Foundry快速参考

bash
undefined
bash
undefined

Create new project

创建新项目

forge init <project-name>
forge init <project-name>

Install dependency

安装依赖

forge install OpenZeppelin/openzeppelin-contracts@v4.9.6
forge install OpenZeppelin/openzeppelin-contracts@v4.9.6

Build contracts

编译合约

forge build
forge build

Format code

格式化代码

forge fmt
forge fmt

Update remappings

更新重映射规则

forge remappings > remappings.txt
undefined
forge remappings > remappings.txt
undefined