Smart Contract Gas Optimization: Audit & Reduce Transaction Costs

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Smart Contract Gas Optimization: Audit & Reduce Transaction Costs
Medium
~2-3 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1347
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    948
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Smart Contract Gas Optimization

We were approached by a DeFi project: deploying their ERC-1155 contract cost 0.8 ETH instead of the expected 0.3. Users were paying $15 per transfer() at 30 gwei gas price, while competitors paid $4. The cause was poor storage layout and suboptimal patterns that the Solidity compiler doesn't fix for you. We conducted a gas audit and reduced deployment cost by 62%, and transaction costs by 3x, saving the project over $50,000 in user fees annually. Our experience optimizing 50+ contracts shows that 80% of losses are eliminated by proper storage architecture. Every extra SLOAD or SSTORE operation multiplies across thousands of calls. In this article, we'll cover specific patterns that save 30-50% on typical contracts.

Why Storage Is the Main Source of Gas Loss

SSTORE costs 20,000 gas when writing to a cold slot, 2,900 gas when updating a warm one. SLOAD costs 2,100 gas for cold, 100 for warm (per EIP-2929). That's why storage architecture determines 60-80% of a contract's cost.

Slot packing is the first tool. The EVM stores data in 32-byte slots. If you declare variables like this:

// Bad: 3 slots
uint128 a;
uint256 b;
uint128 c;

// Good: 2 slots (a and c packed)
uint128 a;
uint128 c;
uint256 b;

This saves two SLOADs on read. On a contract with 10,000 deployments, the savings total hundreds of ETH.

Storage Operation Gas Costs

Operation Gas (cold) Gas (warm)
SLOAD 2100 100
SSTORE (new) 20000 20000
SSTORE (update) 2900 2900
BALANCE 2600 100

These aren't just numbers—knowing them lets you choose between reading from storage and computing.

How to Find Bottlenecks in Your Contract

Analysis Tools

Tool What It Shows
Hardhat Gas Reporter Gas per function call in tests
Foundry forge test --gas-report Same, but faster with diff between commits
eth-gas-reporter Opcode breakdown via --verbose
Tenderly Gas Profiler EVM trace breakdown of real transactions
Remix Gas Estimation Quick check without setup

Foundry is our preferred choice. forge snapshot creates a .gas-snapshot file that can be committed and tracked in CI:

forge snapshot
# change code
forge snapshot --diff

Differences are shown line by line per function.

Mappings vs Arrays

mapping(uint256 => address) is O(1) access, gas-efficient. address[] with value lookup is O(n) and an architecture mistake 99% of the time. If iteration is needed, index via events and read off-chain through The Graph.

Unobvious Source: keccak256 on Short Strings

string memory name in a function called thousands of times incurs ABI encoding overhead. Replacing strings with bytes32 constants where strings are known upfront saves 200-500 gas per call.

Specific Optimization Patterns

Custom Errors Instead of require with Strings

// Before: 24,000 gas to deploy one string
require(amount > 0, "Amount must be positive");

// After: ~200 gas saved per revert + smaller bytecode
error AmountZero();
if (amount == 0) revert AmountZero();

Custom errors (EIP-838) became standard with Solidity 0.8.4. Strings in require are bytecode that increases deployment cost and revert cost.

Unchecked Arithmetic

Since Solidity 0.8.0, all arithmetic operations check for overflow by default. The check costs ~100 gas per operation. Where overflow is mathematically impossible:

unchecked {
    ++i; // in for loop – standard pattern
    total += amounts[i]; // if sums are bounded and validated above
}

On a loop of 100 iterations, that saves 10,000+ gas.

Immutable and Constant

constant values are inlined into bytecode—no SLOAD needed. immutable values are written into bytecode at deploy time, read as PUSH32. Both are ~3x cheaper than reading from storage. Token addresses, fee basis points, owner addresses in non-upgradeable contracts—all candidates for immutable.

Calldata vs Memory for Input Parameters

// memory – copies data to memory
function process(uint256[] memory ids) external

// calldata – reads directly from calldata, no copy
function process(uint256[] calldata ids) external

For external functions that only read data, calldata is cheaper. The difference grows with array size: for an array of 50 elements, it's 3,000-5,000 gas.

