---
eip: 3860
label: EIP-3860
title: Limit and meter initcode
status: Final
type: Standards Track
category: Core
created: 2021-07-16
requires: 170
official: https://eips.ethereum.org/EIPS/eip-3860
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3860.md
canonical: https://eips.huatuo.xyz/zh/eip-3860/
lang: zh
tldr: 把合约 initcode 限制在 49,152 字节，并对其每 32 字节字收取 2 gas，使客户端分析部署代码所做的工作有上限且有偿。
tags: [evm, gas, contract-creation, initcode, core, shanghai]
---

# EIP-3860: Limit and meter initcode

> Limit the maximum size of initcode to 49152 and apply extra gas cost of 2 for every 32-byte chunk of initcode

**TL;DR:** 把合约 initcode 限制在 49,152 字节，并对其每 32 字节字收取 2 gas，使客户端分析部署代码所做的工作有上限且有偿。

## 它解决什么问题？

创建合约时，EVM 会运行其 **initcode**（构造函数加上要部署的代码）。在运行之前，客户端必须对整个 initcode 做 jumpdest 分析，这项工作随长度增长。在该 EIP 之前，这项工作既没有限制，也没有计量：

- 创建*交易*要为 initcode 支付 calldata gas，但从合约中调用的 `CREATE` 和 `CREATE2` 不需要支付任何与 initcode 大小成比例的费用（`CREATE2` 的哈希成本除外）。
- 协议没有对 initcode 大小设置上限，这使得最坏情况的分析很困难，也让其他几项 EVM 提案变得复杂。

EIP-3860 同时增加了大小限制和按字收费。它随 Shanghai 升级（2023 年）上线。

## 它如何运作

两个参数：

| 常量 | 值 |
| --- | --- |
| `MAX_INITCODE_SIZE` | `2 * MAX_CODE_SIZE` = 49152 字节（[EIP-170](/eip-170/) 规定 `MAX_CODE_SIZE` = 24576） |
| `INITCODE_WORD_COST` | 每 32 字节字 2 gas |

`initcode_cost(initcode) = 2 * ceil(len(initcode) / 32)`

规则：

1. initcode 超过 `MAX_INITCODE_SIZE` 的**创建交易**无效，不能被打包进区块。
2. 创建交易会把 `initcode_cost` 加到其**固有 gas** 上，因此无法覆盖该费用的交易无效。
3. initcode 超出限制的 `CREATE` / `CREATE2` 会**异常中止**，就像 gas 耗尽一样。
4. `CREATE` / `CREATE2` 在计算新地址和运行 initcode 之前，先预先收取 `initcode_cost`。对于 `CREATE2`，这与其原有的每字 6 gas 的哈希成本（[EIP-1014](/eip-1014/)）并存，因此现在总共每字支付 8 gas。

该限制还意味着代码大小、`PC` 和跳转偏移量都能用 16 位表示，这对 EVM 实现是一种简化。

## 示例代码

额外成本和限制检查，按客户端的计算方式给出：

```python
MAX_CODE_SIZE = 24576
MAX_INITCODE_SIZE = 2 * MAX_CODE_SIZE   # 49152
INITCODE_WORD_COST = 2

def initcode_cost(initcode: bytes) -> int:
    return INITCODE_WORD_COST * ((len(initcode) + 31) // 32)

def check_create(initcode: bytes) -> int:
    if len(initcode) > MAX_INITCODE_SIZE:
        raise Exception("exceptional abort: initcode too large")
    return initcode_cost(initcode)

print(initcode_cost(b"\x00" * 49152))  # 3072 gas at the maximum size
```

脚本中的部署前检查（ethers v6）：

```ts
import { ContractFactory, getBytes } from "ethers";

const tx = await factory.getDeployTransaction(...args); // factory: ContractFactory
const size = getBytes(tx.data!).length;
if (size > 49152) throw new Error(`initcode is ${size} bytes; limit is 49152`);
```

## 需要注意

- **状态：Final**，自 Shanghai 起在主网生效。
- 对于普通部署，该限制给完整的 24 KB 运行时合约加上同样大的构造函数留出了空间。把多个合约的字节码嵌入同一个 initcode 的工厂合约最有可能触及该限制。
- 超大的创建*交易*会被直接拒绝；执行中超大的 `CREATE`/`CREATE2` 只会使该次调用失败（消耗其 gas），外层交易仍然可以被打包。
- 与 calldata 的定价（每字节 4/16 gas）相比，创建交易的成本微不足道；加入它主要是为了一致性和未来的可扩展性。
- 已部署的合约不受影响。


---

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