Skip to main content

light_client/interface/
load_accounts.rs

1//! Load cold accounts API.
2
3use light_account::{derive_rent_sponsor_pda, Pack};
4use light_compressed_account::{
5    compressed_account::PackedMerkleContext, instruction_data::compressed_proof::ValidityProof,
6};
7use light_compressed_token_sdk::compressed_token::{
8    transfer2::{
9        create_transfer2_instruction, Transfer2AccountsMetaConfig, Transfer2Config, Transfer2Inputs,
10    },
11    CTokenAccount2,
12};
13use light_sdk::instruction::PackedAccounts;
14use light_token::{
15    compat::AccountState,
16    instruction::{
17        derive_token_ata, CreateAssociatedTokenAccount, DecompressMint, LIGHT_TOKEN_PROGRAM_ID,
18    },
19};
20use light_token_interface::{
21    instructions::{
22        extensions::{CompressedOnlyExtensionInstructionData, ExtensionInstructionData},
23        mint_action::{MintInstructionData, MintWithContext},
24        transfer2::MultiInputTokenDataWithContext,
25    },
26    state::{ExtensionStruct, TokenDataVersion},
27};
28use solana_instruction::Instruction;
29use solana_pubkey::Pubkey;
30use thiserror::Error;
31
32use super::{
33    decompress_mint::{DEFAULT_RENT_PAYMENT, DEFAULT_WRITE_TOP_UP},
34    instructions::{self, DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR},
35    light_program_interface::{AccountSpec, PdaSpec},
36    AccountInterface, TokenAccountInterface,
37};
38use crate::indexer::{
39    CompressedAccount, CompressedTokenAccount, Indexer, IndexerError, ValidityProofWithContext,
40};
41
42#[derive(Debug, Error)]
43pub enum LoadAccountsError {
44    #[error("Indexer error: {0}")]
45    Indexer(#[from] IndexerError),
46
47    #[error("Build instruction failed: {0}")]
48    BuildInstruction(String),
49
50    #[error("Token SDK error: {0}")]
51    TokenSdk(#[from] light_token::error::TokenSdkError),
52
53    #[error("Cold PDA at index {index} (pubkey {pubkey}) missing data")]
54    MissingPdaCompressed { index: usize, pubkey: Pubkey },
55
56    #[error("Cold ATA at index {index} (pubkey {pubkey}) missing data")]
57    MissingAtaCompressed { index: usize, pubkey: Pubkey },
58
59    #[error("Cold mint at index {index} (mint {mint}) missing hash")]
60    MissingMintHash { index: usize, mint: Pubkey },
61
62    #[error("ATA at index {index} (pubkey {pubkey}) missing compressed data or ATA bump")]
63    MissingAtaContext { index: usize, pubkey: Pubkey },
64
65    #[error("Tree info index {index} out of bounds (len {len})")]
66    TreeInfoIndexOutOfBounds { index: usize, len: usize },
67}
68
69const MAX_ATAS_PER_IX: usize = 8;
70
71/// Build load instructions for cold accounts. Returns empty vec if all hot.
72///
73/// The rent sponsor PDA is derived internally from the program_id.
74/// Seeds: ["rent_sponsor"]
75///
76/// TODO: reduce ixn count and txn size, reduce roundtrips.
77#[allow(clippy::too_many_arguments)]
78pub async fn create_load_instructions<V, I>(
79    specs: &[AccountSpec<V>],
80    fee_payer: Pubkey,
81    compression_config: Pubkey,
82    indexer: &I,
83) -> Result<Vec<Instruction>, LoadAccountsError>
84where
85    V: Pack<solana_instruction::AccountMeta> + Clone + std::fmt::Debug,
86    I: Indexer,
87{
88    if !super::light_program_interface::any_cold(specs) {
89        return Ok(vec![]);
90    }
91
92    let cold_pdas: Vec<_> = specs
93        .iter()
94        .filter_map(|s| match s {
95            AccountSpec::Pda(p) if p.is_cold() => Some(p),
96            _ => None,
97        })
98        .collect();
99
100    let cold_atas: Vec<_> = specs
101        .iter()
102        .filter_map(|s| match s {
103            AccountSpec::Ata(a) if a.is_cold() => Some(a),
104            _ => None,
105        })
106        .collect();
107
108    let cold_mints: Vec<_> = specs
109        .iter()
110        .filter_map(|s| match s {
111            AccountSpec::Mint(m) if m.is_cold() => Some(m),
112            _ => None,
113        })
114        .collect();
115
116    let pda_hashes = collect_pda_hashes(&cold_pdas)?;
117    let ata_hashes = collect_ata_hashes(&cold_atas)?;
118    let mint_hashes = collect_mint_hashes(&cold_mints)?;
119
120    let (pda_proofs, ata_proofs, mint_proofs) = futures::join!(
121        fetch_proofs(&pda_hashes, indexer),
122        fetch_proofs_batched(&ata_hashes, MAX_ATAS_PER_IX, indexer),
123        fetch_proofs(&mint_hashes, indexer),
124    );
125
126    let pda_proofs = pda_proofs?;
127    let ata_proofs = ata_proofs?;
128    let mint_proofs = mint_proofs?;
129
130    let mut out = Vec::new();
131
132    // 1. DecompressAccountsIdempotent for all cold PDAs (including token PDAs).
133    //    Token PDAs are created on-chain via CPI inside DecompressVariant.
134    for (spec, proof) in cold_pdas.iter().zip(pda_proofs) {
135        out.push(build_pda_load(
136            &[spec],
137            proof,
138            fee_payer,
139            compression_config,
140        )?);
141    }
142
143    // 2. ATA loads (CreateAssociatedTokenAccount + Transfer2)
144    let ata_chunks: Vec<_> = cold_atas.chunks(MAX_ATAS_PER_IX).collect();
145    for (chunk, proof) in ata_chunks.into_iter().zip(ata_proofs) {
146        out.extend(build_ata_load(chunk, proof, fee_payer)?);
147    }
148
149    // 3. Mint loads
150    for (iface, proof) in cold_mints.iter().zip(mint_proofs) {
151        out.push(build_mint_load(iface, proof, fee_payer)?);
152    }
153    Ok(out)
154}
155
156fn collect_pda_hashes<V>(specs: &[&PdaSpec<V>]) -> Result<Vec<[u8; 32]>, LoadAccountsError> {
157    specs
158        .iter()
159        .enumerate()
160        .map(|(i, s)| {
161            s.hash().ok_or(LoadAccountsError::MissingPdaCompressed {
162                index: i,
163                pubkey: s.address(),
164            })
165        })
166        .collect()
167}
168
169fn collect_ata_hashes(
170    ifaces: &[&TokenAccountInterface],
171) -> Result<Vec<[u8; 32]>, LoadAccountsError> {
172    ifaces
173        .iter()
174        .enumerate()
175        .map(|(i, s)| {
176            s.hash().ok_or(LoadAccountsError::MissingAtaCompressed {
177                index: i,
178                pubkey: s.key,
179            })
180        })
181        .collect()
182}
183
184fn collect_mint_hashes(ifaces: &[&AccountInterface]) -> Result<Vec<[u8; 32]>, LoadAccountsError> {
185    ifaces
186        .iter()
187        .enumerate()
188        .map(|(i, s)| {
189            s.hash().ok_or(LoadAccountsError::MissingMintHash {
190                index: i,
191                mint: s.key,
192            })
193        })
194        .collect()
195}
196
197async fn fetch_proofs<I: Indexer>(
198    hashes: &[[u8; 32]],
199    indexer: &I,
200) -> Result<Vec<ValidityProofWithContext>, IndexerError> {
201    if hashes.is_empty() {
202        return Ok(vec![]);
203    }
204    let mut proofs = Vec::with_capacity(hashes.len());
205    for hash in hashes {
206        proofs.push(
207            indexer
208                .get_validity_proof(vec![*hash], vec![], None)
209                .await?
210                .value,
211        );
212    }
213    Ok(proofs)
214}
215
216async fn fetch_proofs_batched<I: Indexer>(
217    hashes: &[[u8; 32]],
218    batch_size: usize,
219    indexer: &I,
220) -> Result<Vec<ValidityProofWithContext>, IndexerError> {
221    if hashes.is_empty() {
222        return Ok(vec![]);
223    }
224    let mut proofs = Vec::with_capacity(hashes.len().div_ceil(batch_size));
225    for chunk in hashes.chunks(batch_size) {
226        proofs.push(
227            indexer
228                .get_validity_proof(chunk.to_vec(), vec![], None)
229                .await?
230                .value,
231        );
232    }
233    Ok(proofs)
234}
235
236fn build_pda_load<V>(
237    specs: &[&PdaSpec<V>],
238    proof: ValidityProofWithContext,
239    fee_payer: Pubkey,
240    compression_config: Pubkey,
241) -> Result<Instruction, LoadAccountsError>
242where
243    V: Pack<solana_instruction::AccountMeta> + Clone + std::fmt::Debug,
244{
245    let has_tokens = specs.iter().any(|s| {
246        s.compressed()
247            .map(|c| c.owner == LIGHT_TOKEN_PROGRAM_ID)
248            .unwrap_or(false)
249    });
250
251    // Derive rent sponsor PDA from program_id
252    let program_id = specs.first().map(|s| s.program_id()).unwrap_or_default();
253    let (rent_sponsor, _) = derive_rent_sponsor_pda(&program_id);
254
255    let metas = if has_tokens {
256        instructions::load::accounts(fee_payer, compression_config, rent_sponsor)
257    } else {
258        instructions::load::accounts_pda_only(fee_payer, compression_config, rent_sponsor)
259    };
260
261    let hot_addresses: Vec<Pubkey> = specs.iter().map(|s| s.address()).collect();
262    let cold_accounts: Vec<(CompressedAccount, V)> = specs
263        .iter()
264        .map(|s| {
265            let compressed = s.compressed().expect("cold spec must have data").clone();
266            (compressed, s.variant.clone())
267        })
268        .collect();
269
270    let program_id = specs.first().map(|s| s.program_id()).unwrap_or_default();
271
272    instructions::create_decompress_accounts_idempotent_instruction(
273        &program_id,
274        &DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR,
275        &hot_addresses,
276        &cold_accounts,
277        &metas,
278        proof,
279    )
280    .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))
281}
282
283struct AtaContext<'a> {
284    compressed: &'a CompressedTokenAccount,
285    wallet_owner: Pubkey,
286    mint: Pubkey,
287    bump: u8,
288}
289
290impl<'a> AtaContext<'a> {
291    fn from_interface(
292        iface: &'a TokenAccountInterface,
293        index: usize,
294    ) -> Result<Self, LoadAccountsError> {
295        let compressed = iface
296            .compressed()
297            .ok_or(LoadAccountsError::MissingAtaContext {
298                index,
299                pubkey: iface.key,
300            })?;
301        let bump = iface
302            .ata_bump()
303            .ok_or(LoadAccountsError::MissingAtaContext {
304                index,
305                pubkey: iface.key,
306            })?;
307        Ok(Self {
308            compressed,
309            wallet_owner: iface.owner(),
310            mint: iface.mint(),
311            bump,
312        })
313    }
314}
315
316fn build_ata_load(
317    ifaces: &[&TokenAccountInterface],
318    proof: ValidityProofWithContext,
319    fee_payer: Pubkey,
320) -> Result<Vec<Instruction>, LoadAccountsError> {
321    let contexts: Vec<AtaContext> = ifaces
322        .iter()
323        .enumerate()
324        .map(|(i, a)| AtaContext::from_interface(a, i))
325        .collect::<Result<Vec<_>, _>>()?;
326
327    let mut out = Vec::with_capacity(contexts.len() + 1);
328
329    for ctx in &contexts {
330        let ix = CreateAssociatedTokenAccount::new(fee_payer, ctx.wallet_owner, ctx.mint)
331            .idempotent()
332            .instruction()
333            .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))?;
334        out.push(ix);
335    }
336
337    out.push(build_transfer2(&contexts, proof, fee_payer)?);
338    Ok(out)
339}
340
341fn build_transfer2(
342    contexts: &[AtaContext],
343    proof: ValidityProofWithContext,
344    fee_payer: Pubkey,
345) -> Result<Instruction, LoadAccountsError> {
346    let mut packed = PackedAccounts::default();
347    let packed_trees = proof.pack_tree_infos(&mut packed);
348    let tree_infos = packed_trees
349        .state_trees
350        .as_ref()
351        .ok_or_else(|| LoadAccountsError::BuildInstruction("no state trees".into()))?;
352
353    let mut token_accounts = Vec::with_capacity(contexts.len());
354    let mut tlv_data: Vec<Vec<ExtensionInstructionData>> = Vec::with_capacity(contexts.len());
355    let mut has_tlv = false;
356
357    for (i, ctx) in contexts.iter().enumerate() {
358        let token = &ctx.compressed.token;
359        let tree = tree_infos.packed_tree_infos.get(i).ok_or(
360            LoadAccountsError::TreeInfoIndexOutOfBounds {
361                index: i,
362                len: tree_infos.packed_tree_infos.len(),
363            },
364        )?;
365
366        let owner_idx = packed.insert_or_get_config(ctx.wallet_owner, true, false);
367        let ata_idx = packed.insert_or_get(derive_token_ata(&ctx.wallet_owner, &ctx.mint).0);
368        let mint_idx = packed.insert_or_get(token.mint);
369        let delegate_idx = token.delegate.map(|d| packed.insert_or_get(d)).unwrap_or(0);
370
371        let source = MultiInputTokenDataWithContext {
372            owner: ata_idx,
373            amount: token.amount,
374            has_delegate: token.delegate.is_some(),
375            delegate: delegate_idx,
376            mint: mint_idx,
377            version: TokenDataVersion::ShaFlat as u8,
378            merkle_context: PackedMerkleContext {
379                merkle_tree_pubkey_index: tree.merkle_tree_pubkey_index,
380                queue_pubkey_index: tree.queue_pubkey_index,
381                prove_by_index: tree.prove_by_index,
382                leaf_index: tree.leaf_index,
383            },
384            root_index: tree.root_index,
385        };
386
387        let mut ctoken = CTokenAccount2::new(vec![source])
388            .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))?;
389        ctoken
390            .decompress(token.amount, ata_idx)
391            .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))?;
392        token_accounts.push(ctoken);
393
394        let is_frozen = token.state == AccountState::Frozen;
395        let tlv: Vec<ExtensionInstructionData> = token
396            .tlv
397            .as_ref()
398            .map(|exts| {
399                exts.iter()
400                    .filter_map(|ext| match ext {
401                        ExtensionStruct::CompressedOnly(co) => {
402                            Some(ExtensionInstructionData::CompressedOnly(
403                                CompressedOnlyExtensionInstructionData {
404                                    delegated_amount: co.delegated_amount,
405                                    withheld_transfer_fee: co.withheld_transfer_fee,
406                                    is_frozen,
407                                    compression_index: i as u8,
408                                    is_ata: true,
409                                    bump: ctx.bump,
410                                    owner_index: owner_idx,
411                                },
412                            ))
413                        }
414                        _ => None,
415                    })
416                    .collect()
417            })
418            .unwrap_or_default();
419
420        if !tlv.is_empty() {
421            has_tlv = true;
422        }
423        tlv_data.push(tlv);
424    }
425
426    let (metas, _, _) = packed.to_account_metas();
427
428    create_transfer2_instruction(Transfer2Inputs {
429        meta_config: Transfer2AccountsMetaConfig::new(fee_payer, metas),
430        token_accounts,
431        transfer_config: Transfer2Config::default().filter_zero_amount_outputs(),
432        validity_proof: proof.proof,
433        in_tlv: if has_tlv { Some(tlv_data) } else { None },
434        ..Default::default()
435    })
436    .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))
437}
438
439fn build_mint_load(
440    iface: &AccountInterface,
441    proof: ValidityProofWithContext,
442    fee_payer: Pubkey,
443) -> Result<Instruction, LoadAccountsError> {
444    let acc = proof
445        .accounts
446        .first()
447        .ok_or_else(|| LoadAccountsError::BuildInstruction("proof has no accounts".into()))?;
448    let state_tree = acc.tree_info.tree;
449    let input_queue = acc.tree_info.queue;
450    let output_queue = acc
451        .tree_info
452        .next_tree_info
453        .as_ref()
454        .map(|n| n.queue)
455        .unwrap_or(input_queue);
456
457    let mint_data = iface
458        .as_mint()
459        .ok_or_else(|| LoadAccountsError::BuildInstruction("missing mint_data".into()))?;
460    let compressed_address = iface
461        .mint_compressed_address()
462        .ok_or_else(|| LoadAccountsError::BuildInstruction("missing compressed_address".into()))?;
463    let mint_ix_data = MintInstructionData::try_from(mint_data)
464        .map_err(|_| LoadAccountsError::BuildInstruction("invalid mint data".into()))?;
465
466    DecompressMint {
467        payer: fee_payer,
468        authority: fee_payer,
469        state_tree,
470        input_queue,
471        output_queue,
472        compressed_mint_with_context: MintWithContext {
473            leaf_index: acc.leaf_index as u32,
474            prove_by_index: acc.root_index.proof_by_index(),
475            root_index: acc.root_index.root_index().unwrap_or_default(),
476            address: compressed_address,
477            mint: Some(mint_ix_data),
478        },
479        proof: ValidityProof(proof.proof.into()),
480        rent_payment: DEFAULT_RENT_PAYMENT,
481        write_top_up: DEFAULT_WRITE_TOP_UP,
482    }
483    .instruction()
484    .map_err(|e| LoadAccountsError::BuildInstruction(e.to_string()))
485}