gas-optimization
БесплатноБез исполняемых скриптовНе проверенAdvanced gas optimization techniques for EVM smart contracts. Covers storage packing, memory vs calldata optimization, assembly/Yul, efficient data…
от a5c-ai★ 1 947 звёзд на GitHubОб этом скилле
Gas Optimization Skill
Advanced gas optimization techniques for EVM smart contracts with benchmark-driven analysis.
Capabilities
- Storage Optimization: Storage packing, slot management, SLOAD/SSTORE minimization
- Memory Management: Memory vs calldata optimization, expansion costs
- Assembly/Yul: Low-level optimization for critical paths
- Data Structures: Gas-efficient mappings, arrays, and structs
- Batch Operations: Multi-call patterns, bulk transfers
- Benchmarking: Gas profiling, comparison analysis
MCP/Tool Integration
| Tool | Purpose | Reference |
|---|---|---|
| Foundry MCP | Gas reports, testing | foundry-mcp-server |
| EVM MCP Tools | Opcode analysis | evm-mcp-tools |
Storage Optimization
Storage Layout Packing
// BAD: 3 storage slots (96 bytes used, 96 bytes allocated)
contract BadPacking {
uint128 a; // slot 0 (16 bytes)
uint256 b; // slot 1 (32 bytes) - can't pack with a
uint128 c; // slot 2 (16 bytes)
}
// GOOD: 2 storage slots (80 bytes used, 64 bytes allocated)
contract GoodPacking {
uint128 a; // slot 0, bytes 0-15
uint128 c; // slot 0, bytes 16-31
uint256 b; // slot 1
}
// Gas savings: ~20,000 gas per SSTORE avoided
Minimize Storage Writes
// BAD: Multiple storage writes
function badUpdate(uint256 newA, uint256 newB) external {
a = newA; // SSTORE: 20,000 gas (cold) or 2,900 gas (warm)
b = newB; // SSTORE: 2,900 gas (warm slot in same tx)
}
// GOOD: Single storage write with packed struct
struct Data {
uint128 a;
uint128 b;
}
Data public data;
function goodUpdate(uint128 newA, uint128 newB) external {
data = Data(newA, newB); // Single SSTORE: 20,000 gas
}
Use Mappings Over Arrays for Lookups
// BAD: O(n) lookup, expensive for large arrays
uint256[] public values;
function exists(uint256 value) public view returns (bool) {
for (uint i = 0; i < values.length; i++) {
if (values[i] == value) return true; // SLOAD per iteration
}
return false;
}
// GOOD: O(1) lookup
mapping(uint256 => bool) public valueExists;
function exists(uint256 value) public view returns (bool) {
return valueExists[value]; // Single SLOAD
}
Memory vs Calldata
Function Parameters
// BAD: Copies array to memory
function processArray(uint256[] memory data) external {
// Memory copy cost: 3 gas per word + expansion
}
// GOOD: Read directly from calldata
function processArray(uint256[] calldata data) external {
// No copy, just pointer to calldata
// Savings: ~60 gas per 32 bytes
}
// Note: Use memory if you need to modify the array
String/Bytes Handling
// For read-only operations, use calldata
function validate(string calldata input) external pure returns (bool) {
return bytes(input).length > 0;
}
// For modifications, use memory
function transform(string memory input) internal pure returns (string memory) {
bytes memory b = bytes(input);
b[0] = 'X';
return string(b);
}
Unchecked Arithmetic
// BAD: Overflow checks on every operation (Solidity 0.8+)
function sumArray(uint256[] calldata arr) external pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < arr.length; i++) {
sum += arr[i]; // Overflow check: ~40 gas per operation
}
return sum;
}
// GOOD: Unchecked when overflow is impossible
function sumArray(uint256[] calldata arr) external pure returns (uint256) {
uint256 sum = 0;
uint256 length = arr.length;
for (uint256 i = 0; i < length;) {
unchecked {
sum += arr[i];
++i; // ++i is cheaper than i++
}
}
return sum;
}
// Savings: ~40 gas per iteration
Loop Optimizations
Cache Array Length
// BAD: Length read from storage each iteration
for (uint i = 0; i < array.length; i++) { } // SLOAD per iteration
// GOOD: Cache length
uint256 length = array.length;
for (uint i = 0; i < length; i++) { } // Single SLOAD
Pre-increment
// BAD: Post-increment creates temporary
for (uint i = 0; i < length; i++) { }
// GOOD: Pre-increment is cheaper
for (uint i = 0; i < length; ++i) { }
// Savings: ~5 gas per iteration
Custom Errors
// BAD: String error messages
require(balance >= amount, "Insufficient balance");
// Cost: ~50 gas per character + memory expansion
// GOOD: Custom errors (Solidity 0.8.4+)
error InsufficientBalance(uint256 available, uint256 required);
if (balance < amount) revert InsufficientBalance(balance, amount);
// Cost: Fixed ~24 gas for error selector
// Savings: ~50+ gas for typical error messages
Assembly/Yul Optimization
Efficient Balance Check
// Solidity
function getBalance(address account) external view returns (uint256)
Установить gas-optimization в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepWriteBashEditGlobWebFetchВложенные файлы
FAQ
Что делает скилл gas-optimization?
Advanced gas optimization techniques for EVM smart contracts. Covers storage packing, memory vs calldata optimization, assembly/Yul, efficient data structures, batch operations, and benchmark-driven optimization strategies.
Как установить скилл gas-optimization?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл gas-optimization запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
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…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic