> For the complete documentation index, see [llms.txt](https://docs.rome.builders/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rome.builders/zh/he-xin-gai-nian/compute-budget.md).

# 计算预算

Rome EVM 操作的 Solana 计算单元（CU）成本——原子模式与迭代模式的预算，以及如何设计更节省 CU 的 Solidity 合约。

每笔 Solana 交易都有一个以 Compute Units（CU）衡量的计算预算。理解 CU 成本有助于你设计高效的 Rome 合约。

## 预算概览

| 模式        | 最大 CU                               | 说明                                            |
| --------- | ----------------------------------- | --------------------------------------------- |
| 原子式（VmAt） | 约 1,400,000 CU                      | 单笔 Solana 交易                                  |
| 迭代式（VmIt） | 每个分支最多约 1,400,000 CU；每个会话最多 160 次迭代 | 每个分支都是独立的 Solana 交易；自适应操作码/步骤——按每笔交易的 CU 预算打包 |

每笔 Solana 交易的默认预算为 200,000 CU，可通过计算预算指令扩展到约 140 万 CU（由 Rome SDK 自动添加）。

迭代执行并非无限制。一个会话在 160 次迭代后结束，Rust 版 Rome SDK 的迭代式 composer 最多规划 128 个分支。由钱包自行签名的计划会经过 `rome_submitSignedV1Plan`，该接口每次调用最多接受 64 笔交易。大多数调用所需远少于此。迭代会话内会拒绝传统路径的 CPI，因此触发这类 CPI 的调用必须符合原子式预算。参见 [转发调用和长调用](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-evm-from-solana.md#relayed-calls-and-long-calls) 和 [约束](https://docs.rome.builders/zh/he-xin-gai-nian/constraints.md).

## CU 成本估算

### EVM 操作

| 操作               | 大致 CU                | 说明                                                   |
| ---------------- | -------------------- | ---------------------------------------------------- |
| 交易签名检查（EVM 密钥通道） | 约 25,000 CU          | 这些 `secp256k1_recover` 系统调用，与下方的 `ecrecover` 预编译成本相同 |
| 简单转账             | 约 50,000-100,000 CU  | 仅更新余额                                                |
| ERC-20 转账        | 约 100,000-150,000 CU | 包含 SPL 预编译调用                                         |
| 合约部署（小型）         | 约 200,000-400,000 CU | 取决于字节码大小                                             |
| 存储写入（SSTORE）     | 约 5,000-20,000 CU    | 冷访问与热访问                                              |

### 预编译操作

| 预编译             | 大致 CU                       | 说明                                                                                                                         |
| --------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| ecrecover       | 约 25,700 CU                 |                                                                                                                            |
| SHA-256         | 每 32 字节字测得约 257 CU          | 外加少量固定成本。该程序对 SHA-256、RIPEMD-160 和 identity 预编译采用一个共享的按字计费值，约 2,200 CU；该数值以三者中成本最高的 RIPEMD-160 为基准，因此 SHA-256 调用的收费高于其实际消耗 |
| BN254 ecAdd     | 接近 0 CU                     | 比复制 32 字节更便宜                                                                                                               |
| BN254 ecMul     | 约 4,200 CU                  |                                                                                                                            |
| BN254 ecPairing | 约 22,000 CU，外加每对约 12,800 CU | 四对检查大约需要 73,000 CU，完全在一次原子交易范围内                                                                                            |

这些数据来自程序自身的校准，使用的是测试网部署中从 Solana 节点回读的计算单元。此页未重新测量；请使用 `computeUnitsConsumed`.

## 优化技巧

### 1. 在热点路径使用 Yul

Solidity 的优化器能生成相当不错的代码，但 Yul（内联汇编）可显著降低关键操作的 CU：

```solidity
// 之前：约 60 万 CU
function createPairAccount(bytes32 token0, bytes32 token1) external {
    // Solidity 层级操作
}

// 之后：约 15 万 CU（Yul 优化）
function createPairAccount(bytes32 token0, bytes32 token1) external {
    assembly {
        // 直接进行内存操作，跳过 ABI 编码开销
    }
}
```

### 2. 缓存 PDA 推导结果

通过 `find_program_address` 进行 PDA 推导成本很高。应将已推导的 PDA 存储在合约存储中，而不是每次调用都重新计算：

```solidity
mapping(address => bytes32) private cachedPdas;

function getPda(address user) internal returns (bytes32) {
    bytes32 cached = cachedPdas[user];
    if (cached != bytes32(0)) return cached;

    bytes32 pda = RomeEVMAccount.pda(user);
    cachedPdas[user] = pda;
    return pda;
}
```

### 3. 硬编码已知程序 ID

不要从存储中读取程序 ID——请使用常量：

```solidity
// 昂贵：从存储中读取
bytes32 splTokenProgram = storage_program_id;

// 低成本：编译期常量
bytes32 constant SPL_TOKEN_PROGRAM = 0x06ddf6e1d765a193d9cbe146ceeb79ac1cb485ed5f5b37913a8cf5857eff00a9;
```

### 4. 尽量减少账户数量

Solana 交易中的每个账户都会增加 CU 开销。可通过以下方式减少账户数量：

* 将共享账户的操作批量处理
* 使用更少的中间账户
* 避免重复的 ATA 创建检查

### 5. 使用优化器设置

```typescript
// hardhat.config.ts — 在构建配置中启用优化器
solidity: {
  profiles: {
    default: { version: "0.8.28" },
    production: {
      version: "0.8.28",
      settings: { optimizer: { enabled: true, runs: 200 } },
    },
  },
}
```

使用以下命令构建 `npx hardhat compile --build-profile production`.

## 衡量 CU 消耗

`eth_estimateGas` 不会测量计算单元，因为 Rome 中一个 gas 单位等于一个 lamport 成本。它决定的是你的 gas 上限。可通过 EVM 哈希背后的 Solana 交易读取计算值：用以下命令获取其签名 `rome_solanaTxForEvmTx`获取 EVM 哈希对应的 Solana 签名，再使用 Solana 的 `getTransaction` 和 `maxSupportedTransactionVersion: 1`，并读取 `computeUnitsConsumed`，或在浏览器中打开该调用。迭代式调用的每个分支对应一笔交易。要在提交前确定 gas 上限：

```bash
cast estimate --rpc-url https://hadrian.testnet.romeprotocol.xyz/ \\
  0xCONTRACT "myFunction(uint256)" 42
```

或者通过 ethers.js：

```javascript
const gas = await contract.myFunction.estimateGas(42);
console.log("预计 gas：", gas.toString());
```

## 下一步

* [约束](https://docs.rome.builders/zh/he-xin-gai-nian/constraints.md) — 完整的限制与边界列表


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.rome.builders/zh/he-xin-gai-nian/compute-budget.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
