What is require in Solidity: Explanation and Usage
require in Solidity is a function used to check conditions and stop execution if the condition is false. It helps ensure that inputs or states meet expected rules, reverting changes and returning an error message if not.How It Works
Think of require as a checkpoint in your smart contract code. It checks if a condition is true before continuing. If the condition is false, it stops the contract from running further and undoes any changes made during the current call.
This is like a safety guard that prevents mistakes or bad data from causing problems. For example, if someone tries to send too little money or call a function when they shouldn't, require will stop the action and give back an error.
When require fails, it also returns any leftover gas to the caller, making it efficient and safe to use for input validation and enforcing rules.
Example
This example shows a simple function that uses require to check if the caller sends enough Ether before proceeding.
pragma solidity ^0.8.0; contract Payment { uint public price = 1 ether; function buy() public payable { require(msg.value >= price, "Not enough Ether sent"); // Continue with purchase logic } }
When to Use
Use require whenever you need to check that inputs, states, or conditions are correct before running important code. It is perfect for validating user inputs, checking balances, or enforcing permissions.
For example, in a token sale contract, you can use require to ensure buyers send enough funds or that the sale is still active. This prevents errors and protects your contract from invalid actions.
Key Points
requirechecks a condition and reverts if false.- It returns unused gas to the caller on failure.
- Use it for input validation and enforcing rules.
- It helps keep contracts safe and predictable.
Key Takeaways
require stops execution and reverts if a condition is false.require calls return unused gas to the caller.require to protect your contract from invalid actions.