---
eip: 1087
label: EIP-1087
title: Net gas metering for SSTORE operations
status: Stagnant
type: Standards Track
category: Core
created: 2018-05-17
official: https://eips.ethereum.org/EIPS/eip-1087
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1087.md
canonical: https://eips.huatuo.xyz/zh/eip-1087/
lang: zh
tldr: 提议按整个交易中存储槽的净变化来对 SSTORE 收费，这样对同一个槽多次写入或恢复其原始值时，就不再需要支付全价。
tags: [gas, sstore, storage, core, evm]
---

# EIP-1087: Net gas metering for SSTORE operations

> This EIP proposes a change to how gas is charged for EVM SSTORE operations, in order to reduce excessive gas costs in situations where these are unwarranted, and to enable new use-cases for contract storage.

**TL;DR:** 提议按整个交易中存储槽的净变化来对 SSTORE 收费，这样对同一个槽多次写入或恢复其原始值时，就不再需要支付全价。

## 它解决什么问题？

在 2018 年撰写这份 EIP 时，每一次 `SSTORE` 的定价都好像它是对该槽的唯一一次写入：从零变为非零需要 20,000 gas，其他任何变更需要 5,000 gas，清空一个槽则退还 10,000 gas。对单次写入来说这是公平的，但对触及同一个槽的一连串写入来说，收费就严重过高了。

规范给出了三个例子：

- 把一个全新的槽设为 1 再设回 0：收取 15,000 gas，尽管最终磁盘上什么都没有留下。
- 对一个全新的槽递增五次：收取 45,000 gas，尽管最终只写入了一个值。
- 在一笔交易中先转账 A → B，再转账 B → C：四次余额更新需要 20,000 gas。

这使得重入锁（设置一个标志，然后清除它）以及在同一笔交易的多次调用之间传递上下文这类模式，变得不必要地昂贵。

## 它如何运作

客户端为每笔交易维护一个记录已被更改的存储槽的**脏映射（dirty map）**。它遵循正常的调用作用域：如果某个调用帧 revert，它对脏映射的更改也会被丢弃。

- 写入槽中已有的值：**200 gas**。
- 在交易中第一次更改某个槽：如果原来为零则为 **20,000 gas**，否则为 **5,000 gas**，并把该槽标记为脏。
- 之后对脏槽的任何写入：**200 gas**。
- 交易结束时，对每个脏槽：
  - 原来为 0，现在又是 0 → 退还 19,800
  - 原来非零，现在恢复为原始值 → 退还 4,800
  - 原来非零，现在为 0 → 退还 15,000

按这些规则，上面的例子分别花费 400、21,000 和 10,400 gas。只对某个槽写入一次的交易，支付的费用与之前完全相同，因此没有任何合约会变得更贵。

## 示例代码

收费规则的伪代码（原始值 = 交易开始时的值）：

```python
def sstore_cost(slot, new_value, current, dirty):
    if new_value == current:
        return 200
    if slot in dirty:
        return 200
    dirty.add(slot)
    return 20000 if current == 0 else 5000

def end_of_tx_refund(dirty, original, final):
    refund = 0
    for slot in dirty:
        o, f = original[slot], final[slot]
        if o == 0 and f == 0:
            refund += 19800
        elif o != 0 and f == o:
            refund += 4800
        elif o != 0 and f == 0:
            refund += 15000
    return refund
```

从中受益的合约代码类型，一个简单的重入锁：

```solidity
uint256 private locked = 1;

modifier nonReentrant() {
    require(locked == 1, "reentrant");
    locked = 2;   // 第一次更改：5,000 gas
    _;
    locked = 1;   // 恢复为原始值：便宜，并且交易结束时还有退款
}
```

## 需要注意

- **状态：Stagnant。** EIP-1087 本身从未被激活。它的后继者 [EIP-1283](/eip-1283/) 通过比较槽的原始值、当前值和新值，在*没有*脏映射的情况下实现了同样的净计量思路。
- EIP-1283 原本计划纳入 Constantinople，但在激活前被撤下，因为更便宜的 `SSTORE` 使得代码可以在 `transfer`/`send` 所提供的 2,300 gas 津贴内运行，带来了重入风险。这个想法最终在 Istanbul 中以 [EIP-2200](/eip-2200/) 上线，它增加了一道防护：当剩余 gas 小于等于该津贴时，`SSTORE` 会失败（这一想法来自 [EIP-1706](/eip-1706/)）。
- 存储定价后来又随着冷/热访问成本（[EIP-2929](/eip-2929/)）和退款减少（[EIP-3529](/eip-3529/)）而再次改变，因此这里的具体数字属于历史信息。


---

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