Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

gas-optimization-foundry

БесплатноБез исполняемых скриптовНе проверен

Use when measuring or reducing gas in a Foundry project. Enforces a measurement-first workflow with forge snapshot / forge snapshot --diff / forge test…

idchain-worldот idchain-world★ 19 звёзд на GitHub

Об этом скилле

Gas Optimization with Foundry

You are reducing gas on a Solidity contract. Gas is a real cost paid by real users; it is worth spending time to bring it down. But every "optimization" in Solidity folklore either:

  • Works, measurably, and is worth the code complexity cost.
  • Worked on solc 0.6 but the modern optimizer already does it.
  • Never worked and is cargo cult.

This skill makes you prove which category you are in before you change any code.

The Iron Laws

  1. NO OPTIMIZATION WITHOUT A BEFORE-AND-AFTER SNAPSHOT. Every gas change lands with a forge snapshot --diff in the PR. A commit message that says "optimize loop" without a number is rejected. Exact format: quote the before, the after, and the delta.
  2. NO OPTIMIZATION THAT HURTS READABILITY WITHOUT A HOT-PATH JUSTIFICATION. A cryptic trick saving 50 gas in a function called once per deploy is negative value. A cryptic trick saving 5,000 gas in a function called per swap is the job. Name the hot path in the comment.
  3. NO INLINE YUL FOR PERFORMANCE UNTIL THE SOLIDITY VERSION HAS BEEN MEASURED. The optimizer is smarter than it used to be. Write the Solidity version first, forge snapshot, then decide if yul is worth the maintenance burden.
  4. NO MICRO-OPTIMIZATION BEFORE CORRECTNESS. forge test must pass at every commit in the gas-optimization branch. If you are chasing gas numbers with red tests, stop.
  5. ALWAYS RE-RUN THE WHOLE SUITE, NOT JUST THE TARGETED TEST. Gas changes in one function ripple through shared code paths. forge snapshot runs everything and catches regressions elsewhere.

The measurement-first workflow

1. Baseline       → forge snapshot  (saves .gas-snapshot)
2. Change         → edit code, forge test passes
3. Measure        → forge snapshot --diff
4. Keep or revert → paste diff in PR or revert

Every optimization follows this loop. No loop, no optimization.

forge snapshot

forge snapshot

Writes .gas-snapshot with one line per test: testName() (gas: 123456). Commit this file. It is your baseline.

forge snapshot --diff

forge snapshot --diff

Shows the delta against the committed .gas-snapshot. Positive numbers (red) are regressions. Negative numbers (green) are wins.

forge snapshot --check

forge snapshot --check

Exits non-zero if any test's gas increased beyond the tolerance. Use in CI to block silent regressions.

forge test --gas-report

forge test --gas-report

Per-function gas table (min / avg / median / max) across all tests. Use when you want to know which function is expensive, not just which test is expensive. (Source: https://getfoundry.sh/forge/gas-reports)

Verbosity levels for traces

Flag Shows
-v Test pass/fail lines. Default.
-vv Logs from console2.log.
-vvv Stack traces for failing tests.
-vvvv Full call traces, including gas used per call.
-vvvvv Setup call traces too.

Read -vvvv traces when you want to see which call in a sequence is the expensive one. Don't guess.

Real optimizations

The list below is roughly ordered by effect size. Measure before and after.

1. Struct packing

Before (three slots):

struct Position {
    uint256 collateral;
    uint128 lastUpdate;
    address owner;
}

After (two slots):

struct Position {
    uint128 collateral;       // uint128 is plenty for ETH-scale amounts
    uint128 lastUpdate;       // seconds since epoch, fits in uint64 but uint128 pads to slot
    address owner;            // 20 bytes, slot 1 alongside a uint64 if we had one
}

Saves one SSTORE per mutation (~20,000 gas on first write, ~2,900 on update).

Rule: adjacent storage variables that together fit in 32 bytes go in the same slot. Put them next to each other in the declaration — the compiler does not reorder.

2. calldata over memory for external function array and bytes parameters

// External function, caller passes an array. Mark calldata.
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts)
    external
{ ... }

memory forces a copy from calldata to memory. calldata reads directly from calldata. Saves roughly 3 * length gas plus a chunk of static overhead.

Only use memory when you need to mutate the array inside the function.

3. Custom errors over require-strings

Custom errors encode as a 4-byte selector; require-strings encode as a length-prefixed string. The selector path saves bytecode (cheaper deploy) and runtime gas when the revert fires (less data to return).

See solidity-style-modern for the rule; the gas win is the reason.

4. immutable over storage reads in hot paths

Immutables are embedded into the bytecode at deploy time. Reading one is a PUSH, not an SLOAD (2100 gas cold, 100 warm).

// DO
address public immutable i_owner;

constructor(address owner_) {
    i_own
Полный SKILL.md на GitHub

Установить gas-optimization-foundry в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл gas-optimization-foundry?

Use when measuring or reducing gas in a Foundry project. Enforces a measurement-first workflow with forge snapshot / forge snapshot --diff / forge test --gas-report / call traces at -vvvv, and lists the real wins (struct packing, calldata, custom errors, immutable, caching storage) vs the anti-patterns (++i micro-opts on 0.8.22+, unmeasured yul, readability-destroying tricks).

Как установить скилл gas-optimization-foundry?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл gas-optimization-foundry запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить gas-optimization-foundry с