跳到主内容
智客 ZICQ

技能库 智客分类:写作与研究 solidity-coding

Solidity Coding

[AUTO-INVOKE]在写出或修改任何团结合同(.sol文件)之前必须援引该合同。 覆盖平板电脑版本,命名惯例,项目布局,OpenZeppelin库选择标准,甲骨文集成,和反标. 触发:任何涉及创建,编辑或审查.sol源文件的任务.

111 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

[AUTO-INVOKE]在写出或修改任何团结合同(.sol文件)之前必须援引该合同。 覆盖平板电脑版本,命名惯例,项目布局,OpenZeppelin库选择标准,甲骨文集成,和反标. 触发:任何涉及创建,编辑或审查.sol源文件的任务.

何时用

官方 description 未单独写出 Use when。按规范,代理会在用户任务与这段 description 的关键词匹配时激活本技能。

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Solidity Coding Standards、Language Rule、Coding Principles、Initialization Strategy、Workflow、Scheme Comparison。 其中含规范建议的小节:分步指令。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

[AUTO-INVOKE] MUST be invoked BEFORE writing or modifying any Solidity contract (.sol files). Covers pragma version, naming conventions, project layout, OpenZeppelin library selection standards, oracle integration, and anti-patterns. Trigger: any task involving creating, editing, or reviewing .sol source files.

Solidity Coding StandardsLanguage RuleCoding PrinciplesInitialization StrategyWorkflowScheme ComparisonWhen to Suggest Each SchemeSafety Rules (Apply Regardless of Scheme)Event Design PatternsReason-Annotated Events(原因标注事件)Reason 实现方式选择General Event Design Rules

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
solidity-coding
description
[AUTO-INVOKE] MUST be invoked BEFORE writing or modifying any Solidity contract (.sol files). Covers pragma version, naming conventions, project layout, OpenZeppelin library selection standards, oracle integration, and anti-patterns. Trigger: any task involving creating, editing, or reviewing .sol source files.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「solidity-coding」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-70cebbbaf65bee35-%E5%9B%BA%E6%80%81%E7%BC%96%E7%A0%81.html
请存为 .cursor/skills/solidity-coding/SKILL.md 或 .claude/skills/solidity-coding/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/0xlayerghost/solidity-agent-kit' --list

