0xlayerghost/solidity-agent-kit/solidity-coding

Claude Code and agent skill by 0xlayerghost/solidity-agent-kit

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

[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.

Install

npx vskill@latest install 0xlayerghost/solidity-agent-kit/solidity-coding

SKILL.md

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

  • Compiler: Use solc 0.8.24 and pragma solidity ^0.8.24; consistently across the project
  • Dependencies: Use OpenZeppelin Contracts 5.0.2 and its 5.x APIs/import paths; manage imports with the project's Foundry configuration
  • 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 OnlyScheme B: Initializer OnlyScheme C: Hybrid
ApproachAll init in constructor paramsDeploy empty, call initialize() afterConstructor handles known params; initialize() handles post-deploy dependencies
AtomicityDeploy fails = nothing exists, no dangerous half-init stateRisk of "deployed but not initialized" windowPartially atomic — constructor part is safe, initializer part has the window
Front-run riskNone — constructor cannot be front-runinitialize() can be front-run if unprotectedOnly the initializer portion has risk
GasOne tx for deploy + initDeploy tx + N init txsDeploy tx + 1 init tx
FlexibilityLow — all params must be known at deploy timeHigh — can set dependencies after other contracts deployMedium — split between deploy-time and post-deploy
UpgradeableNot compatible with proxy patternsRequired for UUPS / Transparent ProxyPartial — constructor sets proxy-safe params, initializer for the rest
When to Suggest Each Scheme
ScenarioSuggested Scheme
Non-upgradeable, all dependencies known at deployA
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 referencesC
Simple utility / library-style contractA
Contract needs post-deploy configuration by multisig / DAOB 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

ElementConventionExample
Contract / LibraryPascalCaseMyToken, StakingPool
InterfaceI + PascalCaseIMyToken, IStakingPool
State variable / FunctionlowerCamelCasetotalSupply, claimDividend
Constant / ImmutableUPPER_SNAKE_CASEMAX_SUPPLY, ROUTER_ADDRESS
EventPascalCase (past tense)TokenTransferred, PoolCreated
Custom ErrorPascalCaseInsufficientBalance, Unauthorized
Function parameterprefix _ for setterfunction 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

SituationRule
Cross-contract constantsPlace in src/common/Const.sol
Interface definitionsPlace in src/interfaces/I<Name>.sol, separate from implementation
Shared stateful behaviorPlace in src/abstract/<Name>.sol and inherit it instead of copying the implementation
Simple on-chain queriesUse Foundry cast CLI (call / send)
Complex multi-step operationsUse Foundry script (*.s.sol)
Import styleUse named imports: import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
Shared Administrative Functions

When the same administrative operation is needed by multiple contracts, keep one canonical function name, parameter order, event, errors, NatSpec, and implementation. Search the repository before adding a new variant.

Use a shared abstract contract for stateful behavior or modifiers, an interface when external consumers need a stable ABI, and a library only for stateless logic. Business contracts MUST inherit the shared implementation instead of copying it.

For the project's canonical owner-controlled asset recovery function and inheritance rules, read references/shared-contract-behaviors.md. The project policy intentionally treats the owner as the highest authority and permits recovery of every ERC20 token and native currency held by the contract.

Complex Function Refactoring

When a function coordinates multiple business stages, mixes validation with several state changes or external calls, or approaches compiler stack limits, read references/complex-function-refactoring.md before modifying it.

Do not split small functions merely to increase function count. Preserve the external ABI, execution order, revert behavior, state-transition ordering, emitted events, and fund-flow invariants unless the user explicitly requests a behavioral change.

Project Directory Structure

src/ — Contract source code
interfaces/ — Interface definitions (I*.sol)
abstract/ — Shared stateful base contracts (AssetRescue.sol, etc.)
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
ScenarioLibraryImport Path
Single owner managementOwnable@openzeppelin/contracts/access/Ownable.sol
Owner transfer needs safetyOwnable2Step@openzeppelin/contracts/access/Ownable2Step.sol
Multi-role permission (admin/operator/minter)AccessControl@openzeppelin/contracts/access/AccessControl.sol
Need to enumerate role membersAccessControlEnumerable@openzeppelin/contracts/access/AccessControlEnumerable.sol
Governance with timelock delayTimelockController@openzeppelin/contracts/governance/TimelockController.sol
Ownership Model Selection

For a single-owner contract, the developer MUST choose the ownership model before code generation:

ChoiceBehaviorUse When
OwnableOwnership transfer completes in one transactionSimplicity and immediate transfer are explicitly preferred
Ownable2StepNew owner must call acceptOwnership()Protection against transferring ownership to the wrong address is preferred

Do not silently force Ownable2Step. If the project has no recorded choice, present both options and let the developer choose. Once selected, use that model consistently across the project, including shared base contracts, deployment scripts, tests, and ownership-transfer commands. Generate the selected inheritance and imports from the start; do not generate Ownable2Step and leave the developer to replace it manually.

Rule: 1 role → developer chooses Ownable or Ownable2Step; 2+ roles → AccessControl; governance/DAO → TimelockController

Security Protection

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
1
7-day trend score
3

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 24 Mar 2026, 8 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/0xlayerghost/solidity-agent-kit/solidity-coding/badge)](https://verified-skill.com/skills/0xlayerghost/solidity-agent-kit/solidity-coding)

Something wrong with this skill or its page? Tell us.