---
eip: 1283
label: EIP-1283
title: Net gas metering for SSTORE without dirty maps
status: Final
type: Standards Track
category: Core
created: 2018-08-01
official: https://eips.ethereum.org/EIPS/eip-1283
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1283.md
canonical: https://eips.huatuo.xyz/zh/eip-1283/
lang: zh
tldr: SSTORE 的净 gas 计量：在同一笔交易中多次写入同一个存储槽，首次写入之后每次只需 200 gas，槽被恢复原值时还有退款。因重入风险被撤出 Constantinople，后来以 EIP-2200 重新上线。
tags: [gas, sstore, storage, core, constantinople]
---

# EIP-1283: Net gas metering for SSTORE without dirty maps

> This EIP proposes net gas metering changes for SSTORE opcode, enabling new usages for contract storage, and reducing excessive gas costs where it doesn't match how most implementations work.

**TL;DR:** SSTORE 的净 gas 计量：在同一笔交易中多次写入同一个存储槽，首次写入之后每次只需 200 gas，槽被恢复原值时还有退款。因重入风险被撤出 Constantinople，后来以 EIP-2200 重新上线。

## 它解决什么问题？

在这项提案之前，每个改变存储槽的 `SSTORE` 都要花 5,000 gas（对为零的槽进行设置则为 20,000 gas），不管该槽在同一笔交易中已经被写入过多少次。常见的模式因此付出了高昂的代价：

- 重入锁先设为 1 再设回 0，要为两次完整的写入付费，
- 合约在一次调用中多次更新计数器，每次写入都要付费，
- 通过存储在调用帧之间传递值的合约，按每个值都会被持久化来付费。

客户端实际上并不会在每次 `SSTORE` 时都写磁盘，而是在最后统一提交。EIP-1283 让 gas 反映这一点，只使用大多数客户端已经在跟踪的信息：该存储槽的**原始**值（交易开始时）和**当前**值。

## 它如何运作

对于每次 `SSTORE`，比较*原始*值、*当前*值和*新*值：

- **空操作**（`current == new`）：200 gas。
- **全新**的槽（`original == current`，这笔交易中的首次修改）：
  - 原始值为 0：20,000 gas；
  - 否则为 5,000 gas，如果新值为 0，则另有 15,000 的退款。
- **脏**槽（`original != current`，已被修改过）：200 gas，并调整退款计数器：
  - 如果原始值 ≠ 0 且当前值为 0，收回 15,000 的清除退款；如果新值为 0，则给予该退款；
  - 如果新值等于原始值（槽被重置），退款 19,800（原始值为 0）或 4,800（原始值 ≠ 0）。

规范中的例子：

- 空槽先设为 1 再设回 0：`20000 + 200 - 19800 = 400` gas。
- 空槽递增 5 次：`20000 + 5 × 200 = 21000` gas。

它收取的费用从不高于旧方案，并且无需单独的"dirty map"，就大致达到了瞬态存储的效果。

## 示例代码

用类 Python 伪代码表示的费用规则：

```python
def sstore_cost(original, current, new, refund):
    if current == new:
        return 200, refund
    if original == current:
        if original == 0:
            return 20000, refund
        if new == 0:
            refund += 15000
        return 5000, refund
    # dirty slot
    if original != 0:
        if current == 0:
            refund -= 15000
        if new == 0:
            refund += 15000
    if original == new:
        refund += 19800 if original == 0 else 4800
    return 200, refund
```

## 需要注意

- EIP-1283 原本计划纳入 Constantinople，但在激活前夕因发现重入问题而被撤出：花费 200 gas 的脏槽 `SSTORE` 可以装进 Solidity `transfer`/`send` 的 2,300 gas 补贴之内，而现有合约曾假设这点 gas 不足以改变状态。[Petersburg](/eip-1716/) 升级把它从该分叉中移除了。
- 它的状态显示为 **Final**，但以这种形式并未在主网上生效。同样的逻辑在 Istanbul 中以 [EIP-2200](/eip-2200/) 上线，并结合了 [EIP-1706](/eip-1706/) 的规则：如果剩余 gas 小于等于补贴，`SSTORE` 就会失败。
- 退款数值后来又有变化；当前的演进脉络请参阅 EIP-2200。对于真正临时的值，如今 [EIP-1153](/eip-1153/) 的瞬态存储（transient storage）是专门为此设计的工具。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-1283
