{"eip":5,"title":"Gas Usage for `RETURN` and `CALL*`","description":"This EIP makes it possible to call functions that return strings and other dynamically-sized arrays. Currently, when another contract / function is called from inside the Ethereum Virtual Machine, the size of the output has to be specified in advance.","authors":["Christian Reitwiessner \u003cc@ethdev.com\u003e"],"status":"Final","type":"Standards Track","category":"Core","created":"2015-11-22","repo":"EIPs","label":"EIP-5","officialUrl":"https://eips.ethereum.org/EIPS/eip-5","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-5.md","url":"https://eips.huatuo.xyz/eip-5/","tldr":{"en":"Proposed charging CALL* for output memory only once the callee has actually written it, so contracts could cheaply receive strings and other dynamically sized return data.","ja":"呼び出し先が実際に書き込んだ分だけ CALL* の出力メモリに課金することを提案し、コントラクトが文字列などの可変長の戻りデータを安く受け取れるようにした。","ko":"피호출자가 실제로 쓴 뒤에만 CALL*의 출력 메모리에 비용을 매기도록 제안해, 컨트랙트가 문자열 같은 가변 크기 반환 데이터를 저렴하게 받을 수 있게 했다.","zh":"提议仅在被调用方真正写入输出内存后才对 CALL* 的输出内存收费，让合约可以低成本地接收字符串等动态大小的返回数据。"},"tags":["evm","gas","memory","calls","core"],"explainers":{"en":{"lang":"en","tldr":"Proposed charging CALL* for output memory only once the callee has actually written it, so contracts could cheaply receive strings and other dynamically sized return data.","tags":["evm","gas","memory","calls","core"],"related":[211,7,214],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-5/","markdown":"## What problem does it solve?\n\nWhen one contract calls another with `CALL`, `CALLCODE` or `DELEGATECALL`, the caller names an output area in its own memory: a start offset and a size. The return data is copied there. In the early EVM, the caller paid the memory expansion gas for that whole area up front, whether or not the callee wrote anything to it.\n\nThe caller usually does not know how large the answer will be. A string or a dynamic array might live in the other contract's storage. If you reserve a small area, you lose data. If you reserve a large one, you pay for memory you never use. This made returning dynamic data costly and inflexible, and it made generic \"proxy\" contracts that forward any call's output very hard to write.\n\n## How it works\n\nEIP-5 changes only the gas and memory rules around `CALL*`. Opcode signatures stay the same:\n\n- At the start of the call, memory expansion is charged only for the **input** area (`input_start + input_size`), not the output area.\n- When the callee returns `n` bytes, memory grows to `output_start + min(output_size, n)`. The caller pays for that growth at this point and the data is written to `[output_start, output_start + min(n, output_size))`.\n- The call can therefore run out of gas at the start or at the end of the opcode.\n- After the call, `MSIZE` reflects the size memory actually grew to.\n\nThat last point gives a trick for learning the return size. Set `output_start = MSIZE` and `output_size = 2**256 - 1`. After the call, the bytes between the old and new `MSIZE` are exactly what was returned.\n\n`CREATE` is unaffected because it writes nothing to the caller's memory.\n\n## Sample code\n\nPseudocode for the gas accounting, before and after:\n\n```python\n# before EIP-5: pay for both areas up front\ncharge_memory(max(input_start + input_size, output_start + output_size))\nresult = run_callee(...)\nwrite(output_start, result[:output_size])\n\n# with EIP-5: pay for the input now, for the output only once it is known\ncharge_memory(input_start + input_size)\nresult = run_callee(...)\nn = len(result)\ncharge_memory(output_start + min(output_size, n))   # may run out of gas here\nwrite(output_start, result[:min(n, output_size)])\n```\n\nThe return-size trick described in the spec, as EVM assembly:\n\n```\nMSIZE                    // output_start = current end of memory\nPUSH32 0xff..ff          // output_size = 2**256 - 1\n...                      // input area, value, address, gas\nCALL\nMSIZE                    // new end of memory; difference = returned size\n```\n\n## Things to know\n\n- The spec says the VM never charges more gas than before. Contracts might see more gas left over and a smaller `MSIZE` after a call. The authors judged that unlikely to break real contracts.\n- The status is Final, but the EVM in use today still charges memory expansion for the full output area at the start of a call.\n- In practice, dynamic return data was solved by [EIP-211](/eip-211/) (Byzantium). It added `RETURNDATASIZE` and `RETURNDATACOPY`, so a caller can check the size first and then copy exactly that many bytes. Solidity and proxy contracts rely on those opcodes.\n- The `CALL*` family here includes `DELEGATECALL`, which [EIP-7](/eip-7/) introduced.\n"},"ja":{"lang":"ja","tldr":"呼び出し先が実際に書き込んだ分だけ CALL* の出力メモリに課金することを提案し、コントラクトが文字列などの可変長の戻りデータを安く受け取れるようにした。","tags":["evm","gas","memory","calls","core"],"related":[211,7,214],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-5/","markdown":"## 何を解決するのか\n\nあるコントラクトが `CALL`、`CALLCODE`、`DELEGATECALL` で別のコントラクトを呼ぶとき、呼び出し元は自分のメモリ内の出力領域（開始オフセットとサイズ）を指定します。戻りデータはそこへコピーされます。初期の EVM では、呼び出し先が実際に何かを書き込むかどうかにかかわらず、呼び出し元がその領域全体のメモリ拡張ガスを先に支払っていました。\n\n呼び出し元は通常、返ってくるデータの大きさを知りません。文字列や動的配列が相手コントラクトのストレージにあるかもしれません。小さな領域を確保するとデータが失われ、大きな領域を確保すると使わないメモリ分まで支払うことになります。このため可変長データを返すにはコストがかかって柔軟性もなく、どんな呼び出しの出力でも転送する汎用の「プロキシ」コントラクトを書くのも非常に困難でした。\n\n## 仕組み\n\nEIP-5 が変更するのは `CALL*` まわりのガスとメモリのルールだけです。オペコードのシグネチャは変わりません。\n\n- 呼び出しの開始時に、メモリ拡張が課金されるのは**入力**領域（`input_start + input_size`）だけで、出力領域には課金されません。\n- 呼び出し先が `n` バイトを返すと、メモリは `output_start + min(output_size, n)` まで拡張されます。呼び出し元はこの時点でその拡張分を支払い、データは `[output_start, output_start + min(n, output_size))` に書き込まれます。\n- そのため、呼び出しはオペコードの開始時にも終了時にもガス切れになり得ます。\n- 呼び出し後の `MSIZE` は、メモリが実際に拡張されたサイズを反映します。\n\nこの最後の点により、戻りサイズを知るためのテクニックが使えます。`output_start = MSIZE`、`output_size = 2**256 - 1` に設定します。呼び出し後、古い `MSIZE` と新しい `MSIZE` の間のバイトが、返されたデータそのものになります。\n\n`CREATE` は呼び出し元のメモリに何も書き込まないため、影響を受けません。\n\n## サンプルコード\n\nガス計算の前後を示す擬似コード:\n\n```python\n# before EIP-5: pay for both areas up front\ncharge_memory(max(input_start + input_size, output_start + output_size))\nresult = run_callee(...)\nwrite(output_start, result[:output_size])\n\n# with EIP-5: pay for the input now, for the output only once it is known\ncharge_memory(input_start + input_size)\nresult = run_callee(...)\nn = len(result)\ncharge_memory(output_start + min(output_size, n))   # may run out of gas here\nwrite(output_start, result[:min(n, output_size)])\n```\n\n仕様に記載されている戻りサイズのテクニックを EVM アセンブリで示します。\n\n```\nMSIZE                    // output_start = current end of memory\nPUSH32 0xff..ff          // output_size = 2**256 - 1\n...                      // input area, value, address, gas\nCALL\nMSIZE                    // new end of memory; difference = returned size\n```\n\n## 知っておくべきこと\n\n- 仕様では、VM が以前より多くのガスを課金することはないとされています。コントラクトは呼び出し後に残りガスが増えたり、`MSIZE` が小さくなったりすることがあります。著者らは、これが実際のコントラクトを壊す可能性は低いと判断しました。\n- ステータスは Final ですが、現在使われている EVM は呼び出しの開始時に出力領域全体のメモリ拡張を課金しています。\n- 実際には、可変長の戻りデータの問題は [EIP-211](/eip-211/)（Byzantium）で解決されました。`RETURNDATASIZE` と `RETURNDATACOPY` が追加され、呼び出し元は先にサイズを確認してからそのバイト数だけコピーできます。Solidity やプロキシコントラクトはこれらのオペコードに依存しています。\n- ここでの `CALL*` ファミリーには、[EIP-7](/eip-7/) が導入した `DELEGATECALL` も含まれます。\n"},"ko":{"lang":"ko","tldr":"피호출자가 실제로 쓴 뒤에만 CALL*의 출력 메모리에 비용을 매기도록 제안해, 컨트랙트가 문자열 같은 가변 크기 반환 데이터를 저렴하게 받을 수 있게 했다.","tags":["evm","gas","memory","calls","core"],"related":[211,7,214],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-5/","markdown":"## 어떤 문제를 해결하나요?\n\n한 컨트랙트가 `CALL`, `CALLCODE`, `DELEGATECALL`로 다른 컨트랙트를 호출할 때, 호출자는 자신의 메모리 안에 출력 영역(시작 오프셋과 크기)을 지정합니다. 반환 데이터는 그곳으로 복사됩니다. 초기 EVM에서는 피호출자가 실제로 무언가를 쓰든 쓰지 않든, 호출자가 그 영역 전체의 메모리 확장 가스를 미리 냈습니다.\n\n호출자는 보통 응답이 얼마나 클지 모릅니다. 문자열이나 동적 배열이 다른 컨트랙트의 스토리지에 있을 수도 있습니다. 작은 영역을 잡으면 데이터를 잃고, 큰 영역을 잡으면 쓰지도 않는 메모리 비용을 냅니다. 그래서 동적 데이터를 반환하는 일은 비싸고 유연하지 못했으며, 어떤 호출의 출력이든 전달하는 범용 \"프록시\" 컨트랙트를 작성하기도 매우 어려웠습니다.\n\n## 어떻게 동작하나요?\n\nEIP-5는 `CALL*` 주변의 가스와 메모리 규칙만 바꿉니다. 오피코드 시그니처는 그대로입니다.\n\n- 호출이 시작될 때 메모리 확장 비용은 **입력** 영역(`input_start + input_size`)에만 부과되고, 출력 영역에는 부과되지 않습니다.\n- 피호출자가 `n` 바이트를 반환하면 메모리는 `output_start + min(output_size, n)`까지 확장됩니다. 호출자는 이 시점에 그 확장분을 지불하고, 데이터는 `[output_start, output_start + min(n, output_size))`에 기록됩니다.\n- 따라서 호출은 오피코드의 시작 시점이나 끝 시점 모두에서 가스가 부족해질 수 있습니다.\n- 호출 후 `MSIZE`는 메모리가 실제로 확장된 크기를 반영합니다.\n\n마지막 점 덕분에 반환 크기를 알아내는 요령이 생깁니다. `output_start = MSIZE`, `output_size = 2**256 - 1`로 설정합니다. 호출 후 이전 `MSIZE`와 새 `MSIZE` 사이의 바이트가 바로 반환된 데이터입니다.\n\n`CREATE`는 호출자의 메모리에 아무것도 쓰지 않으므로 영향을 받지 않습니다.\n\n## 샘플 코드\n\n가스 계산을 변경 전과 후로 비교한 의사 코드:\n\n```python\n# before EIP-5: pay for both areas up front\ncharge_memory(max(input_start + input_size, output_start + output_size))\nresult = run_callee(...)\nwrite(output_start, result[:output_size])\n\n# with EIP-5: pay for the input now, for the output only once it is known\ncharge_memory(input_start + input_size)\nresult = run_callee(...)\nn = len(result)\ncharge_memory(output_start + min(output_size, n))   # may run out of gas here\nwrite(output_start, result[:min(n, output_size)])\n```\n\n명세에 설명된 반환 크기 요령을 EVM 어셈블리로 나타내면 다음과 같습니다.\n\n```\nMSIZE                    // output_start = current end of memory\nPUSH32 0xff..ff          // output_size = 2**256 - 1\n...                      // input area, value, address, gas\nCALL\nMSIZE                    // new end of memory; difference = returned size\n```\n\n## 알아둘 점\n\n- 명세에 따르면 VM은 이전보다 더 많은 가스를 청구하지 않습니다. 컨트랙트는 호출 후 남은 가스가 더 많거나 `MSIZE`가 더 작은 것을 볼 수 있습니다. 작성자들은 이것이 실제 컨트랙트를 깨뜨릴 가능성은 낮다고 판단했습니다.\n- 상태는 Final이지만, 오늘날 사용되는 EVM은 여전히 호출 시작 시점에 출력 영역 전체의 메모리 확장 비용을 청구합니다.\n- 실제로 동적 반환 데이터 문제는 [EIP-211](/eip-211/)(Byzantium)이 해결했습니다. `RETURNDATASIZE`와 `RETURNDATACOPY`가 추가되어 호출자가 먼저 크기를 확인한 뒤 정확히 그만큼의 바이트를 복사할 수 있습니다. Solidity와 프록시 컨트랙트는 이 오피코드에 의존합니다.\n- 여기서 `CALL*` 계열에는 [EIP-7](/eip-7/)이 도입한 `DELEGATECALL`도 포함됩니다.\n"},"zh":{"lang":"zh","tldr":"提议仅在被调用方真正写入输出内存后才对 CALL* 的输出内存收费，让合约可以低成本地接收字符串等动态大小的返回数据。","tags":["evm","gas","memory","calls","core"],"related":[211,7,214],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-5/","markdown":"## 它解决什么问题？\n\n当一个合约用 `CALL`、`CALLCODE` 或 `DELEGATECALL` 调用另一个合约时，调用者会在自己的内存中指定一块输出区域：起始偏移和大小。返回数据会被复制到那里。在早期的 EVM 中，无论被调用方是否真的往里写了数据，调用者都要提前为整块区域支付内存扩展的 gas。\n\n调用者通常不知道返回的结果有多大。字符串或动态数组可能存放在另一个合约的存储中。预留的区域太小会丢数据，预留得太大又要为从未用到的内存付费。这使得返回动态数据既昂贵又不灵活，也让转发任意调用输出的通用\"代理\"合约非常难写。\n\n## 它如何运作\n\nEIP-5 只修改 `CALL*` 周围的 gas 和内存规则，操作码签名保持不变：\n\n- 调用开始时，内存扩展只对**输入**区域（`input_start + input_size`）收费，不对输出区域收费。\n- 被调用方返回 `n` 字节时，内存扩展到 `output_start + min(output_size, n)`。调用者在此时为这次扩展付费，数据写入 `[output_start, output_start + min(n, output_size))`。\n- 因此调用可能在操作码开始时或结束时耗尽 gas。\n- 调用之后，`MSIZE` 反映内存实际扩展到的大小。\n\n最后一点带来了一个获知返回大小的技巧：设置 `output_start = MSIZE` 和 `output_size = 2**256 - 1`。调用之后，旧 `MSIZE` 与新 `MSIZE` 之间的字节正是返回的数据。\n\n`CREATE` 不受影响，因为它不会向调用者的内存写入任何内容。\n\n## 示例代码\n\ngas 计费在修改前后的伪代码：\n\n```python\n# before EIP-5: pay for both areas up front\ncharge_memory(max(input_start + input_size, output_start + output_size))\nresult = run_callee(...)\nwrite(output_start, result[:output_size])\n\n# with EIP-5: pay for the input now, for the output only once it is known\ncharge_memory(input_start + input_size)\nresult = run_callee(...)\nn = len(result)\ncharge_memory(output_start + min(output_size, n))   # may run out of gas here\nwrite(output_start, result[:min(n, output_size)])\n```\n\n规范中描述的返回大小技巧，用 EVM 汇编表示：\n\n```\nMSIZE                    // output_start = current end of memory\nPUSH32 0xff..ff          // output_size = 2**256 - 1\n...                      // input area, value, address, gas\nCALL\nMSIZE                    // new end of memory; difference = returned size\n```\n\n## 需要注意\n\n- 规范指出，VM 收取的 gas 不会比以前更多。合约在调用后可能会看到剩余 gas 更多、`MSIZE` 更小。作者认为这不太可能破坏真实的合约。\n- 状态为 Final，但如今使用的 EVM 仍然在调用开始时就对整个输出区域收取内存扩展费用。\n- 实际上，动态返回数据的问题由 [EIP-211](/eip-211/)（Byzantium）解决。它新增了 `RETURNDATASIZE` 和 `RETURNDATACOPY`，调用者可以先检查大小，再精确复制相应字节数。Solidity 和代理合约都依赖这些操作码。\n- 这里的 `CALL*` 家族包括由 [EIP-7](/eip-7/) 引入的 `DELEGATECALL`。\n"}}}
