{"eip":6823,"title":"Token Mapping Slot Retrieval Extension","description":"Approach to enhance precision of off-chain transaction simulations by accessing mapping storage slot in ERC-20/721/1155 contracts.","authors":["qdqd (@qd-qd) \u003cqdqdqdqdqd@protonmail.com\u003e"],"status":"Draft","type":"Standards Track","category":"ERC","created":"2023-03-29","requires":[20,721,1155],"discussionsTo":"https://ethereum-magicians.org/t/eip-6823-token-mapping-slot-retrieval-extension/13666","repo":"ERCs","label":"ERC-6823","officialUrl":"https://eips.ethereum.org/EIPS/eip-6823","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-6823.md","url":"https://eips.huatuo.xyz/eip-6823/","tldr":{"en":"A draft one-function extension, getTokenLocationRoot(), that tells off-chain tools which storage slot holds a token's balance or ownership mapping, so simulations can read state instead of trusting events.","ja":"ドラフトの 1 関数拡張 `getTokenLocationRoot()`。トークンの残高または所有権のマッピングがどのストレージスロットにあるかをオフチェーンのツールに伝え、シミュレーションがイベントを信用せずにステートを読めるようにする。","ko":"초안 단계의 한 함수짜리 확장 getTokenLocationRoot(). 토큰의 잔액 또는 소유권 매핑이 어떤 스토리지 슬롯에 있는지 오프체인 도구에 알려, 시뮬레이션이 이벤트를 믿는 대신 상태를 직접 읽을 수 있게 한다.","zh":"一个草案的单函数扩展 getTokenLocationRoot()，告诉链下工具代币的余额或所有权映射位于哪个存储槽，使模拟可以直接读取状态，而不必信任事件。"},"tags":["storage","simulation","tooling","token","draft"],"explainers":{"en":{"lang":"en","tldr":"A draft one-function extension, getTokenLocationRoot(), that tells off-chain tools which storage slot holds a token's balance or ownership mapping, so simulations can read state instead of trusting events.","tags":["storage","simulation","tooling","token","draft"],"related":[20,721,1155,1967],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-6823/","markdown":"## What problem does it solve?\n\nWallets and security tools simulate a transaction before you sign it to show \"you will send 100 USDC, receive NFT #42\". Today those previews mostly rely on **events**, because events have a standard shape. But events are just logs that a contract chooses to emit; a buggy or malicious contract can emit a `Transfer` that does not match what really happened. The real source of truth is **storage**.\n\nReading storage generically is hard. A Solidity mapping such as `balanceOf` sits at a base slot `p` that depends on how many variables were declared before it, which differs for every implementation. The value for key `k` lives at `keccak256(h(k) . p)`, so without knowing `p` a tool cannot find, say, an account's balance in an arbitrary [ERC-20](/eip-20/).\n\nERC-6823 asks token contracts to simply publish `p`.\n\n## How it works\n\n[ERC-20](/eip-20/), [ERC-721](/eip-721/) and [ERC-1155](/eip-1155/) contracts add one function:\n\n```solidity\nfunction getTokenLocationRoot() external pure returns (bytes32 slot);\n```\n\nIt returns the storage slot of the mapping that tracks ownership (balances for ERC-20/1155, owners for ERC-721), typically implemented with inline assembly `slot := _balances.slot`. Because it is `pure`, calling it costs nothing for off-chain callers and adds only a little deployment bytecode.\n\nA simulator can then:\n\n1. Call `getTokenLocationRoot()` to get `p`.\n2. Compute the slot for the key it cares about.\n3. Read that slot before and after a simulated transaction (`eth_getStorageAt`, or a state diff from a tracer) and compare it with what the events claim.\n\nThe function name is intentionally the same for all three standards, so one selector works for any compliant token.\n\n## Sample code\n\nContract side:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ncontract SimpleToken {\n    string public name = \"Simple\";\n    mapping(address =\u003e uint256) public balanceOf; // the ownership mapping\n\n    function getTokenLocationRoot() external pure returns (bytes32 slot) {\n        assembly { slot := balanceOf.slot }\n    }\n}\n```\n\nReading a balance straight from storage (ethers v6):\n\n```ts\nimport { AbiCoder, Contract, JsonRpcProvider, keccak256 } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst token = new Contract(tokenAddr, [\"function getTokenLocationRoot() pure returns (bytes32)\"], provider);\n\nconst root: string = await token.getTokenLocationRoot();\n// Solidity layout for mapping(address =\u003e uint256): keccak256(abi.encode(key, slot))\nconst slot = keccak256(AbiCoder.defaultAbiCoder().encode([\"address\", \"bytes32\"], [holder, root]));\nconst raw = await provider.getStorage(tokenAddr, slot);\nconsole.log(\"balance from storage:\", BigInt(raw));\n```\n\n## Things to know\n\n- Status is **Draft**.\n- It only reveals the *base* slot. Callers still need to know how keys are hashed: ERC-1155 balances are usually a nested mapping (`id =\u003e account =\u003e amount`), which requires hashing twice, and Vyper or packed layouts may differ from the Solidity rule above.\n- Behind a proxy ([ERC-1967](/eip-1967/)), storage belongs to the proxy, so read the slot at the proxy's address, not the implementation's.\n- A malicious contract could return a wrong slot, so tools should treat it as a hint and cross-check.\n"},"ja":{"lang":"ja","tldr":"ドラフトの 1 関数拡張 `getTokenLocationRoot()`。トークンの残高または所有権のマッピングがどのストレージスロットにあるかをオフチェーンのツールに伝え、シミュレーションがイベントを信用せずにステートを読めるようにする。","tags":["storage","simulation","tooling","token","draft"],"related":[20,721,1155,1967],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-6823/","markdown":"## 何を解決するのか\n\nウォレットやセキュリティツールは、署名の前にトランザクションをシミュレーションして「100 USDC を送り、NFT #42 を受け取ります」と表示します。現在これらのプレビューは主に**イベント**に頼っています。イベントには標準的な形式があるためです。しかしイベントは、コントラクトが emit することを選んだログにすぎません。バグのあるコントラクトや悪意のあるコントラクトは、実際に起きたことと一致しない `Transfer` を emit できます。真の情報源は**ストレージ**です。\n\nストレージを汎用的に読むのは困難です。`balanceOf` のような Solidity のマッピングは、それより前に宣言された変数の数によって決まるベーススロット `p` に置かれ、これは実装ごとに異なります。キー `k` の値は `keccak256(h(k) . p)` の位置にあるため、`p` を知らないと、ツールは任意の [ERC-20](/eip-20/) からたとえばあるアカウントの残高を見つけられません。\n\nERC-6823 は、トークンコントラクトが `p` をそのまま公開することを求めます。\n\n## 仕組み\n\n[ERC-20](/eip-20/)、[ERC-721](/eip-721/)、[ERC-1155](/eip-1155/) のコントラクトに、次の関数を 1 つ追加します。\n\n```solidity\nfunction getTokenLocationRoot() external pure returns (bytes32 slot);\n```\n\nこれは所有権を追跡するマッピング（ERC-20/1155 では残高、ERC-721 では所有者）のストレージスロットを返します。通常はインラインアセンブリ `slot := _balances.slot` で実装されます。`pure` なので、オフチェーンの呼び出し側にとっては呼び出しコストがかからず、デプロイ時のバイトコードがわずかに増えるだけです。\n\nシミュレーターは次のことができます。\n\n1. `getTokenLocationRoot()` を呼び出して `p` を取得する。\n2. 対象のキーに対応するスロットを計算する。\n3. シミュレーション対象のトランザクションの前後でそのスロットを読み（`eth_getStorageAt`、またはトレーサーによるステート差分）、イベントの内容と比較する。\n\n関数名は 3 つの標準すべてで意図的に同じにしてあるため、1 つのセレクターで準拠するどのトークンにも使えます。\n\n## サンプルコード\n\nコントラクト側:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ncontract SimpleToken {\n    string public name = \"Simple\";\n    mapping(address =\u003e uint256) public balanceOf; // the ownership mapping\n\n    function getTokenLocationRoot() external pure returns (bytes32 slot) {\n        assembly { slot := balanceOf.slot }\n    }\n}\n```\n\nストレージから直接残高を読む（ethers v6）:\n\n```ts\nimport { AbiCoder, Contract, JsonRpcProvider, keccak256 } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst token = new Contract(tokenAddr, [\"function getTokenLocationRoot() pure returns (bytes32)\"], provider);\n\nconst root: string = await token.getTokenLocationRoot();\n// Solidity layout for mapping(address =\u003e uint256): keccak256(abi.encode(key, slot))\nconst slot = keccak256(AbiCoder.defaultAbiCoder().encode([\"address\", \"bytes32\"], [holder, root]));\nconst raw = await provider.getStorage(tokenAddr, slot);\nconsole.log(\"balance from storage:\", BigInt(raw));\n```\n\n## 知っておくべきこと\n\n- ステータスは **Draft** です。\n- 公開されるのは*ベース*スロットだけです。キーのハッシュ方法は呼び出し側が知っている必要があります。ERC-1155 の残高は通常ネストされたマッピング（`id =\u003e account =\u003e amount`）なので 2 回ハッシュする必要があり、Vyper やパックされたレイアウトでは上記の Solidity のルールと異なる場合があります。\n- プロキシ（[ERC-1967](/eip-1967/)）の背後では、ストレージはプロキシに属します。実装コントラクトではなくプロキシのアドレスでスロットを読んでください。\n- 悪意のあるコントラクトが誤ったスロットを返す可能性があるため、ツールはこれをヒントとして扱い、照合して確認すべきです。\n"},"ko":{"lang":"ko","tldr":"초안 단계의 한 함수짜리 확장 getTokenLocationRoot(). 토큰의 잔액 또는 소유권 매핑이 어떤 스토리지 슬롯에 있는지 오프체인 도구에 알려, 시뮬레이션이 이벤트를 믿는 대신 상태를 직접 읽을 수 있게 한다.","tags":["storage","simulation","tooling","token","draft"],"related":[20,721,1155,1967],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-6823/","markdown":"## 어떤 문제를 해결하나요?\n\n지갑과 보안 도구는 서명하기 전에 트랜잭션을 시뮬레이션해 \"100 USDC를 보내고 NFT #42를 받습니다\"라고 보여줍니다. 현재 이런 미리보기는 대부분 **이벤트**에 의존하는데, 이벤트에는 표준 형식이 있기 때문입니다. 하지만 이벤트는 컨트랙트가 emit하기로 선택한 로그일 뿐이며, 버그가 있거나 악의적인 컨트랙트는 실제로 일어난 일과 맞지 않는 `Transfer`를 emit할 수 있습니다. 진짜 사실의 원천은 **스토리지**입니다.\n\n스토리지를 범용적으로 읽는 것은 어렵습니다. `balanceOf` 같은 Solidity 매핑은 그 앞에 선언된 변수 수에 따라 달라지는 기준 슬롯 `p`에 위치하며, 이는 구현마다 다릅니다. 키 `k`의 값은 `keccak256(h(k) . p)`에 있으므로, `p`를 모르면 도구는 임의의 [ERC-20](/eip-20/)에서 예컨대 어떤 계정의 잔액을 찾을 수 없습니다.\n\nERC-6823은 토큰 컨트랙트가 `p`를 그냥 공개하도록 요청합니다.\n\n## 어떻게 동작하나요?\n\n[ERC-20](/eip-20/), [ERC-721](/eip-721/), [ERC-1155](/eip-1155/) 컨트랙트에 함수 하나를 추가합니다.\n\n```solidity\nfunction getTokenLocationRoot() external pure returns (bytes32 slot);\n```\n\n소유권을 추적하는 매핑(ERC-20/1155는 잔액, ERC-721은 소유자)의 스토리지 슬롯을 반환하며, 보통 인라인 어셈블리 `slot := _balances.slot`로 구현합니다. `pure`이므로 오프체인 호출자에게는 호출 비용이 들지 않고 배포 바이트코드만 조금 늘어납니다.\n\n그러면 시뮬레이터는 다음을 할 수 있습니다.\n\n1. `getTokenLocationRoot()`를 호출해 `p`를 얻습니다.\n2. 관심 있는 키에 대한 슬롯을 계산합니다.\n3. 시뮬레이션한 트랜잭션의 전후에 해당 슬롯을 읽고(`eth_getStorageAt` 또는 트레이서의 상태 diff), 이벤트가 주장하는 내용과 비교합니다.\n\n함수 이름은 세 표준 모두에서 의도적으로 같으므로, 하나의 셀렉터로 어떤 호환 토큰에도 쓸 수 있습니다.\n\n## 샘플 코드\n\n컨트랙트 쪽:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ncontract SimpleToken {\n    string public name = \"Simple\";\n    mapping(address =\u003e uint256) public balanceOf; // the ownership mapping\n\n    function getTokenLocationRoot() external pure returns (bytes32 slot) {\n        assembly { slot := balanceOf.slot }\n    }\n}\n```\n\n스토리지에서 바로 잔액 읽기(ethers v6):\n\n```ts\nimport { AbiCoder, Contract, JsonRpcProvider, keccak256 } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst token = new Contract(tokenAddr, [\"function getTokenLocationRoot() pure returns (bytes32)\"], provider);\n\nconst root: string = await token.getTokenLocationRoot();\n// Solidity layout for mapping(address =\u003e uint256): keccak256(abi.encode(key, slot))\nconst slot = keccak256(AbiCoder.defaultAbiCoder().encode([\"address\", \"bytes32\"], [holder, root]));\nconst raw = await provider.getStorage(tokenAddr, slot);\nconsole.log(\"balance from storage:\", BigInt(raw));\n```\n\n## 알아둘 점\n\n- 상태는 **Draft**입니다.\n- *기준* 슬롯만 알려줍니다. 호출자는 키가 어떻게 해시되는지 여전히 알아야 합니다. ERC-1155 잔액은 보통 중첩 매핑(`id =\u003e account =\u003e amount`)이라 해시를 두 번 해야 하고, Vyper나 패킹된 레이아웃은 위의 Solidity 규칙과 다를 수 있습니다.\n- 프록시([ERC-1967](/eip-1967/)) 뒤에서는 스토리지가 프록시에 속하므로, 구현 컨트랙트가 아니라 프록시 주소에서 슬롯을 읽어야 합니다.\n- 악의적인 컨트랙트가 잘못된 슬롯을 반환할 수 있으므로, 도구는 이를 힌트로 취급하고 교차 검증해야 합니다.\n"},"zh":{"lang":"zh","tldr":"一个草案的单函数扩展 getTokenLocationRoot()，告诉链下工具代币的余额或所有权映射位于哪个存储槽，使模拟可以直接读取状态，而不必信任事件。","tags":["storage","simulation","tooling","token","draft"],"related":[20,721,1155,1967],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-6823/","markdown":"## 它解决什么问题？\n\n钱包和安全工具会在你签名之前模拟交易，显示\"你将发送 100 USDC，收到 NFT #42\"。目前这些预览主要依赖**事件**，因为事件有标准格式。但事件只是合约选择发出的日志；有缺陷或恶意的合约可以发出与实际发生情况不符的 `Transfer`。真正的事实来源是**存储**。\n\n通用地读取存储很困难。像 `balanceOf` 这样的 Solidity 映射位于基础槽 `p`，它取决于在它之前声明了多少变量，每个实现都不同。键 `k` 对应的值位于 `keccak256(h(k) . p)`，因此不知道 `p`，工具就无法在任意 [ERC-20](/eip-20/) 中找到某个账户的余额。\n\nERC-6823 要求代币合约直接公开 `p`。\n\n## 它如何运作\n\n[ERC-20](/eip-20/)、[ERC-721](/eip-721/) 和 [ERC-1155](/eip-1155/) 合约增加一个函数：\n\n```solidity\nfunction getTokenLocationRoot() external pure returns (bytes32 slot);\n```\n\n它返回记录所有权的映射所在的存储槽（ERC-20/1155 为余额，ERC-721 为所有者），通常用内联汇编 `slot := _balances.slot` 实现。由于它是 `pure` 的，链下调用方调用它不花费任何成本，只会略微增加部署字节码。\n\n随后模拟器可以：\n\n1. 调用 `getTokenLocationRoot()` 获取 `p`。\n2. 计算它所关心的键对应的存储槽。\n3. 在模拟交易前后读取该槽（`eth_getStorageAt`，或来自 tracer 的状态差异），并与事件所声称的内容对比。\n\n这个函数名在三个标准中有意保持一致，因此同一个 selector 适用于任何兼容的代币。\n\n## 示例代码\n\n合约端：\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ncontract SimpleToken {\n    string public name = \"Simple\";\n    mapping(address =\u003e uint256) public balanceOf; // the ownership mapping\n\n    function getTokenLocationRoot() external pure returns (bytes32 slot) {\n        assembly { slot := balanceOf.slot }\n    }\n}\n```\n\n直接从存储读取余额（ethers v6）：\n\n```ts\nimport { AbiCoder, Contract, JsonRpcProvider, keccak256 } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst token = new Contract(tokenAddr, [\"function getTokenLocationRoot() pure returns (bytes32)\"], provider);\n\nconst root: string = await token.getTokenLocationRoot();\n// Solidity layout for mapping(address =\u003e uint256): keccak256(abi.encode(key, slot))\nconst slot = keccak256(AbiCoder.defaultAbiCoder().encode([\"address\", \"bytes32\"], [holder, root]));\nconst raw = await provider.getStorage(tokenAddr, slot);\nconsole.log(\"balance from storage:\", BigInt(raw));\n```\n\n## 需要注意\n\n- 状态为 **Draft**。\n- 它只暴露*基础*槽。调用方仍需知道键是如何哈希的：ERC-1155 的余额通常是嵌套映射（`id =\u003e account =\u003e amount`），需要哈希两次；Vyper 或打包布局也可能与上述 Solidity 规则不同。\n- 在代理（[ERC-1967](/eip-1967/)）之后，存储属于代理，因此应在代理的地址而不是实现合约的地址读取该槽。\n- 恶意合约可能返回错误的槽，因此工具应将其视为提示并进行交叉验证。\n"}}}
