### Install LUMOS CLI and VSCode Extension Source: https://docs.lumos-lang.org/getting-started/quick-start Installs the LUMOS command-line interface using Cargo and optionally installs the VSCode extension for syntax highlighting. Dependencies include Rust and Cargo for the CLI, and the 'code' command for the VSCode extension. ```bash cargo install lumos-cli lumos --version code --install-extension lumos.lumos-vscode ``` -------------------------------- ### Use Lumos Core in Rust Code (Rust) Source: https://docs.lumos-lang.org/getting-started/installation Example of how to import and use functions from the 'lumos-core' library within a Rust program to parse a schema and generate code. ```rust use lumos_core::{parse_schema, generate_rust, generate_typescript}; fn main() { let schema = parse_schema("schema.lumos")?; let rust_code = generate_rust(&schema)?; let ts_code = generate_typescript(&schema)?; } ``` -------------------------------- ### Use Generated Code in Anchor Program for Account Creation Source: https://docs.lumos-lang.org/getting-started/quick-start Demonstrates how to use the generated Rust code within an Anchor program. It includes the necessary module imports, program definition, and an example 'create_player' function that initializes a PlayerAccount, setting its fields based on the generated struct. ```rust mod generated; use generated::*; #[program] pub mod my_game { use super::*; pub fn create_player(ctx: Context) -> Result<()> { let player = &mut ctx.accounts.player; player.wallet = *ctx.accounts.user.key; player.level = 1; player.experience = 0; player.equipped_items = Vec::new(); Ok(()) } } #[derive(Accounts)] pub struct CreatePlayer<'info> { #[account( init, payer = user, space = 8 + std::mem::size_of::() )] pub player: Account<'info, PlayerAccount>, #[account(mut)] pub user: Signer<'info>, pub system_program: Program<'info, System>, } ``` -------------------------------- ### Define Solana Account and Struct Schemas in LUMOS Source: https://docs.lumos-lang.org/getting-started/quick-start Defines data structures for Solana programs using LUMOS schema language. It includes examples for a 'PlayerAccount' which is an Anchor account, and a 'MatchResult' struct. Key types like PublicKey, arrays, and optional values are demonstrated. ```lumos #[solana] #[account] struct PlayerAccount { wallet: PublicKey, level: u16, experience: u64, equipped_items: [PublicKey], } #[solana] struct MatchResult { player: PublicKey, opponent: Option, score: u64, timestamp: i64, } ``` -------------------------------- ### Verify Lumos Installation (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Command to run after installation to check if the Lumos CLI is accessible and display its help information. ```shell lumos --help ``` -------------------------------- ### Install Lumos CLI from crates.io (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Installs the Lumos command-line interface using Cargo, the Rust package manager. This is the recommended installation method. ```shell # Install the CLI cargo install lumos-cli # Verify installation lumos --version # lumos-cli 0.1.0 ``` -------------------------------- ### Add Cargo Bin to PATH (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Example shell commands to add Cargo's binary directory to the PATH environment variable for bash and zsh shells, necessary if 'lumos' command is not found. ```shell # For bash (~/.bashrc) export PATH="$HOME/.cargo/bin:$PATH" # For zsh (~/.zshrc) export PATH="$HOME/.cargo/bin:$PATH" # Reload shell source ~/.bashrc # or ~/.zshrc ``` -------------------------------- ### Initialize LUMOS Project and Project Structure Source: https://docs.lumos-lang.org/getting-started/quick-start Initializes a new LUMOS project named 'my-game'. This command creates essential project files including the schema definition file ('schema.lumos'), a configuration file ('lumos.toml'), and a README file. The output shows the directory structure of the newly created project. ```bash lumos init my-game ``` -------------------------------- ### Check Lumos Schema for Updates Source: https://docs.lumos-lang.org/getting-started/quick-start Verifies if the generated code for a Lumos schema is up-to-date with the schema definition. This command helps maintain consistency between your schema and the generated types. ```bash lumos check schema.lumos ``` -------------------------------- ### Install and Verify LUMOS CLI Source: https://docs.lumos-lang.org/guides/migration-guide Installs the LUMOS command-line interface using Cargo and verifies the installation by checking the CLI version. Ensure you have Rust and Cargo installed. ```bash cargo install lumos-cli # Verify installation lumos --version # Output: lumos-cli 0.1.0 ``` -------------------------------- ### Check Rust Version (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Command to verify the installed Rust version. Requires Rust to be installed on the system. ```shell rustc --version # rustc 1.70.0 or higher ``` -------------------------------- ### Build Lumos CLI from Source (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Builds the Lumos CLI from its source code repository. This method is suitable for obtaining the latest development version and requires Git and Rust installed. ```shell # Clone the repository git clone https://github.com/getlumos/lumos.git cd lumos # Build the CLI cargo build --release --all-features --workspace # The binary will be at: target/release/lumos ./target/release/lumos --version ``` -------------------------------- ### LUMOS Schema Example (`schema.lumos`) Source: https://docs.lumos-lang.org/api/cli-commands An example of a `.lumos` schema file defining a Solana account structure with fields for wallet, level, and experience. ```rust #[solana] #[account] struct PlayerAccount { wallet: PublicKey, level: u16, experience: u64, } ``` -------------------------------- ### Initialize LUMOS Project Source: https://docs.lumos-lang.org/api/cli-commands Initializes a new LUMOS project with an example schema, configuration file, and README. Can specify a project name or initialize the current directory. ```bash lumos init [PROJECT_NAME] lumos init my-solana-app cd my-solana-app lumos init ``` -------------------------------- ### Get Player Account in TypeScript Source: https://docs.lumos-lang.org/getting-started/quick-start Fetches and deserializes player account data from the Solana blockchain using a provided connection and player public key. It relies on generated Borsh schemas for deserialization and throws an error if the account is not found. The function returns a PlayerAccount object. ```typescript import { PlayerAccount, PlayerAccountBorshSchema } from './generated'; import { Connection, PublicKey } from '@solana/web3.js'; async function getPlayerAccount( connection: Connection, playerPubkey: PublicKey ): Promise { const accountInfo = await connection.getAccountInfo(playerPubkey); if (!accountInfo) { throw new Error('Player account not found'); } // Deserialize using generated Borsh schema const player = PlayerAccountBorshSchema.deserialize(accountInfo.data); console.log(`Level: ${player.level}, XP: ${player.experience}`); return player; } ``` -------------------------------- ### Generate Lumos Code with Watch Mode Source: https://docs.lumos-lang.org/getting-started/quick-start Generates code from a Lumos schema and enables watch mode, which automatically regenerates code upon detecting file changes. This is useful for a streamlined development workflow. ```bash lumos generate schema.lumos --watch ``` -------------------------------- ### LUMOS Project Configuration Example (`lumos.toml`) Source: https://docs.lumos-lang.org/api/cli-commands An example of a `lumos.toml` configuration file, specifying output paths for Rust and TypeScript code generation, formatting preferences, and Rust prelude settings. ```toml [generation] rust_output = "generated.rs" typescript_output = "generated.ts" format = true [imports] rust_prelude = true ``` -------------------------------- ### Validate Lumos Schema Syntax Source: https://docs.lumos-lang.org/getting-started/quick-start Checks the syntax of a Lumos schema file. This command-line tool helps ensure that the schema definition is valid before code generation or other operations. ```bash lumos validate schema.lumos ``` -------------------------------- ### Inspect Generated Rust Code for Solana Programs Source: https://docs.lumos-lang.org/getting-started/quick-start Displays the Rust code generated by LUMOS from the schema definition. This includes Anchor account structs and regular structs, featuring types like Pubkey, u16, u64, and Option, suitable for use in Solana programs. ```rust use anchor_lang::prelude::*; #[account] pub struct PlayerAccount { pub wallet: Pubkey, pub level: u16, pub experience: u64, pub equipped_items: Vec, } pub struct MatchResult { pub player: Pubkey, pub opponent: Option, pub score: u64, pub timestamp: i64, } ``` -------------------------------- ### Inspect Generated TypeScript Code for Solana Programs Source: https://docs.lumos-lang.org/getting-started/quick-start Shows the TypeScript code generated by LUMOS, including interfaces for data structures and Borsh schemas for serialization. It demonstrates synchronization of types like PublicKey, number, and arrays, along with handling of optional fields. ```typescript import { PublicKey } from '@solana/web3.js'; import * as borsh from '@coral-xyz/borsh'; export interface PlayerAccount { wallet: PublicKey; level: number; experience: number; equipped_items: PublicKey[]; } export const PlayerAccountBorshSchema = borsh.struct([ borsh.publicKey('wallet'), borsh.u16('level'), borsh.u64('experience'), borsh.vec(borsh.publicKey(), 'equipped_items'), ]); export interface MatchResult { player: PublicKey; opponent: PublicKey | undefined; score: number; timestamp: number; } export const MatchResultBorshSchema = borsh.struct([ borsh.publicKey('player'), borsh.option(borsh.publicKey(), 'opponent'), borsh.u64('score'), borsh.i64('timestamp'), ]); ``` -------------------------------- ### Tips & Best Practices - Automate Generation Source: https://docs.lumos-lang.org/api/cli-commands Example 'package.json' scripts demonstrating how to automate schema generation using 'lumos generate' as a codegen step and a 'prebuild' hook. ```json { "scripts": { "codegen": "lumos generate schema.lumos", "prebuild": "npm run codegen" } } ``` -------------------------------- ### Update Rust Toolchain and Rebuild (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Commands to update the Rust toolchain and clean/rebuild the project from source, used for resolving build errors. ```shell rustup update cargo clean cargo build --release ``` -------------------------------- ### Add Lumos Core as Library Dependency (TOML) Source: https://docs.lumos-lang.org/getting-started/installation Configuration for adding the 'lumos-core' library to a Rust project's dependencies in the Cargo.toml file. ```toml [dependencies] lumos-core = "0.1" ``` -------------------------------- ### Generate Rust and TypeScript Code from LUMOS Schema Source: https://docs.lumos-lang.org/getting-started/quick-start Generates Rust and TypeScript code from a LUMOS schema file ('schema.lumos'). This command is executed within the project directory and produces corresponding code files ('generated.rs' and 'generated.ts') that are synchronized with the schema definitions. ```bash cd my-game lumos generate schema.lumos ``` -------------------------------- ### Install LUMOS CLI Source: https://docs.lumos-lang.org/api/cli-commands Installs the LUMOS CLI using Cargo. It's recommended to verify the installation by checking the version. ```bash cargo install lumos-cli lumos --version ``` -------------------------------- ### Check Cargo Bin Directory in PATH (Shell) Source: https://docs.lumos-lang.org/getting-started/installation Shell command to check if Cargo's binary directory is included in the system's PATH environment variable, used for troubleshooting 'command not found' errors. ```shell echo $PATH | grep .cargo/bin ``` -------------------------------- ### CI/CD Integration for Lumos Code Generation and Testing Source: https://docs.lumos-lang.org/guides/migration-guide GitHub Actions workflow to automate Lumos code generation and testing. It installs the Lumos CLI, generates code using a Makefile target, checks for uncommitted changes in generated code, and runs tests. ```yaml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install LUMOS CLI run: cargo install lumos-cli - name: Generate code run: make codegen - name: Check for uncommitted changes run: | git diff --exit-code || \ (echo "Generated code is outdated. Run 'make codegen' locally." && exit 1) - name: Run tests run: make test ``` -------------------------------- ### package.json Script for Pre-build Check Source: https://docs.lumos-lang.org/api/cli-commands An example of how to integrate Lumos schema checking into a 'package.json' file's 'prebuild' script. It ensures schemas are up-to-date before the main build process. ```json { "scripts": { "prebuild": "lumos check schema.lumos || lumos generate schema.lumos", "build": "anchor build" } } ``` -------------------------------- ### Rust Borsh Struct Definition Source: https://docs.lumos-lang.org/guides/migration-guide An example of a Rust struct 'PlayerAccount' using Anchor's '#[account]' derive for on-chain data, including fields like Pubkey, u16, u64, and Vec. ```rust use anchor_lang::prelude::*; #[account] pub struct PlayerAccount { pub wallet: Pubkey, pub level: u16, pub experience: u64, pub items: Vec, } ``` -------------------------------- ### Example: Pre-commit Hook for LUMOS Schema Validation Source: https://docs.lumos-lang.org/api/cli-commands A bash script demonstrating how to use `lumos validate` as a pre-commit hook to ensure all staged `.lumos` files are syntactically correct before committing. ```bash #!/bin/bash # Find all .lumos files LUMOS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.lumos$') if [ -n "$LUMOS_FILES" ]; then for file in $LUMOS_FILES; do lumos validate "$file" if [ $? -ne 0 ]; then echo "❌ Validation failed for $file" exit 1 fi done echo "✅ All schemas valid" fi ``` -------------------------------- ### Rust Example for Using Option for Nullable Fields Source: https://docs.lumos-lang.org/api/types Illustrates the best practice of using Rust's `Option` type for fields that may be null or absent, ensuring type safety for nullable values. ```rust struct User { name: String, email: Option, // Not all users have email } ``` -------------------------------- ### Troubleshooting Lumos Lang: Serialization and Field Order Source: https://docs.lumos-lang.org/guides/migration-guide This example addresses the 'Serialization produces different bytes' issue in Lumos Lang migrations, which typically arises from field order mismatches between manual Rust structs and their Lumos equivalents. The fix involves ensuring that the fields in the Lumos struct definition maintain the exact same order as in the original manual struct to preserve binary compatibility. ```rust pub struct Account { pub authority: Pubkey, // Field 1 pub balance: u64, // Field 2 } ``` ```rust struct Account { authority: PublicKey, // Field 1 balance: u64, // Field 2 } ``` -------------------------------- ### Lumos Generate Command - Verbose Mode Source: https://docs.lumos-lang.org/api/cli-commands Example of using the 'lumos generate' command with the verbose flag ('-v'). This flag provides detailed output about the generation process, including parsing, transformation, and file generation steps. ```bash lumos generate schema.lumos -v # Output: # [DEBUG] Parsing schema file... # [DEBUG] Transforming AST to IR... # [DEBUG] Generating Rust code... # [DEBUG] Generating TypeScript code... # ✓ Generated 2 files ``` -------------------------------- ### Environment Variables Configuration - Change Output Directory Source: https://docs.lumos-lang.org/api/cli-commands Example of changing the default output directory for generated files by setting the 'LUMOS_OUTPUT_DIR' environment variable. ```bash # Change default output directory export LUMOS_OUTPUT_DIR=./generated lumos generate schema.lumos ``` -------------------------------- ### Lumos Schema Attributes for Solana Source: https://docs.lumos-lang.org/api/generated-code Demonstrates the usage of Lumos schema attributes for Solana development. The `#[account]` attribute is recommended for data that persists on-chain in PDAs or accounts, while it can be omitted for events and instruction parameters. ```rust /* Use #[account] for On-Chain Storage */ #[solana] #[account] struct UserProfile { /* ... */ } /* Omit #[account] for Events and Arguments */ #[solana] struct TransferEvent { /* ... */ } ``` -------------------------------- ### Immediate Rollback Strategy for Lumos Migrations Source: https://docs.lumos-lang.org/guides/migration-guide This code snippet outlines an immediate rollback strategy using Git and Anchor. It involves reverting Git commits and redeploying the previous version of the program. ```shell git revert HEAD~1 # Revert LUMOS migration commit git push origin main --force anchor build anchor deploy --program-id ``` -------------------------------- ### Tips & Best Practices - Validate in CI Source: https://docs.lumos-lang.org/api/cli-commands Example of validating Lumos schemas within a CI/CD pipeline using the 'lumos validate' command, ensuring the pipeline fails if validation fails. ```bash lumos validate schema.lumos || exit 1 ``` -------------------------------- ### Partial Rollback for Lumos Migrations Source: https://docs.lumos-lang.org/guides/migration-guide This code demonstrates a partial rollback strategy, allowing specific Lumos-migrated types to be reverted while keeping others. It involves checking out a previous version of a specific file. ```shell git checkout HEAD~1 -- programs/my-game/src/state.rs ``` -------------------------------- ### Generate Lumos Code Command Source: https://docs.lumos-lang.org/api/generated-code This snippet shows the basic command to generate code from a Lumos schema file. It includes an option to disable automatic code formatting. ```shell lumos generate schema.lumos lumos generate schema.lumos --no-format ``` -------------------------------- ### GitHub Actions Workflow for Schema Check Source: https://docs.lumos-lang.org/api/cli-commands A GitHub Actions workflow that checks all '.lumos' files in the repository on each push or pull request. It installs the Lumos CLI and iterates through schemas to ensure they are up-to-date. ```yaml name: Check LUMOS Schemas on: [push, pull_request] jobs: check-schemas: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install LUMOS CLI run: cargo install lumos-cli - name: Check schemas are up-to-date run: | for schema in $(find . -name "*.lumos"); do lumos check "$schema" done ``` -------------------------------- ### Rust Workarounds for Unsupported Types (Fixed-size arrays, Tuples) Source: https://docs.lumos-lang.org/api/types Provides Rust code examples demonstrating workarounds for unsupported types like fixed-size arrays and tuples by converting them to Vec and structs, respectively. ```rust // ❌ Not supported struct Data { buffer: [u8; 1024], } // ✅ Use Vec instead struct Data { buffer: [u8], // Vec } // ❌ Not supported struct Pair { data: (u64, String), } // ✅ Use struct instead struct Pair { first: u64, second: String, } ``` -------------------------------- ### Automating Lumos Code Generation with npm Scripts Source: https://docs.lumos-lang.org/guides/migration-guide Integrates Lumos code generation into the npm build process. The 'codegen' script runs the Lumos CLI, 'prebuild' ensures generation before building, and 'build' compiles the project. ```json { "scripts": { "codegen": "lumos generate schema/types.lumos --output-dir ./generated", "prebuild": "npm run codegen", "build": "anchor build" } } ``` -------------------------------- ### Solana Best Practices: Consistent Attribute Order Source: https://docs.lumos-lang.org/api/attributes Emphasizes the importance of a consistent attribute order for Solana data structures: #[solana] first, followed by #[account], and then the type definition. Provides an example of the correct attribute order. ```rust #[solana] #[account] struct Account { /* ... */ } ``` -------------------------------- ### Rust Import Strategy: Anchor Imports with #[solana] Source: https://docs.lumos-lang.org/api/generated-code Shows that even if a module only contains structs with the `#[solana]` attribute and no `#[account]` attributes, the import strategy still defaults to using Anchor imports (`anchor_lang::prelude::*`). Manual Borsh implementations might still be required. ```rust // Has #[solana] but no #[account] → Still use Anchor use anchor_lang::prelude::* pub struct MatchResult { /* ... */ } // Manual Borsh impls added ``` -------------------------------- ### Integrate Generated Types in Anchor Programs (Rust) Source: https://docs.lumos-lang.org/api/generated-code Demonstrates how to use Lumos-generated types within an Anchor program. It shows importing generated types and defining an `Accounts` struct for a program instruction, specifying the generated `PlayerAccount` type for on-chain storage. ```rust use anchor_lang::prelude::*; // Import your generated types use crate::generated::*; #[program] pub mod my_game { use super::*; pub fn create_player(ctx: Context) -> Result<()> { let player = &mut ctx.accounts.player; player.wallet = *ctx.accounts.user.key; player.level = 1; player.experience = 0; Ok(()) } } #[derive(Accounts)] pub struct CreatePlayer<'info> { #[account( init, payer = user, space = 8 + std::mem::size_of::() )] pub player: Account<'info, PlayerAccount>, // ← Generated type #[account(mut)] pub user: Signer<'info>, pub system_program: Program<'info, System>, } ``` -------------------------------- ### Generate LUMOS Code for Rust and TypeScript Source: https://docs.lumos-lang.org/guides/migration-guide Uses the LUMOS CLI to generate Rust and TypeScript code from a LUMOS schema file. Specify the output file paths for each language. ```bash # Generate Rust lumos generate schema/player.lumos --rust-file programs/my-game/src/generated.rs # Generate TypeScript lumos generate schema/player.lumos --typescript-file sdk/src/generated.ts ``` -------------------------------- ### Rust Import Strategy: Anchor Imports with #[account] Source: https://docs.lumos-lang.org/api/generated-code Illustrates the import strategy where if any struct in a module has the `#[account]` attribute, the entire module defaults to using Anchor imports (`anchor_lang::prelude::*`), even for structs without Solana-specific attributes. ```rust // ANY struct has #[account] → Use Anchor imports for ENTIRE module use anchor_lang::prelude::* #[account] pub struct PlayerAccount { /* ... */ } pub struct GameEvent { /* ... */ } // Also uses Anchor imports ``` -------------------------------- ### Automating Lumos Code Generation with Makefile Source: https://docs.lumos-lang.org/guides/migration-guide This Makefile automates Lumos code generation for both Rust and TypeScript. The 'codegen' target generates Rust code for the program and TypeScript code for the SDK. The 'build' and 'test' targets depend on 'codegen'. ```makefile .PHONY: codegen codegen: lumos generate schema/types.lumos -o programs/my-game/src/generated.rs lumos generate schema/types.lumos -o sdk/src/generated.ts build: codegen anchor build test: codegen cargo test npm test ``` -------------------------------- ### Rust Import Strategy: Pure Borsh Imports Source: https://docs.lumos-lang.org/api/generated-code Demonstrates the import strategy for modules containing only pure Borsh types. In this case, it uses direct imports from the `borsh` crate (`borsh::{BorshSerialize, BorshDeserialize}`) and applies `#[derive]` macros for serialization. ```rust // Pure Borsh types use borsh::{BorshSerialize, BorshDeserialize}; #[derive(BorshSerialize, BorshDeserialize)] pub struct GenericData { /* ... */ } ``` -------------------------------- ### TypeScript Borsh Struct Definition Source: https://docs.lumos-lang.org/guides/migration-guide Defines a TypeScript interface 'PlayerAccount' and its corresponding Borsh schema using '@coral-xyz/borsh'. This example includes PublicKey, numbers, and an array of PublicKeys. ```typescript import { PublicKey } from '@solana/web3.js'; import * as borsh from '@coral-xyz/borsh'; export interface PlayerAccount { wallet: PublicKey; level: number; experience: number; items: PublicKey[]; } export const PlayerAccountSchema = borsh.struct([ borsh.publicKey('wallet'), borsh.u16('level'), borsh.u64('experience'), borsh.vec(borsh.publicKey(), 'items'), ]); ``` -------------------------------- ### Workaround for Unsupported f32/f64 Types in Lumos Lang Source: https://docs.lumos-lang.org/guides/migration-guide This example provides a workaround for the 'Unsupported type 'f64'' error encountered when migrating to Lumos Lang. Since Lumos does not directly support floating-point types (aligned with Solana best practices), the solution is to represent monetary values or other float-based data using fixed-point integers, such as storing amounts in the smallest unit (e.g., lamports). ```rust // Before price: f64, // After (store as lamports, e.g., 1.5 SOL = 1_500_000_000) price_lamports: u64, ``` -------------------------------- ### Solana Player Account Structure and Creation Source: https://docs.lumos-lang.org/api/attributes Defines the 'PlayerAccount' structure for on-chain storage using Solana's #[account] attribute and demonstrates its creation within an Anchor program. It includes fields for wallet, level, experience, and inventory. ```rust #[solana] #[account] struct PlayerAccount { wallet: PublicKey, level: u16, experience: u64, inventory: [PublicKey], } #[program] pub mod game { use super::*; pub fn create_player(ctx: Context) -> Result<()> { let player = &mut ctx.accounts.player; player.wallet = *ctx.accounts.user.key; player.level = 1; player.experience = 0; player.inventory = Vec::new(); Ok(()) } } #[derive(Accounts)] pub struct CreatePlayer<'info> { #[account( init, payer = user, space = 8 + std::mem::size_of::() )] pub player: Account<'info, PlayerAccount>, #[account(mut)] pub user: Signer<'info>, pub system_program: Program<'info, System>, } ``` -------------------------------- ### Define Solana Account Structure in LUMOS and Generate Rust/TypeScript Code Source: https://docs.lumos-lang.org/index This example illustrates how to define a Solana program account using LUMOS's custom DSL. It then shows the corresponding type-safe Rust code, compatible with Anchor, and TypeScript SDK code, complete with Borsh schema, generated from that single definition. This demonstrates LUMOS's ability to maintain synchronized data structures across different languages. ```LUMOS #[solana] #[account] struct PlayerAccount { wallet: PublicKey, level: u16, experience: u64, } ``` ```Rust use anchor_lang::prelude::*; #[account] pub struct PlayerAccount { pub wallet: Pubkey, pub level: u16, pub experience: u64, } ``` ```TypeScript import { PublicKey } from '@solana/web3.js'; import * as borsh from '@coral-xyz/borsh'; export interface PlayerAccount { wallet: PublicKey; level: number; experience: number; } export const PlayerAccountBorshSchema = borsh.struct([ borsh.publicKey('wallet'), borsh.u16('level'), borsh.u64('experience'), ]); ``` -------------------------------- ### Environment Variables Configuration - Disable Color Source: https://docs.lumos-lang.org/api/cli-commands Example of disabling colored output in the Lumos CLI by setting the 'LUMOS_COLOR' environment variable to 'never'. ```bash # Disable colored output export LUMOS_COLOR=never lumos generate schema.lumos ``` -------------------------------- ### Check Schema Status - Missing Files Source: https://docs.lumos-lang.org/api/cli-commands Illustrates the scenario where generated files are missing entirely, prompting the user to run the 'generate' command. ```bash lumos check schema.lumos # Output: ⚠️ Generated files not found # Run: lumos generate schema.lumos # Exit code: 1 ``` -------------------------------- ### LUMOS Schema for PlayerAccount Source: https://docs.lumos-lang.org/guides/migration-guide Defines the 'PlayerAccount' struct in LUMOS schema format. This schema uses Solana-specific types and array notation for fields. ```lumos #[solana] #[account] struct PlayerAccount { wallet: PublicKey, level: u16, experience: u64, items: [PublicKey], } ``` -------------------------------- ### Shadow Deployment for Lumos Lang Serialization Source: https://docs.lumos-lang.org/guides/migration-guide This Rust function demonstrates shadow deployment by comparing manual serialization with Lumos-generated serialization. It runs both serialization paths, logs any mismatches, and logs errors if they occur. It is intended for mission-critical systems to build confidence before fully switching to Lumos. ```rust #[cfg(feature = "lumos-migration")] fn serialize_player(account: &PlayerAccount) -> Vec { let manual_bytes = borsh::to_vec(&account).unwrap(); let lumos_bytes = borsh::to_vec(&lumos_generated::PlayerAccount::from(account)).unwrap(); if manual_bytes != lumos_bytes { log::error!("LUMOS serialization mismatch detected!"); } manual_bytes // Still use manual for now } ``` -------------------------------- ### Solana Best Practices: Omit #[account] for Events Source: https://docs.lumos-lang.org/api/attributes Advises against using the #[account] attribute for event data, as events are emitted and not stored on-chain. Provides an example of a TransferEvent struct with only the #[solana] attribute. ```rust #[solana] struct TransferEvent { /* ... */ } ``` -------------------------------- ### Lumos Generate Command - Quiet Mode Source: https://docs.lumos-lang.org/api/cli-commands Demonstrates the 'lumos generate' command in quiet mode ('-q'). In this mode, no output is produced on success, only errors are reported. ```bash lumos generate schema.lumos -q # No output on success, only errors ``` -------------------------------- ### Troubleshooting Lumos Lang Migration: Type Mismatches and Imports Source: https://docs.lumos-lang.org/guides/migration-guide This snippet addresses common type mismatch issues during Lumos Lang migration, specifically the 'expected `Pubkey`, found `PublicKey`' error. It illustrates the fix by showing how to update imports, often by using generated types or aliasing to resolve discrepancies between standard Solana types and Lumos-generated types. ```rust // Before use solana_program::pubkey::Pubkey; // After mod generated; use generated::PlayerAccount; // Already has Pubkey internally ``` -------------------------------- ### LUMOS GameState Definition (With LUMOS) Source: https://docs.lumos-lang.org/getting-started/introduction Example of a GameState struct defined in LUMOS. This single definition is used to generate both Rust and TypeScript code, ensuring synchronization and automatic Borsh schema generation. ```rust #[solana] struct GameState { player: PublicKey, score: u64, level: u16, } ``` -------------------------------- ### TypeScript GameState Definition (Without LUMOS) Source: https://docs.lumos-lang.org/getting-started/introduction Example of a TypeScript GameState interface and its corresponding manual Borsh schema definition. Manual synchronization with Rust code is required, increasing the risk of errors. ```typescript interface GameState { player: PublicKey; score: number; level: number; } const GameStateBorshSchema = borsh.struct([ borsh.publicKey('player'), borsh.u64('score'), borsh.u16('level'), ]); ``` -------------------------------- ### Rust GameState Definition (Without LUMOS) Source: https://docs.lumos-lang.org/getting-started/introduction Example of a Rust GameState struct used in Solana programs. It requires manual implementation of Borsh serialization and deserialization using `#[derive(BorshSerialize, BorshDeserialize)]`. ```rust #[derive(BorshSerialize, BorshDeserialize)] pub struct GameState { pub player: Pubkey, pub score: u64, pub level: u16, } ``` -------------------------------- ### Solana Best Practices: #[account] for Persistent Data Source: https://docs.lumos-lang.org/api/attributes Recommends using the #[account] attribute for data that is intended to be stored persistently on-chain, such as in PDAs or accounts. Provides an example of a UserProfile struct with #[solana] and #[account] attributes. ```rust #[solana] #[account] struct UserProfile { /* ... */ } ``` -------------------------------- ### Generate Rust and TypeScript Code from LUMOS Schema Source: https://docs.lumos-lang.org/api/cli-commands Generates Rust and TypeScript code from a .lumos schema file. Supports custom output directories, file names, and formatting options. ```bash lumos generate [OPTIONS] lumos generate schema.lumos lumos generate schema.lumos --output-dir ./src/generated lumos generate schema.lumos \ --rust-file types.rs \ --typescript-file types.ts lumos generate schema.lumos --no-format ``` -------------------------------- ### Rust: Test Borsh Serialization and Deserialization Compatibility Source: https://docs.lumos-lang.org/guides/migration-guide Tests Rust code for Borsh serialization and deserialization compatibility between manually implemented and LUMOS-generated code. It ensures that both methods produce byte-for-byte identical results for a given account structure. Dependencies include `borsh`, `solana_program`, and `anchor_lang`. ```rust use borsh::{BorshSerialize, BorshDeserialize}; use solana_program::pubkey::Pubkey; // Manual implementation mod manual { use super::*; use anchor_lang::prelude::*; #[account] pub struct PlayerAccount { pub wallet: Pubkey, pub level: u16, pub experience: u64, pub items: Vec, } } // LUMOS-generated mod generated { include!("../programs/my-game/src/generated.rs"); } #[test] fn test_serialization_compatibility() { let wallet = Pubkey::new_unique(); let items = vec![Pubkey::new_unique(), Pubkey::new_unique()]; // Serialize with manual code let manual_account = manual::PlayerAccount { wallet, level: 42, experience: 1000, items: items.clone(), }; let manual_bytes = borsh::to_vec(&manual_account).unwrap(); // Serialize with LUMOS-generated code let lumos_account = generated::PlayerAccount { wallet, level: 42, experience: 1000, items: items.clone(), }; let lumos_bytes = borsh::to_vec(&lumos_account).unwrap(); // MUST be byte-for-byte identical assert_eq!(manual_bytes, lumos_bytes, "Serialization mismatch!"); } #[test] fn test_deserialization_compatibility() { let wallet = Pubkey::new_unique(); let items = vec![Pubkey::new_unique()]; // Create bytes with manual code let manual_account = manual::PlayerAccount { wallet, level: 10, experience: 500, items: items.clone(), }; let bytes = borsh::to_vec(&manual_account).unwrap(); // Deserialize with LUMOS-generated code let lumos_account = borsh::from_slice::(&bytes).unwrap(); assert_eq!(lumos_account.wallet, wallet); assert_eq!(lumos_account.level, 10); assert_eq!(lumos_account.experience, 500); assert_eq!(lumos_account.items, items); } ```