solidity-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Solidity Development Skill

Solidity智能合约开发技能

Master Solidity smart contract development with design patterns, testing strategies, and production best practices.
借助设计模式、测试策略和生产环境最佳实践,精通Solidity智能合约开发。

Quick Start

快速入门

python
undefined
python
undefined

Invoke this skill for Solidity development

调用此技能进行Solidity开发

Skill("solidity-development", topic="patterns", solidity_version="0.8.24")
undefined
Skill("solidity-development", topic="patterns", solidity_version="0.8.24")
undefined

Topics Covered

涵盖主题

1. Language Features (0.8.x)

1. 语言特性(0.8.x版本)

Modern Solidity essentials:
  • Data Types: Value, reference, mappings
  • Functions: Visibility, modifiers, overloading
  • Inheritance: Diamond problem, C3 linearization
  • Custom Errors: Gas-efficient error handling
现代Solidity核心内容:
  • 数据类型:值类型、引用类型、映射
  • 函数:可见性、修饰器、重载
  • 继承:菱形问题、C3线性化
  • 自定义错误:省Gas的错误处理

2. Design Patterns

2. 设计模式

Battle-tested patterns:
  • CEI: Checks-Effects-Interactions
  • Factory: Contract deployment patterns
  • Proxy: Upgradeable contracts
  • Access Control: RBAC, Ownable
经实战验证的模式:
  • CEI:检查-效果-交互模式
  • 工厂模式:合约部署模式
  • 代理模式:可升级合约
  • 访问控制:RBAC、Ownable

3. Testing

3. 测试

Comprehensive test strategies:
  • Unit Tests: Foundry, Hardhat
  • Fuzz Testing: Property-based testing
  • Invariant Testing: System-wide properties
  • Fork Testing: Mainnet simulation
全面的测试策略:
  • 单元测试:Foundry、Hardhat
  • 模糊测试:基于属性的测试
  • 不变量测试:系统级属性验证
  • 分叉测试:主网模拟

4. Upgradability

4. 可升级性

Safe upgrade patterns:
  • UUPS: Self-upgrading proxy
  • Transparent: Admin separation
  • Beacon: Shared implementation
  • Diamond: Multi-facet
安全的升级模式:
  • UUPS:自升级代理
  • 透明代理:管理员分离
  • Beacon:共享实现
  • 钻石模式:多切面

Code Examples

代码示例

CEI Pattern

