{"eip":2542,"title":"New opcodes TXGASLIMIT and CALLGASLIMIT","description":"A mechanism to allow smart contracts to access information on gas limits for the current transaction and execution frame.","authors":["Alex Forshtat \u003cforshtat1@gmail.com\u003e"],"status":"Withdrawn","type":"Standards Track","category":"Core","created":"2020-02-29","discussionsTo":"https://ethereum-magicians.org/t/eip-2542-add-txgaslimit-callgaslimit-txgasrefund-opcodes","repo":"EIPs","label":"EIP-2542","officialUrl":"https://eips.ethereum.org/EIPS/eip-2542","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2542.md","url":"https://eips.huatuo.xyz/eip-2542/","tldr":{"en":"A withdrawn proposal for TXGASLIMIT and CALLGASLIMIT opcodes, which would have let contracts read the gas limit of the whole transaction and of the current call frame for exact gas accounting.","ja":"撤回された提案。TXGASLIMIT と CALLGASLIMIT の opcode により、コントラクトがトランザクション全体と現在のコールフレームのガスリミットを読み取り、正確なガス計算ができるようにするものだった。","ko":"철회된 제안. TXGASLIMIT와 CALLGASLIMIT opcode로 컨트랙트가 트랜잭션 전체와 현재 호출 프레임의 가스 한도를 읽어 정확하게 가스를 계산할 수 있게 하려 했다.","zh":"一项已撤回的提案：新增 TXGASLIMIT 和 CALLGASLIMIT 操作码，使合约能读取整个交易和当前调用帧的 gas 上限，以便精确核算 gas。"},"tags":["evm","opcodes","gas","meta-transactions","core"],"explainers":{"en":{"lang":"en","tldr":"A withdrawn proposal for TXGASLIMIT and CALLGASLIMIT opcodes, which would have let contracts read the gas limit of the whole transaction and of the current call frame for exact gas accounting.","tags":["evm","opcodes","gas","meta-transactions","core"],"related":[8141,150,2771,4337],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-2542/","markdown":"## What problem does it solve?\n\nRelayers, meta-transaction forwarders and account abstraction systems often need to know exactly how much gas a transaction has used so they can charge or reimburse the right amount. The EVM only exposes:\n\n- `GASLIMIT` (`0x45`) – the **block** gas limit, which contracts rarely care about.\n- `GAS` (`0x5a`, `gasleft()`) – the gas **remaining**, not the amount you started with.\n\nSo contracts approximate. A common trick is to call `gasleft()` on the first line and subtract later, but that misses intrinsic costs (the 21,000 base, calldata bytes) and whatever Solidity spent copying calldata before your first line ran. Another use case is enforcing a gas limit that a user signed in a meta-transaction: `gasleft()` is dynamic and cannot be compared with a signed value.\n\n## How it works\n\nThe proposal adds two opcodes, each costing 2 gas (the same as `GASLIMIT`):\n\n| Opcode | Byte | Pushes |\n| --- | --- | --- |\n| `TXGASLIMIT` | `0x5c` | The gas limit signed into the transaction (`startgas`) |\n| `CALLGASLIMIT` | `0x5d` | The gas given to the current frame, after the [EIP-150](/eip-150/) \"all but one 64th\" rule |\n\nIt also suggests renaming `GASLIMIT` to `BLOCKGASLIMIT` to avoid confusion. Nothing else in the EVM changes, so existing contracts are unaffected.\n\nThe authors stress that these values should be used as information about the execution environment, not as the core of a security mechanism.\n\n## Sample code\n\nPseudo-Solidity from the proposal's rationale. `msg.gasLimit` and `tx.gasLimit` were never added to Solidity, so this does **not** compile:\n\n```solidity\n// Illustrative only: would map to CALLGASLIMIT / TXGASLIMIT\nfunction keepTrackOfGas() public {\n    // ... work ...\n    uint256 gasUsed = msg.gasLimit - gasleft();   // CALLGASLIMIT - GAS\n}\n\nfunction verifyGasLimit(uint256 desiredGasLimit /*, signature ... */) public {\n    // the user signed desiredGasLimit; check the relayer honoured it\n    require(tx.gasLimit == desiredGasLimit, \"gas limit not authorized\"); // TXGASLIMIT\n}\n```\n\nWhat developers do today instead (approximate):\n\n```solidity\nfunction relayed(bytes calldata data) external {\n    uint256 start = gasleft();          // misses intrinsic + calldata cost\n    // ... execute ...\n    uint256 used = start - gasleft() + 21_000 + OVERHEAD_ESTIMATE;\n}\n```\n\n## Things to know\n\n- **Status: Withdrawn.** The withdrawal reason given is \"Superseded by [EIP-8141](/eip-8141/)\" (Frame Transaction), which is itself still a Draft.\n- Opcode bytes `0x5c` and `0x5d` were later assigned to other instructions (`TLOAD`/`TSTORE` in [EIP-1153](/eip-1153/)), so these numbers are no longer available.\n- Gas introspection is controversial: some core developers prefer that contracts not depend on gas values at all, so that gas costs can be repriced freely.\n- For relayed calls today, see [ERC-2771](/eip-2771/) (trusted forwarders) and [ERC-4337](/eip-4337/), which handle gas accounting at the bundler/EntryPoint level.\n"},"ja":{"lang":"ja","tldr":"撤回された提案。TXGASLIMIT と CALLGASLIMIT の opcode により、コントラクトがトランザクション全体と現在のコールフレームのガスリミットを読み取り、正確なガス計算ができるようにするものだった。","tags":["evm","opcodes","gas","meta-transactions","core"],"related":[8141,150,2771,4337],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-2542/","markdown":"## 何を解決するのか\n\nリレイヤー、メタトランザクションのフォワーダー、アカウントアブストラクションのシステムは、適切な額を請求または払い戻すために、トランザクションが実際にどれだけガスを使ったかを正確に知る必要がしばしばあります。EVM が公開しているのは次のものだけです。\n\n- `GASLIMIT`（`0x45`）: **ブロック**のガスリミット。コントラクトがほとんど必要としない値です。\n- `GAS`（`0x5a`、`gasleft()`）: **残りの**ガス。開始時の量ではありません。\n\nそのため、コントラクトは近似に頼ります。よくある手は、最初の行で `gasleft()` を呼び、あとで差し引くというものですが、これでは固有コスト（基本の 21,000、calldata のバイト分）や、最初の行が実行される前に Solidity が calldata のコピーに使った分が漏れます。別のユースケースは、メタトランザクションでユーザーが署名したガスリミットを強制することです。`gasleft()` は動的な値なので、署名された値と比較できません。\n\n## 仕組み\n\nこの提案は、それぞれ 2 ガスのコスト（`GASLIMIT` と同じ）の opcode を 2 つ追加します。\n\n| Opcode | バイト | プッシュする値 |\n| --- | --- | --- |\n| `TXGASLIMIT` | `0x5c` | トランザクションに署名されたガスリミット（`startgas`） |\n| `CALLGASLIMIT` | `0x5d` | [EIP-150](/eip-150/) の「64 分の 1 を除くすべて」ルール適用後に、現在のフレームに与えられたガス |\n\nまた、混乱を避けるために `GASLIMIT` を `BLOCKGASLIMIT` に改名することも提案しています。EVM のそれ以外の部分は変わらないため、既存のコントラクトには影響しません。\n\n著者は、これらの値は実行環境に関する情報として使うべきであり、セキュリティ機構の中核にすべきではないと強調しています。\n\n## サンプルコード\n\n提案の根拠部分にある疑似 Solidity。`msg.gasLimit` と `tx.gasLimit` は Solidity に追加されなかったため、これは**コンパイルできません**。\n\n```solidity\n// Illustrative only: would map to CALLGASLIMIT / TXGASLIMIT\nfunction keepTrackOfGas() public {\n    // ... work ...\n    uint256 gasUsed = msg.gasLimit - gasleft();   // CALLGASLIMIT - GAS\n}\n\nfunction verifyGasLimit(uint256 desiredGasLimit /*, signature ... */) public {\n    // the user signed desiredGasLimit; check the relayer honoured it\n    require(tx.gasLimit == desiredGasLimit, \"gas limit not authorized\"); // TXGASLIMIT\n}\n```\n\n現在、開発者が代わりに行っていること（近似）:\n\n```solidity\nfunction relayed(bytes calldata data) external {\n    uint256 start = gasleft();          // misses intrinsic + calldata cost\n    // ... execute ...\n    uint256 used = start - gasleft() + 21_000 + OVERHEAD_ESTIMATE;\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Withdrawn（撤回）。** 撤回理由は「[EIP-8141](/eip-8141/)（Frame Transaction）に置き換えられた」とされていますが、EIP-8141 自体はまだ Draft です。\n- opcode のバイト `0x5c` と `0x5d` は、のちに他の命令（[EIP-1153](/eip-1153/) の `TLOAD` / `TSTORE`）に割り当てられたため、これらの番号はもう使えません。\n- ガスの内省（introspection）には賛否があります。ガスコストを自由に再設定できるよう、コントラクトがガスの値にまったく依存しないほうがよいと考えるコア開発者もいます。\n- リレーされる呼び出しについては、現在は [ERC-2771](/eip-2771/)（信頼できるフォワーダー）と [ERC-4337](/eip-4337/) を参照してください。これらはバンドラー／EntryPoint のレベルでガス計算を扱います。\n"},"ko":{"lang":"ko","tldr":"철회된 제안. TXGASLIMIT와 CALLGASLIMIT opcode로 컨트랙트가 트랜잭션 전체와 현재 호출 프레임의 가스 한도를 읽어 정확하게 가스를 계산할 수 있게 하려 했다.","tags":["evm","opcodes","gas","meta-transactions","core"],"related":[8141,150,2771,4337],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-2542/","markdown":"## 어떤 문제를 해결하나요?\n\n릴레이어, 메타 트랜잭션 포워더, 계정 추상화 시스템은 올바른 금액을 청구하거나 환급하려고 트랜잭션이 가스를 정확히 얼마나 썼는지 알아야 할 때가 많습니다. EVM이 노출하는 것은 다음뿐입니다.\n\n- `GASLIMIT`(`0x45`) – **블록**의 가스 한도로, 컨트랙트가 거의 신경 쓰지 않는 값입니다.\n- `GAS`(`0x5a`, `gasleft()`) – **남은** 가스이며, 시작할 때의 양이 아닙니다.\n\n그래서 컨트랙트는 근사치를 씁니다. 흔한 요령은 첫 줄에서 `gasleft()`를 호출하고 나중에 빼는 것이지만, 이는 고유 비용(기본 21,000, calldata 바이트)과 첫 줄이 실행되기 전에 Solidity가 calldata를 복사하느라 쓴 가스를 놓칩니다. 또 다른 사용 사례는 메타 트랜잭션에서 사용자가 서명한 가스 한도를 강제하는 것입니다. `gasleft()`는 동적이어서 서명된 값과 비교할 수 없습니다.\n\n## 어떻게 동작하나요?\n\n이 제안은 opcode 두 개를 추가하며, 각각 2 가스가 듭니다(`GASLIMIT`와 같음).\n\n| Opcode | 바이트 | 푸시하는 값 |\n| --- | --- | --- |\n| `TXGASLIMIT` | `0x5c` | 트랜잭션에 서명된 가스 한도(`startgas`) |\n| `CALLGASLIMIT` | `0x5d` | [EIP-150](/eip-150/)의 \"64분의 1을 제외한 전부\" 규칙을 적용한 뒤 현재 프레임에 주어진 가스 |\n\n또한 혼동을 피하기 위해 `GASLIMIT`를 `BLOCKGASLIMIT`로 이름을 바꾸자고 제안합니다. EVM의 다른 부분은 바뀌지 않으므로 기존 컨트랙트는 영향을 받지 않습니다.\n\n저자들은 이 값들이 실행 환경에 대한 정보로 쓰여야 하며 보안 메커니즘의 핵심이 되어서는 안 된다고 강조합니다.\n\n## 샘플 코드\n\n제안의 근거 부분에 있는 의사 Solidity입니다. `msg.gasLimit`와 `tx.gasLimit`는 Solidity에 추가된 적이 없으므로 **컴파일되지 않습니다**.\n\n```solidity\n// Illustrative only: would map to CALLGASLIMIT / TXGASLIMIT\nfunction keepTrackOfGas() public {\n    // ... work ...\n    uint256 gasUsed = msg.gasLimit - gasleft();   // CALLGASLIMIT - GAS\n}\n\nfunction verifyGasLimit(uint256 desiredGasLimit /*, signature ... */) public {\n    // the user signed desiredGasLimit; check the relayer honoured it\n    require(tx.gasLimit == desiredGasLimit, \"gas limit not authorized\"); // TXGASLIMIT\n}\n```\n\n현재 개발자들이 대신 하는 방식(근사치):\n\n```solidity\nfunction relayed(bytes calldata data) external {\n    uint256 start = gasleft();          // misses intrinsic + calldata cost\n    // ... execute ...\n    uint256 used = start - gasleft() + 21_000 + OVERHEAD_ESTIMATE;\n}\n```\n\n## 알아둘 점\n\n- **상태: Withdrawn(철회).** 제시된 철회 사유는 \"[EIP-8141](/eip-8141/)(Frame Transaction)로 대체됨\"이며, EIP-8141 자체는 아직 Draft입니다.\n- opcode 바이트 `0x5c`와 `0x5d`는 이후 다른 명령([EIP-1153](/eip-1153/)의 `TLOAD`/`TSTORE`)에 할당되어, 이 번호들은 더 이상 쓸 수 없습니다.\n- 가스 introspection은 논란이 있습니다. 일부 코어 개발자는 가스 비용을 자유롭게 재조정할 수 있도록 컨트랙트가 가스 값에 전혀 의존하지 않기를 선호합니다.\n- 현재의 릴레이 호출은 번들러/EntryPoint 수준에서 가스 계산을 처리하는 [ERC-2771](/eip-2771/)(신뢰할 수 있는 포워더)과 [ERC-4337](/eip-4337/)을 참고하세요.\n"},"zh":{"lang":"zh","tldr":"一项已撤回的提案：新增 TXGASLIMIT 和 CALLGASLIMIT 操作码，使合约能读取整个交易和当前调用帧的 gas 上限，以便精确核算 gas。","tags":["evm","opcodes","gas","meta-transactions","core"],"related":[8141,150,2771,4337],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-2542/","markdown":"## 它解决什么问题？\n\n中继者、元交易转发器和账户抽象系统常常需要准确知道一笔交易用了多少 gas，才能收取或补偿正确的金额。EVM 只公开了：\n\n- `GASLIMIT`（`0x45`）：**区块**的 gas 上限，合约很少关心它。\n- `GAS`（`0x5a`，`gasleft()`）：**剩余的** gas，而不是起始时的数量。\n\n因此合约只能做近似。一个常见的技巧是在第一行调用 `gasleft()`，之后再相减，但这会漏掉固有成本（21,000 的基础费用、calldata 字节），以及 Solidity 在你的第一行运行之前为复制 calldata 所花的 gas。另一个用例是强制执行用户在元交易中签名的 gas 上限：`gasleft()` 是动态的，无法与签名值比较。\n\n## 它如何运作\n\n该提案新增两个操作码，各消耗 2 gas（与 `GASLIMIT` 相同）：\n\n| 操作码 | 字节 | 压入 |\n| --- | --- | --- |\n| `TXGASLIMIT` | `0x5c` | 签入交易的 gas 上限（`startgas`） |\n| `CALLGASLIMIT` | `0x5d` | 按 [EIP-150](/eip-150/) \"除去六十四分之一的全部\"规则之后，分配给当前调用帧的 gas |\n\n它还建议把 `GASLIMIT` 改名为 `BLOCKGASLIMIT` 以避免混淆。EVM 的其他部分不变，所以现有合约不受影响。\n\n作者强调，这些值应当作为执行环境的信息使用，而不应成为安全机制的核心。\n\n## 示例代码\n\n提案原理说明中的伪 Solidity。`msg.gasLimit` 和 `tx.gasLimit` 从未被加入 Solidity，所以这段代码**无法编译**：\n\n```solidity\n// Illustrative only: would map to CALLGASLIMIT / TXGASLIMIT\nfunction keepTrackOfGas() public {\n    // ... work ...\n    uint256 gasUsed = msg.gasLimit - gasleft();   // CALLGASLIMIT - GAS\n}\n\nfunction verifyGasLimit(uint256 desiredGasLimit /*, signature ... */) public {\n    // the user signed desiredGasLimit; check the relayer honoured it\n    require(tx.gasLimit == desiredGasLimit, \"gas limit not authorized\"); // TXGASLIMIT\n}\n```\n\n开发者现在的替代做法（近似）：\n\n```solidity\nfunction relayed(bytes calldata data) external {\n    uint256 start = gasleft();          // misses intrinsic + calldata cost\n    // ... execute ...\n    uint256 used = start - gasleft() + 21_000 + OVERHEAD_ESTIMATE;\n}\n```\n\n## 需要注意\n\n- **状态：Withdrawn（已撤回）。** 给出的撤回原因是\"被 [EIP-8141](/eip-8141/)（Frame Transaction）取代\"，而 EIP-8141 本身仍是 Draft。\n- 操作码字节 `0x5c` 和 `0x5d` 后来被分配给了其他指令（[EIP-1153](/eip-1153/) 中的 `TLOAD` / `TSTORE`），因此这些编号已不可用。\n- gas 自省存在争议：一些核心开发者希望合约完全不依赖 gas 值，以便可以随意重新定价 gas 成本。\n- 对于当前的中继调用，请参阅 [ERC-2771](/eip-2771/)（可信转发器）和 [ERC-4337](/eip-4337/)，它们在 bundler/EntryPoint 层面处理 gas 核算。\n"}}}
