---
eip: 7686
label: EIP-7686
title: Linear EVM memory limits
status: Stagnant
type: Standards Track
category: Core
created: 2024-04-15
official: https://eips.ethereum.org/EIPS/eip-7686
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7686.md
canonical: https://eips.huatuo.xyz/zh/eip-7686/
lang: zh
tldr: 用每个字固定 3 gas 加硬性上限取代二次方内存定价，使得消耗 N gas 的 EVM 执行最多只能使用 N 字节内存。
tags: [evm, memory, gas, core, zk]
---

# EIP-7686: Linear EVM memory limits

> Adjust memory limits and gas limits of sub-calls to create a clear linear bound on how much total memory an EVM execution can consume

**TL;DR:** 用每个字固定 3 gas 加硬性上限取代二次方内存定价，使得消耗 N gas 的 EVM 执行最多只能使用 N 字节内存。

## 它解决什么问题？

EVM 内存的定价由两条相互作用的规则决定：内存扩展成本随大小呈二次方增长，而一次调用最多只能向子调用转发其剩余 gas 的 63/64（[EIP-150](/eip-150/)）。两者合起来确实能让内存保持有界，但要算出一笔交易在最坏情况下所需的内存却很困难。这对客户端尤其是 ZK 证明器等受限环境很重要，它们希望预先分配固定大小的内存。

EIP-7686 由 Vitalik Buterin 提出，它简化了这些规则，并给出一个清晰、可证明的上界：**一笔 gas 为 N 的交易，在所有嵌套调用中合计最多使用 N 字节内存。**

## 它如何运作

三项改动：

1. **线性内存成本。** 去掉二次项：

   ```python
   # before
   memory_cost = (words ** 2) // 512 + 3 * words
   # after
   memory_cost = 3 * words
   ```

2. **每次调用的硬性上限。** 如果扩展内存会使当前调用的内存大小严格超过该调用的*初始 gas 上限*，执行将 revert。

3. **子调用要扣除已使用的内存。** 一次调用可以传递的 gas 变为：

   ```python
   def max_call_gas(gas, memory_byte_size):
       return gas - max(gas // 64, memory_byte_size)
   ```

   因此，已经使用了 M 字节内存的父调用，只能转发"gas 减去 M"，子调用自身的内存上限（即它的 gas 上限）也相应减小。

有了这些规则，客户端就可以在一个 N 字节的缓冲区内运行 N gas 的交易：当前调用帧使用缓冲区的起始部分，子调用使用紧接在父调用内存之后的空间，如此递归下去。

每字 3 gas 这个数值与 [MCOPY](/eip-5656/) 一致，因此子调用返回后清理其内存的逻辑可以复用。63/64 规则被保留，以维持当前实际的调用深度限制。

## 示例代码

对比新旧内存扩展成本以及新的调用 gas 规则（伪代码，Python 语法）：

```python
def old_memory_cost(byte_size: int) -> int:
    w = (byte_size + 31) // 32
    return w * w // 512 + 3 * w

def new_memory_cost(byte_size: int) -> int:
    w = (byte_size + 31) // 32
    return 3 * w

def check_expansion(new_byte_size: int, call_initial_gas: int) -> None:
    if new_byte_size > call_initial_gas:
        raise Exception("memory limit exceeded: revert")

def max_call_gas(gas: int, memory_byte_size: int) -> int:
    return gas - max(gas // 64, memory_byte_size)

# 1 MiB of memory
print(old_memory_cost(1 << 20))   # 2,195,456 gas
print(new_memory_cost(1 << 20))   #    98,304 gas, but the call now needs >= 1,048,576 gas
```

## 需要注意

- 状态为 **Stagnant**：尚未被安排进任何网络升级。
- 大内存的单位字节成本会便宜很多，但你能使用的字节数不会超过该调用拥有的 gas 数，因此一个 100k gas 的调用最多只能使用 100k 字节内存。
- 以较小 gas 上限被调用、却访问较高内存偏移的代码，可能开始 revert。规范认为这在实践中很少见：任何执行状态写入的调用本来就需要数千 gas，因此也就有数千字节的内存可用。
- 大量扩展过内存的父调用，能转发给子调用的 gas 会比以前更少，这对在发起调用前先构建大缓冲区的合约可能有影响。


---

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