{"eip":1087,"title":"Net gas metering for SSTORE operations","description":"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.","authors":["Nick Johnson (@arachnid)"],"status":"Stagnant","type":"Standards Track","category":"Core","created":"2018-05-17","discussionsTo":"https://ethereum-magicians.org/t/eip-net-storage-gas-metering-for-the-evm/383","repo":"EIPs","label":"EIP-1087","officialUrl":"https://eips.ethereum.org/EIPS/eip-1087","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1087.md","url":"https://eips.huatuo.xyz/eip-1087/","tldr":{"en":"Proposed charging SSTORE by the net change to a storage slot over a whole transaction, so writing a slot several times or restoring its original value no longer costs full price.","ja":"SSTORE の料金を、トランザクション全体でのストレージスロットの正味の変化量に基づいて課す提案。同じスロットに複数回書き込んだり、元の値に戻したりしても、満額を支払わなくて済むようにする。","ko":"SSTORE 요금을 트랜잭션 전체에서 스토리지 슬롯의 순변화량을 기준으로 부과하자는 제안. 한 슬롯에 여러 번 쓰거나 원래 값으로 되돌려도 더 이상 전액을 내지 않게 한다.","zh":"提议按整个交易中存储槽的净变化来对 SSTORE 收费，这样对同一个槽多次写入或恢复其原始值时，就不再需要支付全价。"},"tags":["gas","sstore","storage","core","evm"],"explainers":{"en":{"lang":"en","tldr":"Proposed charging SSTORE by the net change to a storage slot over a whole transaction, so writing a slot several times or restoring its original value no longer costs full price.","tags":["gas","sstore","storage","core","evm"],"related":[1283,2200,1706,2929,3529],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-1087/","markdown":"## What problem does it solve?\n\nWhen this EIP was written in 2018, every `SSTORE` was priced as if it were the only write to that slot: 20,000 gas to go from zero to non-zero, 5,000 gas for any other change, and a 10,000 gas refund for clearing a slot. That is fair for a single write, but wildly overcharges sequences of writes that touch the same slot.\n\nThe spec gives three examples:\n\n- Set a fresh slot to 1 and back to 0: charged 15,000 gas, though nothing ends up on disk.\n- Increment a fresh slot five times: charged 45,000 gas, though only one final value is written.\n- Transfer A → B, then B → C within one transaction: 20,000 gas for four balance updates.\n\nThis made patterns like reentrancy locks (set a flag, then clear it) and passing context between calls in the same transaction needlessly expensive.\n\n## How it works\n\nThe client keeps a per-transaction **dirty map** of storage slots that have been changed. It follows normal call scoping: if a call frame reverts, its dirty-map changes are discarded too.\n\n- Writing the value a slot already holds: **200 gas**.\n- First change to a slot in the transaction: **20,000 gas** if it was zero, otherwise **5,000 gas**, and the slot is marked dirty.\n- Any further write to a dirty slot: **200 gas**.\n- At the end of the transaction, for each dirty slot:\n  - was 0 and is 0 again → refund 19,800\n  - was non-zero and is back to its original value → refund 4,800\n  - was non-zero and is now 0 → refund 15,000\n\nUnder these rules the examples above cost 400, 21,000 and 10,400 gas respectively. A transaction that writes a slot only once pays exactly what it did before, so no contract gets more expensive.\n\n## Sample code\n\nPseudocode for the charging rule (original value = value at transaction start):\n\n```python\ndef sstore_cost(slot, new_value, current, dirty):\n    if new_value == current:\n        return 200\n    if slot in dirty:\n        return 200\n    dirty.add(slot)\n    return 20000 if current == 0 else 5000\n\ndef end_of_tx_refund(dirty, original, final):\n    refund = 0\n    for slot in dirty:\n        o, f = original[slot], final[slot]\n        if o == 0 and f == 0:\n            refund += 19800\n        elif o != 0 and f == o:\n            refund += 4800\n        elif o != 0 and f == 0:\n            refund += 15000\n    return refund\n```\n\nThe kind of contract code that benefits, a simple reentrancy lock:\n\n```solidity\nuint256 private locked = 1;\n\nmodifier nonReentrant() {\n    require(locked == 1, \"reentrant\");\n    locked = 2;   // first change: 5,000 gas\n    _;\n    locked = 1;   // back to original: cheap, plus a refund at tx end\n}\n```\n\n## Things to know\n\n- **Status: Stagnant.** EIP-1087 itself was never activated. Its successor [EIP-1283](/eip-1283/) achieved the same net-metering idea *without* a dirty map by comparing the original, current and new values of a slot.\n- EIP-1283 was scheduled for Constantinople but pulled before activation because cheaper `SSTORE` let code run within the 2,300-gas stipend given to `transfer`/`send`, opening a reentrancy risk. The idea finally shipped in Istanbul as [EIP-2200](/eip-2200/), which adds a guard that `SSTORE` fails when gas left is at or below the stipend (an idea from [EIP-1706](/eip-1706/)).\n- Storage pricing has since changed again with cold/warm access costs ([EIP-2929](/eip-2929/)) and reduced refunds ([EIP-3529](/eip-3529/)), so the exact numbers here are historical.\n"},"ja":{"lang":"ja","tldr":"SSTORE の料金を、トランザクション全体でのストレージスロットの正味の変化量に基づいて課す提案。同じスロットに複数回書き込んだり、元の値に戻したりしても、満額を支払わなくて済むようにする。","tags":["gas","sstore","storage","core","evm"],"related":[1283,2200,1706,2929,3529],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-1087/","markdown":"## 何を解決するのか\n\nこの EIP が書かれた 2018 年当時、すべての `SSTORE` は、そのスロットへの唯一の書き込みであるかのように価格が付けられていました。ゼロから非ゼロへの変更は 20,000 ガス、それ以外の変更は 5,000 ガス、スロットをクリアすると 10,000 ガスの返金です。1 回の書き込みならこれは公平ですが、同じスロットに触れる一連の書き込みに対しては、大幅に課金しすぎになります。\n\n仕様には 3 つの例が挙げられています。\n\n- 新しいスロットを 1 に設定して 0 に戻す。最終的にディスクには何も残らないのに、15,000 ガスが課金される。\n- 新しいスロットを 5 回インクリメントする。最終的に書き込まれる値は 1 つだけなのに、45,000 ガスが課金される。\n- 1 つのトランザクション内で A → B、続けて B → C と送金する。4 回の残高更新に 20,000 ガスかかる。\n\nこのため、リエントランシーロック（フラグを設定して、あとでクリアする）や、同じトランザクション内の呼び出し間でコンテキストを受け渡すといったパターンが、不必要に高くなっていました。\n\n## 仕組み\n\nクライアントは、変更されたストレージスロットのトランザクションごとの**ダーティマップ**を保持します。これは通常の呼び出しスコープに従います。呼び出しフレームが revert した場合、そのダーティマップの変更も破棄されます。\n\n- スロットがすでに持っている値を書き込む: **200 ガス**。\n- トランザクション内でそのスロットを初めて変更する: ゼロだった場合は **20,000 ガス**、そうでなければ **5,000 ガス**で、スロットはダーティとしてマークされます。\n- ダーティなスロットへのそれ以降の書き込み: **200 ガス**。\n- トランザクションの終了時、各ダーティスロットについて:\n  - 0 だったものが再び 0 になった → 19,800 を返金\n  - 非ゼロだったものが元の値に戻った → 4,800 を返金\n  - 非ゼロだったものが 0 になった → 15,000 を返金\n\nこれらのルールでは、上の例はそれぞれ 400、21,000、10,400 ガスになります。スロットに 1 回しか書き込まないトランザクションは、以前とまったく同じ額を支払うため、料金が高くなるコントラクトはありません。\n\n## サンプルコード\n\n課金ルールの擬似コードです（元の値 = トランザクション開始時の値）。\n\n```python\ndef sstore_cost(slot, new_value, current, dirty):\n    if new_value == current:\n        return 200\n    if slot in dirty:\n        return 200\n    dirty.add(slot)\n    return 20000 if current == 0 else 5000\n\ndef end_of_tx_refund(dirty, original, final):\n    refund = 0\n    for slot in dirty:\n        o, f = original[slot], final[slot]\n        if o == 0 and f == 0:\n            refund += 19800\n        elif o != 0 and f == o:\n            refund += 4800\n        elif o != 0 and f == 0:\n            refund += 15000\n    return refund\n```\n\n恩恵を受けるコントラクトコードの種類として、単純なリエントランシーロックを示します。\n\n```solidity\nuint256 private locked = 1;\n\nmodifier nonReentrant() {\n    require(locked == 1, \"reentrant\");\n    locked = 2;   // 最初の変更: 5,000 ガス\n    _;\n    locked = 1;   // 元の値に戻る: 安価で、トランザクション終了時に返金もある\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Stagnant。** EIP-1087 自体が有効化されることはありませんでした。後継の [EIP-1283](/eip-1283/) は、スロットの元の値・現在の値・新しい値を比較することで、ダーティマップを使わずに同じ正味計測の考え方を実現しました。\n- EIP-1283 は Constantinople に予定されていましたが、`SSTORE` が安くなると `transfer`/`send` に与えられる 2,300 ガスのスタイペンド内でコードを実行できてしまい、リエントランシーのリスクが生じるため、有効化の前に取り下げられました。このアイデアは最終的に Istanbul で [EIP-2200](/eip-2200/) として導入され、残りガスがスタイペンド以下のときは `SSTORE` が失敗するというガード（[EIP-1706](/eip-1706/) のアイデア）が追加されました。\n- ストレージの価格設定はその後、コールド/ウォームアクセスのコスト（[EIP-2929](/eip-2929/)）と返金の削減（[EIP-3529](/eip-3529/)）によって再び変更されたため、ここに示した正確な数値は歴史的なものです。\n"},"ko":{"lang":"ko","tldr":"SSTORE 요금을 트랜잭션 전체에서 스토리지 슬롯의 순변화량을 기준으로 부과하자는 제안. 한 슬롯에 여러 번 쓰거나 원래 값으로 되돌려도 더 이상 전액을 내지 않게 한다.","tags":["gas","sstore","storage","core","evm"],"related":[1283,2200,1706,2929,3529],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-1087/","markdown":"## 어떤 문제를 해결하나요?\n\n이 EIP가 작성된 2018년에는 모든 `SSTORE`가 그 슬롯에 대한 유일한 쓰기인 것처럼 가격이 매겨졌습니다. 0에서 0이 아닌 값으로 바꾸면 20,000 가스, 그 외의 변경은 5,000 가스, 슬롯을 비우면 10,000 가스를 환불했습니다. 쓰기가 한 번뿐이라면 공정하지만, 같은 슬롯을 건드리는 연속된 쓰기에는 터무니없이 과다 청구가 됩니다.\n\n명세는 세 가지 예를 듭니다.\n\n- 새 슬롯을 1로 설정했다가 0으로 되돌림: 결국 디스크에 남는 것이 없는데도 15,000 가스가 청구됩니다.\n- 새 슬롯을 다섯 번 증가시킴: 마지막 값 하나만 기록되는데도 45,000 가스가 청구됩니다.\n- 한 트랜잭션 안에서 A → B, 이어서 B → C로 전송: 잔액 업데이트 네 번에 20,000 가스가 듭니다.\n\n이 때문에 재진입 잠금(플래그를 설정했다가 지우는 방식)이나 같은 트랜잭션 안의 호출 사이에 컨텍스트를 전달하는 패턴이 불필요하게 비쌌습니다.\n\n## 어떻게 동작하나요?\n\n클라이언트는 변경된 스토리지 슬롯의 트랜잭션별 **더티 맵(dirty map)**을 유지합니다. 이는 일반적인 호출 스코프를 따릅니다. 호출 프레임이 revert되면 그 프레임의 더티 맵 변경도 폐기됩니다.\n\n- 슬롯이 이미 가진 값을 쓰는 경우: **200 가스**.\n- 트랜잭션에서 슬롯을 처음 변경하는 경우: 0이었다면 **20,000 가스**, 아니면 **5,000 가스**이며, 슬롯은 더티로 표시됩니다.\n- 더티 슬롯에 대한 이후의 모든 쓰기: **200 가스**.\n- 트랜잭션이 끝날 때 각 더티 슬롯에 대해:\n  - 0이었다가 다시 0이 됨 → 19,800 환불\n  - 0이 아니었다가 원래 값으로 돌아옴 → 4,800 환불\n  - 0이 아니었다가 지금은 0임 → 15,000 환불\n\n이 규칙에 따르면 위의 예시는 각각 400, 21,000, 10,400 가스가 듭니다. 슬롯에 한 번만 쓰는 트랜잭션은 이전과 정확히 같은 금액을 내므로, 더 비싸지는 컨트랙트는 없습니다.\n\n## 샘플 코드\n\n요금 부과 규칙의 의사 코드입니다(원래 값 = 트랜잭션 시작 시점의 값).\n\n```python\ndef sstore_cost(slot, new_value, current, dirty):\n    if new_value == current:\n        return 200\n    if slot in dirty:\n        return 200\n    dirty.add(slot)\n    return 20000 if current == 0 else 5000\n\ndef end_of_tx_refund(dirty, original, final):\n    refund = 0\n    for slot in dirty:\n        o, f = original[slot], final[slot]\n        if o == 0 and f == 0:\n            refund += 19800\n        elif o != 0 and f == o:\n            refund += 4800\n        elif o != 0 and f == 0:\n            refund += 15000\n    return refund\n```\n\n혜택을 받는 컨트랙트 코드의 한 종류로, 간단한 재진입 잠금입니다.\n\n```solidity\nuint256 private locked = 1;\n\nmodifier nonReentrant() {\n    require(locked == 1, \"reentrant\");\n    locked = 2;   // 첫 번째 변경: 5,000 가스\n    _;\n    locked = 1;   // 원래 값으로 복귀: 저렴하고, 트랜잭션 종료 시 환불도 있음\n}\n```\n\n## 알아둘 점\n\n- **상태: Stagnant.** EIP-1087 자체는 활성화된 적이 없습니다. 후속 제안인 [EIP-1283](/eip-1283/)은 슬롯의 원래 값, 현재 값, 새 값을 비교하는 방식으로 더티 맵 *없이* 같은 순 계량 아이디어를 구현했습니다.\n- EIP-1283은 Constantinople에 포함될 예정이었지만, `SSTORE`가 싸지면 `transfer`/`send`에 주어지는 2,300 가스 스타이펜드 안에서도 코드를 실행할 수 있게 되어 재진입 위험이 생기므로 활성화 전에 철회되었습니다. 이 아이디어는 결국 Istanbul에서 [EIP-2200](/eip-2200/)으로 출시되었고, 남은 가스가 스타이펜드 이하일 때 `SSTORE`가 실패하도록 하는 안전장치([EIP-1706](/eip-1706/)의 아이디어)가 추가되었습니다.\n- 스토리지 가격은 이후 콜드/웜 접근 비용([EIP-2929](/eip-2929/))과 환불 축소([EIP-3529](/eip-3529/))로 다시 바뀌었으므로, 여기 나온 정확한 수치는 역사적인 것입니다.\n"},"zh":{"lang":"zh","tldr":"提议按整个交易中存储槽的净变化来对 SSTORE 收费，这样对同一个槽多次写入或恢复其原始值时，就不再需要支付全价。","tags":["gas","sstore","storage","core","evm"],"related":[1283,2200,1706,2929,3529],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-1087/","markdown":"## 它解决什么问题？\n\n在 2018 年撰写这份 EIP 时，每一次 `SSTORE` 的定价都好像它是对该槽的唯一一次写入：从零变为非零需要 20,000 gas，其他任何变更需要 5,000 gas，清空一个槽则退还 10,000 gas。对单次写入来说这是公平的，但对触及同一个槽的一连串写入来说，收费就严重过高了。\n\n规范给出了三个例子：\n\n- 把一个全新的槽设为 1 再设回 0：收取 15,000 gas，尽管最终磁盘上什么都没有留下。\n- 对一个全新的槽递增五次：收取 45,000 gas，尽管最终只写入了一个值。\n- 在一笔交易中先转账 A → B，再转账 B → C：四次余额更新需要 20,000 gas。\n\n这使得重入锁（设置一个标志，然后清除它）以及在同一笔交易的多次调用之间传递上下文这类模式，变得不必要地昂贵。\n\n## 它如何运作\n\n客户端为每笔交易维护一个记录已被更改的存储槽的**脏映射（dirty map）**。它遵循正常的调用作用域：如果某个调用帧 revert，它对脏映射的更改也会被丢弃。\n\n- 写入槽中已有的值：**200 gas**。\n- 在交易中第一次更改某个槽：如果原来为零则为 **20,000 gas**，否则为 **5,000 gas**，并把该槽标记为脏。\n- 之后对脏槽的任何写入：**200 gas**。\n- 交易结束时，对每个脏槽：\n  - 原来为 0，现在又是 0 → 退还 19,800\n  - 原来非零，现在恢复为原始值 → 退还 4,800\n  - 原来非零，现在为 0 → 退还 15,000\n\n按这些规则，上面的例子分别花费 400、21,000 和 10,400 gas。只对某个槽写入一次的交易，支付的费用与之前完全相同，因此没有任何合约会变得更贵。\n\n## 示例代码\n\n收费规则的伪代码（原始值 = 交易开始时的值）：\n\n```python\ndef sstore_cost(slot, new_value, current, dirty):\n    if new_value == current:\n        return 200\n    if slot in dirty:\n        return 200\n    dirty.add(slot)\n    return 20000 if current == 0 else 5000\n\ndef end_of_tx_refund(dirty, original, final):\n    refund = 0\n    for slot in dirty:\n        o, f = original[slot], final[slot]\n        if o == 0 and f == 0:\n            refund += 19800\n        elif o != 0 and f == o:\n            refund += 4800\n        elif o != 0 and f == 0:\n            refund += 15000\n    return refund\n```\n\n从中受益的合约代码类型，一个简单的重入锁：\n\n```solidity\nuint256 private locked = 1;\n\nmodifier nonReentrant() {\n    require(locked == 1, \"reentrant\");\n    locked = 2;   // 第一次更改：5,000 gas\n    _;\n    locked = 1;   // 恢复为原始值：便宜，并且交易结束时还有退款\n}\n```\n\n## 需要注意\n\n- **状态：Stagnant。** EIP-1087 本身从未被激活。它的后继者 [EIP-1283](/eip-1283/) 通过比较槽的原始值、当前值和新值，在*没有*脏映射的情况下实现了同样的净计量思路。\n- EIP-1283 原本计划纳入 Constantinople，但在激活前被撤下，因为更便宜的 `SSTORE` 使得代码可以在 `transfer`/`send` 所提供的 2,300 gas 津贴内运行，带来了重入风险。这个想法最终在 Istanbul 中以 [EIP-2200](/eip-2200/) 上线，它增加了一道防护：当剩余 gas 小于等于该津贴时，`SSTORE` 会失败（这一想法来自 [EIP-1706](/eip-1706/)）。\n- 存储定价后来又随着冷/热访问成本（[EIP-2929](/eip-2929/)）和退款减少（[EIP-3529](/eip-3529/)）而再次改变，因此这里的具体数字属于历史信息。\n"}}}
