---
eip: 2542
label: EIP-2542
title: New opcodes TXGASLIMIT and CALLGASLIMIT
status: Withdrawn
type: Standards Track
category: Core
created: 2020-02-29
official: https://eips.ethereum.org/EIPS/eip-2542
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2542.md
canonical: https://eips.huatuo.xyz/zh/eip-2542/
lang: zh
tldr: 一项已撤回的提案：新增 TXGASLIMIT 和 CALLGASLIMIT 操作码，使合约能读取整个交易和当前调用帧的 gas 上限，以便精确核算 gas。
tags: [evm, opcodes, gas, meta-transactions, core]
---

# EIP-2542: New opcodes TXGASLIMIT and CALLGASLIMIT

> A mechanism to allow smart contracts to access information on gas limits for the current transaction and execution frame.

**TL;DR:** 一项已撤回的提案：新增 TXGASLIMIT 和 CALLGASLIMIT 操作码，使合约能读取整个交易和当前调用帧的 gas 上限，以便精确核算 gas。

## 它解决什么问题？

中继者、元交易转发器和账户抽象系统常常需要准确知道一笔交易用了多少 gas，才能收取或补偿正确的金额。EVM 只公开了：

- `GASLIMIT`（`0x45`）：**区块**的 gas 上限，合约很少关心它。
- `GAS`（`0x5a`，`gasleft()`）：**剩余的** gas，而不是起始时的数量。

因此合约只能做近似。一个常见的技巧是在第一行调用 `gasleft()`，之后再相减，但这会漏掉固有成本（21,000 的基础费用、calldata 字节），以及 Solidity 在你的第一行运行之前为复制 calldata 所花的 gas。另一个用例是强制执行用户在元交易中签名的 gas 上限：`gasleft()` 是动态的，无法与签名值比较。

## 它如何运作

该提案新增两个操作码，各消耗 2 gas（与 `GASLIMIT` 相同）：

| 操作码 | 字节 | 压入 |
| --- | --- | --- |
| `TXGASLIMIT` | `0x5c` | 签入交易的 gas 上限（`startgas`） |
| `CALLGASLIMIT` | `0x5d` | 按 [EIP-150](/eip-150/) "除去六十四分之一的全部"规则之后，分配给当前调用帧的 gas |

它还建议把 `GASLIMIT` 改名为 `BLOCKGASLIMIT` 以避免混淆。EVM 的其他部分不变，所以现有合约不受影响。

作者强调，这些值应当作为执行环境的信息使用，而不应成为安全机制的核心。

## 示例代码

提案原理说明中的伪 Solidity。`msg.gasLimit` 和 `tx.gasLimit` 从未被加入 Solidity，所以这段代码**无法编译**：

```solidity
// Illustrative only: would map to CALLGASLIMIT / TXGASLIMIT
function keepTrackOfGas() public {
    // ... work ...
    uint256 gasUsed = msg.gasLimit - gasleft();   // CALLGASLIMIT - GAS
}

function verifyGasLimit(uint256 desiredGasLimit /*, signature ... */) public {
    // the user signed desiredGasLimit; check the relayer honoured it
    require(tx.gasLimit == desiredGasLimit, "gas limit not authorized"); // TXGASLIMIT
}
```

开发者现在的替代做法（近似）：

```solidity
function relayed(bytes calldata data) external {
    uint256 start = gasleft();          // misses intrinsic + calldata cost
    // ... execute ...
    uint256 used = start - gasleft() + 21_000 + OVERHEAD_ESTIMATE;
}
```

## 需要注意

- **状态：Withdrawn（已撤回）。** 给出的撤回原因是"被 [EIP-8141](/eip-8141/)（Frame Transaction）取代"，而 EIP-8141 本身仍是 Draft。
- 操作码字节 `0x5c` 和 `0x5d` 后来被分配给了其他指令（[EIP-1153](/eip-1153/) 中的 `TLOAD` / `TSTORE`），因此这些编号已不可用。
- gas 自省存在争议：一些核心开发者希望合约完全不依赖 gas 值，以便可以随意重新定价 gas 成本。
- 对于当前的中继调用，请参阅 [ERC-2771](/eip-2771/)（可信转发器）和 [ERC-4337](/eip-4337/)，它们在 bundler/EntryPoint 层面处理 gas 核算。


---

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