
solidity-gas-optimization
Solidity smart contract gas optimization guidelines based on RareSkills. Use when writing, reviewing, or auditing Solidity code. Triggers on tasks involving smart contracts, EVM development, gas optimization, or Solidity best practices.
- Installs
- 564
- Last 24h
- +18
- Trending rank
- #6344
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/pseudoyu/agent-skills --skill solidity-gas-optimization- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads solidity-gas-optimization automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Solidity Gas Optimization
Overview
Comprehensive gas optimization guide for Solidity smart contracts, containing 80+ techniques across 8 categories. Based on the RareSkills Book of Gas Optimization. Rules are prioritized by impact and safety.
When to Apply
Reference these guidelines when:
- Writing new Solidity smart contracts
- Reviewing or auditing existing contracts
- Optimizing gas costs for deployment or execution
- Refactoring contract storage layouts
- Implementing cross-contract interactions
- Choosing between design patterns (ERC721 vs ERC1155, etc.)
Priority-Ordered Categories
| Priority | Category | Impact | Risk |
|---|---|---|---|
| 1 | Storage Optimization | CRITICAL | LOW |
| 2 | Deployment Optimization | HIGH | LOW |
| 3 | Calldata Optimization | HIGH | LOW |
| 4 | Design Patterns | HIGH | MEDIUM |
| 5 | Cross-Contract Calls | MEDIUM-HIGH | MEDIUM |
| 6 | Compiler Optimizations | MEDIUM | LOW |
| 7 | Assembly Tricks | MEDIUM | HIGH |
| 8 | Dangerous Techniques | LOW | CRITICAL |
Quick Reference
Critical: Storage Optimization (Apply First)
Zero-to-One Writes:
- Avoid zero-to-one storage writes (costs 22,100 gas)
- Use 1/2 instead of 0/1 for boolean-like values
- Keep minimum balances in ERC20 contracts
Variable Packing:
// Bad: 3 slots
struct Unpacked {
uint64 time; // slot 1
uint256 amount; // slot 2
address user; // slot 3
}
// Good: 2 slots
struct Packed {
uint64 time; // slot 1 (with address)
address user; // slot 1
uint256 amount; // slot 2
}
Caching:
// Bad: reads storage twice
function increment() public {
require(count < 10);
count = count + 1;
}
// Good: reads storage once
function increment() public {
uint256 _count = count;
require(_count < 10);
count = _count + 1;
}
Constants & Immutables:
uint256 constant MAX = 100; // No storage slot
address immutable owner; // Set in constructor, no storage
High: Deployment Optimization
Custom Errors:
// Bad: ~64+ bytes
require(amount <= limit, "Amount exceeds limit");
// Good: ~4 bytes
error ExceedsLimit();
if (amount > limit) revert ExceedsLimit();
Payable Constructors:
// Saves ~200 gas on deployment
constructor() payable {}
Clone Patterns:
- Use EIP-1167 minimal proxies for repeated deployments
- Use UUPS over Transparent Proxy for upgradeable contracts
High: Calldata Optimization
Calldata vs Memory:
// Bad: copies to memory
function process(bytes memory data) external {}
// Good: reads directly from calldata
function process(bytes calldata data) external {}
Avoid Signed Integers:
- Small negative numbers are expensive (e.g., -1 = 0xffff...)
- Use unsigned integers in function parameters
High: Design Patterns
Token Standards:
- Prefer ERC1155 over ERC721 for NFTs (no balanceOf overhead)
- Consider consolidating multiple ERC20s into one ERC1155
Signature vs Merkle:
- Prefer ECDSA signatures over Merkle trees for allowlists
- Implement ERC20Permit for approve + transfer in one tx
Alternative Libraries:
- Consider Solmate/Solady over OpenZeppelin for gas efficiency
Medium-High: Cross-Contract Calls
Reduce Interactions:
- Use ERC1363 transferAndCall instead of approve + transferFrom
- Implement multicall for batching operations
- Cache external call results (e.g., Chainlink oracles)
Access Lists:
- Use ERC2930 access list transactions to pre-warm storage
Medium: Compiler Optimizations
Loop Patterns:
// Good: unchecked increment, cached length
uint256 len = arr.length;
for (uint256 i; i < len; ) {
// logic
unchecked { ++i; }
}
Named Returns:
// More efficient bytecode
function calc(uint256 x) pure returns (uint256 result) {
result = x * 2;
}
Bitshifting:
// Cheaper: 3 gas
x << 1 // x * 2
x >> 2 // x / 4
// Expensive: 5 gas
x * 2
x / 4
Short-Circuit Booleans:
- Place likely-to-fail conditions first in
&& - Place likely-to-succeed conditions first in
||
Medium: Assembly (Use Carefully)
Efficient Checks:
// Check address(0) with assembly
assembly {
if iszero(caller()) { revert(0, 0) }
}
// Even/odd check
x & 1 // instead of x % 2
Memory Reuse:
- Reuse scratch space (0x00-0x40) for small operations
- Avoid memory expansion in loops
Avoid: Dangerous Techniques
These are unsafe for production:
- Making all functions payable
- Ignoring send() return values
- Using gasleft() for branching
- Manipulating block.number in tests
Outdated Patterns
These no longer apply in modern Solidity:
- "external is cheaper than public" - No longer true
- "!= 0 is cheaper than > 0" - Changed around 0.8.12
References
Full documentation with code examples:
references/solidity-gas-guidelines.md- Complete guidereferences/rules/- Individual patterns by category
To look up specific patterns:
grep -l "storage" references/rules/
grep -l "assembly" references/rules/
grep -l "struct" references/rules/
Rule Categories in references/rules/
storage-*- Storage optimization patternsdeploy-*- Deployment gas savingscalldata-*- Calldata optimizationdesign-*- Design pattern choicescrosscall-*- Cross-contract call optimizationcompiler-*- Compiler optimization patternsassembly-*- Low-level assembly tricks
Key Principles
- Always Benchmark - Compiler behavior varies by context and version
- Balance Readability - Not all optimizations are worth code complexity
- Test Both Approaches - Counterintuitive optimizations sometimes increase costs
- Consider
--via-ir- Modern compiler option may obsolete some tricks - Use Alternative Libraries - Solmate/Solady often beat OpenZeppelin on gas
FAQ
What does the solidity-gas-optimization skill do?
Solidity smart contract gas optimization guidelines based on RareSkills. Use when writing, reviewing, or auditing Solidity code. Triggers on tasks involving smart contracts, EVM development, gas optimization, or Solidity best practices.
How do I install solidity-gas-optimization?
Run npx skills add https://github.com/pseudoyu/agent-skills --skill solidity-gas-optimization in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/solidity-gas-optimization/ (personal) or .claude/skills/solidity-gas-optimization/ (project).
Which AI agents can use solidity-gas-optimization?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is solidity-gas-optimization safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains solidity-gas-optimization?
It is published by pseudoyu in pseudoyu/agent-skills. It has 564 recorded installs.
Popular ai & agents skills
google-agents-cli-publish
google/agents-cli
This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).
google-agents-cli-eval
google/agents-cli
This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).
skill-creator
anthropics/skills
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
codex-pet
prime-skills/runcomfy-agent-skills
Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.
full-output-enforcement
leonxlnx/taste-skill
Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.
executing-plans
obra/superpowers
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available