Tag: Smart Contracts

  • Gas Optimization Part 4: Solidity Tips for Cheaper Contracts

    Gas Optimization Part 4: Solidity Tips for Cheaper Contracts

    Every line of your smart contract costs something.

    Some lines cost more than others.

    In this part of our gas saving series, we’ll explore how to write smarter Solidity code that keeps your contract lean and efficient.

    Here are six simple and practical ways to reduce gas costs while writing Solidity smart contracts.

    1. Use payable Only When Needed, But Know It Saves Gas

    In Solidity, a function marked payable can actually use slightly less gas than a non-payable one.

    Even if you’re not sending ETH, the EVM skips some internal checks when the function is marked payable.

    See this example:

    function hello() external payable {}    // 21,137 gas

    function hello2() external {}           // 21,161 gas

    That tiny difference may not seem like much, but across thousands of calls, it adds up.

    • Only use payable when your function is actually meant to accept ETH

    2. Use unchecked for Safe Arithmetic When You’re Sure

    Since Solidity 0.8.0, all arithmetic operations automatically check for overflows and underflows. While this makes contracts safer, it also uses extra gas. When you’re certain that overflow won’t occur, you can use the unchecked keyword to skip these safety checks.

    uint256 public myNumber = 0;

    function increment() external {

    unchecked {

    myNumber++;

    }

    }

    Gas used: 24,347 (much cheaper than using safe math)

    Warning: Use unchecked carefully. Only when you’re confident there’s no risk of overflow.

    3. Turn On the Solidity Optimizer

    The Solidity Optimizer is like a smart helper that cleans up and tightens your compiled bytecode.

    It does not change how your contract works, but it removes waste and makes it cheaper to run.

    If you’re using tools like Hardhat or Remix, always enable the Optimizer before deploying to mainnet.

    4. Use uint256 Instead of Smaller Integers (Most of the Time)

    Smaller types like uint8 or uint16 might look more efficient, but they can cost more gas during execution.

    That’s because the EVM automatically converts them to uint256 behind the scenes.

    So, if you’re not tightly packing them in a struct for storage savings, just use uint256.

    Use smaller types only in structs when trying to save storage space.

    5. Understand Storage Costs: Read + Write Costs Almost Same as Write

    Storage operations are expensive. But here’s something surprising:

    Reading a storage variable before writing to it doesn’t cost much more than writing directly.

    Example:

    • Read + Write = 2,100 (read) + 20,100 (write) = 22,200 gas
    • Write only = 22,100 gas

    That means if your code needs to read before writing, it’s okay, you are not losing much.

    Plan your storage usage wisely. Reuse variables and avoid unnecessary writes.

    Reference: https://ethereum.github.io/yellowpaper/paper.pdf

    6. Use < Instead of <= in Comparisons

    When comparing numbers, use < instead of <=.

    Why? Because:

    • < needs just one check
    • <= takes two checks (a comparison and an extra step to flip the result)

    Fewer steps mean lower gas usage.

    Example:

    for (uint i = 0; i < limit; i++) {

    }

    This small change saves gas on every loop iteration and comparison operation.

    Conclusion

    Gas optimization is about understanding how the EVM works and making informed decisions about your code structure. Each of these techniques might seem to save small amounts of gas individually, but combined and applied across a large contract, they can result in significant cost savings.

    Remember: Always test your optimizations thoroughly. Sometimes gas savings come at the cost of code readability or safety. Strike the right balance for your specific use case.

    Key Takeaways:

    1. Use payable functions when appropriate
    2. Apply unchecked carefully for safe arithmetic
    3. Enable the Solidity optimizer
    4. Prefer uint256 for most variables
    5. Understand storage access patterns
    6. Choose efficient comparison operators

    By implementing these strategies, you’ll create contracts that not only work well but also cost less to deploy and interact with, making them more accessible to users and more profitable for developers.

  • Gas Optimization Part 3: The Foundation of Gas in Solidity and Smart Contract Efficiency

    Gas Optimization Part 3: The Foundation of Gas in Solidity and Smart Contract Efficiency

    You just deployed a smart contract, and it’s costing 98 gas to run a function that does nothing. Literally.

    See for yourself, Why?

    Because even doing “nothing” on Ethereum still means something to the Ethereum Virtual Machine (EVM).

    Welcome to Part 3 of our gas optimization series, where we will look at how gas really works behind the scenes and how you can make your Solidity smart contracts use less gas by removing anything that’s not needed.

    The Building Blocks: OPCODEs Are the DNA of Ethereum

    In Solidity, saving on gas is like saving fuel in your car. To do that, you need to know about OPCODEs – the basic commands that tell Ethereum what to do. They’re the ABCs of Ethereum’s language.

    When you write Solidity code, it doesn’t run directly on the Ethereum network. Instead, it gets compiled into a set of OPCODEs that the Ethereum Virtual Machine (EVM) can understand and execute. Think of it like translating English into machine language that computers can process

    What Are OPCODEs?

    OPCODEs are low level instructions that perform specific operations:

    Arithmetic Operations: ADD, SUB, MUL, DIV for mathematical calculations

    Memory Operations: MLOAD, MSTORE for temporary data storage

    Storage Operations: SLOAD, SSTORE for permanent blockchain storage

    Program Flow: JUMP, JUMPI for conditional logic.

    Cryptographic Functions: SHA3, ECRECOVER for security operations

    Contract Interactions: CALL, DELEGATECALL for inter-contract communication

    And here’s the catch:

    Each OPCODE consumes gas, and some cost way more than others.

    Pro Tip:

    You can see the full list of OPCODE gas costs here: ethereum.org/en/developers/docs/evm/opcodes

    The Secret Code: Function Selectors

    Here’s something that might surprise you: when you compile your Solidity code into bytecode, the names of your functions don’t actually show up in the final assembly output. Instead, what ends up on the Ethereum network is something like a secret code called function selectors

    How Function Selectors Work

    Function selectors are created by taking the first four bytes of the hash of the function’s signature. Let’s look at a real example:

    function doNothig() external pure {}

    After compilation, this becomes:

    46aad107

    So when someone sends a transaction to your contract, they don’t send the name doNothig(),they send the selector 0x46aad107.

    That’s how the EVM knows which function to run, without storing long names on-chain.

    Gas Optimization Tips Every Developer Should Know

    1. Keep It Light

    The less code you deploy, the less gas you’ll use during deployment. Think of it as packing light for a flight – every extra byte costs money.

    Code size optimization strategies:

    • Remove unnecessary functions and variables
    • Use libraries for common operations instead of duplicating code
    • Implement proxy patterns for upgradeable contracts
    • Strip out debugging code and comments in production

    Real impact: A 1KB reduction in contract size saves approximately 200,000 gas units during deployment

    2. Choose Wisely: OPCODE Selection

    Certain commands are cheaper than others. Picking the right ones is like choosing a budget airline over a luxury carrier.

    Cost-effective choices:

    • Some instructions (like ADD) cost less than others (like SSTORE).
    • Store fewer variables
    • Avoid unnecessary require checks
    • Minimize state changes

    3. Pack Data Tight: Transaction Data Optimization

    The more data you send in a transaction, the more you spend. Keep your transaction data lean.

    Data packing techniques:

    • Use struct packing to fit multiple variables in single storage slots
    • Compress arrays and use fixed-size arrays when possible
    • Batch multiple operations to reduce transaction overhead
    • Use events instead of storage for data that doesn’t need to be queried on-chain

    4. Minimize Memory Use

    Memory is temporary, but still costs gas.

    Avoid creating new memory variables when not required.

    Use calldata instead of memory for function inputs when possible

    5. Be Smart About Storage

    Storage is the most expensive operation.

    • Only write to storage if you must
    • Use events to log non-critical data instead of storing it
    • Don’t overwrite storage values unless necessary

    Every time you write to SSTORE, you’re paying a premium.

    The Compound Effect

    A little bit of gas saved on every transaction can add up to significant savings over time. If your contract processes 1,000 transactions per day and you save 500 gas per transaction, that’s 500,000 gas units daily – potentially saving hundreds of dollars monthly at current gas prices.

    Understanding OPCODEs and function selectors is just the beginning. In Part 4, we’ll explore advanced Solidity techniques that can dramatically reduce gas consumption

  • Gas Optimization Part 2: Timing Strategies and Batch Processing

    Gas Optimization Part 2: Timing Strategies and Batch Processing

    You’ve learned what gas fees are and how they’re calculated. Now comes the practical part: how to actually save money on every transaction you make. The difference between a novice and an expert Ethereum user often comes down to understanding when and how to execute transactions efficiently.

    Haven’t read Part 1 yet? Check out our introduction to gas fees and how they work to understand the fundamentals before diving into these optimization strategies.

    Let’s explore the proven strategies that can cut your gas costs by 50-90% without compromising transaction security or speed

    Strategy 1: Master the Art of Timing

    Weekends: Saturday and Sunday typically see 20-30% lower gas fees as business activity decreases.

    Off-peak hours: Between 2 AM and 6 AM UTC, when both American and European users are asleep, gas prices often drop significantly.

    Avoid these high-traffic periods:

    • NFT mint launches
    • Major DeFi protocol updates
    • Market crash periods (panic selling drives up demand)
    • Weekday mornings (8-10 AM UTC)

    You can use trackers like:

    Pro tip: Set up gas price alerts on your phone. When prices drop below your target threshold, that’s your window to execute pending transactions.

    Strategy 2: Batch Processing

    Why send 10 separate transactions…

    When you can send one batch?

    Batching reduces overhead, saves time, and lowers gas.

    Let’s explore 3 Ethereum standards that enable powerful batching:

    1) ERC-3005: Batched Meta Transactions – https://eips.ethereum.org/EIPS/eip-3005

    This standard lets users combine multiple actions into one meta transaction.

    Example:

    1. Approve token
    2. Swap on DEX
    3. Send output to wallet

    All in one call, reducing gas and relayer fees.

    Great for:

    1. Wallet apps
    2. Gasless UX
    3. Relayer-backed platforms

    2) ERC-7821: Minimal Batch Executor –  https://eips.ethereum.org/EIPS/eip-7821

    This one’s about delegations and shared execution.

    Think of it like batching multiple on-chain delegations, such as:

    • Voting
    • Staking
    • DAO participation

    With atomic execution, if one part fails, nothing gets through so it keeps safe and predictable.

    Perfect for:

    • DAO tools
    • Governance app
    • Delegation-heavy protocols

    Example scenario: You want to withdraw from a liquidity pool, swap the tokens, and deposit them into a yield farming protocol. ERC-7821 ensures all these operations happen atomically, preventing scenarios where only part of your strategy executes

    3) ERC-4393: Batch Micropayments – https://eips.ethereum.org/EIPS/eip-4393

    When you need to make multiple small payments, ERC-4393 shines. This standard enables multiple tips or payments in a single transaction call.

    Use case: Tipping multiple content creators or making several small purchases. Instead of paying gas fees for each micropayment, you pay once for the entire batch

    Strategy 3: Wait for gas to go down

    Gas prices go up and down every twelve seconds based on how congested Ethereum is. When gas prices are high, waiting just a few minutes before making a transaction could see a significant drop in what you pay.

    Strategy 4: Use Layer 2 Solutions

    Layer 2 solutions like zkSync, Arbitrum, and Optimism reduce gas fees by up to 95%. By bundling a large number of transactions together, these solutions reduce the number of on-chain transactions.

    Popular options:

    • Arbitrum
    • Optimism
    • Base
    • Polygon (PoS)

    Many dApps are now L2-ready. Just bridge your ETH once, and you’re good to go.

    Wrap-up

    Ethereum gas fees aren’t going away, but you can outsmart them with:

    1. Good timing
    2. Layer 2 networks
    3. Batched transactions using ERC-3005, ERC-7821, and ERC-4393
    4. Wait for the gas to go down

    What’s next?

    While timing and batching strategies can dramatically reduce your transaction costs, the next frontier in gas optimization lies in smart contract efficiency. In Part 3, we will explore advanced Solidity techniques that developers use to minimize gas consumption at the code level.

  • Gas Optimization Part 1: Understanding Ethereum Gas Fees

    Gas Optimization Part 1: Understanding Ethereum Gas Fees

    “I paid $62 just to send $100. What?”

    That’s the kind of reaction many new users have after making their first Ethereum transaction during peak congestion.

    No NFTs. No DeFi. Just a simple ETH transfer.

    Yet the gas fee was more than half the value of the transaction.

    And they thought it was a bug.

    But it wasn’t.

    It was Ethereum being busy.

    Welcome to the world of gas fees.

    What Is Gas, Really?

    If you’ve ever driven a car, you already understand gas.

    Think of your Ethereum transaction as a car trip. To drive (process your transaction), you need fuel, and on Ethereum, that fuel is called Gas.

    Just like fuel powers a car, gas powers your transaction on the Ethereum network.

    But there’s a catch: The busier the road, the higher the fuel price.

    So when the Ethereum network is crowded (say, during a hyped NFT mint), gas prices shoot up because everyone’s trying to get their transactions through.

    Why Gas Prices Change

    Back to our highway example:

    If traffic is light, fuel is cheap, and if traffic is jammed, fuel costs more to cut through

    Ethereum works similarly.

    You can pay a higher gas price to get your transaction picked up faster by validators

    Or you can set a lower price and wait.

    Understanding the Components

    Gas Limit

    This is the maximum amount of gas you’re willing to use.

    For simple ETH transfers, it’s usually 21,000.

    Gas Price

    This is how much you’re willing to pay per unit of gas, measured in Gwei.

    Gas Usage:

    This is the actual amount of gas consumed by your transaction. It’s often the same as your gas limit for simple transactions, but complex operations might use less than the limit you set.

    Breaking Down Gas Fees: A Real Example:

    • Gas Limit = 21,000
    • Gas Price = 35.06 Gwei
    • ETH Price = $3,492.21

    Step 1: Calculate Gas Fee in ETH

    21,000 × 35.06 / 1,000,000,000 = 0.000736 ETH

    Step 2: Convert to Dollars

    0.000736 × 3,492.21 = $2.57

    So, the fee for that simple transaction is about $2.57.

    But when the network gets congested, gas prices might 10x,  and that’s how people end up paying $50+ just to send ETH.

    The Game-Changer: EIP-1559

    In August 2021, Ethereum introduced EIP-1559, which revolutionized how gas fees work. Instead of the old auction-style system where users had to guess appropriate gas prices, EIP-1559 brought predictability and efficiency.

    How EIP-1559 Works

    The new system introduces several key components:

    Base Fee: This is a fixed price per unit of gas that the network automatically adjusts based on demand. Here’s the interesting part: this base fee gets burned (destroyed), permanently removing ETH from circulation.

    Max Fee: The maximum amount you’re willing to pay for the transaction. This acts as your safety net.

    Max Priority Fee: The tip you’re willing to give to miners to prioritize your transaction.

    A Real EIP-1559 Example

    Let’s say you’re making a transaction with these parameters:

    Base Fee: 70 Gwei

    Max Fee per Gas: 90 Gwei

    Max Priority Fee per Gas: 15 Gwei

    Here’s what happens:

    1. 70 Gwei gets burned (the base fee is destroyed)
    2. Miners receive 15 Gwei (your full priority fee since Max Fee – Base Fee = 20 Gwei, which is higher than your 15 Gwei priority fee)
    3. You get 5 Gwei refunded (90 – 70 – 15 = 5 Gwei back to your wallet)

    This system eliminates the guesswork. You know exactly what you’ll pay upfront, and any excess gets refunded automatically.

    Looking Ahead

    Gas optimization isn’t just about understanding current fees. It’s about developing strategies to minimize costs while maintaining transaction reliability. In the next part of this series, we’ll dive into practical techniques for optimizing your gas usage, including timing strategies, transaction batching, and smart contract optimization tips.

    The key takeaway? Gas fees might seem complex, but they follow predictable patterns. Once you understand these patterns, you can navigate the Ethereum network like a pro, saving money and avoiding the frustration of failed transactions.

    Remember: every Gwei saved is money back in your pocket. And in the world of DeFi and NFTs, where you might make dozens of transactions per month, those savings add up quickly.