---
eip: 5
label: EIP-5
title: Gas Usage for `RETURN` and `CALL*`
status: Final
type: Standards Track
category: Core
created: 2015-11-22
official: https://eips.ethereum.org/EIPS/eip-5
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-5.md
canonical: https://eips.huatuo.xyz/zh/eip-5/
lang: zh
tldr: 提议仅在被调用方真正写入输出内存后才对 CALL* 的输出内存收费，让合约可以低成本地接收字符串等动态大小的返回数据。
tags: [evm, gas, memory, calls, core]
---

# EIP-5: Gas Usage for `RETURN` and `CALL*`

> 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.

**TL;DR:** 提议仅在被调用方真正写入输出内存后才对 CALL* 的输出内存收费，让合约可以低成本地接收字符串等动态大小的返回数据。

## 它解决什么问题？

当一个合约用 `CALL`、`CALLCODE` 或 `DELEGATECALL` 调用另一个合约时，调用者会在自己的内存中指定一块输出区域：起始偏移和大小。返回数据会被复制到那里。在早期的 EVM 中，无论被调用方是否真的往里写了数据，调用者都要提前为整块区域支付内存扩展的 gas。

调用者通常不知道返回的结果有多大。字符串或动态数组可能存放在另一个合约的存储中。预留的区域太小会丢数据，预留得太大又要为从未用到的内存付费。这使得返回动态数据既昂贵又不灵活，也让转发任意调用输出的通用"代理"合约非常难写。

## 它如何运作

EIP-5 只修改 `CALL*` 周围的 gas 和内存规则，操作码签名保持不变：

- 调用开始时，内存扩展只对**输入**区域（`input_start + input_size`）收费，不对输出区域收费。
- 被调用方返回 `n` 字节时，内存扩展到 `output_start + min(output_size, n)`。调用者在此时为这次扩展付费，数据写入 `[output_start, output_start + min(n, output_size))`。
- 因此调用可能在操作码开始时或结束时耗尽 gas。
- 调用之后，`MSIZE` 反映内存实际扩展到的大小。

最后一点带来了一个获知返回大小的技巧：设置 `output_start = MSIZE` 和 `output_size = 2**256 - 1`。调用之后，旧 `MSIZE` 与新 `MSIZE` 之间的字节正是返回的数据。

`CREATE` 不受影响，因为它不会向调用者的内存写入任何内容。

## 示例代码

gas 计费在修改前后的伪代码：

```python
# before EIP-5: pay for both areas up front
charge_memory(max(input_start + input_size, output_start + output_size))
result = run_callee(...)
write(output_start, result[:output_size])

# with EIP-5: pay for the input now, for the output only once it is known
charge_memory(input_start + input_size)
result = run_callee(...)
n = len(result)
charge_memory(output_start + min(output_size, n))   # may run out of gas here
write(output_start, result[:min(n, output_size)])
```

规范中描述的返回大小技巧，用 EVM 汇编表示：

```
MSIZE                    // output_start = current end of memory
PUSH32 0xff..ff          // output_size = 2**256 - 1
...                      // input area, value, address, gas
CALL
MSIZE                    // new end of memory; difference = returned size
```

## 需要注意

- 规范指出，VM 收取的 gas 不会比以前更多。合约在调用后可能会看到剩余 gas 更多、`MSIZE` 更小。作者认为这不太可能破坏真实的合约。
- 状态为 Final，但如今使用的 EVM 仍然在调用开始时就对整个输出区域收取内存扩展费用。
- 实际上，动态返回数据的问题由 [EIP-211](/eip-211/)（Byzantium）解决。它新增了 `RETURNDATASIZE` 和 `RETURNDATACOPY`，调用者可以先检查大小，再精确复制相应字节数。Solidity 和代理合约都依赖这些操作码。
- 这里的 `CALL*` 家族包括由 [EIP-7](/eip-7/) 引入的 `DELEGATECALL`。


---

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