Skip to main content

Crate light_account

Crate light_account 

Source
Expand description

§Light Accounts

Rent-free Light Accounts and Light Token Accounts for Anchor programs.

§How It Works

Light Accounts (PDAs)

  1. Create a Solana PDA normally (Anchor init)
  2. Add #[light_account(init)] - becomes a Light Account
  3. Use it as normal Solana account
  4. When rent runs out, account compresses (cold state)
  5. State preserved on-chain, client loads when needed (hot state)
  6. When account is hot, use it as normal Solana account

Light Token Accounts (associated token accounts, Vaults)

  • Use #[light_account(init, associated_token, ...)] for associated token accounts
  • Use #[light_account(init, token, ...)] for program-owned vaults
  • Cold/hot lifecycle

Light Mints

  • Created via CreateMintsCpi
  • Cold/hot lifecycle

§Quick Start

§1. Program Setup

use light_account::{derive_light_cpi_signer, light_program, CpiSigner};

declare_id!("Your11111111111111111111111111111111111111");

pub const LIGHT_CPI_SIGNER: CpiSigner =
    derive_light_cpi_signer!("Your11111111111111111111111111111111111111");

#[light_program]
#[program]
pub mod my_program {
    // ...
}

§2. State Definition

use light_account::{CompressionInfo, LightAccount};

#[derive(Default, LightAccount)]
#[account]
pub struct UserRecord {
    pub compression_info: CompressionInfo,  // Required field
    pub owner: Pubkey,
    pub data: u64,
}

§3. Accounts Struct

use light_account::{CreateAccountsProof, LightAccounts};

#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct CreateParams {
    pub create_accounts_proof: CreateAccountsProof,
    pub owner: Pubkey,
}

#[derive(Accounts, LightAccounts)]
#[instruction(params: CreateParams)]
pub struct CreateRecord<'info> {
    #[account(mut)]
    pub fee_payer: Signer<'info>,

    /// CHECK: Compression config
    pub compression_config: AccountInfo<'info>,

    /// CHECK: Rent sponsor
    #[account(mut)]
    pub pda_rent_sponsor: AccountInfo<'info>,

    #[account(init, payer = fee_payer, space = 8 + UserRecord::INIT_SPACE, seeds = [b"record", params.owner.as_ref()], bump)]
    #[light_account(init)]
    pub record: Account<'info, UserRecord>,

    pub system_program: Program<'info, System>,
}

§Account Types

§1. Light Account (PDA)

#[account(init, payer = fee_payer, space = 8 + MyRecord::INIT_SPACE, seeds = [...], bump)]
#[light_account(init)]
pub record: Account<'info, MyRecord>,

§2. Light Account (zero-copy)

#[account(init, payer = fee_payer, space = 8 + size_of::<MyZcRecord>(), seeds = [...], bump)]
#[light_account(init, zero_copy)]
pub record: AccountLoader<'info, MyZcRecord>,

§3. Light Token Account (vault)

With init (Anchor-created):

#[account(mut, seeds = [b"vault", mint.key().as_ref()], bump)]
#[light_account(init, token::seeds = [b"vault", self.mint.key()], token::owner_seeds = [b"vault_authority"])]
pub vault: UncheckedAccount<'info>,

Without init (manual creation via CreateTokenAccountCpi):

#[account(mut, seeds = [b"vault", mint.key().as_ref()], bump)]
#[light_account(token::seeds = [b"vault", self.mint.key()], token::owner_seeds = [b"vault_authority"])]
pub vault: UncheckedAccount<'info>,

§4. Light Token Account (associated token account)

With init (Anchor-created):

#[account(mut)]
#[light_account(init, associated_token::authority = owner, associated_token::mint = mint, associated_token::bump = params.bump)]
pub token_account: UncheckedAccount<'info>,

Without init (manual creation via CreateTokenAtaCpi):

#[account(mut)]
#[light_account(associated_token::authority = owner, associated_token::mint = mint)]
pub token_account: UncheckedAccount<'info>,

§5. Light Mint

