Zokyo Gas Savings
  • ⛽Zokyo Gas Savings
  • 📚Tutorials
    • ✔️Gas Saving Technique 1: Unchecked Arithmetic
    • ⛓️Gas Saving Technique 2: Immutable Variable
    • ✨Gas Saving Technique 3: Double star ** inefficiency
    • 💰Gas Saving Technique 4: Cache Array Length
    • ⬅️Gas Saving Technique 5: ++i costs less gas compared to i++
    • ⚖️Gas Saving Technique 6: NOT operator ! cheaper than boolean FALSE
    • 🪡Gas Saving Technique 7: Using Short Reason Strings
    • 🪵Gas Saving Technique 8: Use Custom Errors instead of Revert Strings to save Gas
    • ✒️Gas Saving Technique 9: Use Custom Errors instead of Revert Strings to save Gas
    • 👾Gas Saving Technique 10: Calldata cheaper than memory
    • ⛔Gas Saving Technique 11: > 0 is less efficient than != 0 for unsigned integers
    • ➗Gas Saving Technique 12: SafeMath no longer needed
    • 😮Gas Saving Technique 13: variables default to 0
    • 🧱Gas Saving Technique 14: struct layout/ variable packing
    • 📞Gas Saving Technique 15: Cache External Call
    • ✍️Gas Saving Technique 16: Early Validation before external call
    • 😎Gas Saving Technique 17: Don’t cache value that is used once
    • 😧Gas Saving Technique 18: Redundant code
    • ✅Gas Saving Technique 19: Early Validation before external call
    • ⛏️Gas Saving Technique 20: Storage vs Memory read optimizations
    • ✒️Gas Saving Technique 21: Unneeded If statements
    • 🌗Gas Saving Technique 22: >= is cheaper than >
    • 🎒Gas Saving Technique 23: Public to private constants
    • ⏹️Gas Saving Technique 24: Make unchanged variables constant/immutable
    • ⏱️Gas Saving Techniques 25: Redundant Access Control Checks
    • ➡️Gas Saving Technique 26: Shift Right instead of Dividing by 2
    • 🪃Gas Saving Tutorial 27: Efficient Boolean Comparison
    • 🤝Gas Saving Technique 28: && operator uses more gas
    • 👓Gas Saving Technique 29: x = x + y is cheaper than x += y
    • 👂Gas Saving Technique 30: Using 1 and 2 rather than 0 and 1 saves gas
    • ⚽Gas Saving Technique 31: Optimize Storage by Avoiding Booleans
    • 🔙Gas Saving Technique 32: Optimal Use of Named Return Variables in Solidity
    • 🛢️Gas Saving Technique 33: Making Functions Payable for Optimized Gas Costs
    • ✍️Gas Saving Technique 34: Optimizing Storage References in Smart Contracts
    • ⛰️Gas Saving Technique 35: Usage of uints/ints smaller than 32 bytes (256 bits) incurs overhead
    • 🌪️Gas Saving Technique 36: Inlining Single Use Internal Functions for Savings
    • ☄️Gas Saving Technique 37: Switching from Public to External Functions for Savings
    • 🎆Gas Saving Technique 38: Upgrading Solidity Compiler to Improve Gas Efficiency and Security
    • 🕶️Gas Saving Technique 39: Avoiding Duplicated Code for Gas Savings
    • 😄Gas Saving Technique 40: Removal of Unused Internal Functions for Gas Savings
    • 🖋️Gas Saving Tutorial 41: In-lining Single Use Modifiers For Gas Saving
    • ⛏️Gas Saving Technique 42: `require` vs`assert`
Powered by GitBook
On this page
  1. Tutorials

Gas Saving Technique 16: Early Validation before external call

PreviousGas Saving Technique 15: Cache External CallNextGas Saving Technique 17: Don’t cache value that is used once

Last updated 1 year ago

Introduction

In smart contract development on Ethereum, conserving gas is a top priority. A notable practice to achieve gas efficiency is performing validation checks as early as possible in the function, ideally before making external calls. Early validation not only enhances the contract's security but also prevents unnecessary gas expenditure by terminating the execution early in case of invalid conditions.

Impact & Details

Understanding Gas Consumption

  • Gas Cost of External Calls: External calls are expensive in terms of gas usage. If a function makes an external call and later finds out a condition isn’t met (through validation), the gas spent on the external call is wasted.

  • Early Validation Benefits: By conducting necessary validation checks before external calls, you can ensure that the function only proceeds with these calls when conditions are met, saving gas in scenarios where the call would be unnecessary.

How to Implement Early Validation for Gas Savings

Practical Example: Early Validation Optimization

Here’s a contract function example before and after implementing early validation:

Before Optimization:

solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IExternalContract {
    function externalFunction() external;
}

contract MyContract {
    IExternalContract public externalContractInstance;
    uint256 public threshold;

    function myFunction(uint256 amount) public {
        externalContractInstance.externalFunction();  // External call before validation
        require(amount >= threshold, "Amount below threshold");  // Validation after external call
        // ... rest of the function ...
    }
}

After Optimization:

solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IExternalContract {
    function externalFunction() external;
}

contract MyContract {
    IExternalContract public externalContractInstance;
    uint256 public threshold;

    function myFunction(uint256 amount) public {
        require(amount >= threshold, "Amount below threshold");  // Early validation
        externalContractInstance.externalFunction();  // External call after validation
        // ... rest of the function ...
    }
}

In the optimized version, the validation check is moved before the external call, saving gas when the require condition isn't met.

Recommended Mitigation Steps

  1. Identify Late Validations: Review your smart contracts to locate validation checks that occur after external calls.

  2. Rearrange Validations: Move validation checks to occur as early as possible in the function, preferably before any external calls.

  3. Test: Rigorously test the contract after rearrangement to ensure it maintains its functionality while efficiently saving gas.

Conclusion

Implementing validation checks early in the function, especially before making external calls, is a simple and effective optimization technique for gas saving in smart contract development. The practice is crucial in scenarios where external calls are costly, ensuring that gas isn't wastefully expended when conditions aren’t met. Always ensure to test the contract extensively after such optimizations to validate its functionality and gas efficiency.

📚
✍️
Book an audit with Zokyo