What Our Gas Optimization Service Includes

  • Baseline audit: run all tests with forge test --gas-report, record baseline. No changes without before/after measurements.
  • Profiling via Tenderly: take real mainnet transactions (if already deployed) or simulate in Tenderly fork. See breakdown by EVM opcodes.
  • Iterative optimization: apply changes one at a time, measure. Slot packing usually gives the biggest effect—we start there.
  • Regression testing: forge snapshot in CI. Any PR that increases gas by more than 1% requires justification.
  • Documentation and report: record all changes, savings per function, recommendations for ongoing maintenance.
Example: Savings from storage packing Contract with 1,000,000 `mint` calls using 3 slots instead of 2: each extra SLOAD costs 100 gas (warm) or 2100 (cold). At 30 gwei, savings range from a few hundred dollars.

Our Process

  1. Analysis: audit current contract, analyze gas profile.
  2. Design: identify patterns that will yield the biggest savings.
  3. Implementation: modify code, write tests.
  4. Testing: regression, stress test, deploy to testnet.
  5. Deployment: deploy optimized contract, migrate data (if needed).

Timeline Estimates

Gas audit of existing contract + report with recommendations: 1-2 days. Optimization with implementation and testing: 2-3 days depending on contract complexity. Full storage layout redesign (if architecture is initially suboptimal): from 1 week, as it requires migration scripts for existing data.

Cost is determined after analyzing the contract and current gas profile. Typical audit costs range from $5,000 to $15,000 depending on complexity, with guaranteed 20-50% gas reduction on key functions.

What's Included in the Work

  • Detailed gas audit report with breakdown per function
  • Optimized smart contract code with diff from original
  • Test suite covering regressions and gas savings
  • Deployment scripts and migration support (if needed)
  • Access to our gas monitoring dashboard via Tenderly
  • Training session for your team on best practices
  • 30 days of post-deployment support

Why Choose Us?

  • Over 5 years of experience developing smart contracts in Solidity, Rust, and Vyper.
  • Performed audits and optimizations for 30+ DeFi projects, including protocols with TVL > $50M.
  • Guarantee 20-50% gas reduction on key functions.
  • Work with contracts on Ethereum, Polygon, Arbitrum, Optimism, Base, Solana, BNB Chain.

Our gas optimization service focuses on storage packing to achieve gas savings. If you're looking to reduce transaction costs and save on deployment, contact us for a free preliminary assessment. Get an engineer's consultation—we'll determine the optimization potential in 1 hour.

Note: Memory expansion costs linearly with data size due to the quadratic gas cost formula (G_memory + expansion_cost). Understanding this helps in choosing the right data location for variables to minimize gas overhead.

Smart Contract Development

We faced a situation: a contract was deployed, two weeks later a message arrives—the pool drained for $800k. Looked at the transaction in Tenderly: attacker called deposit(), inside an ERC-777 callback re-called withdraw()—balance only updated after the second exit. Classic reentrancy, but not via ETH transfer—through an ERC-777 hook. ReentrancyGuard was only on withdraw().

Such cases are not rare. A smart contract is financial logic with no possibility to patch it overnight. Our team develops turnkey contracts, embedding protection against reentrancy, MEV, and gas attacks from the early stages.

How We Develop Smart Contracts Turnkey

We start with business logic audit and stack selection. Solidity 0.8.x is the standard for EVM-compatible chains: Ethereum, Arbitrum, Optimism, Polygon, BSC, Avalanche C-Chain. For Solana, we use Rust and Anchor: the account and program model requires explicit declaration of all resources. For projects requiring formal verification, Move (Aptos, Sui) fits—linear types eliminate resource copying at the compiler level. Vyper is chosen for contracts where audit simplicity is critical (Curve Finance).

Language Execution Model Typical Domain Risks
Solidity 0.8.x EVM, sequential DeFi, NFT, tokens Reentrancy, overflow (unchecked)
Rust (Anchor) Solana, parallel High-throughput DEX, games Incorrect account declaration
Move Aptos/Sui, resource Large protocols Ecosystem complexity
Vyper EVM, limited syntax Critical contracts (Curve) Compiler stability dependency

