light_sdk/
lib.rs

1//! The base library to use Compressed Accounts in Solana on-chain Rust and Anchor programs.
2//!
3//! Compressed Accounts store state as account hashes in State Merkle trees.
4//! and unique addresses in Address Merkle trees.
5//! Validity proofs (zero-knowledge proofs) verify that compressed account
6//! state exists and new addresses do not exist yet.
7//!
8//! - No rent exemption payment required.
9//! - Constant 128-byte validity proof per transaction for one or multiple compressed accounts and addresses.
10//! - Compressed account data is sent as instruction data when accessed.
11//! - State and address trees are managed by the protocol.
12//!
13//! For full program examples, see the [Program Examples](https://github.com/Lightprotocol/program-examples).
14//! For detailed documentation, visit [zkcompression.com](https://www.zkcompression.com/).
15//! For pinocchio solana program development see [`light-sdk-pinocchio`](https://docs.rs/light-sdk-pinocchio).
16//! For rust client development see [`light-client`](https://docs.rs/light-client).
17//! For rust program testing see [`light-program-test`](https://docs.rs/light-program-test).
18//! For local test validator with light system programs see [Light CLI](https://www.npmjs.com/package/@lightprotocol/zk-compression-cli).
19//!
20//! #  Using Compressed Accounts in Solana Programs
21//! 1. [`Instruction`](crate::instruction)
22//!     - [`CompressedAccountMeta`](crate::instruction::account_meta::CompressedAccountMeta) - Compressed account metadata structs for instruction data.
23//!     - [`PackedAccounts`](crate::instruction::PackedAccounts) - Abstraction to prepare accounts offchain for instructions with compressed accounts.
24//!     - [`ValidityProof`](crate::instruction::ValidityProof) - Proves that new addresses don't exist yet, and compressed account state exists.
25//! 2. Compressed Account in Program
26//!     - [`LightAccount`](crate::account) - Compressed account abstraction similar to anchor Account.
27//!     - [`derive_address`](crate::address) - Create a compressed account address.
28//!     - [`LightDiscriminator`] - DeriveMacro to derive a compressed account discriminator.
29//! 3. [`Cpi`](crate::cpi)
30//!     - [`CpiAccounts`](crate::cpi::v1::CpiAccounts) - Prepare accounts to cpi the light system program.
31//!     - [`LightSystemProgramCpi`](crate::cpi::v1::LightSystemProgramCpi) - Prepare instruction data to cpi the light system program.
32//!     - [`InvokeLightSystemProgram::invoke`](crate::cpi) - Invoke the light system program via cpi.
33//!
34//! #  Client Program Interaction Flow
35//! ```text
36//!  ├─ 𝐂𝐥𝐢𝐞𝐧𝐭
37//!  │  ├─ Get ValidityProof from RPC.
38//!  │  ├─ pack accounts with PackedAccounts into PackedAddressTreeInfo and PackedStateTreeInfo.
39//!  │  ├─ pack CompressedAccountMeta.
40//!  │  ├─ Build Instruction from PackedAccounts and CompressedAccountMetas.
41//!  │  └─ Send transaction.
42//!  │
43//!  └─ 𝐂𝐮𝐬𝐭𝐨𝐦 𝐏𝐫𝐨𝐠𝐫𝐚𝐦
44//!     ├─ CpiAccounts parse accounts consistent with PackedAccounts.
45//!     ├─ LightAccount instantiates from CompressedAccountMeta.
46//!     │
47//!     └─ 𝐋𝐢𝐠𝐡𝐭 𝐒𝐲𝐬𝐭𝐞𝐦 𝐏𝐫𝐨𝐠𝐫𝐚𝐦 𝐂𝐏𝐈
48//!        ├─ Verify ValidityProof.
49//!        ├─ Update State Merkle tree.
50//!        ├─ Update Address Merkle tree.
51//!        └─ Complete atomic state transition.
52//! ```
53//!
54//! # Features
55//! 1. `anchor` - Derives AnchorSerialize, AnchorDeserialize instead of BorshSerialize, BorshDeserialize.
56//!
57//! 2. `v2`
58//!     - available on devnet, localnet, and light-program-test.
59//!     - Support for optimized v2 light system program instructions.
60//!
61//! 3. `cpi-context` - Enables CPI context operations for batched compressed account operations.
62//!    - available on devnet, localnet, and light-program-test.
63//!    - Enables the use of one validity proof across multiple cpis from different programs in one instruction.
64//!    - For example spending compressed tokens (owned by the ctoken program) and updating a compressed pda (owned by a custom program)
65//!      with one validity proof.
66//!    - An instruction should not use more than one validity proof.
67//!    - Requires the v2 feature.
68//!
69//! ### Example Solana program code to create a compressed account
70//! ```rust, compile_fail
71//! use anchor_lang::{prelude::*, Discriminator};
72//! use light_sdk::{
73//!     account::LightAccount,
74//!     address::v1::derive_address,
75//!     cpi::{v1::LightSystemProgramCpi, CpiAccounts, InvokeLightSystemProgram, LightCpiInstruction},
76//!     derive_light_cpi_signer,
77//!     instruction::{account_meta::CompressedAccountMeta, PackedAddressTreeInfo},
78//!     CpiSigner, LightDiscriminator, LightHasher, ValidityProof,
79//! };
80//!
81//! declare_id!("2tzfijPBGbrR5PboyFUFKzfEoLTwdDSHUjANCw929wyt");
82//!
83//! pub const LIGHT_CPI_SIGNER: CpiSigner =
84//!     derive_light_cpi_signer!("2tzfijPBGbrR5PboyFUFKzfEoLTwdDSHUjANCw929wyt");
85//!
86//! #[program]
87//! pub mod counter {
88//!
89//!     use super::*;
90//!
91//!     pub fn create_compressed_account<'info>(
92//!         ctx: Context<'_, '_, '_, 'info, CreateCompressedAccount<'info>>,
93//!         proof: ValidityProof,
94//!         address_tree_info: PackedAddressTreeInfo,
95//!         output_tree_index: u8,
96//!     ) -> Result<()> {
97//!         let light_cpi_accounts = CpiAccounts::new(
98//!             ctx.accounts.fee_payer.as_ref(),
99//!             ctx.remaining_accounts,
100//!             crate::LIGHT_CPI_SIGNER,
101//!         )?;
102//!
103//!         let (address, address_seed) = derive_address(
104//!             &[b"counter", ctx.accounts.fee_payer.key().as_ref()],
105//!             &address_tree_info.get_tree_pubkey(&light_cpi_accounts)?,
106//!             &crate::ID,
107//!         );
108//!         let new_address_params = address_tree_info
109//!             .into_new_address_params_packed(address_seed);
110//!
111//!         let mut my_compressed_account = LightAccount::<CounterAccount>::new_init(
112//!             &crate::ID,
113//!             Some(address),
114//!             output_tree_index,
115//!         );
116//!
117//!         my_compressed_account.owner = ctx.accounts.fee_payer.key();
118//!
119//!         LightSystemProgramCpi::new_cpi(crate::LIGHT_CPI_SIGNER, proof)
120//!             .with_light_account(my_compressed_account)?
121//!             .with_new_addresses(&[new_address_params])
122//!             .invoke(light_cpi_accounts)
123//!     }
124//! }
125//!
126//! #[derive(Accounts)]
127//! pub struct CreateCompressedAccount<'info> {
128//!    #[account(mut)]
129//!    pub fee_payer: Signer<'info>,
130//! }
131//!
132//! #[derive(Clone, Debug, Default, LightDiscriminator)]
133//!pub struct CounterAccount {
134//!    pub owner: Pubkey,
135//!    pub counter: u64
136//!}
137//! ```
138
139/// Compressed account abstraction similar to anchor Account.
140pub mod account;
141pub use account::sha::LightAccount;
142
143/// Functions to derive compressed account addresses.
144pub mod address;
145/// Utilities to invoke the light-system-program via cpi.
146pub mod cpi;
147pub mod error;
148/// Utilities to build instructions for programs with compressed accounts.
149pub mod instruction;
150pub mod legacy;
151pub mod proof;
152/// Transfer compressed sol between compressed accounts.
153pub mod transfer;
154pub mod utils;
155
156pub use proof::borsh_compat;
157pub mod compressible;
158#[cfg(feature = "merkle-tree")]
159pub mod merkle_tree;
160
161#[cfg(feature = "anchor")]
162use anchor_lang::{AnchorDeserialize, AnchorSerialize};
163#[cfg(not(feature = "anchor"))]
164use borsh::{BorshDeserialize as AnchorDeserialize, BorshSerialize as AnchorSerialize};
165pub use compressible::{
166    process_initialize_compression_config_account_info,
167    process_initialize_compression_config_checked, process_update_compression_config, CompressAs,
168    CompressedInitSpace, CompressibleConfig, CompressionInfo, HasCompressionInfo, Pack, Space,
169    Unpack, COMPRESSIBLE_CONFIG_SEED, MAX_ADDRESS_TREES_PER_SPACE,
170};
171pub use light_account_checks::{self, discriminator::Discriminator as LightDiscriminator};
172pub use light_hasher;
173#[cfg(feature = "poseidon")]
174use light_hasher::DataHasher;
175pub use light_macros::{derive_light_cpi_signer, derive_light_cpi_signer_pda};
176pub use light_sdk_macros::{
177    derive_light_rent_sponsor, derive_light_rent_sponsor_pda, light_system_accounts,
178    LightDiscriminator, LightHasher, LightHasherSha, LightTraits,
179};
180pub use light_sdk_types::{constants, CpiSigner};
181use solana_account_info::AccountInfo;
182use solana_cpi::invoke_signed;
183use solana_instruction::{AccountMeta, Instruction};
184use solana_program_error::ProgramError;
185use solana_pubkey::Pubkey;
186
187pub trait PubkeyTrait {
188    fn to_solana_pubkey(&self) -> Pubkey;
189    fn to_array(&self) -> [u8; 32];
190}
191
192impl PubkeyTrait for [u8; 32] {
193    fn to_solana_pubkey(&self) -> Pubkey {
194        Pubkey::from(*self)
195    }
196
197    fn to_array(&self) -> [u8; 32] {
198        *self
199    }
200}
201
202#[cfg(not(feature = "anchor"))]
203impl PubkeyTrait for Pubkey {
204    fn to_solana_pubkey(&self) -> Pubkey {
205        *self
206    }
207
208    fn to_array(&self) -> [u8; 32] {
209        self.to_bytes()
210    }
211}
212
213#[cfg(feature = "anchor")]
214impl PubkeyTrait for anchor_lang::prelude::Pubkey {
215    fn to_solana_pubkey(&self) -> Pubkey {
216        Pubkey::from(self.to_bytes())
217    }
218
219    fn to_array(&self) -> [u8; 32] {
220        self.to_bytes()
221    }
222}