Solidity If-Else, Require, Assert: Conditional Logic Made Easy

Rishabh parmar·2025년 6월 2일
0

Smart contracts are changing how we build applications—bringing trustless, decentralized systems to everything from finance to gaming. At the heart of every smart contract lies a simple but powerful concept: conditional logic. Whether you’re checking permissions, validating input, or enforcing business rules, Solidity gives you several tools to handle decisions in code.
In this post, we’ll break down the basics of if-else statements, and the built-in functions require, assert, and revert, which are essential for Conditional Execution in Solidity. You’ll learn not just how they work, but when and why to use them—so your smart contracts are both secure and efficient.

Why Conditional Logic Matters in Smart Contracts
Unlike traditional applications, smart contracts are immutable once deployed. That means you don’t get a second chance to fix poor logic. You must build in safeguards from the start. This is where conditional execution comes in. By checking certain conditions before allowing functions to proceed, you can prevent invalid operations, save gas, and reduce attack surfaces.
Whether it's checking if a user is the owner, ensuring enough funds are sent, or blocking unexpected behavior, Solidity gives you the tools to enforce rules cleanly.

  1. If-Else Statements in Solidity
    Just like other programming languages, Solidity supports basic if-else control flow. It allows you to perform actions based on specific conditions.
    Example:
    solidity
    CopyEdit
    pragma solidity ^0.8.0;

contract Voting {
uint public voteCount;

function vote(bool hasVoted) public {
    if (hasVoted) {
        revert("You have already voted.");
    } else {
        voteCount++;
    }
}

}
In the example above, we’re checking if the user has already voted. If they have, we block further execution using revert(). Otherwise, we increase the vote count.
Best Practices:
• Keep your conditionals clear and concise.
• Use nested if-else only when absolutely necessary—flatten logic where possible to improve readability.

  1. Using require() for Input Validation
    The require() function is one of the most commonly used tools for Conditional Execution in Solidity. It checks whether a condition is true. If not, it throws an error and reverts the transaction, returning unused gas to the caller.
    Example:
    solidity
    CopyEdit
    function deposit(uint amount) public {
    require(amount > 0, "Amount must be greater than zero.");
    // Continue with deposit logic
    }
    This line ensures users can’t deposit a zero or negative amount. If they try, the transaction fails gracefully with a helpful error message.
    Use require() for:
    • Input validation
    • Authorization checks (e.g., only the owner can call a function)
    • Ensuring contract state meets a precondition before proceeding

  2. Using assert() for Internal Errors
    While require() is for user errors or input validation, assert() is used to catch programming bugs or check for invariants—things that should never be false if your contract is functioning correctly.
    Example:
    solidity
    CopyEdit
    function updateBalance(uint newBalance) public {
    balance = newBalance;
    assert(balance == newBalance);
    }
    If the assert() fails, it indicates a serious issue—possibly a logic error or data corruption. That’s why assert() consumes all remaining gas and should be used sparingly.
    Use assert() for:
    • Checking for conditions that should always be true
    • Verifying internal consistency
    • Debugging during development (and removed before deployment, in many cases)

  3. Using revert() to Handle Failures
    While require() is more concise, the revert() function gives you more control, especially when combined with complex logic.
    Example:
    solidity
    CopyEdit
    function withdraw(uint amount) public {
    if (amount > balance) {
    revert("Not enough balance.");
    }
    balance -= amount;
    }
    This is functionally similar to require(), but it makes your logic structure more explicit, which can be useful for readability or debugging.

Gas Costs and Behavior
• require(): Returns unused gas to the user and provides an error message.
• assert(): Consumes all remaining gas, useful for critical checks.
• revert(): Like require(), but more flexible for nested conditions.
Keeping these differences in mind can help optimize your contract for performance and user experience.

When to Use What?
Tool Use Case Gas Behavior
if-else Basic decision-making No gas refund
require Input validation, permission checks Refunds unused gas
assert Invariants, internal errors Consumes all gas
revert Custom error handling in complex logic flows Refunds unused gas


Final Thoughts
Conditional logic may sound basic, but it forms the foundation of secure and reliable smart contract design. Knowing how and when to use if-else, require(), assert(), and revert() helps you write contracts that behave as expected, protect against bad actors, and reduce the risk of costly bugs.
Always remember: smart contracts are not forgiving. A small mistake in your conditions can lead to frozen funds, broken logic, or exploitable vulnerabilities. That’s why mastering Conditional Execution in Solidity
is not optional—it’s essential.
Take the time to understand these tools, use them wisely, and build with confidence on the Ethereum blockchain.

profile
i am digital marketing intern at Tpoint Tech

0개의 댓글