CEI模式

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract SecureVault {
    mapping(address => uint256) public balances;

    error InsufficientBalance();
    error TransferFailed();

    function withdraw(uint256 amount) external {
        // 1. CHECKS
        if (balances[msg.sender] < amount) revert InsufficientBalance();

        // 2. EFFECTS
        balances[msg.sender] -= amount;

        // 3. INTERACTIONS
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract SecureVault {
    mapping(address => uint256) public balances;

    error InsufficientBalance();
    error TransferFailed();

    function withdraw(uint256 amount) external {
        // 1. CHECKS
        if (balances[msg.sender] < amount) revert InsufficientBalance();

        // 2. EFFECTS
        balances[msg.sender] -= amount;

        // 3. INTERACTIONS
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}

Factory Pattern

工厂模式

solidity
contract TokenFactory {
    event TokenCreated(address indexed token, address indexed owner);

    function createToken(
        string memory name,
        string memory symbol
    ) external returns (address) {
        Token token = new Token(name, symbol, msg.sender);
        emit TokenCreated(address(token), msg.sender);
        return address(token);
    }
}
solidity
contract TokenFactory {
    event TokenCreated(address indexed token, address indexed owner);

    function createToken(
        string memory name,
        string memory symbol
    ) external returns (address) {
        Token token = new Token(name, symbol, msg.sender);
        emit TokenCreated(address(token), msg.sender);
        return address(token);
    }
}

Foundry Test

Foundry测试

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "forge-std/Test.sol";

contract VaultTest is Test {
    Vault vault;
    address alice = makeAddr("alice");

    function setUp() public {
        vault = new Vault();
        vm.deal(alice, 10 ether);
    }

    function test_Deposit() public {
        vm.prank(alice);
        vault.deposit{value: 1 ether}();

        assertEq(vault.balances(alice), 1 ether);
    }

    function testFuzz_Withdraw(uint256 amount) public {
        amount = bound(amount, 0.01 ether, 10 ether);

        vm.startPrank(alice);
        vault.deposit{value: amount}();
        vault.withdraw(amount);
        vm.stopPrank();

        assertEq(vault.balances(alice), 0);
    }

    function test_RevertWhen_InsufficientBalance() public {
        vm.prank(alice);
        vm.expectRevert(Vault.InsufficientBalance.selector);
        vault.withdraw(1 ether);
    }
}
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "forge-std/Test.sol";

contract VaultTest is Test {
    Vault vault;
    address alice = makeAddr("alice");

    function setUp() public {
        vault = new Vault();
        vm.deal(alice, 10 ether);
    }

    function test_Deposit() public {
        vm.prank(alice);
        vault.deposit{value: 1 ether}();

        assertEq(vault.balances(alice), 1 ether);
    }

    function testFuzz_Withdraw(uint256 amount) public {
        amount = bound(amount, 0.01 ether, 10 ether);

        vm.startPrank(alice);
        vault.deposit{value: amount}();
        vault.withdraw(amount);
        vm.stopPrank();

        assertEq(vault.balances(alice), 0);
    }

    function test_RevertWhen_InsufficientBalance() public {
        vm.prank(alice);
        vm.expectRevert(Vault.InsufficientBalance.selector);
        vault.withdraw(1 ether);
    }
}

Pattern Reference

模式参考

PatternUse CaseComplexity
CEIAll state changesLow
FactoryMultiple instancesLow
Clone (1167)Gas-efficient copiesMedium
UUPSUpgradeableMedium
DiamondUnlimited sizeHigh
模式适用场景复杂度
CEI所有状态变更
工厂模式多实例部署
Clone (1167)省Gas的合约复制
UUPS可升级合约
钻石模式无限制合约规模

Common Pitfalls

常见陷阱

PitfallIssueSolution
Stack too deep>16 variablesUse structs or helpers
Contract too large>24KBSplit into libraries
ReentrancyState after callUse CEI pattern
Missing accessAnyone can callAdd modifiers
陷阱问题解决方案
栈过深变量数量超过16个使用结构体或辅助函数
合约体积过大超过24KB拆分到库中
重入攻击调用外部合约后修改状态使用CEI模式
缺失访问控制任何人都可调用添加修饰器

Troubleshooting

问题排查

"Stack too deep"

"栈过深"

solidity
// Solution 1: Use struct
struct Params { uint256 a; uint256 b; uint256 c; }

// Solution 2: Block scoping
{ uint256 temp = x + y; }

// Solution 3: Internal function
function _helper(uint256 a) internal { }
solidity
// 解决方案1:使用结构体
struct Params { uint256 a; uint256 b; uint256 c; }

// 解决方案2:代码块作用域
{ uint256 temp = x + y; }

// 解决方案3:内部函数
function _helper(uint256 a) internal { }

"Contract size exceeds limit"

"合约体积超过限制"

bash
undefined
bash
undefined

Check contract sizes

检查合约体积

forge build --sizes
Solutions: Split into libraries, use Diamond pattern.
forge build --sizes
解决方案:拆分到库中,使用钻石模式。

Security Checklist

安全检查清单

  • CEI pattern on all withdrawals
  • Access control on admin functions
  • Input validation (zero address, bounds)
  • Reentrancy guards on external calls
  • Event emission for state changes
  • Custom errors for gas efficiency
  • 所有提现操作使用CEI模式
  • 管理员函数添加访问控制
  • 输入验证(零地址、边界值)
  • 外部调用添加重入防护
  • 状态变更时触发事件
  • 使用自定义错误以节省Gas

CLI Commands

CLI命令

bash
undefined
bash
undefined

Development workflow

开发工作流

forge init # New project forge build # Compile forge test -vvv # Run tests forge coverage # Coverage report forge fmt # Format code forge snapshot # Gas snapshot
undefined
forge init # 新建项目 forge build # 编译 forge test -vvv # 运行测试 forge coverage # 生成覆盖率报告 forge fmt # 代码格式化 forge snapshot # Gas快照
undefined

Cross-References

交叉引用

  • Bonded Agent:
    03-solidity-expert
  • Related Skills:
    ethereum-development
    ,
    smart-contract-security
  • 关联Agent
    03-solidity-expert
  • 相关技能
    ethereum-development
    ,
    smart-contract-security

Version History

版本历史

VersionDateChanges
2.0.02025-01Production-grade with Foundry, patterns
1.0.02024-12Initial release
版本日期变更
2.0.02025-01新增Foundry框架支持、设计模式的生产级内容
1.0.02024-12初始版本