Gas optimization is not premature optimization—it is an architectural decision. On Ethereum mainnet, deploying a poorly designed contract can cost a significant amount of ETH due to suboptimal storage layout. Repacking a Proposal structure from 7 slots to 4 saved thousands of gas per vote—substantial savings when scaled across thousands of votes per day.

Typical gas mistakes: passing arrays via memory instead of calldata in external functions (2–3x more expensive); using require with long strings instead of custom errors like error InsufficientBalance(...). Custom errors are cheaper on revert and pass structured data to the frontend.

Why Smart Contract Audit Is Critical for Security

Audit is not a one-time check—it is a built-in development stage. We use three levels:

  1. Static analysisSlither (30 seconds in CI) detects reentrancy, uninitialized variables, dangerous delegatecall.
  2. Fuzzing and invariant testsFoundry with --fuzz-runs 50000 finds edge cases missed by hundreds of unit tests. Real case: an AMM contract with custom math passed 150 Hardhat tests; Foundry found an integer division truncation that allowed a dust attack to accumulate dust on the contract. Echidna checks invariants ("sum of all balances ≤ totalSupply").
  3. Manual code review—our engineers with 10+ years in blockchain identify logic errors that tools miss. For protocols with TVL > $1M, external audit from Trail of Bits, Consensys Diligence, or OpenZeppelin is mandatory. Timeline: 2–4 weeks.

Any upgradeable protocol must have a timelock. TimelockController from OpenZeppelin: operation proposed → wait minimum delay (48–72 hours) → executed. Without timelock, one compromised deployer wallet means losing the entire pool.

What Upgrade Patterns Do We Choose?

Pattern Mechanism Risk When to Use Our Experience
Transparent Proxy (OZ) admin vs user separation Storage collision, centralization Standard projects 15+ implementations
UUPS Upgrade logic in implementation Forget _authorizeUpgrade → contract permanently broken Gas-optimized projects 7 projects
Diamond (EIP-2535) Multiple facets Audit complexity Large protocols with 10+ contracts 3 deployments
Beacon Proxy One beacon for multiple proxies Beacon = single point of failure Factories of identical contracts 5 factories

Storage collision is the main danger of proxies. Implementation v2 must not add variables before existing ones. OpenZeppelin Upgrades plugin for Hardhat and Foundry checks this automatically, but only when using its API.

How to Protect a Contract from MEV and Front-Running

On Ethereum mainnet, transactions in the mempool are visible to all. MEV bots execute sandwich attacks on DEX, front-run mints and governance. Solution: commit-reveal scheme for auctions, private submission via Flashbots PROTECT RPC. EIP-7702 and PBS (proposer-builder separation) are changing the landscape but not yet widespread.

What Is the Development Process?

  1. Analysis—functional specification, call diagram, edge case analysis. Without this, coding starts in vain.
  2. Development—Solidity/Rust with tests in parallel. Test → code → refactoring. Use Foundry for fuzz and invariant tests.
  3. Internal audit—Slither + Echidna + manual code review. Foundry invariant tests for protocol invariants.
  4. External audit—for projects with real money. Timeline: 2–4 weeks.
  5. Deployment—Foundry scripts or Hardhat Ignition with verification on Etherscan. Gnosis Safe for ownership transfer immediately after deployment.
  6. Monitoring—Tenderly alerts, OpenZeppelin Defender, Forta Network.

What Is Included

  • Architecture documentation and contract specification (NatSpec).
  • Source code with repository and CI (Slither, Foundry, coverage).
  • Deployed contract with verification on blockchain explorer.
  • Audit results (internal and external upon request).
  • Access to monitoring and management (Gnosis Safe).
  • Code warranty: critical bug fixes within one month after deployment.
  • Consultation on web integration (wagmi, RainbowKit).

Estimated Timelines

  • ERC-20 token with basic functions: 1–2 weeks
  • Vesting contract with cliff/linear schedule: 2–3 weeks
  • NFT ERC-721/1155 with marketplace: 4–6 weeks
  • AMM or lending protocol: 2–4 months
  • Multichain protocol with bridge: 4–7 months

Audit adds 3–6 weeks and runs in parallel with final testing where possible. Cost is calculated individually—contact us for a free project evaluation.

Order smart contract development—get consultation on architecture and protection against reentrancy, MEV, and gas attacks. Want to discuss details? Write to us—we will select the optimal stack for your task.