{"eip":7686,"title":"Linear EVM memory limits","description":"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","authors":["Vitalik Buterin (@vbuterin)"],"status":"Stagnant","type":"Standards Track","category":"Core","created":"2024-04-15","discussionsTo":"https://ethereum-magicians.org/t/eip-7686-linear-evm-memory-limits/19448","repo":"EIPs","label":"EIP-7686","officialUrl":"https://eips.ethereum.org/EIPS/eip-7686","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7686.md","url":"https://eips.huatuo.xyz/eip-7686/","tldr":{"en":"Replaces quadratic memory pricing with a flat 3 gas per word plus a hard cap, so an EVM execution with N gas can never use more than N bytes of memory.","ja":"二次関数的なメモリ価格設定を 1 ワードあたり一律 3 gas とハードキャップに置き換え、N gas の EVM 実行が N バイトを超えるメモリを使えないようにする。","ko":"이차 함수 방식의 메모리 가격 책정을 워드당 일률 3 gas와 하드 캡으로 바꿔, N gas로 실행되는 EVM이 N바이트를 넘는 메모리를 쓸 수 없게 한다.","zh":"用每个字固定 3 gas 加硬性上限取代二次方内存定价，使得消耗 N gas 的 EVM 执行最多只能使用 N 字节内存。"},"tags":["evm","memory","gas","core","zk"],"explainers":{"en":{"lang":"en","tldr":"Replaces quadratic memory pricing with a flat 3 gas per word plus a hard cap, so an EVM execution with N gas can never use more than N bytes of memory.","tags":["evm","memory","gas","core","zk"],"related":[150,5656],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7686/","markdown":"## What problem does it solve?\n\nEVM memory is priced with two interacting rules: memory expansion costs grow quadratically with size, and a call can forward at most 63/64 of its remaining gas to a child call ([EIP-150](/eip-150/)). Together they do keep memory bounded, but working out the worst-case memory a transaction can need is hard. That matters for clients and especially for constrained environments such as ZK provers, which want to allocate a fixed amount of memory up front.\n\nEIP-7686, proposed by Vitalik Buterin, simplifies the rules and gives a clean, provable bound: **a transaction with N gas can use at most N bytes of memory in total** across all nested calls.\n\n## How it works\n\nThree changes:\n\n1. **Linear memory cost.** The quadratic term is dropped:\n\n   ```python\n   # before\n   memory_cost = (words ** 2) // 512 + 3 * words\n   # after\n   memory_cost = 3 * words\n   ```\n\n2. **Hard per-call limit.** If expanding memory would make the current call's memory size strictly exceed that call's *initial gas limit*, execution reverts.\n\n3. **Child calls are reduced by memory in use.** The gas a call may pass on becomes:\n\n   ```python\n   def max_call_gas(gas, memory_byte_size):\n       return gas - max(gas // 64, memory_byte_size)\n   ```\n\n   So a parent that has already used M bytes of memory can only forward gas minus M, and the child's own memory cap (its gas limit) is reduced accordingly.\n\nWith these rules a client can run an N-gas transaction inside one N-byte buffer: the current frame uses the bottom of the buffer, a child call uses the space starting right after the parent's memory, and so on recursively.\n\nThe 3 gas per word figure matches [MCOPY](/eip-5656/), so clearing a child's memory after it returns can reuse the same logic. The 63/64 rule is kept to preserve today's practical call-depth limit.\n\n## Sample code\n\nComparing old and new expansion costs and the new call-gas rule (pseudocode, Python syntax):\n\n```python\ndef old_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return w * w // 512 + 3 * w\n\ndef new_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return 3 * w\n\ndef check_expansion(new_byte_size: int, call_initial_gas: int) -\u003e None:\n    if new_byte_size \u003e call_initial_gas:\n        raise Exception(\"memory limit exceeded: revert\")\n\ndef max_call_gas(gas: int, memory_byte_size: int) -\u003e int:\n    return gas - max(gas // 64, memory_byte_size)\n\n# 1 MiB of memory\nprint(old_memory_cost(1 \u003c\u003c 20))   # 2,195,456 gas\nprint(new_memory_cost(1 \u003c\u003c 20))   #    98,304 gas, but the call now needs \u003e= 1,048,576 gas\n```\n\n## Things to know\n\n- Status is **Stagnant**: it has not been scheduled for any network upgrade.\n- Large memory becomes much cheaper per byte, but you can only use as many bytes as the call has gas, so a call with 100k gas can use at most 100k bytes of memory.\n- Code that touches a high memory offset while being called with a small gas limit could start reverting. The spec argues this is rare in practice: any call doing a state write already needs thousands of gas, and therefore has thousands of bytes of memory available.\n- A parent that has expanded memory a lot can forward less gas to its children than before, which can matter for contracts that build large buffers before making calls.\n"},"ja":{"lang":"ja","tldr":"二次関数的なメモリ価格設定を 1 ワードあたり一律 3 gas とハードキャップに置き換え、N gas の EVM 実行が N バイトを超えるメモリを使えないようにする。","tags":["evm","memory","gas","core","zk"],"related":[150,5656],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7686/","markdown":"## 何を解決するのか\n\nEVM のメモリ価格は 2 つのルールが組み合わさって決まります。メモリ拡張のコストはサイズに対して二次関数的に増加し、コールは残りの gas の最大 63/64 までしか子コールに渡せません（[EIP-150](/eip-150/)）。この 2 つによってメモリは確かに有界に保たれますが、トランザクションが必要とする最悪ケースのメモリ量を計算するのは困難です。これはクライアント、とりわけ固定量のメモリを事前に確保したい ZK プルーバーのような制約のある環境にとって重要です。\n\nVitalik Buterin が提案した EIP-7686 はルールを単純化し、明快で証明可能な上限を与えます。**N gas のトランザクションは、ネストしたすべてのコールの合計で最大 N バイトのメモリしか使えません。**\n\n## 仕組み\n\n変更点は 3 つです。\n\n1. **線形のメモリコスト。** 二次の項を取り除きます。\n\n   ```python\n   # before\n   memory_cost = (words ** 2) // 512 + 3 * words\n   # after\n   memory_cost = 3 * words\n   ```\n\n2. **コールごとのハード上限。** メモリを拡張した結果、現在のコールのメモリサイズがそのコールの*初期 gas リミット*を厳密に超える場合、実行は revert します。\n\n3. **子コールは使用中のメモリ分だけ減らされる。** コールが渡せる gas は次のようになります。\n\n   ```python\n   def max_call_gas(gas, memory_byte_size):\n       return gas - max(gas // 64, memory_byte_size)\n   ```\n\n   つまり、すでに M バイトのメモリを使っている親は、gas から M を引いた分しか渡せず、子自身のメモリ上限（その gas リミット）もそれに応じて小さくなります。\n\nこれらのルールにより、クライアントは N gas のトランザクションを 1 つの N バイトのバッファ内で実行できます。現在のフレームはバッファの先頭を使い、子コールは親のメモリの直後から始まる領域を使い、以降も再帰的に同様です。\n\n1 ワードあたり 3 gas という値は [MCOPY](/eip-5656/) と一致するため、子コールが戻った後のメモリのクリア処理も同じロジックを再利用できます。63/64 ルールは、現在の実用上のコール深度の上限を保つために維持されます。\n\n## サンプルコード\n\n旧来と新しい拡張コストの比較、および新しいコール gas ルール（擬似コード、Python 構文）:\n\n```python\ndef old_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return w * w // 512 + 3 * w\n\ndef new_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return 3 * w\n\ndef check_expansion(new_byte_size: int, call_initial_gas: int) -\u003e None:\n    if new_byte_size \u003e call_initial_gas:\n        raise Exception(\"memory limit exceeded: revert\")\n\ndef max_call_gas(gas: int, memory_byte_size: int) -\u003e int:\n    return gas - max(gas // 64, memory_byte_size)\n\n# 1 MiB of memory\nprint(old_memory_cost(1 \u003c\u003c 20))   # 2,195,456 gas\nprint(new_memory_cost(1 \u003c\u003c 20))   #    98,304 gas, but the call now needs \u003e= 1,048,576 gas\n```\n\n## 知っておくべきこと\n\n- ステータスは **Stagnant** です。どのネットワークアップグレードにもスケジュールされていません。\n- 大きなメモリはバイトあたりでかなり安価になりますが、使えるのはコールが持つ gas と同じバイト数までです。たとえば 100k gas のコールが使えるメモリは最大 100k バイトです。\n- 小さな gas リミットで呼び出されながら高いメモリオフセットに触れるコードは、revert するようになる可能性があります。仕様は、これが実際にはまれだと主張しています。ステート書き込みを行うコールはすでに数千 gas を必要とするため、数千バイトのメモリが使えるからです。\n- メモリを大きく拡張した親は、以前より子に渡せる gas が少なくなります。コールの前に大きなバッファを構築するコントラクトでは問題になる可能性があります。\n"},"ko":{"lang":"ko","tldr":"이차 함수 방식의 메모리 가격 책정을 워드당 일률 3 gas와 하드 캡으로 바꿔, N gas로 실행되는 EVM이 N바이트를 넘는 메모리를 쓸 수 없게 한다.","tags":["evm","memory","gas","core","zk"],"related":[150,5656],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7686/","markdown":"## 어떤 문제를 해결하나요?\n\nEVM 메모리 가격은 서로 맞물린 두 규칙으로 정해집니다. 메모리 확장 비용은 크기에 대해 이차 함수로 증가하고, 호출은 남은 gas의 최대 63/64까지만 자식 호출에 전달할 수 있습니다([EIP-150](/eip-150/)). 둘이 합쳐져 메모리가 한없이 커지지는 않지만, 트랜잭션이 필요로 할 수 있는 최악의 메모리 양을 계산하기는 어렵습니다. 이는 클라이언트, 특히 고정된 양의 메모리를 미리 할당하고 싶어 하는 ZK 증명기 같은 제한된 환경에 중요합니다.\n\nVitalik Buterin이 제안한 EIP-7686은 규칙을 단순하게 만들고 명확하게 증명 가능한 상한을 제공합니다. **gas가 N인 트랜잭션은 중첩된 모든 호출을 통틀어 최대 N바이트의 메모리만 사용할 수 있습니다.**\n\n## 어떻게 동작하나요?\n\n세 가지 변경이 있습니다.\n\n1. **선형 메모리 비용.** 이차 항을 없앱니다.\n\n   ```python\n   # before\n   memory_cost = (words ** 2) // 512 + 3 * words\n   # after\n   memory_cost = 3 * words\n   ```\n\n2. **호출별 하드 한도.** 메모리를 확장했을 때 현재 호출의 메모리 크기가 그 호출의 *초기 gas 한도*를 엄격하게 초과하면 실행이 revert됩니다.\n\n3. **자식 호출은 사용 중인 메모리만큼 줄어듭니다.** 호출이 넘길 수 있는 gas는 다음과 같이 됩니다.\n\n   ```python\n   def max_call_gas(gas, memory_byte_size):\n       return gas - max(gas // 64, memory_byte_size)\n   ```\n\n   따라서 이미 M바이트의 메모리를 사용한 부모는 gas에서 M을 뺀 만큼만 전달할 수 있고, 자식 자신의 메모리 상한(곧 gas 한도)도 그만큼 줄어듭니다.\n\n이 규칙을 적용하면 클라이언트는 N gas 트랜잭션을 N바이트짜리 버퍼 하나 안에서 실행할 수 있습니다. 현재 프레임은 버퍼의 앞부분을 쓰고, 자식 호출은 부모의 메모리 바로 뒤에서 시작하는 공간을 쓰며, 이후도 재귀적으로 같습니다.\n\n워드당 3 gas라는 값은 [MCOPY](/eip-5656/)와 같으므로, 자식 호출이 반환된 뒤 그 메모리를 비우는 로직도 같은 것을 재사용할 수 있습니다. 63/64 규칙은 오늘날의 실질적인 호출 깊이 한계를 유지하기 위해 그대로 둡니다.\n\n## 샘플 코드\n\n기존과 새로운 확장 비용, 그리고 새 호출 gas 규칙의 비교(의사 코드, Python 문법):\n\n```python\ndef old_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return w * w // 512 + 3 * w\n\ndef new_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return 3 * w\n\ndef check_expansion(new_byte_size: int, call_initial_gas: int) -\u003e None:\n    if new_byte_size \u003e call_initial_gas:\n        raise Exception(\"memory limit exceeded: revert\")\n\ndef max_call_gas(gas: int, memory_byte_size: int) -\u003e int:\n    return gas - max(gas // 64, memory_byte_size)\n\n# 1 MiB of memory\nprint(old_memory_cost(1 \u003c\u003c 20))   # 2,195,456 gas\nprint(new_memory_cost(1 \u003c\u003c 20))   #    98,304 gas, but the call now needs \u003e= 1,048,576 gas\n```\n\n## 알아둘 점\n\n- 상태는 **Stagnant**입니다. 어떤 네트워크 업그레이드에도 예정되어 있지 않습니다.\n- 큰 메모리는 바이트당 훨씬 저렴해지지만, 호출이 가진 gas만큼의 바이트만 쓸 수 있습니다. 따라서 100k gas의 호출은 최대 100k바이트의 메모리만 쓸 수 있습니다.\n- 작은 gas 한도로 호출되면서 높은 메모리 오프셋을 건드리는 코드는 revert되기 시작할 수 있습니다. 스펙은 실제로는 드문 경우라고 주장합니다. 상태 쓰기를 하는 호출은 이미 수천 gas가 필요하므로 수천 바이트의 메모리를 쓸 수 있기 때문입니다.\n- 메모리를 많이 확장한 부모는 이전보다 자식에게 전달할 수 있는 gas가 줄어듭니다. 호출하기 전에 큰 버퍼를 만드는 컨트랙트에는 영향이 있을 수 있습니다.\n"},"zh":{"lang":"zh","tldr":"用每个字固定 3 gas 加硬性上限取代二次方内存定价，使得消耗 N gas 的 EVM 执行最多只能使用 N 字节内存。","tags":["evm","memory","gas","core","zk"],"related":[150,5656],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7686/","markdown":"## 它解决什么问题？\n\nEVM 内存的定价由两条相互作用的规则决定：内存扩展成本随大小呈二次方增长，而一次调用最多只能向子调用转发其剩余 gas 的 63/64（[EIP-150](/eip-150/)）。两者合起来确实能让内存保持有界，但要算出一笔交易在最坏情况下所需的内存却很困难。这对客户端尤其是 ZK 证明器等受限环境很重要，它们希望预先分配固定大小的内存。\n\nEIP-7686 由 Vitalik Buterin 提出，它简化了这些规则，并给出一个清晰、可证明的上界：**一笔 gas 为 N 的交易，在所有嵌套调用中合计最多使用 N 字节内存。**\n\n## 它如何运作\n\n三项改动：\n\n1. **线性内存成本。** 去掉二次项：\n\n   ```python\n   # before\n   memory_cost = (words ** 2) // 512 + 3 * words\n   # after\n   memory_cost = 3 * words\n   ```\n\n2. **每次调用的硬性上限。** 如果扩展内存会使当前调用的内存大小严格超过该调用的*初始 gas 上限*，执行将 revert。\n\n3. **子调用要扣除已使用的内存。** 一次调用可以传递的 gas 变为：\n\n   ```python\n   def max_call_gas(gas, memory_byte_size):\n       return gas - max(gas // 64, memory_byte_size)\n   ```\n\n   因此，已经使用了 M 字节内存的父调用，只能转发\"gas 减去 M\"，子调用自身的内存上限（即它的 gas 上限）也相应减小。\n\n有了这些规则，客户端就可以在一个 N 字节的缓冲区内运行 N gas 的交易：当前调用帧使用缓冲区的起始部分，子调用使用紧接在父调用内存之后的空间，如此递归下去。\n\n每字 3 gas 这个数值与 [MCOPY](/eip-5656/) 一致，因此子调用返回后清理其内存的逻辑可以复用。63/64 规则被保留，以维持当前实际的调用深度限制。\n\n## 示例代码\n\n对比新旧内存扩展成本以及新的调用 gas 规则（伪代码，Python 语法）：\n\n```python\ndef old_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return w * w // 512 + 3 * w\n\ndef new_memory_cost(byte_size: int) -\u003e int:\n    w = (byte_size + 31) // 32\n    return 3 * w\n\ndef check_expansion(new_byte_size: int, call_initial_gas: int) -\u003e None:\n    if new_byte_size \u003e call_initial_gas:\n        raise Exception(\"memory limit exceeded: revert\")\n\ndef max_call_gas(gas: int, memory_byte_size: int) -\u003e int:\n    return gas - max(gas // 64, memory_byte_size)\n\n# 1 MiB of memory\nprint(old_memory_cost(1 \u003c\u003c 20))   # 2,195,456 gas\nprint(new_memory_cost(1 \u003c\u003c 20))   #    98,304 gas, but the call now needs \u003e= 1,048,576 gas\n```\n\n## 需要注意\n\n- 状态为 **Stagnant**：尚未被安排进任何网络升级。\n- 大内存的单位字节成本会便宜很多，但你能使用的字节数不会超过该调用拥有的 gas 数，因此一个 100k gas 的调用最多只能使用 100k 字节内存。\n- 以较小 gas 上限被调用、却访问较高内存偏移的代码，可能开始 revert。规范认为这在实践中很少见：任何执行状态写入的调用本来就需要数千 gas，因此也就有数千字节的内存可用。\n- 大量扩展过内存的父调用，能转发给子调用的 gas 会比以前更少，这对在发起调用前先构建大缓冲区的合约可能有影响。\n"}},"requiredBy":[8007]}
