LUMOS + Anchor:Solana 开发的完美组合

发布: (2025年12月18日 GMT+8 07:14)
4 min read
原文: Dev.to

Source: Dev.to

概述

LUMOS 与 Anchor 搭配使用,可简化 Solana 开发。它直接从单个 .lumos 架构生成兼容 Anchor 的 Rust 与 TypeScript 代码,自动保持类型和 IDL 同步。

对比

未使用 LUMOS使用 LUMOS
手动编写 Rust 结构体.lumos 架构中定义一次
手动编写 TypeScript 类型自动生成 TypeScript
期望 Rust ↔ TS 保持同步同步有保障(同一来源)
手动计算账户空间自动计算 LEN 常量
手动编写或提取 IDL从架构自动生成 IDL

示例模式 (game.lumos)

#[solana]
#[account]
struct GameConfig {
    authority: PublicKey,
    max_players: u32,
    entry_fee: u64,
    prize_pool: u64,
}

#[solana]
#[account]
struct Player {
    wallet: PublicKey,
    game: PublicKey,
    score: u64,
    joined_at: i64,
}

#[solana]
enum GameInstruction {
    Initialize { max_players: u32, entry_fee: u64 },
    JoinGame,
    UpdateScore { score: u64 },
    ClaimPrize,
}

生成代码

lumos anchor generate game.lumos \
  --name game_program \
  --typescript

该命令会生成如下项目结构:

game_program/
├── programs/game_program/
│   ├── src/
│   │   ├── lib.rs           # 程序入口点
│   │   └── state.rs         # 账户结构体
│   └── Cargo.toml
├── target/idl/
│   └── game_program.json    # Anchor IDL
└── client/
    └── game_program.ts      # TypeScript 客户端

CLI 选项

lumos anchor generate  [OPTIONS]
选项描述
-o, --output输出目录
-n, --name程序名称
-V, --version程序版本(默认:0.1.0
-a, --address程序地址
--typescript生成 TypeScript 客户端
--dry-run预览而不写入文件

示例(附加标志)

lumos anchor generate game.lumos \
  --name my_game \
  --version 1.0.0 \
  --address "Game111111111111111111111111111111111111111" \
  --typescript

其他常用命令:

lumos anchor idl game.lumos --pretty -o target/idl/game.json
lumos anchor space game.lumos --format rust

生成的 Rust 代码 (state.rs)

use anchor_lang::prelude::*;

#[account]
pub struct GameConfig {
    pub authority: Pubkey,
    pub max_players: u32,
    pub entry_fee: u64,
    pub prize_pool: u64,
}

impl GameConfig {
    pub const LEN: usize = 8 + 32 + 4 + 8 + 8; // 60 bytes
}

#[account]
pub struct Player {
    pub wallet: Pubkey,
    pub game: Pubkey,
    pub score: u64,
    pub joined_at: i64,
}

impl Player {
    pub const LEN: usize = 8 + 32 + 32 + 8 + 8; // 88 bytes
}

生成的 TypeScript 客户端 (game_program.ts)

import { PublicKey } from '@solana/web3.js';
import * as borsh from '@coral-xyz/borsh';

export interface GameConfig {
  authority: PublicKey;
  maxPlayers: number;
  entryFee: number;
  prizePool: number;
}

export const GameConfigSchema = borsh.struct([
  borsh.publicKey('authority'),
  borsh.u32('maxPlayers'),
  borsh.u64('entryFee'),
  borsh.u64('prizePool'),
]);

用例与建议

场景推荐
开始一个新的 Anchor 项目✅ 使用 LUMOS
现有项目,需要类型同步✅ 使用 LUMOS
简单程序,账户类型少⚠️ 任意方式均可
复杂程序,拥有大量共享类型✅ 使用 LUMOS
团队中有 Rust 与 TS 开发者混合✅ 使用 LUMOS

结论

如果你为 Anchor 程序编写 TypeScript 客户端,LUMOS 能消除维护重复类型定义的需求,使 Rust 与 TS 完美同步。

安装

cargo install lumos-cli
lumos anchor generate schema.lumos --typescript

参考资料

  • 文档:
  • GitHub:
Back to Blog

相关文章

阅读更多 »