You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以太坊Solidity中require()函数是否消耗Gas?

Does Solidity's require() Function Consume Gas? Even When the Condition is True?

Great question—this is a common point of confusion for Solidity developers, so let's break it down clearly:

When the condition evaluates to true

Yes, it does consume a small amount of Gas, but not because of the require() keyword itself. The Gas cost here comes from the EVM executing the condition check logic: reading variables, comparing values, or any computations needed to evaluate whether the condition holds.

For example, if you have:

require(msg.sender == owner, "Only owner can call this");

When msg.sender matches owner, the EVM still needs to load both addresses from storage/memory, compare them, and confirm they're equal. These operations have standard Gas costs (tiny, but non-zero) just like any other arithmetic or storage read in Solidity.

When the condition evaluates to false

Here's where things get interesting:

  • The EVM will roll back all state changes made in the current transaction (so no partial state updates are left behind).
  • It will refund all unused Gas (minus the Gas already spent to execute up to the point of the failed require()).

The failed require() itself doesn't incur an extra penalty—you only pay for the operations that ran before the check failed. This is a key difference from assert(), which is meant for internal invariants; if assert() fails, it consumes all remaining Gas and doesn't issue a refund.

Quick Summary

  • Condition true: Minimal Gas cost for the condition evaluation (same as running the check without require()).
  • Condition false: Gas is only charged for operations up to the failed check; remaining Gas is refunded, and state is rolled back.

内容的提问来源于stack exchange,提问作者mrsulaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:59:47