# Rome SDK

Rome SDK 提供类型化的 Solidity 接口，用于从 EVM 智能合约与 Solana 程序交互。它是用于在 Rome 上构建跨运行时应用的开发者工具包。

## 两个 SDK

Rome 提供两个用途不同的 SDK：

### Solidity SDK（`@rome-protocol/solidity-sdk`)

**面向 Solidity 开发者。** 提供预编译接口、ERC-20/SPL 封装器、PDA 推导和 CPI 工具。可通过 npm 安装并导入到您的 Solidity 合约中。

```bash
npm install @rome-protocol/solidity-sdk
```

```solidity
import {SplToken, CpiProgram, SystemProgram} from "@rome-protocol/solidity-sdk/contracts/core/Precompiles.sol";
import {SPL_ERC20} from "@rome-protocol/solidity-sdk/contracts/token/ERC20SPL.sol";
import {RomeEVMAccount} from "@rome-protocol/solidity-sdk/contracts/core/RomeEVMAccount.sol";
```

### Rust SDK（`rome-sdk`)

**面向基础设施运营者。** 一个由 9 个 crate 组成的 Rust 工作区，负责交易组装、Solana 交互、Gas 定价、区块索引和服务编排。由 Proxy、Hercules 和 Rhea 使用。

## Solidity SDK：包含内容

### 预编译接口

所有 Rome 预编译的预绑定单例常量：

```solidity
// 导入后全局可用
ISplToken constant SplToken;                    // 0xff...05
IAssociatedSplToken constant AssociatedSplToken; // 0xff...06
ISystemProgram constant SystemProgram;           // 0xff...07
ICrossProgramInvocation constant CpiProgram;     // 0xff...08
IWithdraw constant Withdraw;                     // 0x42...16
```

### SPL 代币操作

```solidity
// 读取代币账户状态
ISplToken.Account memory acc = SplToken.account_state(tokenAccountPubkey);
uint64 balance = acc.amount;
bytes32 owner = acc.owner;

// 转账代币
SplToken.transfer(recipientAta, mintPubkey, amount);

// 初始化一个新的代币账户
SplToken.initialize_account3(newAccount, mintPubkey, ownerPubkey);
```

### PDA 推导

```solidity
// 推导用户的 Solana PDA
bytes32 userPda = RomeEVMAccount.pda(msg.sender);

// 带盐推导 PDA（用于为每个用户创建多个 PDA）
bytes32 pda = RomeEVMAccount.pda_with_salt(msg.sender, salt);

// 查找任意 PDA
(bytes32 pda, uint8 bump) = SystemProgram.find_program_address(programId, seeds);
```

### 跨程序调用

```solidity
// 调用任意 Solana 程序
ICrossProgramInvocation.AccountMeta[] memory accounts = new ICrossProgramInvocation.AccountMeta[](2);
accounts[0] = ICrossProgramInvocation.AccountMeta(signerPda, true, true);
accounts[1] = ICrossProgramInvocation.AccountMeta(targetAccount, false, true);

CpiProgram.invoke(programId, accounts, instructionData);

// 以 PDA 签名调用
CpiProgram.invoke_signed(programId, accounts, data, seeds);

// 读取账户数据
(uint64 lamports, bytes32 owner, bool isSigner, bool isWritable, bool executable, bytes memory data)
    = CpiProgram.account_info(pubkey);
```

### 基于 SPL 代币的 ERC-20

```solidity
// 为任意 SPL 铸币部署封装器
ERC20SPLFactory factory = ERC20SPLFactory(FACTORY_ADDRESS);
address wrapper = factory.add_spl_token_with_metadata(splMint);

// 将封装器作为标准 ERC-20 使用
SPL_ERC20 token = SPL_ERC20(wrapper);
token.transfer(recipient, amount);
uint256 balance = token.balanceOf(user);
```

### 代币注册表

```solidity
TokenRegistry registry = TokenRegistry(REGISTRY_ADDRESS);

// 使用跨链元数据进行注册
registry.registerToken(splMint, TokenOrigin.WormholeWrapped, externalAddr, chainId);

// 通过外部代币查询
TokenEntry memory entry = registry.getTokenByExternal(2, ethUsdcAddress);
```

### Borsh 反序列化