#[account(mut)]
#[light_account(init,
    mint::signer = mint_signer,           // PDA that signs mint creation
    mint::authority = mint_authority,     // Mint authority
    mint::decimals = 9,                   // Token decimals
    mint::seeds = &[SEED, self.key.as_ref()],  // Seeds for mint PDA
    mint::bump = params.bump,             // Bump seed
    // Optional: PDA authority
    mint::authority_seeds = &[b"authority"],
    mint::authority_bump = params.auth_bump,
    // Optional: Token metadata
    mint::name = params.name,
    mint::symbol = params.symbol,
    mint::uri = params.uri,
    mint::update_authority = update_auth,
    mint::additional_metadata = params.metadata
)]
pub mint: UncheckedAccount<'info>,

§Required Derives

DeriveUse
LightAccountState structs (must have compression_info: CompressionInfo)
LightAccountsAccounts structs with #[light_account(...)] fields

§Required Macros

MacroUse
#[light_program]Program module (before #[program])
derive_light_cpi_signer!CPI signer PDA constant
derive_light_rent_sponsor_pda!Rent sponsor PDA (optional)

Re-exports§

pub extern crate light_account_checks;

Modules§

account_info
account_meta
Sub-module for account_meta types (e.g. CompressedAccountMetaNoLamportsNoAddress).
close_account
compression_info
Compression info sub-module for paths like light_account::compression_info::CompressedInitSpace.
constants
hasher
Hasher re-exports for macro-generated code paths like light_account::hasher::DataHasher.
interface
Sub-module for generic PackedAccounts<AM> (not specialized to AccountMeta).
packed_accounts
rent

Macros§

derive_light_cpi_signer
Derives a complete Light Protocol CPI configuration at runtime
derive_light_cpi_signer_pda
Derives a Light Protocol CPI signer PDA at compile time
derive_light_rent_sponsor
Derives a complete Rent Sponsor configuration for a program at compile time.
derive_light_rent_sponsor_pda
Derives a Rent Sponsor PDA for a program at compile time.

Structs§

AccountInfo
Account information
CompressAndCloseParams
Parameters for compress_and_close instruction. Matches SDK’s SaveAccountsData field order for compatibility.
CompressedAccountData
Compressed account data used when decompressing.
CompressionInfo
SDK CompressionInfo - a compact 24-byte struct for custom zero-copy PDAs.
CpiAccountsConfig
CpiContextWriteAccounts
CpiSigner
Configuration struct containing program ID, CPI signer, and bump for Light Protocol
CreateAccountsProof
Proof data for instruction params when creating new compressed accounts. Used in the INIT flow - pass directly to instruction data. All accounts use the same address tree, so only one address_tree_info is needed.
DecompressIdempotentParams
Parameters for decompress_idempotent instruction. Generic over the variant type - each program defines its own PackedProgramAccountVariant.
InitializeLightConfigParams
Parameters for initialize_compression_config instruction. Uses [u8; 32] for pubkeys - borsh-compatible with solana_pubkey::Pubkey.
LightConfig
Global configuration for compressible accounts
PackedAddressTreeInfo
Packed address tree info for instruction data. Contains indices to address tree accounts and root index.
PackedStateTreeInfo
RentConfig
Rent function parameters, used to calculate whether the account is compressible.
UpdateLightConfigParams
Parameters for update_compression_config instruction.
ValidityProof

Enums§

AccountType
CompressionState
Compression state for SDK CompressionInfo.
LightSdkTypesError

Constants§

COMPRESSION_INFO_SIZE
Size of SDK CompressionInfo in bytes (24 bytes). Used for stripping CompressionInfo from Pod data during packing.
CPI_AUTHORITY_PDA_SEED
Seed of the CPI authority.
LIGHT_CONFIG_SEED
LIGHT_TOKEN_CONFIG
Default compressible config PDA for the Light Token Program.
LIGHT_TOKEN_PROGRAM_ID
Re-export LIGHT_TOKEN_PROGRAM_ID as Pubkey for Anchor’s #[account(address = ...)].
LIGHT_TOKEN_RENT_SPONSOR
Default rent sponsor PDA for the Light Token Program.
MAX_ADDRESS_TREES_PER_SPACE
OPTION_COMPRESSION_INFO_SPACE
Space required for Option when Some (1 byte discriminator + INIT_SPACE). Use this constant in account space calculations.
RENT_SPONSOR_SEED
Seed of the rent sponsor PDA.

Traits§

