> 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/kai-fa-zhe-zhi-nan/call-solana-from-evm.md).

# 从 EVM 调用 Solana

通过 Rome 的 CPI 和辅助预编译合约从 Solidity 调用 Solana 程序。

Rome 的预编译合约使 Solidity 合约能够直接调用 Solana 程序。本指南介绍其实现机制。

## 前提条件

* 来自公开 [`rome-solidity`](https://github.com/rome-protocol/rome-solidity) 仓库（从 GitHub 安装，而不是 npm — 见 [部署 Solidity](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/deploy-solidity.md#using-the-rome-solidity-sdk)）— 预编译接口位于 [`contracts/interface.sol`](https://github.com/rome-protocol/rome-solidity/blob/master/contracts/interface.sol)
* 已部署的 Rome 合约（见 [部署 Solidity](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/deploy-solidity.md))

将每个接口绑定到其预编译地址：

```solidity
import {ICrossProgramInvocation, ISystemProgram, IHelperProgram}
    from "@rome-protocol/rome-solidity/contracts/interface.sol";

ICrossProgramInvocation constant CpiProgram    = ICrossProgramInvocation(0xFF00000000000000000000000000000000000008);
ISystemProgram          constant SystemProgram = ISystemProgram(0xFF00000000000000000000000000000000000007);
IHelperProgram          constant Helper        = IHelperProgram(0xFF00000000000000000000000000000000000009);
```

## CpiProgram 预编译合约

`CpiProgram` (`0xFF…08`）分发 CPI（`invoke` / `invoke_signed`）以及跨状态读取快捷方式（`account_info`, `account_data_at`, `account_u64_at`, `account_lamports`, `pdas_batch_derive`):

```solidity
// 调用 Solana 程序
CpiProgram.invoke(programId, accounts, instructionData);

// 通过 PDA 签名调用：你的合约的 external-authority PDA 签名，外加一个
// `salts` 中每个条目对应一个带盐的子 PDA（Rome 派生 ["EXTERNAL_AUTHORITY", contract, salt]）
CpiProgram.invoke_signed(programId, accounts, data, salts);
```

## 转移 lamports

对于简单的 lamport 和 SPL 转账，请使用 HelperProgram 预编译合约——无需手工构建 CPI。调用它的合约会充当 **自身**：下面的转账移动的是合约自身的 lamports 和代币（由其 external-authority PDA 签名），而不是用户的。若合约要将用户的 SPL 代币拉入其控制的代币账户，并知道这些代币属于谁，用户需要授予一个 SPL 授权委托。一个 ERC-20 `transfer` 或 `transferFrom` 转给合约只会记入封装合约的托管账本，并不会给合约一个可供支出的代币账户——见 [集成 Solana 程序](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/integrate-solana-program.md).

```solidity
contract Transfers {
    IHelperProgram constant Helper = IHelperProgram(0xFF00000000000000000000000000000000000009);

    // 将 lamports 从此合约的 PDA 转移到某个 EVM 地址的 PDA
    function transferSol(address to, uint64 lamports) external {
        Helper.transfer_lamports(to, lamports);
    }

    // 从此合约的 PDA 所拥有的代币账户转移一个 SPL 代币
    function transferSpl(address to, uint64 tokens, bytes32 mint) external {
        Helper.transfer_spl(to, tokens, mint);
    }

    // 为某个 mint 创建调用者的 ATA
    function createAta(bytes32 mint) external {
        Helper.create_ata(msg.sender, mint);
    }
}
```

`transfer_spl` 有多个重载（包括用于 `transferFrom` 流程的委托变体）；请参见 `interface.sol`。在缓存轨道上，请改用 `ISplCached` (`0xff…05`) / `IAssociatedSplCached` (`0xff…06`）——合约应始终使用同一轨道，且只有旧版轨道才能 `invoke` 自定义程序（见 [集成 Solana 程序](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/integrate-solana-program.md)).

## 读取账户数据

通过 CpiProgram 的读取快捷方式读取任意 Solana 账户数据：

```solidity
(
    uint64 lamports,
    bytes32 owner,
    bool isSigner,
    bool isWritable,
    bool executable,
    bytes memory data
) = CpiProgram.account_info(accountPubkey);
```

## PDA 派生

通过 System 预编译合约在 Solidity 中查找程序派生地址：

```solidity
ISystemProgram.Seed[] memory seeds = new ISystemProgram.Seed[](2);
seeds[0] = ISystemProgram.Seed("my-program-seed");
seeds[1] = ISystemProgram.Seed(abi.encodePacked(someValue));

(bytes32 pda, uint8 bump) = SystemProgram.find_program_address(targetProgramId, seeds);
```

## Base58 转换

在以下之间转换 `bytes32` 以及 base58（Solana 的地址格式）：

```solidity
bytes memory base58Str = SystemProgram.bytes32_to_base58(pubkey);
bytes32 pubkey = SystemProgram.base58_to_bytes32(base58Bytes);
```

## 调用自定义 Solana 程序

若要调用任意 Solana 程序，请自行构建账户列表和指令数据：

```solidity
contract CustomCPI {
    ICrossProgramInvocation constant CpiProgram = ICrossProgramInvocation(0xFF00000000000000000000000000000000000008);
    bytes32 constant MY_PROGRAM = 0x0000000000000000000000000000000000000000000000000000000000000000; // 你的 Solana 程序 ID

    function callMyProgram(bytes32 account1, bytes32 account2, bytes calldata ixData) external {
        ICrossProgramInvocation.AccountMeta[] memory accounts = new ICrossProgramInvocation.AccountMeta[](2);
        accounts[0] = ICrossProgramInvocation.AccountMeta(account1, false, true);
        accounts[1] = ICrossProgramInvocation.AccountMeta(account2, false, false);

        CpiProgram.invoke(MY_PROGRAM, accounts, ixData);
    }
}
```

## 关键限制

1. **所有账户都必须预先声明。** Solana 交易必须包含 CPI 将触及的每一个账户——CPI 内部无法动态发现账户。
2. **CPI 深度限制：4 层。** Rome EVM → 你的目标 → 目标的调用 → 再一层。请规划好调用深度。
3. **Solana 公钥是 `bytes32`,** 而不是 20 字节的以太坊地址。
4. **指令数据是原始字节** ，格式需符合目标程序的预期（通常为 Borsh，小端序）。

## 下一步

* **在真实应用中查看** —— [cardo](https://github.com/rome-protocol/cardo) 直接从用户的钱包向预编译合约发送 CPI 调用，不需要适配器合约； [rome-dex](https://github.com/rome-protocol/rome-dex) （双轨 AMM）也如此，并且还有一个无托管路由合约； [aerarium](https://github.com/rome-protocol/aerarium) 是一个不会从 Solidity 调用 Solana 程序的借贷应用。
* [集成 Solana 程序](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/integrate-solana-program.md) — 用户的 Solana 身份、以该身份签名、单轨规则，以及为另一侧真实程序提供账户
* [预编译参考](https://docs.rome.builders/zh/can-kao/precompiles.md) — 每个预编译合约上的每个选择器
* [从 Solana 调用 EVM](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/call-evm-from-solana.md) — 反向操作：从 Solana 钱包驱动 EVM 合约
* [代币互操作](https://docs.rome.builders/zh/he-xin-gai-nian/token-interop.md) — ERC-20 和 SPL 代币如何协同工作
* [约束](https://docs.rome.builders/zh/he-xin-gai-nian/constraints.md) — CPI 深度及其他限制


---

# 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/kai-fa-zhe-zhi-nan/call-solana-from-evm.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.
