### Install Dependencies Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Installs necessary command-line tools for LUMOS, Anchor, and project-specific Node.js dependencies. ```bash # Install LUMOS CLI carousel install lumos-cli # Install Anchor carousel install --git https://github.com/coral-xyz/anchor --tag v0.32.1 anchor-cli # Install Node dependencies npm install ``` -------------------------------- ### Setup Commands for Solana Project Source: https://github.com/getlumos/awesome-lumos/blob/main/CONTRIBUTING.md These bash commands demonstrate the typical setup process for a Solana project using Anchor and LUMOS. It covers installing dependencies, generating LUMOS types, running tests, and deployment. ```bash # Install dependencies npm install cargo build # Generate LUMOS types lumos generate schema.lumos # Run tests anchor test # Deploy anchor deploy ``` -------------------------------- ### Install Dependencies for LUMOS Token Vesting Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Installs the necessary command-line tools, LUMOS CLI and Anchor, required for developing and building the token vesting program. These tools are essential for code generation and Solana program compilation. ```bash # Install LUMOS CLI cargo install lumos-cli # Install Anchor cargo install --git https://github.com/coral-xyz/anchor --tag v0.32.1 anchor-cli ``` -------------------------------- ### Example README.md Template for Project Source: https://github.com/getlumos/awesome-lumos/blob/main/CONTRIBUTING.md A template for the README.md file within an example project. It includes sections for project name, features, architecture, prerequisites, setup instructions, LUMOS schema details, testing, deployment, and license. ```markdown # Your Project Name Brief description of what this project demonstrates. ## Features - Feature 1 - Feature 2 - Feature 3 ## Architecture Brief explanation of how LUMOS is used in this project. ## Prerequisites - Rust 1.70+ - Solana CLI 1.18+ - Anchor 0.30+ - Node.js 18+ - LUMOS CLI ## Setup ```bash # Install dependencies npm install cargo build # Generate LUMOS types lumos generate schema.lumos # Run tests anchor test # Deploy anchor deploy ``` ## LUMOS Schema Explanation of the schema design and key types. ## Testing How to run and understand the tests. ## Deployment Step-by-step deployment instructions. ## License MIT or Apache 2.0 ``` -------------------------------- ### Install LUMOS CLI and Verify Installation Source: https://github.com/getlumos/awesome-lumos/blob/main/README.md These commands demonstrate how to install the LUMOS command-line interface using Cargo and subsequently verify the installation by checking the installed version. Ensure Rust and Cargo are set up before execution. ```bash cargo install lumos-cli lumos --version ``` -------------------------------- ### Create Vesting Schedule (Rust) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Creates a vesting schedule for a beneficiary. This Rust function defines the parameters for a vesting schedule, including the type of vesting, total amount, start time, duration, and whether it is revocable. ```Rust pub fn create_schedule( ctx: Context, vesting_type: VestingType, total_amount: u64, start_time: i64, duration: i64, is_revocable: bool, ) -> Result<()> ``` -------------------------------- ### Initialize Marketplace Anchor Program Instruction Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Defines the Anchor program instruction and its corresponding Rust function for initializing a new NFT marketplace. It takes a `fee_percentage` as input and sets up the marketplace configuration account. The provided TypeScript example demonstrates how to call this instruction using the Anchor client. ```rust pub fn initialize_marketplace( ctx: Context, fee_percentage: u16, ) -> Result<()> ``` ```typescript await program.methods .initializeMarketplace(250) // 2.5% fee .accounts({ config: marketplaceConfigPda, authority: provider.wallet.publicKey, treasury: treasuryPublicKey, systemProgram: SystemProgram.programId, }) .rpc(); ``` -------------------------------- ### List NFT Anchor Program Instruction Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Defines the Anchor program instruction and its Rust function for listing an NFT on the marketplace. It accepts the listing `price` and requires accounts for the listing details, marketplace configuration, seller, and the NFT mint. The TypeScript example shows how to invoke this instruction and then fetch and deserialize the listing data using Borsh. ```rust pub fn list_nft( ctx: Context, price: u64, ) -> Result<()> ``` ```typescript import { Listing, ListingBorshSchema } from './generated'; await program.methods .listNft(new BN(1_000_000_000)) // 1 SOL .accounts({ listing: listingPda, config: marketplaceConfigPda, seller: provider.wallet.publicKey, nftMint: nftMintPublicKey, systemProgram: SystemProgram.programId, }) .rpc(); // Fetch listing data const listingAccount = await connection.getAccountInfo(listingPda); const listing = borsh.deserialize( ListingBorshSchema, listingAccount.data ) as Listing; console.log('Listed at:', new Date(listing.listed_at * 1000)); console.log('Status:', listing.status.kind); // 'Active' ``` -------------------------------- ### Create Milestone Vesting Schedule (TypeScript) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Creates a vesting schedule where tokens are released at predefined milestones. Each milestone specifies an unlock time, a percentage of the total amount to be unlocked, and an initial unlocked status. Inputs include pool, authority, beneficiary, milestone configuration, total amount, start time, duration, and revocability. ```TypeScript const schedule = await client.createSchedule({ pool, authority, beneficiary: contractorWallet, vestingType: { Milestone: { milestones: [ { unlockTime: startTime + 90 * 86400, // 90 days percentage: 2500, // 25% isUnlocked: false, }, { unlockTime: startTime + 180 * 86400, // 180 days percentage: 2500, // 25% isUnlocked: false, }, { unlockTime: startTime + 270 * 86400, // 270 days percentage: 2500, // 25% isUnlocked: false, }, { unlockTime: startTime + 365 * 86400, // 365 days percentage: 2500, // 25% isUnlocked: false, }, ], }, } as VestingType, totalAmount: 800_000 * LAMPORTS_PER_SOL, startTime, duration: 365 * 86400, isRevocable: true, }); // Example: 800K tokens across 4 quarterly milestones // After 90 days: 200,000 tokens (25%) // After 180 days: 400,000 tokens (50%) // After 270 days: 600,000 tokens (75%) // After 365 days: 800,000 tokens (100%) ``` -------------------------------- ### Creating and Managing Trade Offers in Rust and TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Covers the functionality for creating, accepting, and canceling trade offers. Rust provides function signatures for these actions, while TypeScript offers concrete examples of initiating trades (item for gold, item for item), accepting trades with specified payments, and canceling existing trades, along with how to retrieve trade offer data. -------------------------------- ### Stake Tokens - Rust and TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Enables users to stake tokens into a designated pool and begin earning rewards. The Rust code outlines the core instruction, and the TypeScript example demonstrates calling this instruction and accessing the resulting `StakeAccount` data, which is automatically typed by LUMOS. ```rust pub fn stake(ctx: Context, amount: u64) -> Result<()> ``` ```typescript await client.stake({ pool: poolAddress, user: wallet, amount: 10 * LAMPORTS_PER_SOL, // Stake 10 SOL }); // The StakeAccount is automatically typed by LUMOS! const stakeData: StakeAccount = await client.getStakeAccount(pool, user); console.log(`Staked: ${stakeData.amount}`); console.log(`Status: ${stakeData.status}`); // "Active" | "Locked" | ... console.log(`Unlock at: ${new Date(stakeData.unlockAt * 1000)}`); ``` -------------------------------- ### Initialize Staking Pool - Rust and TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Initializes a new staking pool with specified reward configurations. The Rust function defines the on-chain logic, while the TypeScript example shows how to interact with the program from a frontend application. Both rely on LUMOS-generated types for consistency. ```rust pub fn initialize_pool( ctx: Context, reward_rate: u64, // APY in basis points (1000 = 10%) min_stake_amount: u64, // Minimum stake in lamports min_lock_duration: i64, // Lock period in seconds cooldown_period: i64, // Cooldown for unstaking ) -> Result<()> ``` ```typescript await client.initializePool({ authority: wallet, tokenMint: tokenMintAddress, vault: vaultAddress, rewardRate: 1000, // 10% APY minStakeAmount: 0.1 * LAMPORTS_PER_SOL, minLockDuration: 7 * 24 * 60 * 60, // 7 days cooldownPeriod: 24 * 60 * 60, // 1 day }); ``` -------------------------------- ### Build and Deploy Anchor Program Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Builds the Anchor (Rust) program and deploys it to the Solana devnet. This step compiles the smart contract and makes it available on the blockchain. ```bash # Build Program carousel build --manifest-path programs/gaming-inventory/Cargo.toml # Deploy to Devnet anchor deploy --provider.cluster devnet ``` -------------------------------- ### Create Cliff + Linear Vesting Schedule (TypeScript) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Creates a vesting schedule with a cliff period followed by linear vesting. The cliff percentage determines the portion vested at the cliff, and the remainder vests linearly over the remaining duration. Inputs include pool, authority, beneficiary, vesting type configuration, total amount, start time, duration, and revocability. ```TypeScript const schedule = await client.createSchedule({ pool, authority, beneficiary: founderWallet, vestingType: { CliffLinear: { cliffDuration: 365 * 86400, // 1 year cliffPercentage: 2500, // 25% (basis points) }, } as VestingType, totalAmount: 2_000_000 * LAMPORTS_PER_SOL, startTime: Math.floor(Date.now() / 1000), duration: 4 * 365 * 86400, // 4 years total isRevocable: true, }); // Example: 2M tokens, 25% cliff after 1 year, then linear over 3 years // After 1 year: 500,000 tokens (25% cliff) // After 2.5 years: 1,000,000 tokens (cliff + 50% of remaining) // After 4 years: 2,000,000 tokens (fully vested) ``` -------------------------------- ### 1. Create Pool API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Initializes a new vesting pool. This pool acts as a container for vesting schedules and manages token distribution. ```APIDOC ## POST /api/pools ### Description Initializes a new vesting pool. ### Method POST ### Endpoint /api/pools ### Parameters #### Query Parameters - **authority** (PublicKey) - Required - The administrator's public key. - **tokenMint** (PublicKey) - Required - The mint address of the token to be vested. - **vault** (PublicKey) - Required - The address of the vault holding the tokens. - **name** (String) - Required - A human-readable name for the vesting pool. ### Request Example ```json { "authority": "adminWalletPublicKey", "tokenMint": "tokenMintAddress", "vault": "vaultAddress", "name": "Team Vesting Pool" } ``` ### Response #### Success Response (200) - **poolAddress** (PublicKey) - The address of the newly created vesting pool. #### Response Example ```json { "poolAddress": "newPoolAddress" } ``` ``` -------------------------------- ### Vesting Calculations Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Provides details on the vesting calculation logic used by the API. ```APIDOC ## Vesting Calculations All calculations are implemented identically on-chain (Rust) and client-side (TypeScript). ### Linear Vesting Formula ``` vested = (totalAmount × elapsedTime) / totalDuration ``` ### Cliff + Linear Vesting - If `time < cliff`: Vested = 0 - If `time >= cliff`: Vested = Cliff Amount + Linear(Remaining, time since cliff) ### Milestone Vesting Tokens vest at specific, predefined milestones, often performance-based. ``` -------------------------------- ### 2. Create Schedule API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Creates a new vesting schedule for a specified beneficiary. ```APIDOC ## POST /api/schedules ### Description Creates a vesting schedule for a beneficiary, defining how and when tokens will vest. ### Method POST ### Endpoint /api/schedules ### Parameters #### Request Body - **pool** (PublicKey) - Required - The address of the vesting pool. - **authority** (PublicKey) - Required - The authority managing the schedule. - **beneficiary** (PublicKey) - Required - The public key of the token recipient. - **vestingType** (Object) - Required - Defines the vesting mechanism. - **CliffLinear** (Object) - For cliff and linear vesting. - **cliffDuration** (Number) - Required - Duration in seconds until the cliff. - **cliffPercentage** (Number) - Required - Percentage of tokens vested at the cliff (basis points). - **Milestone** (Object) - For milestone-based vesting. - **milestones** (Array) - Required - An array of milestone objects. - **unlockTime** (Number) - Required - Unix timestamp for milestone unlock. - **percentage** (Number) - Required - Percentage of total tokens to vest at this milestone (basis points). - **isUnlocked** (Boolean) - Required - Initial state of the milestone. - **totalAmount** (Number) - Required - The total number of tokens to be vested. - **startTime** (Number) - Required - Unix timestamp for the start of vesting. - **duration** (Number) - Required - Total duration of the vesting period in seconds. - **isRevocable** (Boolean) - Required - Whether the schedule can be revoked. ### Request Example (CliffLinear) ```json { "pool": "poolAddress", "authority": "authorityPublicKey", "beneficiary": "founderWalletPublicKey", "vestingType": { "CliffLinear": { "cliffDuration": 31536000, // 1 year "cliffPercentage": 2500 // 25% } }, "totalAmount": 2000000, "startTime": 1678886400, "duration": 126144000, // 4 years "isRevocable": true } ``` ### Request Example (Milestone) ```json { "pool": "poolAddress", "authority": "authorityPublicKey", "beneficiary": "contractorWalletPublicKey", "vestingType": { "Milestone": { "milestones": [ { "unlockTime": 1681564800, // 90 days "percentage": 2500, "isUnlocked": false }, { "unlockTime": 1684243200, // 180 days "percentage": 2500, "isUnlocked": false }, { "unlockTime": 1686921600, // 270 days "percentage": 2500, "isUnlocked": false }, { "unlockTime": 1689600000, // 365 days "percentage": 2500, "isUnlocked": false } ] } }, "totalAmount": 800000, "startTime": 1678886400, "duration": 31536000, "isRevocable": true } ``` ### Response #### Success Response (200) - **scheduleAddress** (PublicKey) - The address of the newly created vesting schedule. #### Response Example ```json { "scheduleAddress": "newScheduleAddress" } ``` ``` -------------------------------- ### Combat System Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Handles the combat mechanics, allowing players to defeat monsters and earn rewards. ```APIDOC ## POST /combat/defeat-monster ### Description Allows a player to engage in combat and defeat a monster, earning experience and gold. ### Method POST ### Endpoint /combat/defeat-monster ### Parameters #### Query Parameters - **player** (address) - Required - The player's address. - **authority** (address) - Required - The authority signing the transaction. #### Request Body - **monsterLevel** (number) - Required - The level of the monster being fought. ### Request Example ```json { "monsterLevel": 5 } ``` ### Response #### Success Response (200) - **experienceGained** (number) - The amount of experience points earned. - **goldGained** (number) - The amount of gold earned. #### Response Example ```json { "experienceGained": 500, "goldGained": 250 } ``` ``` -------------------------------- ### Mint Items Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Allows players to create new in-game items with specified attributes such as name, type, rarity, and power. ```APIDOC ## POST /items ### Description Creates a new item in the game with specified attributes. ### Method POST ### Endpoint /items ### Parameters #### Query Parameters - **player** (address) - Required - The player's address. - **authority** (address) - Required - The authority signing the transaction. #### Request Body - **name** (string) - Required - The name of the item. - **itemType** (object) - Required - The type of the item (e.g., Weapon, Armor). - **Weapon** (object) - Optional - Weapon-specific attributes. - **damage** (number) - Required - The damage value of the weapon. - **attackSpeed** (number) - Required - The attack speed of the weapon. - **Armor** (object) - Optional - Armor-specific attributes. - **defenseBonus** (number) - Required - The defense bonus provided by the armor. - **healthBonus** (number) - Required - The health bonus provided by the armor. - **rarity** (string) - Required - The rarity of the item (e.g., 'Common', 'Rare', 'Legendary'). - **levelRequirement** (number) - Required - The minimum player level to use the item. - **power** (number) - Optional - The power attribute of the item. - **defense** (number) - Optional - The defense attribute of the item. ### Request Example ```json { "name": "Excalibur", "itemType": { "Weapon": { "damage": 200, "attackSpeed": 85 } }, "rarity": "Legendary", "levelRequirement": 15, "power": 200, "defense": 0 } ``` ### Response #### Success Response (200) - **itemId** (string) - The unique identifier of the newly minted item. #### Response Example ```json { "itemId": "some_unique_item_id" } ``` ``` -------------------------------- ### POST /buy_nft Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Purchases a listed NFT from the marketplace. This involves transferring SOL to the seller and the marketplace fee to the treasury, and updating the listing status. ```APIDOC ## POST /buy_nft ### Description Purchases a listed NFT. This function calculates the marketplace fee, transfers the net amount to the seller, transfers the fee to the treasury, updates the listing status to 'Sold', and records the buyer and timestamp. ### Method POST ### Endpoint /buy_nft ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This endpoint does not explicitly define a request body in the provided documentation, but the associated TypeScript example suggests it's called with specific account information. ### Request Example ```typescript await program.methods.buyNft().accounts({ listing: listingPda, config: marketplaceConfigPda, buyer: provider.wallet.publicKey, sellerAccount: sellerPublicKey, treasuryAccount: treasuryPublicKey, systemProgram: SystemProgram.programId, }).rpc(); ``` ### Response #### Success Response (200) Indicates successful execution of the purchase. The specific return data is not detailed, but the state changes described imply success. #### Response Example (No specific JSON response example provided for success.) #### Error Response - **Error**: If the listing is not active, or if there are insufficient funds, or other transaction validation failures. ``` -------------------------------- ### Crafting System Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Enables players to craft new items using a combination of materials and in-game currency. ```APIDOC ## POST /crafting/craft-item ### Description Crafts a new item based on provided specifications, consuming resources. ### Method POST ### Endpoint /crafting/craft-item ### Parameters #### Query Parameters - **player** (address) - Required - The player's address. - **authority** (address) - Required - The authority signing the transaction. #### Request Body - **name** (string) - Required - The name of the item to craft. - **itemType** (object) - Required - The type of the item (e.g., Weapon, Armor). - **Weapon** (object) - Optional - Weapon-specific attributes. - **damage** (number) - Required - The damage value of the weapon. - **attackSpeed** (number) - Required - The attack speed of the weapon. - **rarity** (string) - Required - The rarity of the item (e.g., 'Common', 'Rare', 'Legendary'). - **power** (number) - Optional - The power attribute of the item. ### Request Example ```json { "name": "Iron Sword", "itemType": { "Weapon": { "damage": 50, "attackSpeed": 70 } }, "rarity": "Rare", "power": 50 } ``` ### Response #### Success Response (200) - **itemId** (string) - The unique identifier of the newly crafted item. #### Response Example ```json { "itemId": "some_crafted_item_id" } ``` ``` -------------------------------- ### Equipment System Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Manages the equipping and unequipping of items by players to enhance their character's stats. ```APIDOC ## POST /players/{playerId}/equip ### Description Equips an item to the player's character, potentially boosting stats. ### Method POST ### Endpoint /players/{playerId}/equip ### Parameters #### Path Parameters - **playerId** (address) - Required - The unique identifier of the player. #### Query Parameters - **authority** (address) - Required - The authority signing the transaction. #### Request Body - **item** (string) - Required - The unique identifier of the item to equip. ### Request Example ```json { "item": "some_unique_item_id" } ``` ## POST /players/{playerId}/unequip ### Description Unequips an item from the player's character. ### Method POST ### Endpoint /players/{playerId}/unequip ### Parameters #### Path Parameters - **playerId** (address) - Required - The unique identifier of the player. #### Query Parameters - **authority** (address) - Required - The authority signing the transaction. #### Request Body - **item** (string) - Required - The unique identifier of the item to unequip. ### Request Example ```json { "item": "some_unique_item_id" } ``` ## GET /players/{playerId}/stats ### Description Retrieves the combined stats of a player, including bonuses from equipped items. ### Method GET ### Endpoint /players/{playerId}/stats ### Parameters #### Path Parameters - **playerId** (address) - Required - The unique identifier of the player. ### Response #### Success Response (200) - **totalPower** (number) - The total power attribute of the player. - **totalDefense** (number) - The total defense attribute of the player. #### Response Example ```json { "totalPower": 250, "totalDefense": 150 } ``` ``` -------------------------------- ### Complete Unstake API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Completes the unstaking process after the cooldown period has ended, returning the staked assets to the user. ```APIDOC ## POST /unstake ### Description Complete unstaking after cooldown period ends. ### Method POST ### Endpoint `/unstake` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Implicitly handled by the context in Rust or client object in TypeScript) ### Request Example (TypeScript) ```typescript // Check if cooldown complete const canComplete = await client.canCompleteUnstake(pool, wallet.publicKey); if (canComplete) { await client.unstake({ pool: poolAddress, user: wallet, }); // Tokens returned, status changes to Unstaked } ``` ### Response #### Success Response (200) (Details depend on implementation, typically a confirmation of successful unstake) #### Response Example (Not explicitly defined in source, depends on implementation) ``` -------------------------------- ### Create DAO Proposal - Rust Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/dao-governance/README.md Initiates the creation of a new proposal within the DAO. This function takes context, a title, a description, and the proposal type as parameters. ```rust pub fn create_proposal( ctx: Context, title: String, description: String, proposal_type: ProposalType, ) -> Result<()> ``` -------------------------------- ### Running Marketplace Tests with Anchor Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Provides instructions on how to run the comprehensive test suite for the marketplace using the Anchor framework. It includes commands for running all tests and running tests with additional logging for debugging. ```bash # Run all tests anchor test # Run with logs anchor test --skip-local-validator ``` -------------------------------- ### Request Unstake API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Initiates the unstaking process, starting a cooldown period before the staked assets can be fully withdrawn. ```APIDOC ## POST /request_unstake ### Description Initiate unstaking process (starts cooldown period). ### Method POST ### Endpoint `/request_unstake` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Implicitly handled by the context in Rust or client object in TypeScript) ### Request Example (TypeScript) ```typescript // Check if can unstake const canUnstake = await client.canUnstake(pool, wallet.publicKey); if (canUnstake) { await client.requestUnstake({ pool: poolAddress, user: wallet, }); // Status changes to StakingStatus.UnstakeRequested const stakeData = await client.getStakeAccount(pool, wallet.publicKey); console.log(stakeData.status); // "UnstakeRequested" } ``` ### Response #### Success Response (200) (Details depend on implementation, typically a confirmation of unstake request) #### Response Example (Not explicitly defined in source, depends on implementation) ``` -------------------------------- ### Anchor Test Commands (Bash) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Provides command-line instructions for running tests using the Anchor framework. It includes commands for running all tests, specific tests, and tests with console output enabled. ```bash # Run all tests anchor test # Test specific instruction anchor test --test initialize_pool # Test with console logs anchor test -- --nocapture ``` -------------------------------- ### Linear Vesting Calculation (TypeScript) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Provides the formula for calculating the vested amount in a linear vesting scenario. The vested amount is determined by the total amount, the elapsed time since the start, and the total duration of the vesting period. ```TypeScript vested = (totalAmount × elapsedTime) / totalDuration ``` -------------------------------- ### Calculating Rarity Multipliers in TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md This snippet shows how to get a rarity multiplier using the client. It demonstrates a simple function call that returns a multiplier based on the provided rarity level. The comments indicate the expected multiplier values for different rarity tiers. ```typescript const multiplier = client.getRarityMultiplier(rarity); // Common: 1.0x // Uncommon: 1.5x // Rare: 2.0x // Epic: 3.0x // Legendary: 5.0x // Mythic: 10.0x ``` -------------------------------- ### Create Player Account (TypeScript Client) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Demonstrates how to use the TypeScript client to create a player account. It initiates the player creation process and logs a welcome message with initial player stats. ```typescript const player = await client.createPlayer({ authority: wallet, username: 'DragonSlayer', }); // Player starts with: // - Level 1 // - 0 XP // - 1,000 gold // - 1,000 health // - 500 mana const playerData: Player = await client.getPlayer(player); console.log(`Welcome, ${playerData.username}!`); console.log(`Level ${playerData.level} | ${playerData.gold} gold`); ``` -------------------------------- ### Example Project Directory Structure Source: https://github.com/getlumos/awesome-lumos/blob/main/CONTRIBUTING.md This structure outlines the expected organization for a full-stack Solana project contributing to Awesome LUMOS. It includes directories for the README, LUMOS schema, Solana programs, frontend application, and integration tests. ```tree examples/ └── your-project/ ├── README.md # Project documentation ├── schema.lumos # LUMOS type definitions ├── programs/ # Anchor/Solana programs │ └── your-program/ │ ├── Cargo.toml │ ├── Anchor.toml │ └── src/ │ └── lib.rs # Import generated LUMOS types ├── app/ # Frontend application │ ├── package.json │ ├── src/ │ │ └── types/ # LUMOS generated TypeScript │ └── ... ├── tests/ # Integration tests │ └── integration.ts ├── .gitignore └── LICENSE # MIT or Apache 2.0 ``` -------------------------------- ### Create Player Account (Rust Signature) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Defines the Rust function signature for creating a new player account in the gaming inventory system. It takes context and a username as input. ```rust pub fn create_player( ctx: Context, username: String, // 3-20 characters ) -> Result<()> ``` -------------------------------- ### Lumos Schema for Multi-Stage Proposals Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/dao-governance/README.md Shows an example of extending the Lumos schema to support multi-stage proposals. This is achieved by adding new variants to the `ProposalStatus` enum, such as `UnderReview`, `SecondVoteRequired`, and `PendingCouncilApproval`. ```lumos #[solana] enum ProposalStatus { // ... existing variants UnderReview, SecondVoteRequired, PendingCouncilApproval, } ``` -------------------------------- ### Consuming Items in Rust and TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/gaming-inventory/README.md Demonstrates how to consume items in both Rust and TypeScript. In Rust, it shows the function signature for consuming an item. In TypeScript, it provides an example of minting a health potion and then consuming it, resulting in a health increase. ```rust pub fn consume_item(ctx: Context) -> Result<()> ``` ```typescript // Mint health potion const healthPotion = await client.mintItem({ player, authority: wallet, name: 'Health Potion', itemType: { Consumable: { effect: { HealHealth: { amount: 500 }, } as ConsumableEffect, uses: 3, }, } as ItemType, rarity: 'Common', levelRequirement: 1, power: 0, defense: 0, }); // Use the potion await client.consumeItem({ player, item: healthPotion, authority: wallet, }); // Player health increased by 500! ``` -------------------------------- ### Tiered APY Structure (Lumos Schema) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Defines a tiered structure for APY calculation based on staked amounts. This Lumos schema example shows different APY rates applied to specific ranges of staked tokens. ```lumos enum RewardCalculationType { TieredAPY { tier1_amount: u64, // 0-10 SOL → 5% APY tier1_apy: u64, tier2_amount: u64, // 10-100 SOL → 10% APY tier2_apy: u64, tier3_apy: u64, // 100+ SOL → 15% APY }, } ``` -------------------------------- ### Example LUMOS Project Structure Source: https://github.com/getlumos/awesome-lumos/blob/main/README.md This directory structure outlines a typical contribution to the Awesome LUMOS project, showcasing a full-stack application. It includes the LUMOS schema, Solana programs (Anchor), a frontend application, and tests, adhering to best practices for clarity and maintainability. ```directory examples/ └── your-project/ ├── README.md (Setup, features, architecture) ├── schema.lumos (LUMOS schema definitions) ├── programs/ (Anchor/Solana programs) ├── app/ (Frontend application) └── tests/ (Integration tests) ``` -------------------------------- ### Create DAO Transaction in TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/dao-governance/README.md Example TypeScript code demonstrating how to interact with the generated client to create a new DAO. It specifies governance parameters like voting period and approval thresholds, and retrieves the created DAO's data. ```typescript await client.createDAO({ authority: wallet, name: 'My DAO', treasury: treasuryKeypair.publicKey, votingPeriod: 7 * 24 * 60 * 60, // 7 days timelockDelay: 2 * 24 * 60 * 60, // 2 days quorumThreshold: 3000, // 30% approvalThreshold: 5100, // 51% }); // The DAO is automatically typed by LUMOS! const daoData: DAO = await client.getDAO(daoAddress); console.log(`DAO: ${daoData.name}`); console.log(`Members: ${daoData.totalMembers}`); console.log(`Proposals: ${daoData.totalProposals}`); ``` -------------------------------- ### Using Generated Account Types in Rust Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Demonstrates how Lumos generates Rust account structures using the `#[account]` macro and how these generated types are used within Anchor contexts for initializing accounts. ```rust // LUMOS generates the #[account] macro automatically #[account] pub struct MarketplaceConfig { pub authority: Pubkey, pub fee_percentage: u16, // ... } // Use in Anchor contexts #[derive(Accounts)] pub struct InitializeMarketplace<'info> { #[account(init, payer = authority, space = 8 + std::mem::size_of::())] pub config: Account<'info, MarketplaceConfig>, // ← Generated type! // ... } ``` -------------------------------- ### Fixed APY Calculation Formula Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Provides the mathematical formula for calculating fixed Annual Percentage Yield (APY). It outlines the variables involved, including staked amount, APY rate, and time staked, along with an example calculation. ```plaintext Reward = (Staked Amount × APY Rate × Time Staked) / (100 × 365 × 86400) ``` -------------------------------- ### Frontend Integration with Staking Client (TypeScript) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Demonstrates how to integrate the staking client in a frontend application using TypeScript. It shows how to fetch pool and stake data, calculate APY, and display staking status based on automatically synchronized types. ```typescript import { StakingClient } from './staking-client'; import { StakingPool, StakeAccount, StakingStatus } from './generated'; // All types are automatically synchronized! async function displayStakingInfo(pool: PublicKey, user: PublicKey) { const poolData: StakingPool = await client.getPool(pool); const stakeData: StakeAccount | null = await client.getStakeAccount(pool, user); // TypeScript knows all fields and types console.log(`Pool APY: ${client.calculateAPY(poolData.rewardRate)}%`); console.log(`Total Staked: ${poolData.totalStaked}`); console.log(`Total Stakers: ${poolData.totalStakers}`); if (stakeData) { // Enum type checking works perfectly switch (stakeData.status) { case 'Active': console.log('Actively earning rewards'); break; case 'Locked': console.log(`Locked until: ${new Date(stakeData.unlockAt * 1000)}`); break; case 'UnstakeRequested': console.log('Cooldown period active'); break; case 'Unstaked': console.log('Fully unstaked'); break; } } } ``` -------------------------------- ### Update Pool Parameters (Rust & TypeScript) Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/defi-staking/README.md Enables administrators to update pool parameters such as reward rate and activation status. The Rust function defines the parameters for updating the pool, and the TypeScript code provides an example of calling this update function. ```rust pub fn update_pool( ctx: Context, reward_rate: Option, is_active: Option, ) -> Result<()> ``` ```typescript await client.updatePool({ pool: poolAddress, authority: adminWallet, rewardRate: 1500, // Update to 15% APY isActive: true, }); ``` -------------------------------- ### Buy NFT with TypeScript Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Purchases a listed NFT by interacting with the marketplace smart contract. This function calculates fees, transfers SOL to the seller and treasury, and updates the listing status. It requires the listing details, marketplace configuration, and account information for the buyer, seller, and treasury. ```rust pub fn buy_nft(ctx: Context) -> Result<()> ``` ```typescript await program.methods .buyNft() .accounts({ listing: listingPda, config: marketplaceConfigPda, buyer: provider.wallet.publicKey, sellerAccount: sellerPublicKey, treasuryAccount: treasuryPublicKey, systemProgram: SystemProgram.programId, }) .rpc(); ``` -------------------------------- ### Lumos Schema and Generated Code Structure Source: https://github.com/getlumos/awesome-lumos/blob/main/CLAUDE.md Illustrates the typical file structure for a LUMOS example, including the source of truth schema, generated Rust or TypeScript code, Anchor programs, and the TypeScript client. This structure ensures maintainability and consistency across different examples. ```text examples/[name]/ ├── schema.lumos # Source of truth ├── generated.rs/.ts # Generated code ├── programs/ # Anchor program └── client/ # TypeScript client ``` -------------------------------- ### Mapping Option Types between Lumos, Rust, TypeScript, and Borsh Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Shows how Lumos's optional schema fields are translated into Rust's `Option`, TypeScript's union types with `undefined`, and Borsh serialization formats, ensuring consistent handling of nullable values across the stack. ```rust // LUMOS schema buyer: Option, // Rust output pub buyer: Option, ``` ```typescript // TypeScript output buyer: PublicKey | undefined; ``` ```javascript // Borsh output borsh.option(borsh.publicKey(), 'buyer') ``` -------------------------------- ### Generate Rust and TypeScript Code with LUMOS CLI Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Command-line instructions to generate synchronized Rust and TypeScript code from a LUMOS schema file. This process ensures type consistency between the Solana backend (Anchor program) and the frontend application. The generated files are automatically placed in the appropriate project directories. ```bash # Generate Rust and TypeScript lumos generate schema/marketplace.lumos --output programs # Move generated files to correct locations mv programs/generated.rs programs/nft-marketplace/src/ mv programs/generated.ts app/src/ ``` -------------------------------- ### 6. Close Schedule API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Closes a completed vesting schedule. ```APIDOC ## POST /api/schedules/{scheduleAddress}/close ### Description Closes a vesting schedule that has reached its completion. ### Method POST ### Endpoint /api/schedules/{scheduleAddress}/close ### Parameters #### Path Parameters - **scheduleAddress** (PublicKey) - Required - The address of the vesting schedule to close. #### Request Body - **beneficiary** (PublicKey) - Required - The public key of the beneficiary associated with the schedule. ### Request Example ```json { "beneficiary": "beneficiaryWalletPublicKey" } ``` ### Response #### Success Response (200) - **transactionSignature** (String) - The signature of the close schedule transaction. #### Response Example ```json { "transactionSignature": "txSignature" } ``` ``` -------------------------------- ### Define NFT Marketplace Schema with LUMOS Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Defines the core data structures for an NFT marketplace using LUMOS schema syntax. This includes configurations, listing details, NFT metadata, transaction history, and user profiles. The schema uses Solana-specific attributes and supports enums, options, and timestamps, ensuring type safety. ```rust // Marketplace Configuration #[solana] #[account] struct MarketplaceConfig { authority: PublicKey, fee_percentage: u16, treasury: PublicKey, total_sales: u64, is_paused: bool, } // NFT Listing #[solana] #[account] struct Listing { seller: PublicKey, nft_mint: PublicKey, price: u64, listed_at: i64, status: ListingStatus, buyer: Option, sold_at: Option, } #[solana] enum ListingStatus { Active, Sold, Cancelled, } // NFT Metadata #[solana] #[account] struct NFTMetadata { name: String, symbol: String, uri: String, creator: PublicKey, collection: Option, royalty_percentage: u16, } // Transaction History #[solana] struct TransactionRecord { transaction_type: TransactionType, nft_mint: PublicKey, from: PublicKey, to: PublicKey, price: u64, timestamp: i64, } #[solana] enum TransactionType { Listed, Sold, Cancelled, PriceUpdated { old_price: u64, new_price: u64 }, } // User Profile #[solana] #[account] struct UserProfile { owner: PublicKey, total_listed: u64, total_sold: u64, total_purchased: u64, joined_at: i64, } ``` -------------------------------- ### 4. Revoke Schedule API Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/token-vesting/README.md Allows the authority to revoke a vesting schedule. ```APIDOC ## POST /api/schedules/{scheduleAddress}/revoke ### Description Revokes a vesting schedule. Only unvested tokens are affected; already vested tokens remain with the beneficiary. ### Method POST ### Endpoint /api/schedules/{scheduleAddress}/revoke ### Parameters #### Path Parameters - **scheduleAddress** (PublicKey) - Required - The address of the vesting schedule to revoke. #### Request Body - **pool** (PublicKey) - Required - The address of the vesting pool. - **authority** (PublicKey) - Required - The public key of the schedule authority. - **beneficiary** (PublicKey) - Required - The public key of the schedule beneficiary. - **vaultAccount** (PublicKey) - Required - The address of the vault holding the tokens. - **reason** (String) - Required - The reason for revoking the schedule. ### Request Example ```json { "pool": "poolAddress", "authority": "adminWalletPublicKey", "beneficiary": "employeeWalletPublicKey", "vaultAccount": "vaultAddress", "reason": "Employment terminated" } ``` ### Response #### Success Response (200) - **transactionSignature** (String) - The signature of the revocation transaction. #### Response Example ```json { "transactionSignature": "txSignature" } ``` ``` -------------------------------- ### Calculating and Transferring Royalties in Rust Source: https://github.com/getlumos/awesome-lumos/blob/main/examples/nft-marketplace/README.md Illustrates a Rust code snippet for calculating royalty amounts based on price and percentage, and includes a placeholder comment for transferring funds to the creator. This is part of implementing royalty payments. ```rust // Calculate and transfer royalty let royalty = (price * metadata.royalty_percentage / 10000) as u64; // Transfer to creator... ```