AccountInfoTrait
Trait to abstract over different AccountInfo implementations (pinocchio vs solana)
AccountMetaTrait
Trait abstracting over AccountMeta implementations (solana vs pinocchio).
CompressAs
Override what gets stored when compressing. Return Self or a different type.
CompressedInitSpace
Account space when compressed.
CompressionInfoField
Simple field accessor trait for types with a compression_info: Option<CompressionInfo> field. Implement this trait and get HasCompressionInfo for free via blanket impl.
CpiAccountsTrait
Trait for types that can provide account infos and metas for Light system program CPI.
DecompressVariant
Trait for packed program account variants that support decompression.
HasCompressionInfo
HasTokenVariant
Trait for account variants that can be checked for token or PDA type.
IntoVariant
Trait for seeds that can construct a compressed account variant.
InvokeLightSystemProgram
Trait for invoking the Light system program via CPI.
LightAccount
Trait for compressible account data structs.
LightAccountVariantTrait
Trait for unpacked compressed account variants with seeds.
LightCpi
Base trait for Light CPI instruction types.
LightDiscriminator
LightFinalize
Trait for finalizing compression operations on accounts.
LightPreInit
Trait for pre-initialization operations (mint creation).
Pack
Replace 32-byte Pubkeys with 1-byte indices to save space. If your type has no Pubkeys, just return self.
PackedAddressTreeInfoExt
Extension trait for PackedAddressTreeInfo SDK-specific methods. Since PackedAddressTreeInfo is defined in light-compressed-account, we use an extension trait to add methods that depend on SDK types.
PackedLightAccountVariantTrait
Trait for packed compressed account variants.
PdaSeedDerivation
Trait for PDA types that can derive seeds with full account context access.
Size
Trait to get the serialized size of a compressed account.
Space
Unpack

Functions§

claim_completed_epoch_rent
Claim completed-epoch rent to the provided rent sponsor and update last_claimed_slot. Returns Some(claimed) if any lamports were claimed; None if account is compressible or nothing to claim. Generic over AccountInfoTrait to work with both solana and pinocchio.
close_account
Close a native Solana account by transferring lamports and clearing data.
derive_rent_sponsor_pda
Derives the rent sponsor PDA for a given program.
extract_tail_accounts
Extract PDA accounts from the tail of remaining_accounts.
invoke_light_system_program
Low-level function to invoke the Light system program with a PDA signer.
invoke_write_pdas_to_cpi_context
Write compressed PDA data to CPI context for chaining with subsequent operations.
is_pda_initialized
Check if PDA account is already initialized (has non-zero discriminator).
prepare_account_for_compression
Generic prepare_account_for_compression.
prepare_account_for_decompression
Generic prepare_account_for_decompression.
prepare_compressed_account_on_init
Prepare a compressed account for a PDA during initialization.
process_compress_pda_accounts_idempotent
Process compress-and-close for PDA accounts (idempotent).
process_decompress_pda_accounts_idempotent
Process decompression for PDA accounts (idempotent, PDA-only).
process_initialize_light_config
Creates a new compressible config PDA.
process_initialize_light_config_checked
Initialize a LightConfig PDA with upgrade authority check.
process_update_light_config
Update an existing LightConfig PDA.
reimburse_rent
Reimburse the fee_payer for rent paid during PDA creation.
should_skip_compression
Check if account should be skipped during compression.
split_at_system_accounts_offset
Validate and split remaining_accounts at system_accounts_offset.
validate_compress_accounts
Extract and validate accounts for compress operations (4 accounts including compression_authority).
validate_decompress_accounts
Extract and validate accounts for decompress operations (3 accounts, no compression_authority).

Type Aliases§

CompressCtx
CompressDispatchFn
CpiAccounts
DecompressCtx
PackedAccounts
ValidatedPdaContext

Attribute Macros§

account
light_program
Auto-discovering Light program macro that reads external module files.

Derive Macros§

CompressAs
Legacy CompressAs trait implementation (use Compressible instead).
Discriminator
Derives a discriminator using SHA256(“account:{struct_name}”)[0..8].
HasCompressionInfo
Automatically implements the HasCompressionInfo trait for structs that have a compression_info: Option<CompressionInfo> field.
LightAccount
Generates a unified LightAccount trait implementation for light account structs.
LightAccounts
Generates LightFinalize trait implementation for Light Protocol accounts.
LightDiscriminator
Derives a discriminator using SHA256(“{struct_name}”)[0..8].
LightHasher
Makes the annotated struct hashable by implementing the following traits:
LightHasherSha
SHA256 variant of the LightHasher derive macro.
LightProgram
Derive macro for manually specifying compressed account variants on an enum.