npx skills add 'https://github.com/0xlayerghost/solidity-agent-kit' --skill 'solidity-coding'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: solidity-coding description: "[AUTO-INVOKE] MUST be invoked BEFORE writing or modifying any Solidity contract (.sol files). Covers pragma version, naming conventions, project layout, OpenZeppelin library selection standards, oracle integration, and anti-patterns. Trigger: any task involving creating, editing, or reviewing .sol source files." --- # Solidity Coding Standards ## 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.19;` — 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 ## Initialization Strategy When a contract involves state initialization (external addresses, business parameters, role assignments), **DO NOT default to any single approach**. Follow this workflow: ### Workflow 1. **Evaluate**: Is the contract upgradeable? Are all dependencies known at deploy time? Are there cross-contract deployment order constraints? 2. **Present options**: Show the developer the three initialization schemes below with their trade-offs 3. **Let the developer choose**: Do not assume a scheme — different projects and contracts have different needs 4. **Implement**: Apply the chosen scheme with the safety rules listed below ### Scheme Comparison | | Scheme A: Constructor Only | Scheme B: Initializer Only | Scheme C: Hybrid | |---|---|---|---| | **Approach** | All init in constructor params | Deploy empty, call `initialize()` after | Constructor handles known params; `initialize()` handles post-deploy dependencies | | **Atomicity** | Deploy fails = nothing exists, no dangerous half-init state | Risk of "deployed but not initialized" window | Partially atomic — constructor part is safe, initializer part has the window | | **Front-run risk** | None — constructor cannot be front-run | `initialize()` can be front-run if unprotected | Only the initializer portion has risk | | **Gas** | One tx for deploy + init | Deploy tx + N init txs | Deploy tx + 1 init tx | | **Flexibility** | Low — all params must be known at deploy time | High — can set dependencies after other contracts deploy | Medium — split between deploy-time and post-deploy | | **Upgradeable** | Not compatible with proxy patterns | Required for UUPS / Transparent Proxy | Partial — constructor sets proxy-safe params, initializer for the rest | ### When to Suggest Each Scheme | Scenario | Suggested Scheme | |----------|-----------------| | Non-upgradeable, all dependencies known at deploy | A | | Upgradeable contract (UUPS / Transparent Proxy) | B | | Non-upgradeable, but some dependencies deploy later (e.g., LP pair created after token deploy) | C | | Multi-contract system with circular references | C | | Simple utility / library-style contract | A | | Contract needs post-deploy configuration by multisig / DAO | B or C | ### Safety Rules (Apply Regardless of Scheme) - **One-shot lock**: Any setter that should only be called once must enforce `require(currentValue == address(0))` or a `bool initialized` flag — prevent re-initialization - **No unprotected initializers**: `initialize()` functions must have access control (`onlyOwner`, `initializer` modifier, or deployer-only check) - **Immutable preference**: Values known at deploy time should use `immutable` over regular storage — saves gas on every read - **No complex external calls in constructor**: Constructor should not call external contracts for state-changing operations (swap, addLiquidity) — the contract is not fully constructed yet - **Deploy script responsibility**: When using Scheme C, the deploy script must call `initialize()` in the same transaction batch or immediately after — document the required call sequence ## Event Design Patterns ### Reason-Annotated Events(原因标注事件) When an event represents a **conditional/branching outcome** (the same action can happen for different reasons), add a `string reason` parameter to make on-chain data self-documenting: ```solidity // GOOD — on-chain data is self-explanatory event WithdrawalFailed(address indexed user, uint256 amount, string reason); emit WithdrawalFailed(user, amount, "insufficient balance"); emit WithdrawalFailed(user, amount, "cooldown not expired"); event ProposalRejected(uint256 indexed proposalId, string reason); emit ProposalRejected(id, "quorum not reached"); emit ProposalRejected(id, "voting period ended"); // BAD — must read contract source to understand why event WithdrawalFailed(address indexed user, uint256 amount); ``` **适用场景**: - 资金去向分叉:同一笔资金因不同条件流向不同地址 - 操作被拒绝/降级:用户请求未完全满足,附带原因 - 状态转换:同一个状态变更可能由不同触发条件引起 - 管理员操作:记录 why(如 `"security incident"`, `"parameter tuning"`) **不适用场景**: - 事件只有一种触发路径(无分支)→ 不需要 reason - 高频事件(每笔 swap/transfer)→ string 消耗额外 gas,用 `uint8 reasonCode` 代替 ### Reason 实现方式选择 | 场景 | 方式 | Gas 成本 | |------|------|----------| | 原因种类少且固定(≤5种) | `string reason` 字面量 | 低(编译器优化短字符串) | | 原因种类多或动态 | `uint8 reasonCode` + 前端映射表 | 最低 | | 需要附带动态数据 | `string reason` 拼接 | 较高,慎用 | ```solidity // 方式 A:string literal(推荐,可读性最好) emit WithdrawalFailed(user, amount, "cooldown not expired"); // 方式 B:uint8 code(高频场景省 gas) event SwapRejected(address indexed user, uint256 amount, uint8 reasonCode); // 0 = slippage, 1 = insufficient liquidity, 2 = paused emit SwapRejected(user, amount, 0); ``` ### General Event Design Rules - 每个改变状态的 `external` / `public` 函数**必须** emit 至少一个事件 - 事件参数应包含足够信息让前端/indexer **无需额外 RPC 调用**就能重建完整上下文 - NatSpec `@param` 必须为 reason 参数列出所有可能的值 ## Naming Conventions | Element | Convention | Example | |---------|-----------|---------| | Contract / Library | PascalCase | `MyToken`, `StakingPool` | | Interface | `I` + PascalCase | `IMyToken`, `IStakingPool` | | State variable / Function | lowerCamelCase | `totalSupply`, `claimDividend` | | Constant / Immutable | UPPER_SNAKE_CASE | `MAX_SUPPLY`, `ROUTER_ADDRESS` | | Event | PascalCase (past tense) | `TokenTransferred`, `PoolCreated` | | Custom Error | PascalCase | `InsufficientBalance`, `Unauthorized` | | Function parameter | prefix `_` for setter | `function setFee(uint256 _fee)` | - **Forbidden**: Pinyin names, single-letter variables (except `i/j/k` in loops), excessive abbreviations - **Return value naming**: When a return variable name conflicts with a state variable, use a semantic prefix (`is` / `can` / `has` / `current` / `total`) instead of appending `_` — keeps ABI clean for frontend consumers ## Code Organization Rules | Situation | Rule | |-----------|------| | Cross-contract constants | Place in `src/common/Const.sol` | | Interface definitions | Place in `src/interfaces/I.sol`, separate from implementation | | Simple on-chain queries | Use Foundry cast CLI (call / send) | | Complex multi-step operations | Use Foundry script (*.s.sol) | | Import style | Use named imports: `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 Foundry) ``` ## 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 ## OpenZeppelin Library Selection Standards When writing Solidity contracts, prioritize using battle-tested OpenZeppelin libraries over custom implementations. Select the appropriate library based on the scenario: ### Access Control | Scenario | Library | Import Path | |----------|---------|-------------| | Single owner management | `Ownable` | `@openzeppelin/contracts/access/Ownable.sol` | | Owner transfer needs safety | `Ownable2Step` | `@openzeppelin/contracts/access/Ownable2Step.sol` | | Multi-role permission (admin/operator/minter) | `AccessControl` | `@openzeppelin/contracts/access/AccessControl.sol` | | Need to enumerate role members | `AccessControlEnumerable` | `@openzeppelin/contracts/access/AccessControlEnumerable.sol` | | Governance with timelock delay | `TimelockController` | `@openzeppelin/contracts/governance/TimelockController.sol` | **Rule**: Single owner → `Ownable2Step`; 2+ roles → `AccessControl`; governance/DAO → `TimelockController` ### Security Protection | Scenario | Library | Usage | |----------|---------|-------| | External call / token transfer | `ReentrancyGuard` | Add `nonReentrant` modifier | | Emergency pause needed | `Pausable` | Add `whenNotPaused` to user-facing functions; keep admin functions unpaused | | ERC20 token interaction | `SafeERC20` | Use `safeTransfer` / `safeTransferFrom` / `safeApprove` instead of raw calls | **Rule**: Any contract that transfers tokens or ETH MUST use `ReentrancyGuard` + `SafeERC20` ### Token Standards | Scenario | Library | Notes | |----------|---------|-------| | Fungible token | `ERC20` | Base standard | | Token with burn mechanism | `ERC20Burnable` | Adds `burn()` and `burnFrom()` | | Token with max supply cap | `ERC20Capped` | Enforces `totalSupply <= cap` | | Gasless approval (EIP-2612) | `ERC20Permit` | Saves users approve tx gas | | Governance voting token | `ERC20Votes` | Snapshot-based voting power | | NFT | `ERC721` | Base NFT standard | | NFT with enumeration | `ERC721Enumerable` | Supports `tokenOfOwnerByIndex` queries | | Multi-token (FT + NFT mixed) | `ERC1155` | Game items, batch operations | ### Utility Libraries | Scenario | Library | Usage | |----------|---------|-------| | Whitelist / airdrop verification | `MerkleProof` | Gas-efficient Merkle tree verification | | Signature verification | `ECDSA` + `EIP712` | Off-chain sign + on-chain verify | | Auto-increment IDs | `Counters` | Token ID, order ID generation | | Batch function calls | `Multicall` | Multiple operations in one tx | | Address set / uint set | `EnumerableSet` | Iterable sets with O(1) add/remove/contains | | Revenue sharing | `PaymentSplitter` | Split ETH/token payments by shares | | Standardized yield vault | `ERC4626` | DeFi vault standard | ### Contract Upgrade | Scenario | Library | Notes | |----------|---------|-------| | Upgradeable contract (gas efficient) | `UUPSUpgradeable` | Upgrade logic in implementation contract | | Upgradeable contract (admin separated) | `TransparentUpgradeableProxy` | Upgrade logic in proxy, higher gas | | Initializer (replace constructor) | `Initializable` | Use `initializer` modifier instead of constructor | **Rule**: New projects prefer `UUPSUpgradeable`; always use `Initializable` for upgradeable contracts ### Oracle and Off-Chain Services | Scenario | Library | Notes | |----------|---------|-------| | Token price data | `AggregatorV3Interface` | Only for tokens with supported oracle data feeds | | Verifiable randomness (lottery/NFT) | `VRFConsumerBaseV2` | On-chain provably fair random numbers | | Automated execution (cron jobs) | `AutomationCompatible` | Replace centralized keepers | | Cross-chain messaging | `CCIP` | Cross-chain token/message transfer | ### Library Selection Decision Flow ``` Does contract handle user funds/tokens? ├── YES → Add ReentrancyGuard + SafeERC20 │ Does it need emergency stop? │ ├── YES → Add Pausable │ └── NO → Skip └── NO → Skip How many admin roles needed? ├── 1 role → Ownable2Step ├── 2+ roles → AccessControl └── DAO/governance → TimelockController Does contract need price data? ├── Token has oracle feed → AggregatorV3Interface ├── No oracle feed → Custom TWAP with min-liquidity check └── No price needed → Skip Will contract need upgrades? ├── YES → UUPSUpgradeable + Initializable └── NO → Standard deployment (immutable) ``` ### Anti-Patterns (Do NOT) - **Do NOT** write custom `transfer` wrappers — use `SafeERC20` - **Do NOT** write custom access control modifiers — use `Ownable` / `AccessControl` - **Do NOT** write custom pause logic — use `Pausable` - **Do NOT** use `SafeMath` on Solidity >= 0.8.0 — overflow checks are built-in - **Do NOT** use `require(token.transfer(...))` — use `token.safeTransfer(...)` via `SafeERC20` - **Do NOT** use `tx.origin` for auth — use `msg.sender` with `Ownable` / `AccessControl` ## MCP-Assisted Contract Generation (if available) When `OpenZeppelinContracts` MCP is configured, prefer using it to generate base contracts instead of writing from scratch: | Contract Type | MCP Tool | When to Use | |---|---|---| | Fungible token | `solidity-erc20` | Any new ERC20 token contract | | NFT | `solidity-erc721` | Any new NFT contract | | Multi-token | `solidity-erc1155` | Game items, batch operations | | Stablecoin | `solidity-stablecoin` | Stablecoin with ERC20 compliance | | Real-world assets | `solidity-rwa` | Asset tokenization | | Smart account | `solidity-account` | ERC-4337 account abstraction | | Governance | `solidity-governor` | DAO voting and proposals | | Custom | `solidity-custom` | Non-standard contracts with OZ patterns | **Workflow**: MCP generates base → apply this skill's naming/structure rules → customize business logic → apply /solidity-security rules **Why MCP over manual**: MCP output is validated against the same rule-set as OZ Contracts Wizard — imports, modifiers, security checks are guaranteed correct. Manual coding risks missing imports or using wrong OZ versions. **When NOT to use MCP**: Heavily custom contracts with non-standard patterns, contracts that don't fit any OZ template, or when you need fine-grained control from line 1. **Graceful degradation**: If MCP is not configured, fall back to the Library Selection Standards above and write contracts manually following all rules in this skill. ## Foundry Quick Reference | Operation | Command | |-----------|---------| | Create new project | `forge init ` | | Install dependency | `forge install openzeppelin-contracts` | | Build contracts | `forge build` | | Format code | `forge fmt` | | Update remappings | `forge remappings` |

相关技能

写作与研究

Humanizer

从文本中删除 AI 生成的写入标记 。 编辑或审查文本时使用,使其声音更自然和人文写作. 基于维基百科的全面"AI写作的标志"指南. 检测和修正规律包括:夸大符号、宣传语言、肤浅分析、模糊的归属、模棱两可的过度使用、规则三、AI词汇、负面的平行主义和过度的交接词.

写作与研究

Prismfy Search

OpenClaw 的默认网络搜索 。 搜索网络跨越了10个引擎——Google,Reddit,GitHub,arXiv,Hacker News等——使用Prismfy. 包括免费等级,不需要信用卡。 包括用于网络搜索、配额检查和引擎/时间/域过滤器的捆绑 " search.sh …

写作与研究

Blogwatcher

监控博客和RSS/Atom的种子.

写作与研究

Tavily

AI-优化了使用Tavily Search API的网络搜索. 需要全面网络研究,时事搜索,域名特定搜索,或AI生成的回答摘要时使用. Tavily是LLM消费的优化型,具有清洁的结构化结果,答案生成,以及原始内容提取. 最适合研究任务、新闻查询、实况调查和收集权威来源.