Skip to main content

Claude/ChatGPT Prompt for Solidity Gas Optimization

Cut Solidity gas with storage packing, calldata tricks, loop and custom-error optimizations, batch operations, and Foundry gas benchmarks.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Optimize gas consumption for a ERC-20 token with staking and rewards distribution Solidity contract currently using ~150,000 gas per typical transaction on Ethereum mainnet where gas is expensive. The contract has 12 external functions and 8 mappings and 15 value types storage variables. Optimize: 1) Storage optimization: analyze current storage layout and repack variables — group lastUpdateTime (uint40), rewardRate (uint96), totalStaked (uint128) — currently each in separate slots into single slots (uint128+uint128, multiple bool/uint8), replace bool arrays with bitmaps using replace mapping(uint256 => bool) hasClaimedEpoch with a uint256 bitmap per user, and convert supported token list (small, needs iteration) from mapping to array where enumeration is needed. 2) Calldata vs memory: change stake(address[] memory tokens, uint256[] memory amounts) function parameters from memory to calldata for external/public functions. Use bytes32 instead of string for pool identifiers, token symbols used as keys short fixed-length identifiers. 3) Loop optimization: optimize reward distribution loop over all stakers, batch transfer loop — cache array length in local variable, use unchecked{++i}, break early when possible, and consider whether the loop can be replaced with lazy evaluation pattern — update reward on user interaction instead of iterating all users. 4) Custom errors: replace all require(condition, "error message") with custom errors (error InsufficientBalance(uint256 requested, uint256 available)), saving ~200 gas (eliminating string storage) gas per revert. 5) Batch operations: design a batchStake that deposits multiple tokens in one transaction that processes multiple operations in one transaction using array of structs decoded from calldata with length prefix, amortizing base transaction cost. 6) Assembly optimization for token balance checks, hash computations, and address validation: implement using Yul for 500-1000 gas savings per call — include extensive comments and verify equivalence with Solidity version. 7) Benchmarking: provide a Foundry test using vm.snapshotGas that compares before and after gas usage for single stake, batch stake 10 tokens, claim rewards, emergency withdraw.

What this prompt does

This prompt optimizes gas for a Solidity contract methodically, since on mainnet gas is a real cost to your users. You describe the [contract_type], its [current_gas] per typical transaction on [target_chain], the [function_count], and [storage_variables], and it works through storage packing, calldata versus memory, loop optimization, custom errors, batch operations, targeted assembly, and Foundry benchmarks.

The structure works because gas savings have a clear priority order. Repacking [packable_variables] into single slots, replacing bool arrays with a [bitmap_implementation], switching [memory_params] to calldata, optimizing [hot_loops] with cached length and unchecked{++i}, and replacing revert strings with custom errors usually deliver the biggest wins before you reach for assembly on [assembly_candidates]. By demanding Foundry before/after benchmarks for [benchmark_scenarios], the prompt keeps the savings proven rather than assumed. Knowing the [current_gas] baseline and the [function_count] and [storage_variables] count helps the model target the functions where optimization actually pays off.

When to use it

  • You have a mainnet contract where gas cost materially affects your users
  • You want storage layout analyzed and [packable_variables] repacked into shared slots
  • You need [hot_loops] optimized or replaced with lazy evaluation
  • You want revert strings swapped for custom errors across the contract
  • You want a [batch_function] so users can amortize base transaction cost
  • You are considering assembly for [assembly_candidates] and want it justified and verified
  • You need Foundry benchmarks proving the savings on [benchmark_scenarios]

Example output

Expect an optimization report: a storage-layout analysis repacking [packable_variables] into single slots with a [bitmap_implementation] for boolean state, a list of [memory_params] to switch to calldata and [fixed_strings] to swap for bytes32, optimized versions of [hot_loops] with [loop_alternatives] like lazy reward accounting where applicable, a custom-error rewrite saving roughly [estimated_savings] per revert, a [batch_function] using [batch_pattern] to amortize base cost, optional Yul implementations for [assembly_candidates] with equivalence notes, and a Foundry test using vm.snapshotGas comparing before and after across [benchmark_scenarios]. Each change comes with a before/after gas figure so you can prioritize by payoff.

Pro tips

  • Chase the cheap wins first: storage packing of [packable_variables] and custom errors usually beat assembly on effort-to-savings
  • Prefer lazy evaluation in [loop_alternatives] over micro-optimizing [hot_loops] — updating rewards on user interaction beats iterating every staker
  • Convert [memory_params] to calldata for external functions; it is a near-free saving that is easy to overlook
  • Replace short [fixed_strings] used as keys with bytes32, since string storage and comparison are far more expensive than a fixed-size type
  • Reserve assembly for [assembly_candidates] where the saving is real and verify Yul equivalence against the Solidity version with tests
  • Always insist on vm.snapshotGas before/after benchmarks for [benchmark_scenarios], so savings are measured, not guessed
  • Re-test correctness after every optimization; gas tricks like unchecked blocks and tight packing are exactly where subtle bugs hide

Frequently Asked Questions

What gives the biggest gas savings?
Usually storage optimization and custom errors. Repacking `[packable_variables]` so multiple values share a slot avoids extra storage writes, and replacing revert strings with custom errors saves roughly `[estimated_savings]` per revert. These typically beat assembly on the ratio of savings to effort and risk.
Is assembly optimization worth it?
Only after the cheaper wins are exhausted. Yul on `[assembly_candidates]` can save `[assembly_savings]` gas per call, but it is harder to read and audit. Reserve it for genuine hot paths and always verify equivalence to the Solidity version with tests before trusting it.
How are the savings verified?
Through Foundry benchmarks using `vm.snapshotGas` that compare gas before and after for `[benchmark_scenarios]`. This makes savings measured rather than assumed, which matters because some optimizations look cheaper but shift cost elsewhere or fail to help in practice.
Can optimization introduce bugs?
Yes. Tight storage packing, `unchecked` blocks, and assembly are exactly where subtle correctness bugs hide. The prompt pairs each optimization with benchmarking, but you should also re-run your full correctness test suite after optimizing, since saving gas on a broken function is no win at all.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Blockchain & Web3 Development Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support