Back to Rules
Security

Solidity Best Practices: Secure Smart Contracts, Gas Optimization & OpenZeppelin Patterns

Claude Directory November 29, 2025
0 copies 4 downloads

Master Solidity development with proven best practices for secure, efficient smart contracts. Implement Checks-Effects-Interactions, ReentrancyGuard, gas optimizations, and comprehensive testing using OpenZeppelin libraries.

Rule Content
## Solidity Coding Standards

Adopt clear naming conventions: use CamelCase for contract names and PascalCase for interfaces prefixed with 'I'. Always specify visibility modifiers explicitly and add detailed NatSpec comments for public/external functions.

```solidity
/// @title IERC20 Interface
/// @notice Standard ERC20 interface
interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
}

contract MyToken is IERC20 {
    // Implementation
}
```

Favor composition over deep inheritance to keep code maintainable.

## Security Patterns

Apply the Checks-Effects-Interactions (CEI) pattern to avoid reentrancy. Use OpenZeppelin's ReentrancyGuard and SafeERC20 for token handling. Prefer custom errors over strings for gas savings.

```solidity
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract Vault is ReentrancyGuard {
    using SafeERC20 for IERC20;

    error InsufficientBalance(uint256 available, uint256 required);

    function withdraw(uint256 amount) external nonReentrant {
        // Checks
        if (balance[msg.sender] < amount) revert InsufficientBalance(balance[msg.sender], amount);
        // Effects
        balance[msg.sender] -= amount;
        // Interactions
        token.safeTransfer(msg.sender, amount);
    }
}
```

Implement timelocks with OpenZeppelin's TimelockController and multisig via AccessControl for critical actions. Add Pausable for emergency pauses.

## Upgradeability & Access Control

For upgradeable contracts, use proxy patterns and secure initializer access. Leverage OpenZeppelin's AccessControl for role-based permissions.

```solidity
import "@openzeppelin/contracts/access/AccessControl.sol";

contract Governed is AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function execute(address target, bytes calldata data) external onlyRole(ADMIN_ROLE) {
        // Execution logic
    }
}
```

## Gas Optimization Techniques

Pack storage variables efficiently, use immutable for constants, and custom errors. Employ assembly sparingly with full docs. Prefer pull payments over push to prevent DoS.

```solidity
contract OptimizedStorage {
    uint128 public packed1; // Pack with uint128
    uint128 public packed2;

    uint immutable constant FEE = 100; // Set once

    error InvalidAmount();

    function process() external {
        if (msg.value == 0) revert InvalidAmount();
    }
}
```

Use view/pure modifiers correctly and OpenZeppelin's Address library for safe external calls.

## Events & State Management

Emit events for all key state changes. Design state machines for complex flows and use ERC20Votes for governance tokens.

```solidity
 event Transfer(address indexed from, address indexed to, uint256 value);
 event Paused(address account);
```

## Randomness & Oracles

Avoid blockhash/timestamp for randomness; integrate Chainlink VRF.

## Testing & Workflow

Build unit, integration, and fuzz tests with Hardhat. Aim for 100% coverage on critical paths. Run Slither/Mythril in CI/CD. Use pre-commit hooks for linting.

```solidity
// Hardhat test example
import { expect } from "chai";
import { ethers } from "hardhat";

describe("Vault", () => {
  it("should withdraw correctly", async () => {
    // Test logic
  });
});
```

Conduct audits and bug bounties. Document architecture and decisions thoroughly.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory