> 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/rome-xue-yuan/05-call-solana-from-solidity.md).

# 5. 从 Solidity 调用 Solana

使用 Rome 的 CPI 和 Helper 预编译合约，从 Solidity 合约中读取 Solana 账户、创建代币账户，并调用 Solana 程序。

在 Rome 上，Solidity 合约可以在同一笔交易中读取 Solana 账户并调用 Solana 程序。你将读取一个 Solana 代币余额，创建一个代币账户，并学习如何构建程序调用。

## 你将学到什么

* Rome 上的 precompile 是什么，以及你最常用的三个 precompile。
* 当你的合约调用 Solana 程序时，Solana 程序看到的是谁的签名。
* 如何从 Solidity 读取 Solana 状态并创建代币账户。
* 决定 Solana 调用是否成功的规则：已声明的账户、单轨道、仅原子执行。

## 开始之前

* 完成 [4. Rome 如何运行你的代码](https://docs.rome.builders/zh/rome-xue-yuan/04-how-rome-runs-your-code.md)。原子预算和 64 个账户上限在这里很重要。
* 确保你的 Hadrian 钱包已有资金，并且第 3 课中的部署设置正常工作。水龙头列在 [水龙头](https://docs.rome.builders/zh/zi-yuan/faucets.md).
* 从 `rome-solidity` 仓库安装 Rome Solidity 接口，如 [部署 Solidity](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/deploy-solidity.md#using-the-rome-solidity-sdk).

## Precompile 是入口

Precompile 是一个固定地址，它运行的是原生代码，而不是字节码。Ethereum 有一些，例如 `ecrecover`。Rome 新增了用于连接 Solana 的 precompile。你可以像调用任何合约一样，通过接口来调用它们。

你会用到三个：

| 预编译           | 它为你提供什么                                                      |
| ------------- | ------------------------------------------------------------ |
| CpiProgram    | `invoke` 和 `invoke_signed` 用于调用任意 Solana 程序，以及只读查看 Solana 账户 |
| HelperProgram | 现成的代币和账户操作：创建代币账户、转移 SPL 代币、派生地址                             |
| System        | PDA 派生和 base58 转换                                            |

这些地址位于 [预编译参考](https://docs.rome.builders/zh/can-kao/precompiles.md) 和 [合约地址](https://docs.rome.builders/zh/can-kao/contract-addresses.md)。你无需手动输入它们。导入 `interface.sol` 由 `rome-solidity` 会为你提供名为 `CpiProgram`, `HelperProgram` 和 `SystemProgram`.

## 谁签名

当你的合约调用 precompile 时，Solana 看到的是合约自身的身份，而不是用户的身份。每个 EVM 地址都有一个 Solana 程序派生地址，也就是它的外部权限 PDA。它拥有该地址的代币账户，并代表它进行签名。

这与 ERC-20 中你熟悉的规则相同：除非用户授权，否则合约不能转移用户的资产。第 6 课展示了在 Rome 上用户如何授权。该规则以及持有用户仓位的三种方式见于 [集成 Solana 程序](https://docs.rome.builders/pages/6d3e31686e4cb73ec09bc01c61a81b4e07583fbf#id-1.-every-evm-address-has-one-solana-identity).

## 第 1 步：先读后写

从读取开始。读取不会更改状态，并且可在原子执行和迭代执行中工作。先读后改：一旦缓存调用已运行，在该交易剩余部分中，旧轨道读取将被拒绝。

```solidity
import "@rome-protocol/rome-solidity/contracts/interface.sol";

contract SolanaPeek {
    // Rome 为调用者和链的 gas 铸币所使用的代币账户
    function myTokenAccount() external view returns (bytes32) {
        return HelperProgram.ata(msg.sender, SystemProgram.mint_id());
    }

    // 该账户中调用者的余额
    function myBalance() external view returns (uint64) {
        return HelperProgram.user_balance(msg.sender, SystemProgram.mint_id());
    }
}
```

Solana 地址是 `bytes32` 这里，而不是 20 字节地址。其他读取项， `account_info`, `account_data_at` 和 `account_u64_at`，可让你检查任意 Solana 账户。见 [读取账户数据](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-solana-from-evm.md#reading-account-data).

## 第 2 步：使用辅助工具

对于常见任务，你无需手写指令。Helper 可创建代币账户、转移 SPL 代币和 lamport，并在 gas 与 lamport 之间转换。签名定义位于 `contracts/interface.sol`，并且一个完整示例合约位于 [转移 lamports](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-solana-from-evm.md#transfer-lamports).

```solidity
function createMyAta() external {
    HelperProgram.create_ata(msg.sender, SystemProgram.mint_id());
}
```

调用 Helper 的合约是以自身身份行事。它移动的代币属于它自己，而不是用户。

## 第 3 步：调用任意 Solana 程序

对于辅助工具未覆盖的程序，需自行构建账户列表和指令字节，然后调用 `invoke`。每个账户都由一个 pubkey 以及两个标志位组成：signer 和 writable。指令数据就是目标程序所期望的内容，通常是 Borsh。

完整合约位于 [调用自定义 Solana 程序](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-solana-from-evm.md#calling-custom-solana-programs). `invoke_signed` 当目标需要你合约中的多个签名者时，会添加带盐的子 PDA。要在 Solidity 中获取 PDA 的地址，请使用 `find_program_address` 在 System precompile 上；参见 [PDA 派生](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-solana-from-evm.md#pda-derivation).

## 决定其是否可用的规则

* **声明每一个账户。** Solana 需要在调用运行前得到完整账户列表。代理会先模拟你的交易来找到它，因此每个账户都必须能够由合约已有的输入推导出来。总数必须保持在 64 个地址上限以内。
* **保持原子性。** 进行 legacy 轨道 CPI 的调用不能在迭代交易中运行。它必须适配为一笔原子交易，因此每个操作都应限制为一次代币移动和一次 CPI。
* **选择一条轨道。** Rome 有两类会更改 Solana 状态的 precompile：legacy（`CpiProgram`, `HelperProgram`, `Withdraw`）和 cached（ `...Cached` 集合）。一笔交易只使用其中一类。只有 legacy 轨道才能调用自定义程序。请阅读 [集成 Solana 程序](https://docs.rome.builders/pages/6d3e31686e4cb73ec09bc01c61a81b4e07583fbf#id-4.-one-track-per-contract-and-per-transaction).
* **保持调用深度浅。** 你对 Solana 程序的调用会使用 CPI 层级，而它随后调用的每个程序也同样如此。Solana 的深度限制很低。 [约束](https://docs.rome.builders/zh/he-xin-gai-nian/constraints.md#cpi-constraints) 解释了这些层级。
* **不要回调到 Rome。** CPI 不能指向或调用 Rome 程序。除非是普通的 System 转账指令，否则它也不能指向 Solana fee payer。

## 自测

添加 `createMyAta` 到 `SolanaPeek` 并将其部署到 Hadrian。然后：

1. 调用 `myTokenAccount` 和 `myBalance` 使用你钱包地址发起一次读取调用。
2. 发送一笔调用 `createMyAta`.
3. 在 Hadrian 浏览器中打开该交易。参见 [Via explorer](https://docs.rome.builders/zh/rome-shang-de-ying-yong/via.md).

你应该能看到你调用背后的 Solana 指令及其计算单元。到达 Solana 的调用会在浏览器中显示为一个 Solana 程序，而不只是一个 EVM 调用。

<details>

<summary>1. 合约调用 <code>HelperProgram.transfer_spl</code>。谁的代币会移动？</summary>

合约自己的。签名者是合约的外部权限 PDA。要移动用户的代币，用户必须先授予权限。

</details>

<details>

<summary>2. 为什么使用 <code>invoke</code> 的调用必须适配为一笔原子交易？</summary>

legacy 轨道 CPI 在迭代交易中会被拒绝。如果该调用需要超过一笔 Solana 交易，它就会失败。

</details>

<details>

<summary>3. 在任何执行模式下，你可以依赖哪些读取？</summary>

只读视图： `account_info`, `account_data_at`, `account_u64_at`, `account_lamports`, `pdas_batch_derive` 以及诸如 `user_balance`这样的 Helper 读取。它们没有副作用。请在同一交易中任何缓存写入之前运行它们。

</details>

## 下一步

[6. 双边代币](https://docs.rome.builders/zh/rome-xue-yuan/06-tokens-on-both-sides.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/rome-xue-yuan/05-call-solana-from-solidity.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.