```solidity
import {Convert} from "@rome-protocol/solidity-sdk/contracts/core/Convert.sol";

// 解析 Solana 账户数据（小端 Borsh 格式）
(uint64 value, uint256 newOffset) = Convert.read_u64le(data, offset);
(bytes32 pubkey, uint256 newOffset2) = Convert.read_bytes32(data, offset);
```

### Metaplex 元数据

```solidity
import {MplTokenMetadataLib} from "@rome-protocol/solidity-sdk/contracts/programs/metadata/MplTokenMetadataLib.sol";

// 从 Metaplex 读取代币元数据
MplTokenMetadataLib.Metadata memory meta = MplTokenMetadataLib.load_metadata(
    mintPubkey, mplProgramId, cpiAddress
);
string memory name = meta.name;
string memory symbol = meta.symbol;
```

## Rust SDK：架构

Rust SDK 是一个包含 9 个 crate 的工作区：

| crate             | 用途                                                   |
| ----------------- | ---------------------------------------------------- |
| `rome-sdk`        | 核心 API： `Rome` 结构体、配置、交易类型（RheaTx、RemusTx、RomulusTx） |
| `rome-evm-client` | EVM Rollup 客户端、TxBuilder、ResourceFactory、模拟器集成       |
| `rome-solana`     | Solana tower、RPC 客户端、交易批处理与跟踪                        |
| `rome-geth`       | 用于区块构建的 OP-Geth Engine API 集成                        |
| `rome-utils`      | RLP、hex、JSON-RPC、认证工具                                |
| `rome-obs`        | OpenTelemetry 可观测性（追踪、指标、日志）                         |
| `rome-da`         | Celestia 数据可用性层                                      |
| `rome-meteora`    | 用于 Gas 定价的 Meteora DEX AMM 池适配器                      |
| `rome-meta-hook`  | Token-2022 Transfer Hook 路由客户端                       |

### 交易类型

```rust
// 单个 Rollup 交易
let rhea = RheaTx::new(signed_eth_tx);
let mut tx = rome.compose_rollup_tx(rhea).await?;
let sig = rome.send_and_confirm(&mut *tx).await?;

// 跨 Rollup 原子交易
let remus = RemusTx::new(vec![tx1, tx2]);
let mut tx = rome.compose_cross_rollup_tx(remus).await?;

// 跨链原子交易（EVM + Solana）
let romulus = RomulusTx::new(eth_txs, sol_ixs);
let mut tx = rome.compose_cross_chain_tx(romulus, signers).await?;
```

### 资源池化

该 SDK 会池化 Solana 密钥对（payer）和持有者账户索引，以便并行提交交易：

```rust
let resource = resource_factory.get().await?;
let payer = resource.payer();       // Solana 密钥对
let holder = resource.holder();     // 持有者账户索引
// 资源会在 Drop 时自动返回池中
```

## SDK 路线图

### 已构建并可运行

* SPL 代币封装器和预编译接口
* 通过 CPI 实现 Meteora DAMM v1 交换
* Oracle Gateway V1 + V2（Pyth Pull、Switchboard V3）
* System Program 辅助工具、Borsh 反序列化
* ERC20SPL 工厂 + 桥接合约
* 带跨链元数据的代币注册表

### 进行中

* JupiterRouter（用于 Jupiter 兑换的 Solidity 接口）
* Meta-Hook Router SDK 客户端

### 计划中（第二阶段）

| 接口       | 协议              |
| -------- | --------------- |
| IJupiter | Jupiter DEX 聚合器 |
| IDrift   | Drift 永续合约      |
| IKamino  | Kamino 借贷       |
| IMeteora | Meteora 流动性     |
| IOndoGM  | Ondo RWA        |

### 计划中（第三阶段）

| 接口            | 程序                |
| ------------- | ----------------- |
| IStakeProgram | Solana Stake      |
| IVoteProgram  | Solana Vote       |
| ISlotHashes   | SlotHashes Sysvar |

## 接下来

* [部署 Solidity](/zh/kai-fa-zhe-zhi-nan/deploy-solidity.md) — 使用 SDK 部署您的第一个合约
* [从 EVM 调用 Solana](/zh/kai-fa-zhe-zhi-nan/call-solana-from-evm.md) — 使用 CPI 与 Solana 程序交互
* [合约地址](/zh/can-kao/contract-addresses.md) — 已部署的 SDK 合约地址


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.rome.builders/zh/chan-pin/rome-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
