Skip to main content

thru_base/
txn_tools.rs

1use crate::{
2    tn_public_address::tn_pubkey_to_address_string,
3    txn_lib::{TnPubkey, Transaction},
4    StateProof,
5};
6use anyhow::{bail, Result};
7use hex;
8use std::collections::HashMap;
9
10/// Canonical managed programs/state for freshly bootstrapped networks.
11pub use crate::bootstrap_addresses::{
12    EOA_PROGRAM_BYTES as EOA_PROGRAM,
13    ATTESTOR_TABLE_BYTES as ATTESTOR_TABLE,
14    CONSENSUS_VALIDATOR_PROGRAM_BYTES as CONSENSUS_VALIDATOR_PROGRAM,
15    FAUCET_PROGRAM_BYTES as FAUCET_PROGRAM,
16    NOOP_PROGRAM_BYTES as NOOP_PROGRAM,
17    TOKEN_PROGRAM_BYTES as TOKEN_PROGRAM,
18    UPLOADER_PROGRAM_BYTES as UPLOADER_PROGRAM,
19    // Test harnesses must upload this fixture; production networks do not install it.
20    SYSTEM_TEST_PROGRAM_BYTES as SYSTEM_TEST_PROGRAM,
21};
22
23/// Domain separation for proofs bound to a registering validator identity.
24pub const CONSENSUS_VALIDATOR_POP_DST: &[u8] = b"BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
25
26/// Return the raw affine key and proof carried by Activate. The proof signs
27/// the compressed BLS key followed by the registering Ed25519 identity.
28pub fn bls_activation_key(
29    secret_key: &blst::min_pk::SecretKey,
30    identity: &TnPubkey,
31) -> (
32    [u8; std::mem::size_of::<blst::blst_p1_affine>()],
33    [u8; std::mem::size_of::<blst::blst_p2_affine>()],
34) {
35    let public_key = secret_key.sk_to_pk();
36    let compressed = public_key.compress();
37    let mut message = [0u8; std::mem::size_of::<blst::blst_fp>() + std::mem::size_of::<TnPubkey>()];
38    message[..compressed.len()].copy_from_slice(&compressed);
39    message[compressed.len()..].copy_from_slice(identity);
40    let proof = secret_key.sign(&message, CONSENSUS_VALIDATOR_POP_DST, &[]);
41    let public_key: blst::blst_p1_affine = public_key.into();
42    let proof: blst::blst_p2_affine = proof.into();
43    let mut key_bytes = [0u8; std::mem::size_of::<blst::blst_p1_affine>()];
44    let mut proof_bytes = [0u8; std::mem::size_of::<blst::blst_p2_affine>()];
45    // Activate carries blst's raw affine structs, including native limbs.
46    unsafe {
47        std::ptr::copy_nonoverlapping(
48            std::ptr::from_ref(&public_key).cast::<u8>(),
49            key_bytes.as_mut_ptr(),
50            key_bytes.len(),
51        );
52        std::ptr::copy_nonoverlapping(
53            std::ptr::from_ref(&proof).cast::<u8>(),
54            proof_bytes.as_mut_ptr(),
55            proof_bytes.len(),
56        );
57    }
58    (key_bytes, proof_bytes)
59}
60
61const CONSENSUS_VALIDATOR_DEFAULT_EXPIRY_AFTER: u32 = 100;
62const CONSENSUS_VALIDATOR_COMPUTE_UNITS: u32 = 500_000_000;
63const CONSENSUS_VALIDATOR_PROOF_COMPUTE_UNITS: u32 = 1_000_000_000;
64const CONSENSUS_VALIDATOR_STATE_UNITS: u16 = 0;
65const CONSENSUS_VALIDATOR_MEMORY_UNITS: u16 = 10_000;
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct ConsensusValidatorAccounts {
69    pub program: TnPubkey,
70    pub attestor_table: TnPubkey,
71    pub token_program: TnPubkey,
72    pub converted_vault: TnPubkey,
73    pub unclaimed_vault: TnPubkey,
74}
75
76impl Default for ConsensusValidatorAccounts {
77    /// The canonical accounts.  The vaults have no constant: they are derived
78    /// as the program's Init creates them ([`consensus_validator_vault_address`]).
79    fn default() -> Self {
80        let wthru_mint = crate::bootstrap_addresses::WTHRU_MINT_BYTES;
81        Self {
82            program: CONSENSUS_VALIDATOR_PROGRAM,
83            attestor_table: ATTESTOR_TABLE,
84            token_program: TOKEN_PROGRAM,
85            converted_vault: consensus_validator_vault_address(
86                &TOKEN_PROGRAM,
87                &CONSENSUS_VALIDATOR_PROGRAM,
88                &wthru_mint,
89                CONSENSUS_CONVERTED_VAULT_SEED,
90            ),
91            unclaimed_vault: consensus_validator_vault_address(
92                &TOKEN_PROGRAM,
93                &CONSENSUS_VALIDATOR_PROGRAM,
94                &wthru_mint,
95                CONSENSUS_UNCLAIMED_VAULT_SEED,
96            ),
97        }
98    }
99}
100
101/// Seed of the consensus validator's converted (stake) vault.
102pub const CONSENSUS_CONVERTED_VAULT_SEED: &[u8] = b"converted_vault";
103/// Seed of the consensus validator's unclaimed (reward) vault.
104pub const CONSENSUS_UNCLAIMED_VAULT_SEED: &[u8] = b"unclaimed_vault";
105
106/// A consensus validator vault, derived as the program's Init creates it
107/// (`tn_consensus_validator_vault_address` in
108/// programs/c/examples/tn_consensus_validator_program.c): the Token account
109/// PDA(token_program, SHA256(program || wthru_mint || seed)), with `seed`
110/// zero-padded to 32 bytes.  On a running chain the attestor table header
111/// records the vaults and the program pins every vault index to it.
112///
113/// # Panics
114///
115/// If `seed` is longer than 32 bytes.
116pub fn consensus_validator_vault_address(
117    token_program: &[u8; 32],
118    program: &[u8; 32],
119    wthru_mint: &[u8; 32],
120    seed: &[u8],
121) -> [u8; 32] {
122    use sha2::{Digest, Sha256};
123    assert!(seed.len() <= 32, "consensus vault seed exceeds 32 bytes");
124    let mut padded = [0u8; 32];
125    padded[..seed.len()].copy_from_slice(seed);
126    let mut hasher = Sha256::new();
127    hasher.update(program);
128    hasher.update(wthru_mint);
129    hasher.update(padded);
130    let mut token_seed = [0u8; 32];
131    token_seed.copy_from_slice(&hasher.finalize()[..32]);
132    crate::tn_public_address::create_program_defined_account_address(
133        token_program,
134        false,
135        &token_seed,
136    )
137}
138
139fn build_consensus_validator_tx(
140    fee_payer: TnPubkey,
141    program: TnPubkey,
142    fee: u64,
143    nonce: u64,
144    start_slot: u64,
145) -> Transaction {
146    Transaction::new(fee_payer, program, fee, nonce)
147        .with_start_slot(start_slot)
148        .with_expiry_after(CONSENSUS_VALIDATOR_DEFAULT_EXPIRY_AFTER)
149        .with_compute_units(CONSENSUS_VALIDATOR_COMPUTE_UNITS)
150        .with_state_units(CONSENSUS_VALIDATOR_STATE_UNITS)
151        .with_memory_units(CONSENSUS_VALIDATOR_MEMORY_UNITS)
152}
153
154/// Base transaction for BP bond mutating ops (deposit/withdraw/update/sweep/
155/// set-authority/delete), which only update existing accounts.
156fn bp_base_tx(
157    fee_payer: TnPubkey,
158    bp_program: TnPubkey,
159    fee: u64,
160    nonce: u64,
161    start_slot: u64,
162) -> Transaction {
163    Transaction::new(fee_payer, bp_program, fee, nonce)
164        .with_start_slot(start_slot)
165        .with_expiry_after(100)
166        .with_compute_units(50_000_000)
167        .with_state_units(0)
168        .with_memory_units(10_000)
169}
170
171#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
172pub struct UploaderWriteOptions {
173    pub skip_elf_check: bool,
174}
175
176/// Account footprint reservation, including the runtime's 64-byte metadata.
177/// Builders without the prior account size reserve the full resulting footprint.
178pub fn account_state_units(data_size: u64) -> Result<u16> {
179    let footprint = data_size
180        .checked_add(64)
181        .ok_or_else(|| anyhow::anyhow!("account footprint overflows"))?;
182    Ok(u16::try_from(footprint.div_ceil(4096))?)
183}
184
185// Packed abi_account_t payload header: pubkey, revision, state, content size.
186pub const ABI_ACCOUNT_HEADER_SIZE: u64 = 32 + 8 + 1 + 4;
187
188#[derive(Debug, Clone)]
189pub struct TransactionBuilder {
190    // fee_payer: FdPubkey,
191    // program: FdPubkey,
192    // fee: u64,
193    // nonce: u64,
194}
195
196impl TransactionBuilder {
197    /// Build balance transfer transaction
198    pub fn build_create_with_fee_payer_proof(
199        fee_payer: TnPubkey,
200        start_slot: u64,
201        fee_payer_state_proof: &StateProof,
202    ) -> Result<Transaction> {
203        let tx = Transaction::new(fee_payer, NOOP_PROGRAM, 0, 0)
204            .with_fee_payer_state_proof(fee_payer_state_proof)
205            .with_start_slot(start_slot)
206            .with_expiry_after(100)
207            .with_compute_units(10_000)
208            .with_memory_units(10_000)
209            .with_state_units(1);
210        Ok(tx)
211    }
212
213    /// Build balance transfer transaction for EOA program (tn_eoa_program.c)
214    ///
215    /// This creates a transaction that calls the TRANSFER instruction of the EOA program,
216    /// which transfers balance from one account to another.
217    ///
218    /// # Arguments
219    /// * `fee_payer` - The account paying the transaction fee (also the from_account for the transfer)
220    /// * `program` - The EOA program pubkey (typically the canonical EOA_PROGRAM)
221    /// * `to_account` - The destination account receiving the transfer
222    /// * `amount` - The amount to transfer
223    /// * `fee` - Transaction fee
224    /// * `nonce` - Account nonce
225    /// * `start_slot` - Starting slot for transaction validity
226    pub fn build_transfer(
227        fee_payer: TnPubkey,
228        program: TnPubkey,
229        to_account: TnPubkey,
230        amount: u64,
231        fee: u64,
232        nonce: u64,
233        start_slot: u64,
234    ) -> Result<Transaction> {
235        // Create transfer instruction data for EOA program
236        // Account layout: [0: fee_payer/from_account, 1: program, 2: to_account]
237        let from_account_idx = 0u16; // fee_payer is also the from_account
238        let to_account_idx = 2u16; // to_account added via add_rw_account
239        let instruction_data =
240            build_transfer_instruction(from_account_idx, to_account_idx, amount)?;
241
242        let tx = Transaction::new(fee_payer, program, fee, nonce)
243            .with_start_slot(start_slot)
244            .add_rw_account(to_account) // Destination account (receives transfer)
245            .with_instructions(instruction_data)
246            .with_expiry_after(100)
247            .with_compute_units(10000)
248            .with_memory_units(10000)
249            .with_state_units(0);
250
251        Ok(tx)
252    }
253
254    /// Build EOA delete transaction for the EOA program (tn_eoa_program.c)
255    ///
256    /// Calls the DELETE_ACCOUNT instruction, which deletes an unused EOA
257    /// (balance == 0, nonce == 0) after the runtime verifies `signature` over
258    /// the canonical delete message. The signature must be produced by signing
259    /// [`build_eoa_delete_message`] (with the same `chain_id`, fee payer, and
260    /// EOA pubkey) using the EOA's private key.
261    ///
262    /// Account layout: `[0: fee_payer, 1: program, 2: eoa_account]`. The EOA
263    /// being deleted cannot be the fee payer, since paying a fee bumps the
264    /// nonce and deletion requires `nonce == 0`.
265    #[allow(clippy::too_many_arguments)]
266    pub fn build_delete_account(
267        fee_payer: TnPubkey,
268        program: TnPubkey,
269        eoa_account: TnPubkey,
270        signature: &[u8; 64],
271        chain_id: u16,
272        fee: u64,
273        nonce: u64,
274        start_slot: u64,
275    ) -> Result<Transaction> {
276        // Account layout: [0: fee_payer, 1: program, 2: eoa_account]
277        let eoa_account_idx = 2u16; // eoa_account added via add_rw_account
278        let instruction_data = build_delete_account_instruction(eoa_account_idx, signature)?;
279
280        let tx = Transaction::new(fee_payer, program, fee, nonce)
281            .with_start_slot(start_slot)
282            .with_chain_id(chain_id)
283            .add_rw_account(eoa_account)
284            .with_instructions(instruction_data)
285            .with_expiry_after(100)
286            .with_compute_units(10_000)
287            .with_memory_units(10_000)
288            .with_state_units(0);
289
290        Ok(tx)
291    }
292
293    /// Build regular account creation transaction (with optional state proof)
294    pub fn build_create_account(
295        fee_payer: TnPubkey,
296        program: TnPubkey,
297        target_account: TnPubkey,
298        seed: &str,
299        state_proof: Option<&[u8]>,
300        fee: u64,
301        nonce: u64,
302        start_slot: u64,
303    ) -> Result<Transaction> {
304        // Account layout: [0: fee_payer, 1: program, 2: target_account]
305        let target_account_idx = 2u16; // target_account added via add_rw_account
306        let instruction_data =
307            build_create_account_instruction(target_account_idx, seed, state_proof)?;
308
309        let tx = Transaction::new(fee_payer, program, fee, nonce)
310            .with_start_slot(start_slot)
311            .add_rw_account(target_account)
312            .with_instructions(instruction_data)
313            .with_expiry_after(100)
314            .with_compute_units(10_000)
315            .with_memory_units(10_000)
316            .with_state_units(1);
317
318        Ok(tx)
319    }
320
321    /// Build account creation transaction
322    pub fn build_create_ephemeral_account(
323        fee_payer: TnPubkey,
324        program: TnPubkey,
325        target_account: TnPubkey,
326        seed: &[u8; 32],
327        fee: u64,
328        nonce: u64,
329        start_slot: u64,
330    ) -> Result<Transaction> {
331        // Account layout: [0: fee_payer, 1: program, 2: target_account]
332        let target_account_idx = 2u16; // target_account added via add_rw_account
333        let instruction_data = build_ephemeral_account_instruction(target_account_idx, seed)?;
334
335        let tx = Transaction::new(fee_payer, program, fee, nonce)
336            .with_start_slot(start_slot)
337            .add_rw_account(target_account)
338            .with_instructions(instruction_data)
339            .with_expiry_after(100)
340            .with_compute_units(50_000)
341            .with_memory_units(10_000)
342            .with_state_units(1);
343        Ok(tx)
344    }
345
346    /// Build account resize transaction
347    pub fn build_resize_account(
348        fee_payer: TnPubkey,
349        program: TnPubkey,
350        target_account: TnPubkey,
351        new_size: u64,
352        fee: u64,
353        nonce: u64,
354        start_slot: u64,
355    ) -> Result<Transaction> {
356        // Account layout: [0: fee_payer, 1: program, 2: target_account]
357        let target_account_idx = 2u16; // target_account added via add_rw_account
358        let instruction_data = build_resize_instruction(target_account_idx, new_size)?;
359
360        let tx = Transaction::new(fee_payer, program, fee, nonce)
361            .with_start_slot(start_slot)
362            .with_expiry_after(100)
363            .with_compute_units(100032)
364            .with_memory_units(10000)
365            .add_rw_account(target_account)
366            .with_instructions(instruction_data)
367            .with_expiry_after(100)
368            .with_compute_units(10_000 + 2 * new_size as u32)
369            .with_memory_units(10_000)
370            .with_state_units(account_state_units(new_size)?.saturating_sub(1));
371
372        Ok(tx)
373    }
374
375    /// Build account compression transaction
376    pub fn build_compress_account(
377        fee_payer: TnPubkey,
378        program: TnPubkey,
379        target_account: TnPubkey,
380        state_proof: &[u8],
381        fee: u64,
382        nonce: u64,
383        start_slot: u64,
384        account_size: u32,
385    ) -> Result<Transaction> {
386        // Account layout: [0: fee_payer, 1: program, 2: target_account]
387        let target_account_idx = 2u16; // target_account added via add_rw_account
388        let instruction_data = build_compress_instruction(target_account_idx, state_proof)?;
389
390        let tx = Transaction::new(fee_payer, program, fee, nonce)
391            .with_start_slot(start_slot)
392            .with_may_compress_account()
393            .add_rw_account(target_account)
394            .with_instructions(instruction_data)
395            .with_expiry_after(100)
396            .with_compute_units(100_300 + account_size * 2)
397            .with_memory_units(10000)
398            .with_state_units(0);
399
400        Ok(tx)
401    }
402
403    /// Build a legacy system-test decompression transaction.
404    /// For the current managed compression program use `build_compression_decompress`.
405    pub fn build_decompress_account(
406        fee_payer: TnPubkey,
407        program: TnPubkey,
408        target_account: TnPubkey,
409        account_data: &[u8],
410        state_proof: &[u8],
411        fee: u64,
412        nonce: u64,
413        start_slot: u64,
414    ) -> Result<Transaction> {
415        // Account layout: [0: fee_payer, 1: program, 2: target_account]
416        let target_account_idx = 2u16; // target_account added via add_rw_account
417        let instruction_data =
418            build_decompress_instruction(target_account_idx, account_data, state_proof)?;
419
420        let tx = Transaction::new(fee_payer, program, fee, nonce)
421            .with_start_slot(start_slot)
422            .add_rw_account(target_account)
423            .with_instructions(instruction_data)
424            .with_compute_units(100_300 + account_data.len() as u32 * 2)
425            .with_state_units(account_state_units(account_data.len() as u64)?)
426            .with_memory_units(10_000)
427            .with_expiry_after(100);
428        Ok(tx)
429    }
430
431    /// Build data write transaction
432    pub fn build_write_data(
433        fee_payer: TnPubkey,
434        program: TnPubkey,
435        target_account: TnPubkey,
436        offset: u16,
437        data: &[u8],
438        fee: u64,
439        nonce: u64,
440        start_slot: u64,
441    ) -> Result<Transaction> {
442        // Account layout: [0: fee_payer, 1: program, 2: target_account]
443        let target_account_idx = 2u16; // target_account added via add_rw_account
444        let instruction_data = build_write_instruction(target_account_idx, offset, data)?;
445
446        let tx = Transaction::new(fee_payer, program, fee, nonce)
447            .with_start_slot(start_slot)
448            .with_expiry_after(100)
449            .with_compute_units(100045)
450            .with_state_units(0)
451            .with_memory_units(10000)
452            .add_rw_account(target_account)
453            .with_instructions(instruction_data);
454
455        Ok(tx)
456    }
457}
458
459/// Build transfer instruction for EOA program (tn_eoa_program.c)
460///
461/// Instruction format (matching tn_eoa_instruction_t and tn_eoa_transfer_args_t):
462/// - Discriminant: u32 (4 bytes) = TN_EOA_INSTRUCTION_TRANSFER (1)
463/// - Amount: u64 (8 bytes)
464/// - From account index: u16 (2 bytes)
465/// - To account index: u16 (2 bytes)
466/// Total: 16 bytes
467fn build_transfer_instruction(
468    from_account_idx: u16,
469    to_account_idx: u16,
470    amount: u64,
471) -> Result<Vec<u8>> {
472    let mut instruction = Vec::new();
473
474    // TN_EOA_INSTRUCTION_TRANSFER = 1 (u32, 4 bytes little-endian)
475    instruction.extend_from_slice(&1u32.to_le_bytes());
476
477    // tn_eoa_transfer_args_t structure:
478    // - amount (u64, 8 bytes little-endian)
479    instruction.extend_from_slice(&amount.to_le_bytes());
480
481    // - from_account_idx (u16, 2 bytes little-endian)
482    instruction.extend_from_slice(&from_account_idx.to_le_bytes());
483
484    // - to_account_idx (u16, 2 bytes little-endian)
485    instruction.extend_from_slice(&to_account_idx.to_le_bytes());
486
487    Ok(instruction)
488}
489
490/// ASCII domain-separation tag for the EOA create authorization message.
491pub const EOA_CREATE_MSG_TAG: &[u8; 16] = b"tn_eoa_create_v1";
492
493/// Total size of the EOA create authorization message: tag(16) + chain_id(2)
494/// + fee_payer(32) + eoa(32).
495pub const EOA_CREATE_MSG_SZ: usize = 16 + 2 + 32 + 32;
496
497/// Build the canonical domain-separated EOA create authorization message:
498/// `"tn_eoa_create_v1" || chain_id || fee_payer_pubkey || eoa_pubkey`.
499///
500/// `chain_id` is encoded little-endian. Byte-identical to what the runtime
501/// constructs in `tn_vm_syscall_account_create_eoa` and to the Go/TS builders.
502/// The EOA's private key signs this message; the resulting signature is embedded
503/// in the create instruction. (Replaces the previous "sign 32 zero bytes".)
504pub fn build_eoa_create_message(
505    chain_id: u16,
506    fee_payer: &TnPubkey,
507    eoa: &TnPubkey,
508) -> [u8; EOA_CREATE_MSG_SZ] {
509    let mut msg = [0u8; EOA_CREATE_MSG_SZ];
510    msg[0..16].copy_from_slice(EOA_CREATE_MSG_TAG);
511    msg[16..18].copy_from_slice(&chain_id.to_le_bytes());
512    msg[18..50].copy_from_slice(fee_payer);
513    msg[50..82].copy_from_slice(eoa);
514    msg
515}
516
517/// ASCII domain-separation tag for the EOA delete authorization message.
518pub const EOA_DELETE_MSG_TAG: &[u8; 16] = b"tn_eoa_delete_v1";
519
520/// Total size of the EOA delete authorization message: tag(16) + chain_id(2)
521/// + fee_payer(32) + eoa(32).
522pub const EOA_DELETE_MSG_SZ: usize = 16 + 2 + 32 + 32;
523
524/// Build the canonical domain-separated EOA delete authorization message:
525/// `"tn_eoa_delete_v1" || chain_id || fee_payer_pubkey || eoa_pubkey`.
526///
527/// `chain_id` is encoded little-endian. The returned bytes must be
528/// byte-identical to what the runtime constructs in
529/// `tn_vm_syscall_account_delete` and to the Go/TS builders. The EOA's
530/// private key signs this message; the resulting signature is passed to
531/// [`TransactionBuilder::build_delete_account`].
532pub fn build_eoa_delete_message(
533    chain_id: u16,
534    fee_payer: &TnPubkey,
535    eoa: &TnPubkey,
536) -> [u8; EOA_DELETE_MSG_SZ] {
537    let mut msg = [0u8; EOA_DELETE_MSG_SZ];
538    msg[0..16].copy_from_slice(EOA_DELETE_MSG_TAG);
539    msg[16..18].copy_from_slice(&chain_id.to_le_bytes());
540    msg[18..50].copy_from_slice(fee_payer);
541    msg[50..82].copy_from_slice(eoa);
542    msg
543}
544
545/// Build delete-account instruction for the EOA program (tn_eoa_program.c)
546///
547/// Instruction format (matching tn_eoa_instruction_t and tn_eoa_delete_account_args_t):
548/// - Discriminant: u32 (4 bytes) = TN_EOA_INSTRUCTION_DELETE_ACCOUNT (2)
549/// - EOA account index: u16 (2 bytes)
550/// - Signature: 64 bytes
551/// Total: 70 bytes
552fn build_delete_account_instruction(eoa_account_idx: u16, signature: &[u8; 64]) -> Result<Vec<u8>> {
553    let mut instruction = Vec::with_capacity(4 + 2 + 64);
554
555    // TN_EOA_INSTRUCTION_DELETE_ACCOUNT = 2 (u32, 4 bytes little-endian)
556    instruction.extend_from_slice(&2u32.to_le_bytes());
557
558    // tn_eoa_delete_account_args_t structure:
559    // - eoa_account_idx (u16, 2 bytes little-endian)
560    instruction.extend_from_slice(&eoa_account_idx.to_le_bytes());
561
562    // - signature (64 bytes)
563    instruction.extend_from_slice(signature);
564
565    Ok(instruction)
566}
567
568/// Build regular account creation instruction (TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_CREATE = 0x00)
569fn build_create_account_instruction(
570    target_account_idx: u16,
571    seed: &str,
572    state_proof: Option<&[u8]>,
573) -> Result<Vec<u8>> {
574    let mut instruction = Vec::new();
575
576    // TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_CREATE = 0x00
577    instruction.push(0x00);
578
579    // Target account index (little-endian u16) - matching tn_system_test_program_account_create_args_t
580    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
581
582    // Seed should be hex-decoded (to match addrtool behavior)
583    let seed_bytes =
584        hex::decode(seed).map_err(|e| anyhow::anyhow!("Failed to decode hex seed: {}", e))?;
585
586    // Seed length (little-endian u64) - matching tn_system_test_program_account_create_args_t.seed_len
587    instruction.extend_from_slice(&(seed_bytes.len() as u64).to_le_bytes());
588
589    // has_proof flag (1 byte) - matching tn_system_test_program_account_create_args_t.has_proof
590    let has_proof = state_proof.is_some();
591    instruction.push(if has_proof { 1u8 } else { 0u8 });
592
593    // Seed data (seed_len bytes follow)
594    instruction.extend_from_slice(&seed_bytes);
595
596    // Proof data (if present, proof follows seed)
597    if let Some(proof) = state_proof {
598        instruction.extend_from_slice(proof);
599    }
600
601    Ok(instruction)
602}
603
604/// Build ephemeral account creation instruction
605fn build_ephemeral_account_instruction(
606    target_account_idx: u16,
607    seed: &[u8; 32],
608) -> Result<Vec<u8>> {
609    let mut instruction = Vec::new();
610
611    // TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_CREATE_EPHEMERAL = 01
612    instruction.push(0x01);
613
614    // Target account index (little-endian u16)
615    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
616
617    // Seed length (little-endian u64)
618    instruction.extend_from_slice(&(seed.len() as u64).to_le_bytes());
619
620    // Seed data
621    instruction.extend_from_slice(seed);
622
623    Ok(instruction)
624}
625
626/// Build account resize instruction
627fn build_resize_instruction(target_account_idx: u16, new_size: u64) -> Result<Vec<u8>> {
628    let mut instruction = Vec::new();
629
630    // TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_RESIZE = 04
631    instruction.push(0x04);
632
633    // Target account index (little-endian u16)
634    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
635
636    // New size (little-endian u64)
637    instruction.extend_from_slice(&new_size.to_le_bytes());
638
639    Ok(instruction)
640}
641
642/// Build data write instruction
643fn build_write_instruction(target_account_idx: u16, offset: u16, data: &[u8]) -> Result<Vec<u8>> {
644    let mut instruction = Vec::new();
645
646    // TN_SYS_TEST_PROG_DISCRIMINANT_WRITE = C8
647    instruction.push(0xC8);
648
649    // Target account index (little-endian u16)
650    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
651
652    // Offset (little-endian u16)
653    instruction.extend_from_slice(&offset.to_le_bytes());
654
655    // Data length (little-endian u16)
656    instruction.extend_from_slice(&(data.len() as u16).to_le_bytes());
657
658    // Data
659    instruction.extend_from_slice(data);
660
661    Ok(instruction)
662}
663
664/// Build account compression instruction
665fn build_compress_instruction(target_account_idx: u16, state_proof: &[u8]) -> Result<Vec<u8>> {
666    let mut instruction = Vec::new();
667
668    // TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_COMPRESS - based on C test, this appears to be different from other discriminants
669    // Looking at the C test pattern and other system discriminants, compression is likely 0x05
670    instruction.push(0x05);
671
672    // Target account index (little-endian u16)
673    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
674
675    // State proof bytes
676    instruction.extend_from_slice(state_proof);
677
678    Ok(instruction)
679}
680
681fn build_decompress_instruction(
682    target_account_idx: u16,
683    account_data: &[u8],
684    state_proof: &[u8],
685) -> Result<Vec<u8>> {
686    let mut instruction = Vec::new();
687
688    // TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_DECOMPRESS = 0x06
689    instruction.push(0x06);
690
691    // tn_system_test_program_account_decompress_args_t: account_idx (u16) + data_len (u64)
692    instruction.extend_from_slice(&target_account_idx.to_le_bytes());
693    instruction.extend_from_slice(&(account_data.len() as u64).to_le_bytes());
694
695    // Account data
696    instruction.extend_from_slice(account_data);
697
698    // State proof bytes
699    instruction.extend_from_slice(state_proof);
700
701    Ok(instruction)
702}
703
704/// Generate ephemeral account address from seed
705/// This replaces the `addrtool --ephemeral` functionality
706/// Based on create_program_defined_account_address from tn_vm_syscalls.c
707/// Note: For ephemeral accounts, the owner is always the system program (all zeros)
708pub fn generate_ephemeral_address(seed: &str) -> Result<String> {
709    // Owner is always system program (all zeros) for ephemeral accounts
710    let owner_pubkey = [0u8; 32];
711
712    // Convert seed string to hex bytes (addrtool expects hex-encoded seed)
713    let seed_bytes =
714        hex::decode(seed).map_err(|e| anyhow::anyhow!("Failed to decode hex seed: {}", e))?;
715
716    // Pad or truncate to exactly 32 bytes (matching C implementation)
717    let mut seed_32 = [0u8; 32];
718    let copy_len = std::cmp::min(seed_bytes.len(), 32);
719    seed_32[..copy_len].copy_from_slice(&seed_bytes[..copy_len]);
720
721    // Use the new implementation from tn_public_address
722    Ok(
723        crate::tn_public_address::create_program_defined_account_address_string(
724            &owner_pubkey,
725            true, // is_ephemeral = true
726            &seed_32,
727        ),
728    )
729}
730
731pub fn generate_system_derived_address(seed: &str, is_ephemeral: bool) -> Result<String> {
732    // Convert seed string to hex bytes (addrtool expects hex-encoded seed)
733    let seed_bytes =
734        hex::decode(seed).map_err(|e| anyhow::anyhow!("Failed to decode hex seed: {}", e))?;
735
736    let pubkey = generate_derived_address(&seed_bytes, &[0u8; 32], is_ephemeral)?;
737
738    Ok(tn_pubkey_to_address_string(&pubkey))
739}
740
741pub fn generate_derived_address(
742    seed: &[u8],
743    owner_pubkey: &[u8; 32],
744    is_ephemeral: bool,
745) -> Result<[u8; 32]> {
746    use sha2::{Digest, Sha256};
747
748    // Create SHA256 hasher
749    let mut hasher = Sha256::new();
750
751    // Hash owner pubkey (32 bytes) - system program
752    hasher.update(&owner_pubkey);
753
754    // Hash is_ephemeral flag (1 byte)
755    hasher.update(&[is_ephemeral as u8]);
756
757    // Hash seed bytes
758    hasher.update(&seed);
759
760    // Finalize hash to get 32-byte result
761    Ok(hasher.finalize().into())
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    #[test]
769    fn account_footprint_reservations_include_metadata() {
770        assert_eq!(account_state_units(0).unwrap(), 1);
771        assert_eq!(account_state_units(4032).unwrap(), 1);
772        assert_eq!(account_state_units(4033).unwrap(), 2);
773        assert_eq!(account_state_units(4096).unwrap(), 2);
774        assert_eq!(account_state_units(16 * 1024 * 1024).unwrap(), 4097);
775        assert!(account_state_units(u64::MAX).is_err());
776        assert!(account_state_units(u16::MAX as u64 * 4096).is_err());
777    }
778
779    #[test]
780    fn test_ephemeral_address_generation() {
781        // Test with hex-encoded seeds (as addrtool expects)
782        let hex_seed1 = hex::encode("test_seed_123");
783        let hex_seed2 = hex::encode("test_seed_123");
784        let hex_seed3 = hex::encode("different_seed");
785
786        let addr1 = generate_ephemeral_address(&hex_seed1).unwrap();
787        let addr2 = generate_ephemeral_address(&hex_seed2).unwrap();
788        let addr3 = generate_ephemeral_address(&hex_seed3).unwrap();
789
790        // Same inputs should produce same address
791        assert_eq!(addr1, addr2);
792
793        // Different seeds should produce different addresses
794        assert_ne!(addr1, addr3);
795
796        // All addresses should be ta... format
797        assert!(addr1.starts_with("ta"));
798        assert!(addr2.starts_with("ta"));
799        assert!(addr3.starts_with("ta"));
800
801        // All addresses should be 46 characters
802        assert_eq!(addr1.len(), 46);
803        assert_eq!(addr2.len(), 46);
804        assert_eq!(addr3.len(), 46);
805    }
806
807    #[test]
808    fn test_eoa_transfer_instruction_format() {
809        // Test that the transfer instruction matches the EOA program's expected format
810        let from_idx = 0u16;
811        let to_idx = 2u16;
812        let amount = 1000u64;
813
814        let instruction = build_transfer_instruction(from_idx, to_idx, amount).unwrap();
815
816        // Expected format (matching tn_eoa_program.c):
817        // - Discriminant: u32 (4 bytes) = 1
818        // - Amount: u64 (8 bytes)
819        // - From account index: u16 (2 bytes)
820        // - To account index: u16 (2 bytes)
821        // Total: 16 bytes
822
823        assert_eq!(instruction.len(), 16, "Instruction should be 16 bytes");
824
825        // Check discriminant (TN_EOA_INSTRUCTION_TRANSFER = 1)
826        let discriminant = u32::from_le_bytes([
827            instruction[0],
828            instruction[1],
829            instruction[2],
830            instruction[3],
831        ]);
832        assert_eq!(discriminant, 1, "Discriminant should be 1 for TRANSFER");
833
834        // Check amount
835        let parsed_amount = u64::from_le_bytes([
836            instruction[4],
837            instruction[5],
838            instruction[6],
839            instruction[7],
840            instruction[8],
841            instruction[9],
842            instruction[10],
843            instruction[11],
844        ]);
845        assert_eq!(parsed_amount, amount, "Amount should match input");
846
847        // Check from_account_idx
848        let parsed_from = u16::from_le_bytes([instruction[12], instruction[13]]);
849        assert_eq!(parsed_from, from_idx, "From index should match input");
850
851        // Check to_account_idx
852        let parsed_to = u16::from_le_bytes([instruction[14], instruction[15]]);
853        assert_eq!(parsed_to, to_idx, "To index should match input");
854    }
855
856    #[test]
857    fn test_eoa_delete_instruction_format() {
858        // Test that the delete instruction matches the EOA program's expected format
859        let eoa_idx = 2u16;
860        let signature = [7u8; 64];
861
862        let instruction = build_delete_account_instruction(eoa_idx, &signature).unwrap();
863
864        // Expected format (matching tn_eoa_program.c):
865        // - Discriminant: u32 (4 bytes) = 2
866        // - EOA account index: u16 (2 bytes)
867        // - Signature: 64 bytes
868        // Total: 70 bytes
869        assert_eq!(instruction.len(), 70, "Instruction should be 70 bytes");
870
871        // Check discriminant (TN_EOA_INSTRUCTION_DELETE_ACCOUNT = 2)
872        let discriminant = u32::from_le_bytes([
873            instruction[0],
874            instruction[1],
875            instruction[2],
876            instruction[3],
877        ]);
878        assert_eq!(
879            discriminant, 2,
880            "Discriminant should be 2 for DELETE_ACCOUNT"
881        );
882
883        // Check eoa_account_idx
884        let parsed_idx = u16::from_le_bytes([instruction[4], instruction[5]]);
885        assert_eq!(parsed_idx, eoa_idx, "EOA index should match input");
886
887        // Check signature
888        assert_eq!(
889            &instruction[6..70],
890            &signature,
891            "Signature should match input"
892        );
893    }
894
895    #[test]
896    fn test_eoa_delete_message_layout() {
897        // The canonical delete message must be byte-identical to the runtime:
898        // "tn_eoa_delete_v1" || chain_id(LE) || fee_payer || eoa  (82 bytes).
899        let chain_id = 0x0102u16;
900        let fee_payer = [0xAAu8; 32];
901        let eoa = [0xBBu8; 32];
902
903        let msg = build_eoa_delete_message(chain_id, &fee_payer, &eoa);
904
905        assert_eq!(msg.len(), 82, "Message should be 82 bytes");
906        assert_eq!(&msg[0..16], b"tn_eoa_delete_v1", "Tag mismatch");
907        // chain_id little-endian: 0x0102 -> [0x02, 0x01]
908        assert_eq!(msg[16], 0x02, "chain_id low byte");
909        assert_eq!(msg[17], 0x01, "chain_id high byte");
910        assert_eq!(&msg[18..50], &fee_payer, "Fee payer mismatch");
911        assert_eq!(&msg[50..82], &eoa, "EOA pubkey mismatch");
912    }
913
914    #[test]
915    fn test_faucet_deposit_instruction_layout_with_fee_payer_depositor() {
916        let fee_payer = [1u8; 32];
917        let faucet_program = FAUCET_PROGRAM;
918        let faucet_account = [2u8; 32];
919        let depositor_account = fee_payer;
920        let amount = 500u64;
921
922        let tx = TransactionBuilder::build_faucet_deposit(
923            fee_payer,
924            faucet_program,
925            faucet_account,
926            depositor_account,
927            EOA_PROGRAM,
928            amount,
929            0,
930            42,
931            100,
932        )
933        .expect("build faucet deposit");
934
935        let rw_accs = tx.rw_accs.expect("rw accounts must exist");
936        assert_eq!(rw_accs.len(), 1);
937        assert_eq!(rw_accs[0], faucet_account);
938
939        let ro_accs = tx.r_accs.expect("ro accounts must exist");
940        assert_eq!(ro_accs.len(), 1);
941        assert_eq!(ro_accs[0], EOA_PROGRAM);
942
943        let instruction = tx.instructions.expect("instruction bytes must exist");
944        assert_eq!(
945            instruction.len(),
946            18,
947            "Deposit instruction must be 18 bytes"
948        );
949
950        let discriminant = u32::from_le_bytes([
951            instruction[0],
952            instruction[1],
953            instruction[2],
954            instruction[3],
955        ]);
956        assert_eq!(discriminant, 0, "Deposit discriminant should be 0");
957
958        let faucet_idx = u16::from_le_bytes([instruction[4], instruction[5]]);
959        let depositor_idx = u16::from_le_bytes([instruction[6], instruction[7]]);
960        let eoa_idx = u16::from_le_bytes([instruction[8], instruction[9]]);
961        let parsed_amount = u64::from_le_bytes([
962            instruction[10],
963            instruction[11],
964            instruction[12],
965            instruction[13],
966            instruction[14],
967            instruction[15],
968            instruction[16],
969            instruction[17],
970        ]);
971
972        assert_eq!(faucet_idx, 2, "Faucet account should be first RW account");
973        assert_eq!(depositor_idx, 0, "Depositor shares the fee payer index");
974        assert_eq!(eoa_idx, 3, "EOA program should follow RW accounts");
975        assert_eq!(parsed_amount, amount, "Amount should match input");
976    }
977
978    #[test]
979    fn test_build_token_initialize_mint() {
980        // Create test keypairs and addresses
981        let fee_payer = [1u8; 32];
982        let token_program = [2u8; 32];
983        let mint_account = [3u8; 32];
984        let creator = [4u8; 32];
985        let mint_authority = [5u8; 32];
986        let freeze_authority = [6u8; 32];
987
988        let decimals = 9u8;
989        let ticker = "TEST";
990        let seed = [7u8; 32];
991        let state_proof = vec![8u8; 64];
992
993        // Test with freeze authority
994        let result = TransactionBuilder::build_token_initialize_mint(
995            fee_payer,
996            token_program,
997            mint_account,
998            creator,
999            mint_authority,
1000            Some(freeze_authority),
1001            decimals,
1002            ticker,
1003            seed,
1004            state_proof.clone(),
1005            1000, // fee
1006            1,    // nonce
1007            100,  // start_slot
1008        );
1009
1010        assert!(
1011            result.is_ok(),
1012            "Should build valid transaction with freeze authority"
1013        );
1014        let tx = result.unwrap();
1015        assert!(
1016            tx.instructions.is_some(),
1017            "Transaction should have instructions"
1018        );
1019
1020        // Test without freeze authority
1021        let result_no_freeze = TransactionBuilder::build_token_initialize_mint(
1022            fee_payer,
1023            token_program,
1024            mint_account,
1025            creator,
1026            mint_authority,
1027            None,
1028            decimals,
1029            ticker,
1030            seed,
1031            state_proof,
1032            1000,
1033            1,
1034            100,
1035        );
1036
1037        assert!(
1038            result_no_freeze.is_ok(),
1039            "Should build valid transaction without freeze authority"
1040        );
1041    }
1042
1043    #[test]
1044    fn token_transfer_checked_instruction_matches_reference_vector() {
1045        let instruction =
1046            build_token_transfer_checked_instruction(2, 3, 4, 1_000_000, 6, b"USDC").unwrap();
1047        let expected: [u8; 25] = [
1048            0x08, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x00, 0x00, 0x00,
1049            0x00, 0x06, 0x04, 0x55, 0x53, 0x44, 0x43, 0x00, 0x00, 0x00, 0x00,
1050        ];
1051        assert_eq!(instruction.len(), 25);
1052        assert_eq!(instruction, expected);
1053    }
1054
1055    #[test]
1056    fn token_transfer_checked_instruction_ticker_forms() {
1057        // Empty ticker: length 0, eight zero bytes.
1058        let empty = build_token_transfer_checked_instruction(2, 3, 4, 1, 6, b"").unwrap();
1059        assert_eq!(empty.len(), 25);
1060        assert_eq!(&empty[16..25], &[0u8; 9]);
1061
1062        // Eight raw bytes (zero and 0xff included) are copied verbatim.
1063        let raw = [0xde, 0xad, 0xbe, 0xef, 0x00, 0x01, 0x02, 0xff];
1064        let full = build_token_transfer_checked_instruction(2, 3, 4, 1, 6, &raw).unwrap();
1065        assert_eq!(full.len(), 25);
1066        assert_eq!(full[16], 8);
1067        assert_eq!(&full[17..25], &raw);
1068
1069        // Seven characters stored with length 8 (trailing NUL counted).
1070        let nul = build_token_transfer_checked_instruction(2, 3, 4, 1, 6, b"EVECOIN\0").unwrap();
1071        assert_eq!(nul[16], 8);
1072        assert_eq!(&nul[17..25], b"EVECOIN\0");
1073
1074        // Nine bytes do not fit.
1075        assert!(build_token_transfer_checked_instruction(2, 3, 4, 1, 6, &[1u8; 9]).is_err());
1076
1077        // Extreme values land at their offsets; indices are little-endian.
1078        let max =
1079            build_token_transfer_checked_instruction(0x0102, 0x0304, 0x0506, u64::MAX, 255, b"AB")
1080                .unwrap();
1081        assert_eq!(&max[1..7], &[0x02, 0x01, 0x04, 0x03, 0x06, 0x05]);
1082        assert_eq!(&max[7..15], &u64::MAX.to_le_bytes());
1083        assert_eq!(max[15], 255);
1084        assert_eq!(max[16], 2);
1085        assert_eq!(&max[17..25], b"AB\0\0\0\0\0\0");
1086    }
1087
1088    #[test]
1089    fn build_token_transfer_checked_orders_accounts_and_indices() {
1090        let (fp, prog) = (key(1), key(2));
1091        let mint = key(3);
1092
1093        // Destination sorts before the source, the mint before both.
1094        let (source, dest) = (key(9), key(5));
1095        let tx = TransactionBuilder::build_token_transfer_checked(
1096            fp, prog, source, dest, mint, 7, 6, b"USDC", 1, 0, 0,
1097        )
1098        .unwrap();
1099        assert_eq!(tx.fee_payer, fp);
1100        assert_eq!(tx.program, prog);
1101        assert_eq!(tx.rw_accs.as_deref(), Some(&[dest, source][..]));
1102        assert_eq!(tx.r_accs.as_deref(), Some(&[mint][..]));
1103        let ix = tx.instructions.as_ref().unwrap();
1104        assert_eq!(ix[0], 8);
1105        assert_eq!(u16::from_le_bytes([ix[1], ix[2]]), 3, "source index");
1106        assert_eq!(u16::from_le_bytes([ix[3], ix[4]]), 2, "destination index");
1107        assert_eq!(u16::from_le_bytes([ix[5], ix[6]]), 4, "mint index");
1108
1109        // Source sorts first.
1110        let (source, dest) = (key(5), key(9));
1111        let tx = TransactionBuilder::build_token_transfer_checked(
1112            fp, prog, source, dest, mint, 7, 6, b"USDC", 1, 0, 0,
1113        )
1114        .unwrap();
1115        assert_eq!(tx.rw_accs.as_deref(), Some(&[source, dest][..]));
1116        let ix = tx.instructions.as_ref().unwrap();
1117        assert_eq!(u16::from_le_bytes([ix[1], ix[2]]), 2, "source index");
1118        assert_eq!(u16::from_le_bytes([ix[3], ix[4]]), 3, "destination index");
1119        assert_eq!(u16::from_le_bytes([ix[5], ix[6]]), 4, "mint index");
1120    }
1121
1122    #[test]
1123    fn build_token_transfer_checked_same_source_and_destination() {
1124        let (fp, prog, acct, mint) = (key(1), key(2), key(5), key(3));
1125        let tx = TransactionBuilder::build_token_transfer_checked(
1126            fp, prog, acct, acct, mint, 7, 6, b"USDC", 1, 0, 0,
1127        )
1128        .unwrap();
1129        assert_eq!(tx.rw_accs.as_deref(), Some(&[acct][..]));
1130        assert_eq!(tx.r_accs.as_deref(), Some(&[mint][..]));
1131        let ix = tx.instructions.as_ref().unwrap();
1132        assert_eq!(u16::from_le_bytes([ix[1], ix[2]]), 2, "source index");
1133        assert_eq!(u16::from_le_bytes([ix[3], ix[4]]), 2, "destination index");
1134        assert_eq!(u16::from_le_bytes([ix[5], ix[6]]), 3, "mint index");
1135    }
1136
1137    #[test]
1138    fn build_token_transfer_checked_rejects_long_ticker() {
1139        let result = TransactionBuilder::build_token_transfer_checked(
1140            key(1),
1141            key(2),
1142            key(5),
1143            key(9),
1144            key(3),
1145            7,
1146            6,
1147            &[b'A'; 9],
1148            1,
1149            0,
1150            0,
1151        );
1152        assert!(result.is_err());
1153    }
1154
1155    #[test]
1156    fn test_build_token_initialize_mint_instruction_format() {
1157        let mint_account_idx = 2u16;
1158        let decimals = 9u8;
1159        let creator = [1u8; 32];
1160        let mint_authority = [2u8; 32];
1161        let freeze_authority = [3u8; 32];
1162        let ticker = "TST";
1163        let seed = [4u8; 32];
1164        let state_proof = vec![5u8; 10];
1165
1166        let instruction = build_token_initialize_mint_instruction(
1167            mint_account_idx,
1168            decimals,
1169            creator,
1170            mint_authority,
1171            Some(freeze_authority),
1172            ticker,
1173            seed,
1174            state_proof.clone(),
1175        )
1176        .unwrap();
1177
1178        // Verify instruction structure
1179        // Tag (1) + mint_account_idx (2) + decimals (1) + creator (32) + mint_authority (32) +
1180        // freeze_authority (32) + has_freeze_authority (1) + ticker_len (1) + ticker_bytes (8) + seed (32) + proof
1181        let expected_min_size = 1 + 2 + 1 + 32 + 32 + 32 + 1 + 1 + 8 + 32 + state_proof.len();
1182        assert_eq!(instruction.len(), expected_min_size);
1183
1184        // Verify tag
1185        assert_eq!(
1186            instruction[0], 0,
1187            "First byte should be InitializeMint tag (0)"
1188        );
1189
1190        // Verify mint account index
1191        let parsed_idx = u16::from_le_bytes([instruction[1], instruction[2]]);
1192        assert_eq!(parsed_idx, mint_account_idx);
1193
1194        // Verify decimals
1195        assert_eq!(instruction[3], decimals);
1196
1197        // Verify creator is at correct position (bytes 4-35)
1198        assert_eq!(&instruction[4..36], &creator);
1199
1200        // Verify mint_authority is at correct position (bytes 36-67)
1201        assert_eq!(&instruction[36..68], &mint_authority);
1202
1203        // Verify freeze_authority is at correct position (bytes 68-99)
1204        assert_eq!(&instruction[68..100], &freeze_authority);
1205
1206        // Verify has_freeze_authority flag
1207        assert_eq!(instruction[100], 1);
1208    }
1209
1210    #[test]
1211    fn test_token_initialize_mint_creator_vs_mint_authority() {
1212        // Test that creator and mint_authority can be different
1213        let fee_payer = [1u8; 32];
1214        let token_program = [2u8; 32];
1215        let mint_account = [3u8; 32];
1216        let creator = [4u8; 32];
1217        let mint_authority = [5u8; 32]; // Different from creator
1218        let seed = [6u8; 32];
1219        let state_proof = vec![7u8; 32];
1220
1221        let result = TransactionBuilder::build_token_initialize_mint(
1222            fee_payer,
1223            token_program,
1224            mint_account,
1225            creator,
1226            mint_authority,
1227            None,
1228            9,
1229            "TEST",
1230            seed,
1231            state_proof,
1232            1000,
1233            1,
1234            100,
1235        );
1236
1237        assert!(
1238            result.is_ok(),
1239            "Should allow different creator and mint_authority"
1240        );
1241
1242        // Test that creator and mint_authority can be the same
1243        let result_same = TransactionBuilder::build_token_initialize_mint(
1244            fee_payer,
1245            token_program,
1246            mint_account,
1247            creator,
1248            creator, // Same as creator
1249            None,
1250            9,
1251            "TEST",
1252            seed,
1253            vec![7u8; 32],
1254            1000,
1255            1,
1256            100,
1257        );
1258
1259        assert!(
1260            result_same.is_ok(),
1261            "Should allow same creator and mint_authority"
1262        );
1263    }
1264
1265    #[test]
1266    fn test_build_activate_with_custom_accounts_sorts_accounts_and_indices() {
1267        let fee_payer = [0x10u8; 32];
1268        let accounts = ConsensusValidatorAccounts {
1269            program: [0xf0u8; 32],
1270            attestor_table: [0x30u8; 32],
1271            token_program: [0x90u8; 32],
1272            converted_vault: [0x40u8; 32],
1273            unclaimed_vault: [0x50u8; 32],
1274        };
1275        let source_token_account = [0x20u8; 32];
1276        let claim_authority = [0x60u8; 32];
1277        let bls_pk = [0x77u8; 96];
1278        let bls_pop = [0x88u8; 192];
1279
1280        let tx = TransactionBuilder::build_activate_with_accounts(
1281            fee_payer,
1282            accounts,
1283            source_token_account,
1284            bls_pk,
1285            bls_pop,
1286            claim_authority,
1287            123,
1288            0,
1289            9,
1290            44,
1291        )
1292        .expect("activate transaction should build");
1293
1294        assert_eq!(tx.program, accounts.program);
1295        assert_eq!(
1296            tx.rw_accs,
1297            Some(vec![
1298                source_token_account,
1299                accounts.attestor_table,
1300                accounts.converted_vault
1301            ])
1302        );
1303        assert_eq!(tx.r_accs, Some(vec![accounts.token_program]));
1304
1305        let instruction = tx.instructions.expect("instruction bytes must exist");
1306        assert_eq!(
1307            u32::from_le_bytes(instruction[0..4].try_into().unwrap()),
1308            1,
1309            "activate discriminant should be 1"
1310        );
1311        assert_eq!(
1312            u64::from_le_bytes(instruction[4..12].try_into().unwrap()),
1313            3,
1314            "attestor table should resolve to rw index 3"
1315        );
1316        assert_eq!(
1317            u16::from_le_bytes(instruction[12..14].try_into().unwrap()),
1318            5,
1319            "token program should resolve to ro index 5"
1320        );
1321        assert_eq!(
1322            u16::from_le_bytes(instruction[14..16].try_into().unwrap()),
1323            2,
1324            "source token account should resolve to rw index 2"
1325        );
1326        assert_eq!(
1327            u16::from_le_bytes(instruction[16..18].try_into().unwrap()),
1328            4,
1329            "converted vault should resolve to rw index 4"
1330        );
1331        let key_start = 20;
1332        assert_eq!(
1333            u16::from_le_bytes(instruction[18..key_start].try_into().unwrap()),
1334            0,
1335            "identity should remain fee payer index 0"
1336        );
1337        let proof_start = key_start + bls_pk.len();
1338        let claim_start = proof_start + bls_pop.len();
1339        let amount_start = claim_start + claim_authority.len();
1340        assert_eq!(&instruction[key_start..proof_start], &bls_pk);
1341        assert_eq!(&instruction[proof_start..claim_start], &bls_pop);
1342        assert_eq!(&instruction[claim_start..amount_start], &claim_authority);
1343        assert_eq!(
1344            &instruction[amount_start..],
1345            &123u64.to_le_bytes(),
1346            "proof must precede claim authority and token amount"
1347        );
1348    }
1349
1350    #[test]
1351    fn test_validator_program_requests_compute_for_proof() {
1352        let payer = [0x10u8; 32];
1353        let token_account = [0x20u8; 32];
1354        let activate = TransactionBuilder::build_activate(
1355            payer,
1356            token_account,
1357            [0x77; 96],
1358            [0x88; 192],
1359            payer,
1360            123,
1361            0,
1362            9,
1363            44,
1364        )
1365        .unwrap();
1366        let deactivate =
1367            TransactionBuilder::build_deactivate(payer, token_account, 0, 9, 44).unwrap();
1368
1369        assert_eq!(activate.req_compute_units, 1_000_000_000);
1370        assert_eq!(deactivate.req_compute_units, 500_000_000);
1371    }
1372
1373    #[test]
1374    fn test_build_deactivate_instruction_format() {
1375        let instruction = build_deactivate_instruction(7, 8, 9, 10, 0).unwrap();
1376
1377        assert_eq!(instruction.len(), 20);
1378        assert_eq!(
1379            u32::from_le_bytes(instruction[0..4].try_into().unwrap()),
1380            2,
1381            "deactivate discriminant should be 2"
1382        );
1383        assert_eq!(
1384            u64::from_le_bytes(instruction[4..12].try_into().unwrap()),
1385            7
1386        );
1387        assert_eq!(
1388            u16::from_le_bytes(instruction[12..14].try_into().unwrap()),
1389            8
1390        );
1391        assert_eq!(
1392            u16::from_le_bytes(instruction[14..16].try_into().unwrap()),
1393            9
1394        );
1395        assert_eq!(
1396            u16::from_le_bytes(instruction[16..18].try_into().unwrap()),
1397            10
1398        );
1399        assert_eq!(
1400            u16::from_le_bytes(instruction[18..20].try_into().unwrap()),
1401            0
1402        );
1403    }
1404
1405    #[test]
1406    fn test_build_convert_tokens_instruction_format() {
1407        let instruction = build_convert_tokens_instruction(11, 12, 13, 14, 0, 500).unwrap();
1408
1409        assert_eq!(instruction.len(), 28);
1410        assert_eq!(
1411            u32::from_le_bytes(instruction[0..4].try_into().unwrap()),
1412            3,
1413            "convert-tokens discriminant should be 3"
1414        );
1415        assert_eq!(
1416            u64::from_le_bytes(instruction[4..12].try_into().unwrap()),
1417            11
1418        );
1419        assert_eq!(
1420            u16::from_le_bytes(instruction[12..14].try_into().unwrap()),
1421            12
1422        );
1423        assert_eq!(
1424            u16::from_le_bytes(instruction[14..16].try_into().unwrap()),
1425            13
1426        );
1427        assert_eq!(
1428            u16::from_le_bytes(instruction[16..18].try_into().unwrap()),
1429            14
1430        );
1431        assert_eq!(
1432            u16::from_le_bytes(instruction[18..20].try_into().unwrap()),
1433            0
1434        );
1435        assert_eq!(
1436            u64::from_le_bytes(instruction[20..28].try_into().unwrap()),
1437            500
1438        );
1439    }
1440
1441    #[test]
1442    fn test_build_claim_instruction_format() {
1443        let subject_attestor = [0xabu8; 32];
1444        let instruction = build_claim_instruction(15, 16, 17, 18, 0, subject_attestor).unwrap();
1445
1446        assert_eq!(instruction.len(), 52);
1447        assert_eq!(
1448            u32::from_le_bytes(instruction[0..4].try_into().unwrap()),
1449            4,
1450            "claim discriminant should be 4"
1451        );
1452        assert_eq!(
1453            u64::from_le_bytes(instruction[4..12].try_into().unwrap()),
1454            15
1455        );
1456        assert_eq!(
1457            u16::from_le_bytes(instruction[12..14].try_into().unwrap()),
1458            16
1459        );
1460        assert_eq!(
1461            u16::from_le_bytes(instruction[14..16].try_into().unwrap()),
1462            17
1463        );
1464        assert_eq!(
1465            u16::from_le_bytes(instruction[16..18].try_into().unwrap()),
1466            18
1467        );
1468        assert_eq!(
1469            u16::from_le_bytes(instruction[18..20].try_into().unwrap()),
1470            0
1471        );
1472        assert_eq!(&instruction[20..52], &subject_attestor);
1473    }
1474
1475    #[test]
1476    fn test_build_set_claim_authority_instruction_format() {
1477        let subject_attestor = [0x55u8; 32];
1478        let new_claim_authority = [0x66u8; 32];
1479        let instruction =
1480            build_set_claim_authority_instruction(19, 0, subject_attestor, new_claim_authority)
1481                .unwrap();
1482
1483        assert_eq!(instruction.len(), 78);
1484        assert_eq!(
1485            u32::from_le_bytes(instruction[0..4].try_into().unwrap()),
1486            5,
1487            "set-claim-authority discriminant should be 5"
1488        );
1489        assert_eq!(
1490            u64::from_le_bytes(instruction[4..12].try_into().unwrap()),
1491            19
1492        );
1493        assert_eq!(
1494            u16::from_le_bytes(instruction[12..14].try_into().unwrap()),
1495            0
1496        );
1497        assert_eq!(&instruction[14..46], &subject_attestor);
1498        assert_eq!(&instruction[46..78], &new_claim_authority);
1499    }
1500
1501    /* ------------------------------------------------------------------ */
1502    /* Block-producer (BP) bond builder tests                              */
1503    /* ------------------------------------------------------------------ */
1504
1505    /// Cross-language guard: the Rust bond/TA derivation must byte-match the C
1506    /// contract in tn_block_producer_derivation.h.  The expected vectors below
1507    /// were computed directly from that contract (signer=0x11*32,
1508    /// legacy bp_program=0x0D01, token_program=0xAA, and the legacy WTHRU mint).
1509    /// If this drifts, the CLI would derive a different bond PDA than the program
1510    /// re-derives and every create would revert with BOND_ADDR_MISMATCH.
1511    #[test]
1512    fn test_bp_bond_legacy_derivation_matches_c() {
1513        let signer = [0x11u8; 32];
1514        let mut bp_program = [0u8; 32];
1515        bp_program[30] = 0x0D;
1516        bp_program[31] = 0x01;
1517        let mut token_program = [0u8; 32];
1518        token_program[31] = 0xAA;
1519        let wthru_mint: [u8; 32] = [
1520            0x71, 0xD8, 0x13, 0x50, 0x6B, 0x9D, 0xF0, 0xE8, 0x33, 0x37, 0x91, 0xE7, 0x55, 0x5B,
1521            0xF8, 0xBB, 0x7C, 0x7C, 0xD9, 0x40, 0x5E, 0xF1, 0xC8, 0x99, 0x02, 0xD8, 0xCE, 0x2C,
1522            0x96, 0x44, 0xFD, 0x23,
1523        ];
1524
1525        let expected_bond: [u8; 32] = [
1526            0x79, 0x2e, 0x8c, 0x94, 0x08, 0xa3, 0x9e, 0x2e, 0x67, 0xcf, 0xf8, 0x67, 0x28, 0xc5,
1527            0xd5, 0x90, 0x7c, 0xa1, 0x01, 0x44, 0x52, 0x15, 0xd4, 0x91, 0x59, 0x5c, 0xb6, 0x9d,
1528            0xe4, 0x9f, 0xca, 0x6d,
1529        ];
1530        let expected_bond_ta: [u8; 32] = [
1531            0xbc, 0xa7, 0x94, 0x54, 0x6c, 0xf0, 0xa2, 0xe5, 0x7e, 0xf0, 0x01, 0xac, 0x54, 0xac,
1532            0xe3, 0x03, 0xbb, 0x1b, 0xf4, 0x4e, 0xd7, 0x04, 0x93, 0xaf, 0x56, 0x65, 0xea, 0x38,
1533            0x19, 0x39, 0xb2, 0x24,
1534        ];
1535
1536        assert_eq!(bp_bond_account_address(&bp_program, &signer), expected_bond);
1537        assert_eq!(
1538            bp_bond_ta_address(&token_program, &bp_program, &wthru_mint, &signer),
1539            expected_bond_ta
1540        );
1541    }
1542
1543    /// The default vaults are the token accounts Init creates, not the retired
1544    /// PDA(program, seed) state addresses.  The pinned bytes were computed
1545    /// independently (python hashlib).
1546    #[test]
1547    fn consensus_default_vaults_match_init_derivation() {
1548        use crate::tn_public_address::{
1549            create_program_defined_account_address, tn_pubkey_to_address_string,
1550        };
1551        let accounts = ConsensusValidatorAccounts::default();
1552        assert_eq!(
1553            tn_pubkey_to_address_string(&accounts.converted_vault),
1554            "tau1YuXs3QDzkjPJXXHACa-5QetQacxoB2Sx1UYAz8yhrL"
1555        );
1556        assert_eq!(
1557            hex::encode(accounts.converted_vault),
1558            "bb562e5ecdd00f39233c95d71c009afb941eb5069cc680764b1d54600cfcca1a"
1559        );
1560        assert_eq!(
1561            tn_pubkey_to_address_string(&accounts.unclaimed_vault),
1562            "taTQvE1X-dPasR88rBCQakbwleuiEUkxyjA1gwmKnGYbT1"
1563        );
1564        assert_eq!(
1565            hex::encode(accounts.unclaimed_vault),
1566            "4d0bc4d57f9d3dab11f3cac10906a46f095eba2114931ca303583098a9c661b4"
1567        );
1568        for (vault, seed) in [
1569            (accounts.converted_vault, CONSENSUS_CONVERTED_VAULT_SEED),
1570            (accounts.unclaimed_vault, CONSENSUS_UNCLAIMED_VAULT_SEED),
1571        ] {
1572            let mut padded = [0u8; 32];
1573            padded[..seed.len()].copy_from_slice(seed);
1574            let retired = create_program_defined_account_address(
1575                &CONSENSUS_VALIDATOR_PROGRAM,
1576                false,
1577                &padded,
1578            );
1579            assert_ne!(vault, retired);
1580        }
1581    }
1582
1583    /// The canonical WTHRU mint derivation must equal TN_WTHRU_MINT_ADDR_BYTES from
1584    /// programs/c/examples/tn_wthru_mint.h, since the bond TA derivation depends
1585    /// on the mint bytes.
1586    #[test]
1587    fn test_wthru_canonical_mint_matches_c() {
1588        use sha2::{Digest, Sha256};
1589        use crate::bootstrap_addresses::{TOKEN_PROGRAM_BYTES, WTHRU_MINT_BYTES, WTHRU_PROGRAM_BYTES};
1590        let wthru_program = WTHRU_PROGRAM_BYTES;
1591        let token_program = TOKEN_PROGRAM_BYTES;
1592        let mut mint_seed = [0u8; 32];
1593        mint_seed[..5].copy_from_slice(b"wthru");
1594
1595        let inner = {
1596            let mut h = Sha256::new();
1597            h.update(wthru_program);
1598            h.update(mint_seed);
1599            let d = h.finalize();
1600            let mut s = [0u8; 32];
1601            s.copy_from_slice(&d[..32]);
1602            s
1603        };
1604        let mint = crate::tn_public_address::create_program_defined_account_address(
1605            &token_program,
1606            false,
1607            &inner,
1608        );
1609        assert_eq!(mint, WTHRU_MINT_BYTES);
1610    }
1611
1612    #[test]
1613    fn test_bp_create_account_mode1_layout() {
1614        let fee_payer = [0x01u8; 32]; // == signer in Mode 1
1615        let bp_program = [0xf0u8; 32];
1616        let token_program = [0x90u8; 32];
1617        let bond_account = [0x20u8; 32];
1618        let bond_ta = [0x30u8; 32];
1619        let mint = [0x40u8; 32];
1620        let signer = fee_payer; // Mode 1: signer is the fee payer
1621        let authority = [0x55u8; 32];
1622
1623        let tx = TransactionBuilder::build_bp_create_account(
1624            fee_payer,
1625            bp_program,
1626            token_program,
1627            bond_account,
1628            bond_ta,
1629            mint,
1630            signer,
1631            authority,
1632            false,         // Mode 1
1633            [0u8; 64],     // no signature
1634            vec![0xAA; 8], // bond proof
1635            vec![0xBB; 8], // ta proof
1636            vec![],        // no eoa proof
1637            0,
1638            0,
1639            5,
1640        )
1641        .expect("mode1 create should build");
1642        assert!(tx.req_memory_units <= 10_000, "default thrud admission");
1643
1644        let instr = tx.instructions.expect("instruction bytes");
1645        assert_eq!(
1646            u32::from_le_bytes(instr[0..4].try_into().unwrap()),
1647            TN_BP_INSTRUCTION_CREATE_ACCOUNT
1648        );
1649        // create_signer_eoa byte is at offset 4 + 10 = 14
1650        assert_eq!(instr[14], 0u8, "Mode 1 create_signer_eoa must be 0");
1651        assert_eq!(instr[15], 0u8, "reserved must be 0");
1652        // signer_pubkey at 16..48, bond_authority at 48..80
1653        assert_eq!(&instr[16..48], &signer);
1654        assert_eq!(&instr[48..80], &authority);
1655        // proof sizes at 144..152 (bond), 152..160 (ta), 160..168 (eoa)
1656        assert_eq!(u64::from_le_bytes(instr[144..152].try_into().unwrap()), 8);
1657        assert_eq!(u64::from_le_bytes(instr[152..160].try_into().unwrap()), 8);
1658        assert_eq!(
1659            u64::from_le_bytes(instr[160..168].try_into().unwrap()),
1660            0,
1661            "Mode 1 eoa_proof_size must be 0"
1662        );
1663        // 164-byte args header + 16 bytes of proofs
1664        assert_eq!(instr.len(), 4 + 164 + 16);
1665        // The signer EOA is not added as an account in Mode 1.
1666        assert!(!tx.rw_accs.clone().unwrap_or_default().contains(&signer) || signer == fee_payer);
1667    }
1668
1669    #[test]
1670    fn test_bp_create_account_mode2_layout() {
1671        let fee_payer = [0x01u8; 32];
1672        let bp_program = [0xf0u8; 32];
1673        let token_program = [0x90u8; 32];
1674        let bond_account = [0x20u8; 32];
1675        let bond_ta = [0x30u8; 32];
1676        let mint = [0x40u8; 32];
1677        let signer = [0x2au8; 32]; // distinct from fee payer
1678        let authority = [0x55u8; 32];
1679        let sig = [0x77u8; 64];
1680
1681        let tx = TransactionBuilder::build_bp_create_account(
1682            fee_payer,
1683            bp_program,
1684            token_program,
1685            bond_account,
1686            bond_ta,
1687            mint,
1688            signer,
1689            authority,
1690            true, // Mode 2
1691            sig,
1692            vec![0xAA; 8],
1693            vec![0xBB; 8],
1694            vec![0xCC; 12], // eoa proof
1695            0,
1696            0,
1697            5,
1698        )
1699        .expect("mode2 create should build");
1700        assert!(tx.req_memory_units <= 10_000, "default thrud admission");
1701
1702        let instr = tx.instructions.expect("instruction bytes");
1703        assert_eq!(instr[14], 1u8, "Mode 2 create_signer_eoa must be 1");
1704        assert_eq!(&instr[80..144], &sig, "signature must be embedded");
1705        assert_eq!(u64::from_le_bytes(instr[144..152].try_into().unwrap()), 8);
1706        assert_eq!(u64::from_le_bytes(instr[152..160].try_into().unwrap()), 8);
1707        assert_eq!(
1708            u64::from_le_bytes(instr[160..168].try_into().unwrap()),
1709            12,
1710            "Mode 2 eoa_proof_size must be the eoa proof len"
1711        );
1712        assert_eq!(instr.len(), 4 + 164 + 8 + 8 + 12);
1713        // The signer EOA (== signer_pubkey) must be a writable account.
1714        assert!(
1715            tx.rw_accs.clone().unwrap_or_default().contains(&signer),
1716            "Mode 2 signer EOA must be in the writable set"
1717        );
1718        // signer_eoa_idx (offset 4+8=12) must be a valid, non-zero index.
1719        let signer_eoa_idx = u16::from_le_bytes(instr[12..14].try_into().unwrap());
1720        assert!(
1721            signer_eoa_idx >= 2,
1722            "signer EOA must not collide with fee payer/program"
1723        );
1724    }
1725
1726    #[test]
1727    fn test_bp_delete_dest_equals_fee_payer() {
1728        let fee_payer = [0x09u8; 32];
1729        let bp_program = [0xf0u8; 32];
1730        let bond_account = [0x20u8; 32];
1731
1732        let tx = TransactionBuilder::build_bp_delete_account(
1733            fee_payer,
1734            bp_program,
1735            bond_account,
1736            fee_payer, // dest == fee payer
1737            0,
1738            0,
1739            5,
1740        )
1741        .expect("delete should build");
1742
1743        let instr = tx.instructions.expect("instruction bytes");
1744        assert_eq!(
1745            u32::from_le_bytes(instr[0..4].try_into().unwrap()),
1746            TN_BP_INSTRUCTION_DELETE_ACCOUNT
1747        );
1748        let dest_idx = u16::from_le_bytes(instr[6..8].try_into().unwrap());
1749        assert_eq!(dest_idx, 0u16, "dest==fee-payer must collapse to index 0");
1750    }
1751
1752    #[test]
1753    fn test_bp_sign_eoa_creation_verifies() {
1754        use ed25519_dalek::{Signature, SigningKey, Verifier};
1755        let priv_key = [0x2au8; 32];
1756        let signing_key = SigningKey::from_bytes(&priv_key);
1757        let verifying_key = signing_key.verifying_key();
1758        let signer: TnPubkey = verifying_key.to_bytes();
1759        let fee_payer: TnPubkey = [0x5cu8; 32];
1760        let chain_id: u16 = 1;
1761        let sig_bytes = bp_sign_eoa_creation(&priv_key, chain_id, &fee_payer, &signer);
1762        let signature = Signature::from_bytes(&sig_bytes);
1763        // Strict Ed25519 over the 82-byte canonical EOA-create authorization --
1764        // what tsys_account_create_eoa checks (tn_vm_syscall_account_create_eoa).
1765        let msg = build_eoa_create_message(chain_id, &fee_payer, &signer);
1766        assert_eq!(msg.len(), EOA_CREATE_MSG_SZ);
1767        assert!(verifying_key.verify_strict(&msg, &signature).is_ok());
1768        // The pre-#2927 zero-byte message must NOT verify: that is the bug that
1769        // made every Mode 2 bond create revert with SYSCALL_INVALID_SIGNATURE.
1770        assert!(verifying_key.verify_strict(&[0u8; 32], &signature).is_err());
1771        // Binding: a different fee payer or chain id yields a different message.
1772        let other_payer_msg = build_eoa_create_message(chain_id, &[0u8; 32], &signer);
1773        let other_chain_msg = build_eoa_create_message(2, &fee_payer, &signer);
1774        assert!(verifying_key
1775                .verify_strict(&other_payer_msg, &signature)
1776            .is_err());
1777        assert!(verifying_key
1778                .verify_strict(&other_chain_msg, &signature)
1779            .is_err());
1780    }
1781
1782    fn key(byte: u8) -> TnPubkey {
1783        [byte; 32]
1784    }
1785
1786    #[test]
1787    fn validator_and_bond_requests_fit_default_thrud_memory_limit() {
1788        let (payer, program) = (key(1), key(2));
1789        for tx in [
1790            build_consensus_validator_tx(payer, program, 1, 0, 0),
1791            bp_base_tx(payer, program, 1, 0, 0),
1792        ] {
1793            assert!(tx.req_memory_units <= 10_000);
1794        }
1795    }
1796
1797    /// A request above zero is rejected whenever the chain has no active-state
1798    /// headroom, so builders that neither create nor grow accounts request none.
1799    #[test]
1800    fn non_growing_builders_request_no_state_units() {
1801        let (fp, prog, a, b, c, d) = (key(1), key(2), key(3), key(4), key(5), key(6));
1802        let (e, f) = (key(7), key(8));
1803        let cases: Vec<(&str, Transaction)> = vec![
1804            ("bp_base_tx", bp_base_tx(fp, prog, 1, 0, 0)),
1805            (
1806                "build_consensus_validator_tx",
1807                build_consensus_validator_tx(fp, prog, 1, 0, 0),
1808            ),
1809            (
1810                "build_transfer",
1811                TransactionBuilder::build_transfer(fp, prog, a, 5, 1, 0, 0).unwrap(),
1812            ),
1813            (
1814                "build_delete_account",
1815                TransactionBuilder::build_delete_account(fp, prog, a, &[0u8; 64], 1, 1, 0, 0)
1816                    .unwrap(),
1817            ),
1818            (
1819                "build_write_data",
1820                TransactionBuilder::build_write_data(fp, prog, a, 0, &[1, 2, 3], 1, 0, 0).unwrap(),
1821            ),
1822            (
1823                "build_uploader_write",
1824                TransactionBuilder::build_uploader_write(fp, prog, a, b, &[1, 2, 3], 0, 1, 0, 0)
1825                    .unwrap(),
1826            ),
1827            (
1828                "build_uploader_finalize",
1829                TransactionBuilder::build_uploader_finalize(fp, prog, a, b, 3, [0u8; 32], 1, 0, 0)
1830                    .unwrap(),
1831            ),
1832            (
1833                "build_uploader_destroy",
1834                TransactionBuilder::build_uploader_destroy(fp, prog, a, b, 1, 0, 0).unwrap(),
1835            ),
1836            (
1837                "build_abi_manager_finalize_abi_official",
1838                TransactionBuilder::build_abi_manager_finalize_abi_official(
1839                    fp, prog, a, b, c, fp, 1, 0, 0,
1840                )
1841                .unwrap(),
1842            ),
1843            (
1844                "build_abi_manager_finalize_abi_external",
1845                TransactionBuilder::build_abi_manager_finalize_abi_external(
1846                    fp, prog, a, b, fp, 1, 0, 0,
1847                )
1848                .unwrap(),
1849            ),
1850            (
1851                "build_abi_manager_close_abi_official",
1852                TransactionBuilder::build_abi_manager_close_abi_official(
1853                    fp, prog, a, b, c, fp, 1, 0, 0,
1854                )
1855                .unwrap(),
1856            ),
1857            (
1858                "build_abi_manager_close_abi_external",
1859                TransactionBuilder::build_abi_manager_close_abi_external(
1860                    fp, prog, a, b, fp, 1, 0, 0,
1861                )
1862                .unwrap(),
1863            ),
1864            (
1865                "build_manager_set_pause",
1866                TransactionBuilder::build_manager_set_pause(fp, prog, a, b, true, 1, 0, 0).unwrap(),
1867            ),
1868            (
1869                "build_manager_simple",
1870                TransactionBuilder::build_manager_simple(
1871                    fp,
1872                    prog,
1873                    a,
1874                    b,
1875                    MANAGER_INSTRUCTION_FINALIZE,
1876                    1,
1877                    0,
1878                    0,
1879                )
1880                .unwrap(),
1881            ),
1882            (
1883                "build_manager_set_authority",
1884                TransactionBuilder::build_manager_set_authority(fp, prog, a, b, c, 1, 0, 0)
1885                    .unwrap(),
1886            ),
1887            (
1888                "build_test_uploader_write",
1889                TransactionBuilder::build_test_uploader_write(fp, prog, a, 0, &[1, 2, 3], 1, 0, 0)
1890                    .unwrap(),
1891            ),
1892            (
1893                "build_token_transfer",
1894                TransactionBuilder::build_token_transfer(fp, prog, a, b, fp, 5, 1, 0, 0).unwrap(),
1895            ),
1896            (
1897                "build_token_transfer_checked",
1898                TransactionBuilder::build_token_transfer_checked(
1899                    fp, prog, a, b, c, 5, 6, b"USDC", 1, 0, 0,
1900                )
1901                .unwrap(),
1902            ),
1903            (
1904                "build_token_mint_to",
1905                TransactionBuilder::build_token_mint_to(fp, prog, a, b, fp, 5, 1, 0, 0).unwrap(),
1906            ),
1907            (
1908                "build_token_burn",
1909                TransactionBuilder::build_token_burn(fp, prog, a, b, fp, 5, 1, 0, 0).unwrap(),
1910            ),
1911            (
1912                "build_token_freeze_account",
1913                TransactionBuilder::build_token_freeze_account(fp, prog, a, b, fp, 1, 0, 0)
1914                    .unwrap(),
1915            ),
1916            (
1917                "build_token_thaw_account",
1918                TransactionBuilder::build_token_thaw_account(fp, prog, a, b, fp, 1, 0, 0).unwrap(),
1919            ),
1920            (
1921                "build_token_close_account",
1922                TransactionBuilder::build_token_close_account(fp, prog, a, b, fp, 1, 0, 0).unwrap(),
1923            ),
1924            (
1925                "build_wthru_deposit",
1926                TransactionBuilder::build_wthru_deposit(fp, prog, a, b, c, d, 1, 0, 0).unwrap(),
1927            ),
1928            (
1929                "build_wthru_deposit_with_transfer",
1930                TransactionBuilder::build_wthru_deposit_with_transfer(
1931                    fp, prog, a, b, c, d, e, f, 5, 1, 0, 0,
1932                )
1933                .unwrap(),
1934            ),
1935            (
1936                "build_wthru_withdraw",
1937                TransactionBuilder::build_wthru_withdraw(fp, prog, a, b, c, d, e, 5, 1, 0, 0)
1938                    .unwrap(),
1939            ),
1940            (
1941                "build_faucet_deposit",
1942                TransactionBuilder::build_faucet_deposit(fp, prog, a, b, c, 5, 1, 0, 0).unwrap(),
1943            ),
1944            (
1945                "build_faucet_withdraw",
1946                TransactionBuilder::build_faucet_withdraw(fp, prog, a, b, 5, 1, 0, 0).unwrap(),
1947            ),
1948            (
1949                "build_name_service_delete_record",
1950                TransactionBuilder::build_name_service_delete_record(
1951                    fp, prog, a, fp, b"key", 1, 0, 0,
1952                )
1953                .unwrap(),
1954            ),
1955            (
1956                "build_name_service_unregister_subdomain",
1957                TransactionBuilder::build_name_service_unregister_subdomain(
1958                    fp, prog, a, fp, 1, 0, 0,
1959                )
1960                .unwrap(),
1961            ),
1962            (
1963                "build_thru_registrar_renew_lease",
1964                TransactionBuilder::build_thru_registrar_renew_lease(
1965                    fp, prog, a, b, c, d, e, f, 1, 1, 0, 0,
1966                )
1967                .unwrap(),
1968            ),
1969            (
1970                "build_thru_registrar_claim_expired_domain",
1971                TransactionBuilder::build_thru_registrar_claim_expired_domain(
1972                    fp, prog, a, b, c, d, e, f, 1, 1, 0, 0,
1973                )
1974                .unwrap(),
1975            ),
1976            (
1977                "build_bp_deposit",
1978                TransactionBuilder::build_bp_deposit(fp, prog, a, b, c, d, 5, 1, 0, 0).unwrap(),
1979            ),
1980        ];
1981        for (name, tx) in cases {
1982            assert_eq!(tx.req_state_units, 0, "{name}");
1983        }
1984    }
1985
1986    /// The atomic WTHRU deposit is one Multicall transaction: the EOA transfer
1987    /// from the fee payer into the vault first, then the WTHRU deposit, with
1988    /// every index pointing at the right account.
1989    #[test]
1990    fn wthru_deposit_with_transfer_batches_transfer_then_deposit() {
1991        let (fee_payer, multicall) = (key(1), key(2));
1992        // Distinct sort orders so a wrong index cannot pass by accident.
1993        let (vault, dest, mint) = (key(0x10), key(0x20), key(0x30));
1994        let (eoa, wthru, token) = (key(0x40), key(0x50), key(0x60));
1995        let amount = 1_234_567u64;
1996
1997        let tx = TransactionBuilder::build_wthru_deposit_with_transfer(
1998            fee_payer, multicall, eoa, wthru, token, mint, vault, dest, amount, 1, 9, 77,
1999        )
2000        .unwrap();
2001
2002        assert_eq!(tx.fee_payer, fee_payer);
2003        assert_eq!(tx.program, multicall);
2004        assert_eq!((tx.fee, tx.nonce, tx.start_slot), (1, 9, 77));
2005        assert_eq!(tx.req_compute_units, WTHRU_DEPOSIT_WITH_TRANSFER_COMPUTE_UNITS);
2006        assert_eq!(tx.req_state_units, 0);
2007
2008        // [0] fee payer, [1] multicall, rw sorted, then ro sorted.
2009        assert_eq!(tx.rw_accs.clone().unwrap(), vec![vault, dest, mint]);
2010        assert_eq!(tx.r_accs.clone().unwrap(), vec![eoa, wthru, token]);
2011        let (vault_idx, dest_idx, mint_idx) = (2u16, 3u16, 4u16);
2012        let (eoa_idx, wthru_idx, token_idx) = (5u16, 6u16, 7u16);
2013
2014        // Decode the Multicall instruction: u16 count, then per call a u16
2015        // program index, a u64 length and the callee's instruction data.
2016        let data = tx.instructions.clone().unwrap();
2017        assert_eq!(u16::from_le_bytes([data[0], data[1]]), 2);
2018        let mut off = 2usize;
2019        let mut calls = Vec::new();
2020        for _ in 0..2 {
2021            let program_idx = u16::from_le_bytes([data[off], data[off + 1]]);
2022            let len = u64::from_le_bytes(data[off + 2..off + 10].try_into().unwrap()) as usize;
2023            calls.push((program_idx, data[off + 10..off + 10 + len].to_vec()));
2024            off += 10 + len;
2025        }
2026        assert_eq!(off, data.len());
2027
2028        // Call 1: EOA Transfer { amount, from: fee payer, to: vault }.
2029        let mut transfer = 1u32.to_le_bytes().to_vec();
2030        transfer.extend_from_slice(&amount.to_le_bytes());
2031        transfer.extend_from_slice(&0u16.to_le_bytes());
2032        transfer.extend_from_slice(&vault_idx.to_le_bytes());
2033        assert_eq!(calls[0], (eoa_idx, transfer));
2034
2035        // Call 2: WTHRU Deposit { token_program, vault, mint, dest }.
2036        let mut deposit = TN_WTHRU_INSTRUCTION_DEPOSIT.to_le_bytes().to_vec();
2037        for idx in [token_idx, vault_idx, mint_idx, dest_idx] {
2038            deposit.extend_from_slice(&idx.to_le_bytes());
2039        }
2040        assert_eq!(calls[1], (wthru_idx, deposit));
2041
2042        // The deposit call is byte-identical to the standalone deposit
2043        // instruction built against the same indices.
2044        assert_eq!(
2045            calls[1].1,
2046            build_wthru_deposit_instruction(token_idx, vault_idx, mint_idx, dest_idx).unwrap()
2047        );
2048    }
2049
2050    /// Builders that create accounts request one unit per new account footprint.
2051    #[test]
2052    fn creating_builders_request_their_account_state_units() {
2053        let (fp, prog, a, b, c, d) = (key(1), key(2), key(3), key(4), key(5), key(6));
2054        let (e, f, g, h) = (key(7), key(8), key(9), key(10));
2055        let proof = vec![0u8; 64];
2056        let fee_payer_proof = StateProof::creation(100, [0u8; 32], [7u8; 32], [8u8; 32], vec![]);
2057        let cases: Vec<(&str, Transaction, u16)> = vec![
2058            (
2059                "build_create_with_fee_payer_proof",
2060                TransactionBuilder::build_create_with_fee_payer_proof(fp, 0, &fee_payer_proof)
2061                    .unwrap(),
2062                1,
2063            ),
2064            (
2065                "build_create_account",
2066                TransactionBuilder::build_create_account(
2067                    fp,
2068                    prog,
2069                    a,
2070                    "5eed",
2071                    Some(&proof),
2072                    1,
2073                    0,
2074                    0,
2075                )
2076                .unwrap(),
2077                1,
2078            ),
2079            (
2080                "build_create_ephemeral_account",
2081                TransactionBuilder::build_create_ephemeral_account(
2082                    fp, prog, a, &[1u8; 32], 1, 0, 0,
2083                )
2084                .unwrap(),
2085                1,
2086            ),
2087            (
2088                "build_token_initialize_mint",
2089                TransactionBuilder::build_token_initialize_mint(
2090                    fp,
2091                    prog,
2092                    a,
2093                    fp,
2094                    fp,
2095                    None,
2096                    6,
2097                    "TKN",
2098                    [1u8; 32],
2099                    proof.clone(),
2100                    1,
2101                    0,
2102                    0,
2103                )
2104                .unwrap(),
2105                1,
2106            ),
2107            (
2108                "build_token_initialize_account",
2109                TransactionBuilder::build_token_initialize_account(
2110                    fp,
2111                    prog,
2112                    a,
2113                    b,
2114                    fp,
2115                    [1u8; 32],
2116                    proof.clone(),
2117                    1,
2118                    0,
2119                    0,
2120                )
2121                .unwrap(),
2122                1,
2123            ),
2124            (
2125                "build_wthru_initialize_mint",
2126                TransactionBuilder::build_wthru_initialize_mint(
2127                    fp,
2128                    prog,
2129                    a,
2130                    b,
2131                    c,
2132                    9,
2133                    [1u8; 32],
2134                    proof.clone(),
2135                    proof.clone(),
2136                    1,
2137                    0,
2138                    0,
2139                )
2140                .unwrap(),
2141                2,
2142            ),
2143            (
2144                "build_name_service_initialize_root",
2145                TransactionBuilder::build_name_service_initialize_root(
2146                    fp,
2147                    prog,
2148                    a,
2149                    fp,
2150                    "thru",
2151                    proof.clone(),
2152                    1,
2153                    0,
2154                    0,
2155                )
2156                .unwrap(),
2157                1,
2158            ),
2159            (
2160                "build_name_service_register_subdomain",
2161                TransactionBuilder::build_name_service_register_subdomain(
2162                    fp,
2163                    prog,
2164                    a,
2165                    b,
2166                    fp,
2167                    fp,
2168                    "name",
2169                    proof.clone(),
2170                    1,
2171                    0,
2172                    0,
2173                )
2174                .unwrap(),
2175                1,
2176            ),
2177            (
2178                "build_thru_registrar_initialize_registry",
2179                TransactionBuilder::build_thru_registrar_initialize_registry(
2180                    fp,
2181                    prog,
2182                    a,
2183                    b,
2184                    c,
2185                    d,
2186                    e,
2187                    f,
2188                    "thru",
2189                    1,
2190                    proof.clone(),
2191                    proof.clone(),
2192                    1,
2193                    0,
2194                    0,
2195                )
2196                .unwrap(),
2197                2,
2198            ),
2199            (
2200                "build_thru_registrar_purchase_domain",
2201                TransactionBuilder::build_thru_registrar_purchase_domain(
2202                    fp,
2203                    prog,
2204                    a,
2205                    b,
2206                    c,
2207                    d,
2208                    e,
2209                    f,
2210                    g,
2211                    h,
2212                    key(11),
2213                    "name",
2214                    1,
2215                    proof.clone(),
2216                    proof.clone(),
2217                    1,
2218                    0,
2219                    0,
2220                )
2221                .unwrap(),
2222                2,
2223            ),
2224            (
2225                "build_bp_create_account",
2226                TransactionBuilder::build_bp_create_account(
2227                    fp,
2228                    prog,
2229                    a,
2230                    b,
2231                    c,
2232                    d,
2233                    e,
2234                    fp,
2235                    false,
2236                    [0u8; 64],
2237                    proof.clone(),
2238                    proof.clone(),
2239                    vec![],
2240                    1,
2241                    0,
2242                    0,
2243                )
2244                .unwrap(),
2245                2,
2246            ),
2247            (
2248                "build_bp_create_account with signer EOA",
2249                TransactionBuilder::build_bp_create_account(
2250                    fp,
2251                    prog,
2252                    a,
2253                    b,
2254                    c,
2255                    d,
2256                    e,
2257                    fp,
2258                    true,
2259                    [0u8; 64],
2260                    proof.clone(),
2261                    proof.clone(),
2262                    proof.clone(),
2263                    1,
2264                    0,
2265                    0,
2266                )
2267                .unwrap(),
2268                3,
2269            ),
2270        ];
2271        for (name, tx, expected) in cases {
2272            assert_eq!(tx.req_state_units, expected, "{name}");
2273        }
2274    }
2275}
2276
2277/// Uploader program instruction discriminants
2278pub const TN_UPLOADER_PROGRAM_INSTRUCTION_CREATE: u32 = 0x00;
2279pub const TN_UPLOADER_PROGRAM_INSTRUCTION_WRITE: u32 = 0x01;
2280pub const TN_UPLOADER_PROGRAM_INSTRUCTION_DESTROY: u32 = 0x02;
2281pub const TN_UPLOADER_PROGRAM_INSTRUCTION_FINALIZE: u32 = 0x03;
2282
2283/// Uploader program CREATE instruction arguments (matches C struct)
2284#[repr(C, packed)]
2285#[derive(Debug, Clone, Copy)]
2286pub struct UploaderCreateArgs {
2287    pub buffer_account_idx: u16,
2288    pub meta_account_idx: u16,
2289    pub authority_account_idx: u16,
2290    pub buffer_account_sz: u32,
2291    pub expected_account_hash: [u8; 32],
2292    pub seed_len: u32,
2293    // seed bytes follow
2294}
2295
2296/// Uploader program WRITE instruction arguments (matches C struct)
2297#[repr(C, packed)]
2298#[derive(Debug, Clone, Copy)]
2299pub struct UploaderWriteArgs {
2300    pub buffer_account_idx: u16,
2301    pub meta_account_idx: u16,
2302    pub data_len: u32,
2303    pub data_offset: u32,
2304    // data bytes follow
2305}
2306
2307/// Uploader program FINALIZE instruction arguments (matches C struct)
2308#[repr(C, packed)]
2309#[derive(Debug, Clone, Copy)]
2310pub struct UploaderFinalizeArgs {
2311    pub buffer_account_idx: u16,
2312    pub meta_account_idx: u16,
2313    pub expected_account_hash: [u8; 32],
2314}
2315
2316/// Uploader program DESTROY instruction arguments (matches C struct)
2317#[repr(C, packed)]
2318#[derive(Debug, Clone, Copy)]
2319pub struct UploaderDestroyArgs {
2320    pub buffer_account_idx: u16,
2321    pub meta_account_idx: u16,
2322}
2323
2324/// Manager program instruction discriminants (matches C defines)
2325pub const MANAGER_INSTRUCTION_CREATE_PERMANENT: u8 = 0x00;
2326pub const MANAGER_INSTRUCTION_CREATE_EPHEMERAL: u8 = 0x01;
2327pub const MANAGER_INSTRUCTION_UPGRADE: u8 = 0x02;
2328pub const MANAGER_INSTRUCTION_SET_PAUSE: u8 = 0x03;
2329pub const MANAGER_INSTRUCTION_DESTROY: u8 = 0x04;
2330pub const MANAGER_INSTRUCTION_FINALIZE: u8 = 0x05;
2331pub const MANAGER_INSTRUCTION_SET_AUTHORITY: u8 = 0x06;
2332pub const MANAGER_INSTRUCTION_CLAIM_AUTHORITY: u8 = 0x07;
2333
2334pub const ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT: u8 = 0x00;
2335pub const ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL: u8 = 0x01;
2336pub const ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_PERMANENT: u8 = 0x02;
2337pub const ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_EPHEMERAL: u8 = 0x03;
2338pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT: u8 = 0x04;
2339pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL: u8 = 0x05;
2340pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_PERMANENT: u8 = 0x06;
2341pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL: u8 = 0x07;
2342pub const ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_OFFICIAL: u8 = 0x08;
2343pub const ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_EXTERNAL: u8 = 0x09;
2344pub const ABI_MANAGER_INSTRUCTION_CLOSE_ABI_OFFICIAL: u8 = 0x0a;
2345pub const ABI_MANAGER_INSTRUCTION_CLOSE_ABI_EXTERNAL: u8 = 0x0b;
2346pub const ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_OFFICIAL: u8 = 0x0c;
2347pub const ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_EXTERNAL: u8 = 0x0d;
2348
2349/// Manager program header arguments (matches C struct)
2350#[repr(C, packed)]
2351#[derive(Debug, Clone, Copy)]
2352pub struct ManagerHeaderArgs {
2353    pub discriminant: u8,
2354    pub meta_account_idx: u16,
2355    pub program_account_idx: u16,
2356}
2357
2358/// Manager program CREATE instruction arguments (matches C struct)
2359#[repr(C, packed)]
2360#[derive(Debug, Clone, Copy)]
2361pub struct ManagerCreateArgs {
2362    pub discriminant: u8,
2363    pub meta_account_idx: u16,
2364    pub program_account_idx: u16,
2365    pub srcbuf_account_idx: u16,
2366    pub srcbuf_offset: u32,
2367    pub srcbuf_size: u32,
2368    /// SHA-256 of exactly `srcbuf[offset, offset + size)`; the manager rejects
2369    /// any other bytes, so the buffer cannot be swapped after approval.
2370    pub srcbuf_sha256: [u8; 32],
2371    pub authority_account_idx: u16,
2372    pub seed_len: u32,
2373    // seed bytes and proof bytes follow
2374}
2375
2376/// Manager program UPGRADE instruction arguments (matches C struct)
2377#[repr(C, packed)]
2378#[derive(Debug, Clone, Copy)]
2379pub struct ManagerUpgradeArgs {
2380    pub discriminant: u8,
2381    pub meta_account_idx: u16,
2382    pub program_account_idx: u16,
2383    pub srcbuf_account_idx: u16,
2384    pub srcbuf_offset: u32,
2385    pub srcbuf_size: u32,
2386    /// SHA-256 of exactly `srcbuf[offset, offset + size)`.
2387    pub srcbuf_sha256: [u8; 32],
2388}
2389
2390/// ABI manager program CREATE META (official) instruction arguments (matches C struct)
2391#[repr(C, packed)]
2392#[derive(Debug, Clone, Copy)]
2393pub struct AbiManagerCreateMetaOfficialArgs {
2394    pub abi_meta_account_idx: u16,
2395    pub program_meta_account_idx: u16,
2396    pub authority_account_idx: u16,
2397}
2398
2399/// ABI manager program CREATE META (external) instruction arguments (matches C struct)
2400#[repr(C, packed)]
2401#[derive(Debug, Clone, Copy)]
2402pub struct AbiManagerCreateMetaExternalArgs {
2403    pub abi_meta_account_idx: u16,
2404    pub authority_account_idx: u16,
2405    pub target_program: TnPubkey,
2406    pub seed: [u8; 32],
2407}
2408
2409/// ABI manager program CREATE ABI (official) instruction arguments (matches C struct)
2410#[repr(C, packed)]
2411#[derive(Debug, Clone, Copy)]
2412pub struct AbiManagerCreateAbiOfficialArgs {
2413    pub abi_meta_account_idx: u16,
2414    pub program_meta_account_idx: u16,
2415    pub abi_account_idx: u16,
2416    pub srcbuf_account_idx: u16,
2417    pub srcbuf_offset: u32,
2418    pub srcbuf_size: u32,
2419    /// SHA-256 of exactly `srcbuf[offset, offset + size)`.
2420    pub srcbuf_sha256: [u8; 32],
2421    pub authority_account_idx: u16,
2422}
2423
2424/// ABI manager program CREATE ABI (external) instruction arguments (matches C struct)
2425#[repr(C, packed)]
2426#[derive(Debug, Clone, Copy)]
2427pub struct AbiManagerCreateAbiExternalArgs {
2428    pub abi_meta_account_idx: u16,
2429    pub abi_account_idx: u16,
2430    pub srcbuf_account_idx: u16,
2431    pub srcbuf_offset: u32,
2432    pub srcbuf_size: u32,
2433    /// SHA-256 of exactly `srcbuf[offset, offset + size)`.
2434    pub srcbuf_sha256: [u8; 32],
2435    pub authority_account_idx: u16,
2436}
2437
2438/// ABI manager program UPGRADE ABI (official) instruction arguments (matches C struct)
2439#[repr(C, packed)]
2440#[derive(Debug, Clone, Copy)]
2441pub struct AbiManagerUpgradeAbiOfficialArgs {
2442    pub abi_meta_account_idx: u16,
2443    pub program_meta_account_idx: u16,
2444    pub abi_account_idx: u16,
2445    pub srcbuf_account_idx: u16,
2446    pub srcbuf_offset: u32,
2447    pub srcbuf_size: u32,
2448    /// SHA-256 of exactly `srcbuf[offset, offset + size)`.
2449    pub srcbuf_sha256: [u8; 32],
2450    pub authority_account_idx: u16,
2451}
2452
2453/// ABI manager program UPGRADE ABI (external) instruction arguments (matches C struct)
2454#[repr(C, packed)]
2455#[derive(Debug, Clone, Copy)]
2456pub struct AbiManagerUpgradeAbiExternalArgs {
2457    pub abi_meta_account_idx: u16,
2458    pub abi_account_idx: u16,
2459    pub srcbuf_account_idx: u16,
2460    pub srcbuf_offset: u32,
2461    pub srcbuf_size: u32,
2462    /// SHA-256 of exactly `srcbuf[offset, offset + size)`.
2463    pub srcbuf_sha256: [u8; 32],
2464    pub authority_account_idx: u16,
2465}
2466
2467/// ABI manager program FINALIZE ABI (official) instruction arguments (matches C struct)
2468#[repr(C, packed)]
2469#[derive(Debug, Clone, Copy)]
2470pub struct AbiManagerFinalizeAbiOfficialArgs {
2471    pub abi_meta_account_idx: u16,
2472    pub program_meta_account_idx: u16,
2473    pub abi_account_idx: u16,
2474    pub authority_account_idx: u16,
2475}
2476
2477/// ABI manager program FINALIZE ABI (external) instruction arguments (matches C struct)
2478#[repr(C, packed)]
2479#[derive(Debug, Clone, Copy)]
2480pub struct AbiManagerFinalizeAbiExternalArgs {
2481    pub abi_meta_account_idx: u16,
2482    pub abi_account_idx: u16,
2483    pub authority_account_idx: u16,
2484}
2485
2486/// ABI manager program CLOSE ABI (official) instruction arguments (matches C struct)
2487#[repr(C, packed)]
2488#[derive(Debug, Clone, Copy)]
2489pub struct AbiManagerCloseAbiOfficialArgs {
2490    pub abi_meta_account_idx: u16,
2491    pub program_meta_account_idx: u16,
2492    pub abi_account_idx: u16,
2493    pub authority_account_idx: u16,
2494}
2495
2496/// ABI manager program CLOSE ABI (external) instruction arguments (matches C struct)
2497#[repr(C, packed)]
2498#[derive(Debug, Clone, Copy)]
2499pub struct AbiManagerCloseAbiExternalArgs {
2500    pub abi_meta_account_idx: u16,
2501    pub abi_account_idx: u16,
2502    pub authority_account_idx: u16,
2503}
2504
2505/// Manager program SET_PAUSE instruction arguments (matches C struct)
2506#[repr(C, packed)]
2507#[derive(Debug, Clone, Copy)]
2508pub struct ManagerSetPauseArgs {
2509    pub discriminant: u8,
2510    pub meta_account_idx: u16,
2511    pub program_account_idx: u16,
2512    pub is_paused: u8,
2513}
2514
2515/// Manager program SET_AUTHORITY instruction arguments (matches C struct)
2516#[repr(C, packed)]
2517#[derive(Debug, Clone, Copy)]
2518pub struct ManagerSetAuthorityArgs {
2519    pub discriminant: u8,
2520    pub meta_account_idx: u16,
2521    pub program_account_idx: u16,
2522    pub authority_candidate: [u8; 32],
2523}
2524
2525/// Test uploader program instruction discriminants (matches C defines)
2526pub const TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_CREATE: u8 = 0x00;
2527pub const TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_WRITE: u8 = 0x01;
2528
2529/// Test uploader program CREATE instruction arguments (matches C struct)
2530#[repr(C, packed)]
2531#[derive(Debug, Clone, Copy)]
2532pub struct TestUploaderCreateArgs {
2533    pub account_idx: u16,
2534    pub is_ephemeral: u8,
2535    pub account_sz: u32,
2536    pub seed_len: u32,
2537    // seed bytes follow, then optional state proof
2538}
2539
2540/// Test uploader program WRITE instruction arguments (matches C struct)
2541#[repr(C, packed)]
2542#[derive(Debug, Clone, Copy)]
2543pub struct TestUploaderWriteArgs {
2544    pub target_account_idx: u16,
2545    pub target_offset: u32,
2546    pub data_len: u32,
2547    // data bytes follow
2548}
2549
2550/// System program DECOMPRESS2 instruction arguments (matches C struct)
2551#[repr(C, packed)]
2552#[derive(Debug, Clone, Copy)]
2553pub struct SystemProgramDecompress2Args {
2554    pub target_account_idx: u16,
2555    pub meta_account_idx: u16,
2556    pub data_account_idx: u16,
2557    pub data_offset: u32,
2558}
2559
2560fn uploader_data_has_elf_magic(data: &[u8]) -> bool {
2561    let elf_magic = [0x7f, b'E', b'L', b'F'];
2562    data.starts_with(&elf_magic)
2563}
2564
2565impl TransactionBuilder {
2566    /// Build uploader program CREATE transaction
2567    pub fn build_uploader_create(
2568        fee_payer: TnPubkey,
2569        uploader_program: TnPubkey,
2570        meta_account: TnPubkey,
2571        buffer_account: TnPubkey,
2572        buffer_size: u32,
2573        expected_hash: [u8; 32],
2574        seed: &[u8],
2575        fee: u64,
2576        nonce: u64,
2577        start_slot: u64,
2578    ) -> Result<Transaction> {
2579        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2580        let authority_account_idx = 0u16;
2581
2582        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2583            .with_start_slot(start_slot)
2584            .with_expiry_after(10)
2585            .with_compute_units(50_000 + 2 * buffer_size as u32)
2586            .with_memory_units(10_000)
2587            .with_state_units(account_state_units(buffer_size as u64 + 4096)?); // Buffer + one-unit uploader metadata.
2588
2589        let mut meta_account_idx = 2u16;
2590        let mut buffer_account_idx = 3u16;
2591        if meta_account > buffer_account {
2592            meta_account_idx = 3u16;
2593            buffer_account_idx = 2u16;
2594            tx = tx
2595                .add_rw_account(buffer_account)
2596                .add_rw_account(meta_account)
2597        } else {
2598            tx = tx
2599                .add_rw_account(meta_account)
2600                .add_rw_account(buffer_account)
2601        }
2602
2603        let instruction_data = build_uploader_create_instruction(
2604            buffer_account_idx,
2605            meta_account_idx,
2606            authority_account_idx,
2607            buffer_size,
2608            expected_hash,
2609            seed,
2610        )?;
2611
2612        tx = tx.with_instructions(instruction_data);
2613
2614        Ok(tx)
2615    }
2616
2617    /// Build uploader program WRITE transaction
2618    pub fn build_uploader_write(
2619        fee_payer: TnPubkey,
2620        uploader_program: TnPubkey,
2621        meta_account: TnPubkey,
2622        buffer_account: TnPubkey,
2623        data: &[u8],
2624        offset: u32,
2625        fee: u64,
2626        nonce: u64,
2627        start_slot: u64,
2628    ) -> Result<Transaction> {
2629        Self::build_uploader_write_with_options(
2630            fee_payer,
2631            uploader_program,
2632            meta_account,
2633            buffer_account,
2634            data,
2635            offset,
2636            fee,
2637            nonce,
2638            start_slot,
2639            UploaderWriteOptions::default(),
2640        )
2641    }
2642
2643    /// Build uploader program WRITE transaction with caller-selected validation options.
2644    pub fn build_uploader_write_with_options(
2645        fee_payer: TnPubkey,
2646        uploader_program: TnPubkey,
2647        meta_account: TnPubkey,
2648        buffer_account: TnPubkey,
2649        data: &[u8],
2650        offset: u32,
2651        fee: u64,
2652        nonce: u64,
2653        start_slot: u64,
2654        options: UploaderWriteOptions,
2655    ) -> Result<Transaction> {
2656        if !options.skip_elf_check && offset == 0 && uploader_data_has_elf_magic(data) {
2657            bail!(
2658                "uploader data begins with ELF magic; upload a Thru program binary, not an ELF executable"
2659            );
2660        }
2661
2662        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2663        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2664            .with_start_slot(start_slot)
2665            .with_expiry_after(10000)
2666            .with_compute_units(500_000_000)
2667            .with_memory_units(5000)
2668            .with_state_units(0);
2669
2670        let mut meta_account_idx = 2u16;
2671        let mut buffer_account_idx = 3u16;
2672        if meta_account > buffer_account {
2673            meta_account_idx = 3u16;
2674            buffer_account_idx = 2u16;
2675            tx = tx
2676                .add_rw_account(buffer_account)
2677                .add_rw_account(meta_account)
2678        } else {
2679            tx = tx
2680                .add_rw_account(meta_account)
2681                .add_rw_account(buffer_account)
2682        }
2683
2684        let instruction_data =
2685            build_uploader_write_instruction(buffer_account_idx, meta_account_idx, data, offset)?;
2686
2687        tx = tx.with_instructions(instruction_data);
2688
2689        Ok(tx)
2690    }
2691
2692    /// Build uploader program FINALIZE transaction
2693    pub fn build_uploader_finalize(
2694        fee_payer: TnPubkey,
2695        uploader_program: TnPubkey,
2696        meta_account: TnPubkey,
2697        buffer_account: TnPubkey,
2698        buffer_size: u32,
2699        expected_hash: [u8; 32],
2700        fee: u64,
2701        nonce: u64,
2702        start_slot: u64,
2703    ) -> Result<Transaction> {
2704        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2705            .with_start_slot(start_slot)
2706            .with_expiry_after(10000)
2707            .with_compute_units(50_000 + 200 * buffer_size as u32)
2708            .with_memory_units(5000)
2709            .with_state_units(0);
2710
2711        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2712        let mut meta_account_idx = 2u16;
2713        let mut buffer_account_idx = 3u16;
2714        if meta_account > buffer_account {
2715            meta_account_idx = 3u16;
2716            buffer_account_idx = 2u16;
2717            tx = tx
2718                .add_rw_account(buffer_account)
2719                .add_rw_account(meta_account)
2720        } else {
2721            tx = tx
2722                .add_rw_account(meta_account)
2723                .add_rw_account(buffer_account)
2724        }
2725
2726        let instruction_data = build_uploader_finalize_instruction(
2727            buffer_account_idx,
2728            meta_account_idx,
2729            expected_hash,
2730        )?;
2731
2732        tx = tx.with_instructions(instruction_data);
2733
2734        Ok(tx)
2735    }
2736
2737    /// Build uploader program DESTROY transaction
2738    pub fn build_uploader_destroy(
2739        fee_payer: TnPubkey,
2740        uploader_program: TnPubkey,
2741        meta_account: TnPubkey,
2742        buffer_account: TnPubkey,
2743        fee: u64,
2744        nonce: u64,
2745        start_slot: u64,
2746    ) -> Result<Transaction> {
2747        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2748            .with_start_slot(start_slot)
2749            .with_expiry_after(10000)
2750            .with_compute_units(50000)
2751            .with_memory_units(5000)
2752            .with_state_units(0);
2753
2754        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2755        let mut meta_account_idx = 2u16;
2756        let mut buffer_account_idx = 3u16;
2757        if meta_account > buffer_account {
2758            meta_account_idx = 3u16;
2759            buffer_account_idx = 2u16;
2760            tx = tx
2761                .add_rw_account(buffer_account)
2762                .add_rw_account(meta_account)
2763        } else {
2764            tx = tx
2765                .add_rw_account(meta_account)
2766                .add_rw_account(buffer_account)
2767        }
2768
2769        let instruction_data =
2770            build_uploader_destroy_instruction(buffer_account_idx, meta_account_idx)?;
2771
2772        tx = tx.with_instructions(instruction_data);
2773        Ok(tx)
2774    }
2775
2776    /// Build manager program CREATE transaction
2777    pub fn build_manager_create(
2778        fee_payer: TnPubkey,
2779        manager_program: TnPubkey,
2780        meta_account: TnPubkey,
2781        program_account: TnPubkey,
2782        srcbuf_account: TnPubkey,
2783        authority_account: TnPubkey,
2784        srcbuf_offset: u32,
2785        srcbuf_size: u32,
2786        srcbuf_sha256: [u8; 32],
2787        seed: &[u8],
2788        is_ephemeral: bool,
2789        meta_proof: Option<&[u8]>,
2790        program_proof: Option<&[u8]>,
2791        fee: u64,
2792        nonce: u64,
2793        start_slot: u64,
2794    ) -> Result<Transaction> {
2795        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
2796            .with_start_slot(start_slot)
2797            .with_expiry_after(10000)
2798            .with_compute_units(500_000_000)
2799            .with_memory_units(5000)
2800            .with_state_units(account_state_units(srcbuf_size as u64 + 4096)?); // Program + one-unit manager metadata.
2801
2802        // Check if authority_account is the same as fee_payer
2803        let authority_is_fee_payer = authority_account == fee_payer;
2804
2805        // Separate accounts by access type and sort each group by pubkey
2806        let mut rw_accounts = vec![(meta_account, "meta"), (program_account, "program")];
2807
2808        let mut r_accounts = vec![(srcbuf_account, "srcbuf")];
2809
2810        // Only add authority_account if it's different from fee_payer
2811        if !authority_is_fee_payer {
2812            r_accounts.push((authority_account, "authority"));
2813        }
2814
2815        // Sort read-write accounts by pubkey
2816        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2817
2818        // Sort read-only accounts by pubkey
2819        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2820
2821        // Combine sorted accounts: read-write first, then read-only
2822        let mut accounts = rw_accounts;
2823        accounts.extend(r_accounts);
2824
2825        let mut meta_account_idx = 0u16;
2826        let mut program_account_idx = 0u16;
2827        let mut srcbuf_account_idx = 0u16;
2828        let mut authority_account_idx = if authority_is_fee_payer {
2829            0u16 // Use fee_payer index (0) when authority is the same as fee_payer
2830        } else {
2831            0u16 // Will be set in the loop below
2832        };
2833
2834        for (i, (account, account_type)) in accounts.iter().enumerate() {
2835            let idx = (i + 2) as u16; // Skip fee_payer (0) and program (1)
2836            match *account_type {
2837                "meta" => {
2838                    meta_account_idx = idx;
2839                    tx = tx.add_rw_account(*account);
2840                }
2841                "program" => {
2842                    program_account_idx = idx;
2843                    tx = tx.add_rw_account(*account);
2844                }
2845                "srcbuf" => {
2846                    srcbuf_account_idx = idx;
2847                    tx = tx.add_r_account(*account);
2848                }
2849                "authority" => {
2850                    authority_account_idx = idx;
2851                    tx = tx.add_r_account(*account);
2852                }
2853                _ => unreachable!(),
2854            }
2855        }
2856
2857        let discriminant = if is_ephemeral {
2858            MANAGER_INSTRUCTION_CREATE_EPHEMERAL
2859        } else {
2860            MANAGER_INSTRUCTION_CREATE_PERMANENT
2861        };
2862
2863        // Concatenate proofs if both are provided (for permanent programs)
2864        let combined_proof = if let (Some(meta), Some(program)) = (meta_proof, program_proof) {
2865            let mut combined = Vec::with_capacity(meta.len() + program.len());
2866            combined.extend_from_slice(meta);
2867            combined.extend_from_slice(program);
2868            Some(combined)
2869        } else {
2870            None
2871        };
2872
2873        let instruction_data = build_manager_create_instruction(
2874            discriminant,
2875            meta_account_idx,
2876            program_account_idx,
2877            srcbuf_account_idx,
2878            authority_account_idx,
2879            srcbuf_offset,
2880            srcbuf_size,
2881            srcbuf_sha256,
2882            seed,
2883            combined_proof.as_deref(),
2884        )?;
2885
2886        tx = tx.with_instructions(instruction_data);
2887        Ok(tx)
2888    }
2889
2890    /// Build ABI manager program CREATE META (official) transaction
2891    pub fn build_abi_manager_create_meta_official(
2892        fee_payer: TnPubkey,
2893        abi_manager_program: TnPubkey,
2894        program_meta_account: TnPubkey,
2895        abi_meta_account: TnPubkey,
2896        authority_account: TnPubkey,
2897        is_ephemeral: bool,
2898        abi_meta_proof: Option<&[u8]>,
2899        fee: u64,
2900        nonce: u64,
2901        start_slot: u64,
2902    ) -> Result<Transaction> {
2903        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2904            .with_start_slot(start_slot)
2905            .with_expiry_after(10000)
2906            .with_compute_units(500_000_000)
2907            .with_memory_units(5000)
2908            .with_state_units(1);
2909
2910        let authority_is_fee_payer = authority_account == fee_payer;
2911
2912        let mut rw_accounts = vec![(abi_meta_account, "abi_meta")];
2913        let mut r_accounts = vec![(program_meta_account, "program_meta")];
2914
2915        if !authority_is_fee_payer {
2916            r_accounts.push((authority_account, "authority"));
2917        }
2918
2919        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2920        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2921
2922        let mut accounts = rw_accounts;
2923        accounts.extend(r_accounts);
2924
2925        let mut abi_meta_account_idx = 0u16;
2926        let mut program_meta_account_idx = 0u16;
2927        let mut authority_account_idx = 0u16;
2928
2929        for (i, (account, account_type)) in accounts.iter().enumerate() {
2930            let idx = (i + 2) as u16;
2931            match *account_type {
2932                "abi_meta" => {
2933                    abi_meta_account_idx = idx;
2934                    tx = tx.add_rw_account(*account);
2935                }
2936                "program_meta" => {
2937                    program_meta_account_idx = idx;
2938                    tx = tx.add_r_account(*account);
2939                }
2940                "authority" => {
2941                    authority_account_idx = idx;
2942                    tx = tx.add_r_account(*account);
2943                }
2944                _ => unreachable!(),
2945            }
2946        }
2947
2948        let authority_idx = if authority_is_fee_payer {
2949            0u16
2950        } else {
2951            authority_account_idx
2952        };
2953
2954        let discriminant = if is_ephemeral {
2955            ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL
2956        } else {
2957            ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT
2958        };
2959
2960        let instruction_data = build_abi_manager_create_meta_official_instruction(
2961            discriminant,
2962            abi_meta_account_idx,
2963            program_meta_account_idx,
2964            authority_idx,
2965            abi_meta_proof,
2966        )?;
2967
2968        tx = tx.with_instructions(instruction_data);
2969        Ok(tx)
2970    }
2971
2972    /// Build ABI manager program CREATE META (external) transaction
2973    pub fn build_abi_manager_create_meta_external(
2974        fee_payer: TnPubkey,
2975        abi_manager_program: TnPubkey,
2976        abi_meta_account: TnPubkey,
2977        authority_account: TnPubkey,
2978        target_program: TnPubkey,
2979        seed: [u8; 32],
2980        is_ephemeral: bool,
2981        abi_meta_proof: Option<&[u8]>,
2982        fee: u64,
2983        nonce: u64,
2984        start_slot: u64,
2985    ) -> Result<Transaction> {
2986        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2987            .with_start_slot(start_slot)
2988            .with_expiry_after(10000)
2989            .with_compute_units(500_000_000)
2990            .with_memory_units(5000)
2991            .with_state_units(1);
2992
2993        let authority_is_fee_payer = authority_account == fee_payer;
2994
2995        let mut rw_accounts = vec![(abi_meta_account, "abi_meta")];
2996        let mut r_accounts = Vec::new();
2997
2998        if !authority_is_fee_payer {
2999            r_accounts.push((authority_account, "authority"));
3000        }
3001
3002        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3003        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3004
3005        let mut accounts = rw_accounts;
3006        accounts.extend(r_accounts);
3007
3008        let mut abi_meta_account_idx = 0u16;
3009        let mut authority_account_idx = 0u16;
3010
3011        for (i, (account, account_type)) in accounts.iter().enumerate() {
3012            let idx = (i + 2) as u16;
3013            match *account_type {
3014                "abi_meta" => {
3015                    abi_meta_account_idx = idx;
3016                    tx = tx.add_rw_account(*account);
3017                }
3018                "authority" => {
3019                    authority_account_idx = idx;
3020                    tx = tx.add_r_account(*account);
3021                }
3022                _ => unreachable!(),
3023            }
3024        }
3025
3026        let authority_idx = if authority_is_fee_payer {
3027            0u16
3028        } else {
3029            authority_account_idx
3030        };
3031
3032        let discriminant = if is_ephemeral {
3033            ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_EPHEMERAL
3034        } else {
3035            ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_PERMANENT
3036        };
3037
3038        let instruction_data = build_abi_manager_create_meta_external_instruction(
3039            discriminant,
3040            abi_meta_account_idx,
3041            authority_idx,
3042            target_program,
3043            seed,
3044            abi_meta_proof,
3045        )?;
3046
3047        tx = tx.with_instructions(instruction_data);
3048        Ok(tx)
3049    }
3050
3051    /// Build ABI manager program CREATE ABI (official) transaction
3052    #[allow(clippy::too_many_arguments)]
3053    pub fn build_abi_manager_create_abi_official(
3054        fee_payer: TnPubkey,
3055        abi_manager_program: TnPubkey,
3056        abi_meta_account: TnPubkey,
3057        program_meta_account: TnPubkey,
3058        abi_account: TnPubkey,
3059        srcbuf_account: TnPubkey,
3060        authority_account: TnPubkey,
3061        srcbuf_offset: u32,
3062        srcbuf_size: u32,
3063        srcbuf_sha256: [u8; 32],
3064        is_ephemeral: bool,
3065        abi_proof: Option<&[u8]>,
3066        fee: u64,
3067        nonce: u64,
3068        start_slot: u64,
3069    ) -> Result<Transaction> {
3070        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3071            .with_start_slot(start_slot)
3072            .with_expiry_after(10000)
3073            .with_compute_units(500_000_000)
3074            .with_memory_units(5000)
3075            .with_state_units(account_state_units(
3076                srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE,
3077            )?);
3078
3079        let authority_is_fee_payer = authority_account == fee_payer;
3080
3081        let mut rw_accounts = vec![(abi_account, "abi")];
3082        let mut r_accounts = vec![
3083            (abi_meta_account, "abi_meta"),
3084            (program_meta_account, "program_meta"),
3085            (srcbuf_account, "srcbuf"),
3086        ];
3087
3088        if !authority_is_fee_payer {
3089            r_accounts.push((authority_account, "authority"));
3090        }
3091
3092        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3093        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3094
3095        let mut accounts = rw_accounts;
3096        accounts.extend(r_accounts);
3097
3098        let mut abi_meta_account_idx = 0u16;
3099        let mut program_meta_account_idx = 0u16;
3100        let mut abi_account_idx = 0u16;
3101        let mut srcbuf_account_idx = 0u16;
3102        let mut authority_account_idx = 0u16;
3103
3104        for (i, (account, account_type)) in accounts.iter().enumerate() {
3105            let idx = (i + 2) as u16;
3106            match *account_type {
3107                "abi_meta" => {
3108                    abi_meta_account_idx = idx;
3109                    tx = tx.add_r_account(*account);
3110                }
3111                "program_meta" => {
3112                    program_meta_account_idx = idx;
3113                    tx = tx.add_r_account(*account);
3114                }
3115                "abi" => {
3116                    abi_account_idx = idx;
3117                    tx = tx.add_rw_account(*account);
3118                }
3119                "srcbuf" => {
3120                    srcbuf_account_idx = idx;
3121                    tx = tx.add_r_account(*account);
3122                }
3123                "authority" => {
3124                    authority_account_idx = idx;
3125                    tx = tx.add_r_account(*account);
3126                }
3127                _ => unreachable!(),
3128            }
3129        }
3130
3131        let authority_idx = if authority_is_fee_payer {
3132            0u16
3133        } else {
3134            authority_account_idx
3135        };
3136
3137        let discriminant = if is_ephemeral {
3138            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL
3139        } else {
3140            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT
3141        };
3142
3143        let instruction_data = build_abi_manager_create_abi_official_instruction(
3144            discriminant,
3145            abi_meta_account_idx,
3146            program_meta_account_idx,
3147            abi_account_idx,
3148            srcbuf_account_idx,
3149            srcbuf_offset,
3150            srcbuf_size,
3151            srcbuf_sha256,
3152            authority_idx,
3153            abi_proof,
3154        )?;
3155
3156        tx = tx.with_instructions(instruction_data);
3157        Ok(tx)
3158    }
3159
3160    /// Build ABI manager program CREATE ABI (external) transaction
3161    #[allow(clippy::too_many_arguments)]
3162    pub fn build_abi_manager_create_abi_external(
3163        fee_payer: TnPubkey,
3164        abi_manager_program: TnPubkey,
3165        abi_meta_account: TnPubkey,
3166        abi_account: TnPubkey,
3167        srcbuf_account: TnPubkey,
3168        authority_account: TnPubkey,
3169        srcbuf_offset: u32,
3170        srcbuf_size: u32,
3171        srcbuf_sha256: [u8; 32],
3172        is_ephemeral: bool,
3173        abi_proof: Option<&[u8]>,
3174        fee: u64,
3175        nonce: u64,
3176        start_slot: u64,
3177    ) -> Result<Transaction> {
3178        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3179            .with_start_slot(start_slot)
3180            .with_expiry_after(10000)
3181            .with_compute_units(500_000_000)
3182            .with_memory_units(5000)
3183            .with_state_units(account_state_units(
3184                srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE,
3185            )?);
3186
3187        let authority_is_fee_payer = authority_account == fee_payer;
3188
3189        let mut rw_accounts = vec![(abi_account, "abi")];
3190        let mut r_accounts = vec![(abi_meta_account, "abi_meta"), (srcbuf_account, "srcbuf")];
3191
3192        if !authority_is_fee_payer {
3193            r_accounts.push((authority_account, "authority"));
3194        }
3195
3196        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3197        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3198
3199        let mut accounts = rw_accounts;
3200        accounts.extend(r_accounts);
3201
3202        let mut abi_meta_account_idx = 0u16;
3203        let mut abi_account_idx = 0u16;
3204        let mut srcbuf_account_idx = 0u16;
3205        let mut authority_account_idx = 0u16;
3206
3207        for (i, (account, account_type)) in accounts.iter().enumerate() {
3208            let idx = (i + 2) as u16;
3209            match *account_type {
3210                "abi_meta" => {
3211                    abi_meta_account_idx = idx;
3212                    tx = tx.add_r_account(*account);
3213                }
3214                "abi" => {
3215                    abi_account_idx = idx;
3216                    tx = tx.add_rw_account(*account);
3217                }
3218                "srcbuf" => {
3219                    srcbuf_account_idx = idx;
3220                    tx = tx.add_r_account(*account);
3221                }
3222                "authority" => {
3223                    authority_account_idx = idx;
3224                    tx = tx.add_r_account(*account);
3225                }
3226                _ => unreachable!(),
3227            }
3228        }
3229
3230        let authority_idx = if authority_is_fee_payer {
3231            0u16
3232        } else {
3233            authority_account_idx
3234        };
3235
3236        let discriminant = if is_ephemeral {
3237            ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL
3238        } else {
3239            ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_PERMANENT
3240        };
3241
3242        let instruction_data = build_abi_manager_create_abi_external_instruction(
3243            discriminant,
3244            abi_meta_account_idx,
3245            abi_account_idx,
3246            srcbuf_account_idx,
3247            srcbuf_offset,
3248            srcbuf_size,
3249            srcbuf_sha256,
3250            authority_idx,
3251            abi_proof,
3252        )?;
3253
3254        tx = tx.with_instructions(instruction_data);
3255        Ok(tx)
3256    }
3257
3258    /// Build ABI manager program UPGRADE ABI (official) transaction
3259    #[allow(clippy::too_many_arguments)]
3260    pub fn build_abi_manager_upgrade_abi_official(
3261        fee_payer: TnPubkey,
3262        abi_manager_program: TnPubkey,
3263        abi_meta_account: TnPubkey,
3264        program_meta_account: TnPubkey,
3265        abi_account: TnPubkey,
3266        srcbuf_account: TnPubkey,
3267        authority_account: TnPubkey,
3268        srcbuf_offset: u32,
3269        srcbuf_size: u32,
3270        srcbuf_sha256: [u8; 32],
3271        fee: u64,
3272        nonce: u64,
3273        start_slot: u64,
3274    ) -> Result<Transaction> {
3275        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3276            .with_start_slot(start_slot)
3277            .with_expiry_after(10000)
3278            .with_compute_units(500_000_000)
3279            .with_memory_units(5000)
3280            .with_state_units(
3281                account_state_units(srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE)?
3282                    .saturating_sub(1),
3283            );
3284
3285        let authority_is_fee_payer = authority_account == fee_payer;
3286
3287        let mut rw_accounts = vec![(abi_account, "abi")];
3288        let mut r_accounts = vec![
3289            (abi_meta_account, "abi_meta"),
3290            (program_meta_account, "program_meta"),
3291            (srcbuf_account, "srcbuf"),
3292        ];
3293
3294        if !authority_is_fee_payer {
3295            r_accounts.push((authority_account, "authority"));
3296        }
3297
3298        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3299        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3300
3301        let mut accounts = rw_accounts;
3302        accounts.extend(r_accounts);
3303
3304        let mut abi_meta_account_idx = 0u16;
3305        let mut program_meta_account_idx = 0u16;
3306        let mut abi_account_idx = 0u16;
3307        let mut srcbuf_account_idx = 0u16;
3308        let mut authority_account_idx = 0u16;
3309
3310        for (i, (account, account_type)) in accounts.iter().enumerate() {
3311            let idx = (i + 2) as u16;
3312            match *account_type {
3313                "abi_meta" => {
3314                    abi_meta_account_idx = idx;
3315                    tx = tx.add_r_account(*account);
3316                }
3317                "program_meta" => {
3318                    program_meta_account_idx = idx;
3319                    tx = tx.add_r_account(*account);
3320                }
3321                "abi" => {
3322                    abi_account_idx = idx;
3323                    tx = tx.add_rw_account(*account);
3324                }
3325                "srcbuf" => {
3326                    srcbuf_account_idx = idx;
3327                    tx = tx.add_r_account(*account);
3328                }
3329                "authority" => {
3330                    authority_account_idx = idx;
3331                    tx = tx.add_r_account(*account);
3332                }
3333                _ => unreachable!(),
3334            }
3335        }
3336
3337        let authority_idx = if authority_is_fee_payer {
3338            0u16
3339        } else {
3340            authority_account_idx
3341        };
3342
3343        let instruction_data = build_abi_manager_upgrade_abi_official_instruction(
3344            abi_meta_account_idx,
3345            program_meta_account_idx,
3346            abi_account_idx,
3347            srcbuf_account_idx,
3348            srcbuf_offset,
3349            srcbuf_size,
3350            srcbuf_sha256,
3351            authority_idx,
3352        )?;
3353
3354        tx = tx.with_instructions(instruction_data);
3355        Ok(tx)
3356    }
3357
3358    /// Build ABI manager program UPGRADE ABI (external) transaction
3359    #[allow(clippy::too_many_arguments)]
3360    pub fn build_abi_manager_upgrade_abi_external(
3361        fee_payer: TnPubkey,
3362        abi_manager_program: TnPubkey,
3363        abi_meta_account: TnPubkey,
3364        abi_account: TnPubkey,
3365        srcbuf_account: TnPubkey,
3366        authority_account: TnPubkey,
3367        srcbuf_offset: u32,
3368        srcbuf_size: u32,
3369        srcbuf_sha256: [u8; 32],
3370        fee: u64,
3371        nonce: u64,
3372        start_slot: u64,
3373    ) -> Result<Transaction> {
3374        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3375            .with_start_slot(start_slot)
3376            .with_expiry_after(10000)
3377            .with_compute_units(500_000_000)
3378            .with_memory_units(5000)
3379            .with_state_units(
3380                account_state_units(srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE)?
3381                    .saturating_sub(1),
3382            );
3383
3384        let authority_is_fee_payer = authority_account == fee_payer;
3385
3386        let mut rw_accounts = vec![(abi_account, "abi")];
3387        let mut r_accounts = vec![(abi_meta_account, "abi_meta"), (srcbuf_account, "srcbuf")];
3388
3389        if !authority_is_fee_payer {
3390            r_accounts.push((authority_account, "authority"));
3391        }
3392
3393        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3394        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3395
3396        let mut accounts = rw_accounts;
3397        accounts.extend(r_accounts);
3398
3399        let mut abi_meta_account_idx = 0u16;
3400        let mut abi_account_idx = 0u16;
3401        let mut srcbuf_account_idx = 0u16;
3402        let mut authority_account_idx = 0u16;
3403
3404        for (i, (account, account_type)) in accounts.iter().enumerate() {
3405            let idx = (i + 2) as u16;
3406            match *account_type {
3407                "abi_meta" => {
3408                    abi_meta_account_idx = idx;
3409                    tx = tx.add_r_account(*account);
3410                }
3411                "abi" => {
3412                    abi_account_idx = idx;
3413                    tx = tx.add_rw_account(*account);
3414                }
3415                "srcbuf" => {
3416                    srcbuf_account_idx = idx;
3417                    tx = tx.add_r_account(*account);
3418                }
3419                "authority" => {
3420                    authority_account_idx = idx;
3421                    tx = tx.add_r_account(*account);
3422                }
3423                _ => unreachable!(),
3424            }
3425        }
3426
3427        let authority_idx = if authority_is_fee_payer {
3428            0u16
3429        } else {
3430            authority_account_idx
3431        };
3432
3433        let instruction_data = build_abi_manager_upgrade_abi_external_instruction(
3434            abi_meta_account_idx,
3435            abi_account_idx,
3436            srcbuf_account_idx,
3437            srcbuf_offset,
3438            srcbuf_size,
3439            srcbuf_sha256,
3440            authority_idx,
3441        )?;
3442
3443        tx = tx.with_instructions(instruction_data);
3444        Ok(tx)
3445    }
3446
3447    /// Build ABI manager program FINALIZE ABI (official) transaction
3448    pub fn build_abi_manager_finalize_abi_official(
3449        fee_payer: TnPubkey,
3450        abi_manager_program: TnPubkey,
3451        abi_meta_account: TnPubkey,
3452        program_meta_account: TnPubkey,
3453        abi_account: TnPubkey,
3454        authority_account: TnPubkey,
3455        fee: u64,
3456        nonce: u64,
3457        start_slot: u64,
3458    ) -> Result<Transaction> {
3459        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3460            .with_start_slot(start_slot)
3461            .with_expiry_after(10000)
3462            .with_compute_units(500_000_000)
3463            .with_memory_units(5000)
3464            .with_state_units(0);
3465
3466        let authority_is_fee_payer = authority_account == fee_payer;
3467
3468        let mut rw_accounts = vec![(abi_account, "abi")];
3469        let mut r_accounts = vec![
3470            (abi_meta_account, "abi_meta"),
3471            (program_meta_account, "program_meta"),
3472        ];
3473
3474        if !authority_is_fee_payer {
3475            r_accounts.push((authority_account, "authority"));
3476        }
3477
3478        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3479        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3480
3481        let mut accounts = rw_accounts;
3482        accounts.extend(r_accounts);
3483
3484        let mut abi_meta_account_idx = 0u16;
3485        let mut program_meta_account_idx = 0u16;
3486        let mut abi_account_idx = 0u16;
3487        let mut authority_account_idx = 0u16;
3488
3489        for (i, (account, account_type)) in accounts.iter().enumerate() {
3490            let idx = (i + 2) as u16;
3491            match *account_type {
3492                "abi_meta" => {
3493                    abi_meta_account_idx = idx;
3494                    tx = tx.add_r_account(*account);
3495                }
3496                "program_meta" => {
3497                    program_meta_account_idx = idx;
3498                    tx = tx.add_r_account(*account);
3499                }
3500                "abi" => {
3501                    abi_account_idx = idx;
3502                    tx = tx.add_rw_account(*account);
3503                }
3504                "authority" => {
3505                    authority_account_idx = idx;
3506                    tx = tx.add_r_account(*account);
3507                }
3508                _ => unreachable!(),
3509            }
3510        }
3511
3512        let authority_idx = if authority_is_fee_payer {
3513            0u16
3514        } else {
3515            authority_account_idx
3516        };
3517
3518        let instruction_data = build_abi_manager_finalize_abi_official_instruction(
3519            abi_meta_account_idx,
3520            program_meta_account_idx,
3521            abi_account_idx,
3522            authority_idx,
3523        )?;
3524
3525        tx = tx.with_instructions(instruction_data);
3526        Ok(tx)
3527    }
3528
3529    /// Build ABI manager program FINALIZE ABI (external) transaction
3530    pub fn build_abi_manager_finalize_abi_external(
3531        fee_payer: TnPubkey,
3532        abi_manager_program: TnPubkey,
3533        abi_meta_account: TnPubkey,
3534        abi_account: TnPubkey,
3535        authority_account: TnPubkey,
3536        fee: u64,
3537        nonce: u64,
3538        start_slot: u64,
3539    ) -> Result<Transaction> {
3540        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3541            .with_start_slot(start_slot)
3542            .with_expiry_after(10000)
3543            .with_compute_units(500_000_000)
3544            .with_memory_units(5000)
3545            .with_state_units(0);
3546
3547        let authority_is_fee_payer = authority_account == fee_payer;
3548
3549        let mut rw_accounts = vec![(abi_account, "abi")];
3550        let mut r_accounts = vec![(abi_meta_account, "abi_meta")];
3551
3552        if !authority_is_fee_payer {
3553            r_accounts.push((authority_account, "authority"));
3554        }
3555
3556        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3557        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3558
3559        let mut accounts = rw_accounts;
3560        accounts.extend(r_accounts);
3561
3562        let mut abi_meta_account_idx = 0u16;
3563        let mut abi_account_idx = 0u16;
3564        let mut authority_account_idx = 0u16;
3565
3566        for (i, (account, account_type)) in accounts.iter().enumerate() {
3567            let idx = (i + 2) as u16;
3568            match *account_type {
3569                "abi_meta" => {
3570                    abi_meta_account_idx = idx;
3571                    tx = tx.add_r_account(*account);
3572                }
3573                "abi" => {
3574                    abi_account_idx = idx;
3575                    tx = tx.add_rw_account(*account);
3576                }
3577                "authority" => {
3578                    authority_account_idx = idx;
3579                    tx = tx.add_r_account(*account);
3580                }
3581                _ => unreachable!(),
3582            }
3583        }
3584
3585        let authority_idx = if authority_is_fee_payer {
3586            0u16
3587        } else {
3588            authority_account_idx
3589        };
3590
3591        let instruction_data = build_abi_manager_finalize_abi_external_instruction(
3592            abi_meta_account_idx,
3593            abi_account_idx,
3594            authority_idx,
3595        )?;
3596
3597        tx = tx.with_instructions(instruction_data);
3598        Ok(tx)
3599    }
3600
3601    /// Build ABI manager program CLOSE ABI (official) transaction
3602    pub fn build_abi_manager_close_abi_official(
3603        fee_payer: TnPubkey,
3604        abi_manager_program: TnPubkey,
3605        abi_meta_account: TnPubkey,
3606        program_meta_account: TnPubkey,
3607        abi_account: TnPubkey,
3608        authority_account: TnPubkey,
3609        fee: u64,
3610        nonce: u64,
3611        start_slot: u64,
3612    ) -> Result<Transaction> {
3613        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3614            .with_start_slot(start_slot)
3615            .with_expiry_after(10000)
3616            .with_compute_units(500_000_000)
3617            .with_memory_units(5000)
3618            .with_state_units(0);
3619
3620        let authority_is_fee_payer = authority_account == fee_payer;
3621
3622        let mut rw_accounts = vec![(abi_account, "abi")];
3623        let mut r_accounts = vec![
3624            (abi_meta_account, "abi_meta"),
3625            (program_meta_account, "program_meta"),
3626        ];
3627
3628        if !authority_is_fee_payer {
3629            r_accounts.push((authority_account, "authority"));
3630        }
3631
3632        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3633        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3634
3635        let mut accounts = rw_accounts;
3636        accounts.extend(r_accounts);
3637
3638        let mut abi_meta_account_idx = 0u16;
3639        let mut program_meta_account_idx = 0u16;
3640        let mut abi_account_idx = 0u16;
3641        let mut authority_account_idx = 0u16;
3642
3643        for (i, (account, account_type)) in accounts.iter().enumerate() {
3644            let idx = (i + 2) as u16;
3645            match *account_type {
3646                "abi_meta" => {
3647                    abi_meta_account_idx = idx;
3648                    tx = tx.add_r_account(*account);
3649                }
3650                "program_meta" => {
3651                    program_meta_account_idx = idx;
3652                    tx = tx.add_r_account(*account);
3653                }
3654                "abi" => {
3655                    abi_account_idx = idx;
3656                    tx = tx.add_rw_account(*account);
3657                }
3658                "authority" => {
3659                    authority_account_idx = idx;
3660                    tx = tx.add_r_account(*account);
3661                }
3662                _ => unreachable!(),
3663            }
3664        }
3665
3666        let authority_idx = if authority_is_fee_payer {
3667            0u16
3668        } else {
3669            authority_account_idx
3670        };
3671
3672        let instruction_data = build_abi_manager_close_abi_official_instruction(
3673            abi_meta_account_idx,
3674            program_meta_account_idx,
3675            abi_account_idx,
3676            authority_idx,
3677        )?;
3678
3679        tx = tx.with_instructions(instruction_data);
3680        Ok(tx)
3681    }
3682
3683    /// Build ABI manager program CLOSE ABI (external) transaction
3684    pub fn build_abi_manager_close_abi_external(
3685        fee_payer: TnPubkey,
3686        abi_manager_program: TnPubkey,
3687        abi_meta_account: TnPubkey,
3688        abi_account: TnPubkey,
3689        authority_account: TnPubkey,
3690        fee: u64,
3691        nonce: u64,
3692        start_slot: u64,
3693    ) -> Result<Transaction> {
3694        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3695            .with_start_slot(start_slot)
3696            .with_expiry_after(10000)
3697            .with_compute_units(500_000_000)
3698            .with_memory_units(5000)
3699            .with_state_units(0);
3700
3701        let authority_is_fee_payer = authority_account == fee_payer;
3702
3703        let mut rw_accounts = vec![(abi_account, "abi")];
3704        let mut r_accounts = vec![(abi_meta_account, "abi_meta")];
3705
3706        if !authority_is_fee_payer {
3707            r_accounts.push((authority_account, "authority"));
3708        }
3709
3710        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3711        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3712
3713        let mut accounts = rw_accounts;
3714        accounts.extend(r_accounts);
3715
3716        let mut abi_meta_account_idx = 0u16;
3717        let mut abi_account_idx = 0u16;
3718        let mut authority_account_idx = 0u16;
3719
3720        for (i, (account, account_type)) in accounts.iter().enumerate() {
3721            let idx = (i + 2) as u16;
3722            match *account_type {
3723                "abi_meta" => {
3724                    abi_meta_account_idx = idx;
3725                    tx = tx.add_r_account(*account);
3726                }
3727                "abi" => {
3728                    abi_account_idx = idx;
3729                    tx = tx.add_rw_account(*account);
3730                }
3731                "authority" => {
3732                    authority_account_idx = idx;
3733                    tx = tx.add_r_account(*account);
3734                }
3735                _ => unreachable!(),
3736            }
3737        }
3738
3739        let authority_idx = if authority_is_fee_payer {
3740            0u16
3741        } else {
3742            authority_account_idx
3743        };
3744
3745        let instruction_data = build_abi_manager_close_abi_external_instruction(
3746            abi_meta_account_idx,
3747            abi_account_idx,
3748            authority_idx,
3749        )?;
3750
3751        tx = tx.with_instructions(instruction_data);
3752        Ok(tx)
3753    }
3754
3755    /// Build manager program UPGRADE transaction
3756    pub fn build_manager_upgrade(
3757        fee_payer: TnPubkey,
3758        manager_program: TnPubkey,
3759        meta_account: TnPubkey,
3760        program_account: TnPubkey,
3761        srcbuf_account: TnPubkey,
3762        srcbuf_offset: u32,
3763        srcbuf_size: u32,
3764        srcbuf_sha256: [u8; 32],
3765        fee: u64,
3766        nonce: u64,
3767        start_slot: u64,
3768    ) -> Result<Transaction> {
3769        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3770            .with_start_slot(start_slot)
3771            .with_expiry_after(10000)
3772            .with_compute_units(500_000_000)
3773            .with_memory_units(5000)
3774            .with_state_units(account_state_units(srcbuf_size as u64)?.saturating_sub(1));
3775
3776        // Separate accounts by access type and sort each group by pubkey
3777        let mut rw_accounts = vec![(meta_account, "meta"), (program_account, "program")];
3778
3779        let mut r_accounts = vec![(srcbuf_account, "srcbuf")];
3780
3781        // Sort read-write accounts by pubkey
3782        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3783
3784        // Sort read-only accounts by pubkey
3785        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3786
3787        // Combine sorted accounts: read-write first, then read-only
3788        let mut accounts = rw_accounts;
3789        accounts.extend(r_accounts);
3790
3791        let mut meta_account_idx = 0u16;
3792        let mut program_account_idx = 0u16;
3793        let mut srcbuf_account_idx = 0u16;
3794
3795        for (i, (account, account_type)) in accounts.iter().enumerate() {
3796            let idx = (i + 2) as u16; // Skip fee_payer (0) and program (1)
3797            match *account_type {
3798                "meta" => {
3799                    meta_account_idx = idx;
3800                    tx = tx.add_rw_account(*account);
3801                }
3802                "program" => {
3803                    program_account_idx = idx;
3804                    tx = tx.add_rw_account(*account);
3805                }
3806                "srcbuf" => {
3807                    srcbuf_account_idx = idx;
3808                    tx = tx.add_r_account(*account);
3809                }
3810                _ => unreachable!(),
3811            }
3812        }
3813
3814        let instruction_data = build_manager_upgrade_instruction(
3815            meta_account_idx,
3816            program_account_idx,
3817            srcbuf_account_idx,
3818            srcbuf_offset,
3819            srcbuf_size,
3820            srcbuf_sha256,
3821        )?;
3822
3823        tx = tx.with_instructions(instruction_data);
3824        Ok(tx)
3825    }
3826
3827    /// Build manager program SET_PAUSE transaction
3828    pub fn build_manager_set_pause(
3829        fee_payer: TnPubkey,
3830        manager_program: TnPubkey,
3831        meta_account: TnPubkey,
3832        program_account: TnPubkey,
3833        is_paused: bool,
3834        fee: u64,
3835        nonce: u64,
3836        start_slot: u64,
3837    ) -> Result<Transaction> {
3838        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3839            .with_start_slot(start_slot)
3840            .with_expiry_after(10000)
3841            .with_compute_units(100_000_000)
3842            .with_memory_units(5000)
3843            .with_state_units(0);
3844
3845        // Add accounts in sorted order
3846        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3847        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3848
3849        let mut meta_account_idx = 0u16;
3850        let mut program_account_idx = 0u16;
3851
3852        for (i, (account, account_type)) in accounts.iter().enumerate() {
3853            let idx = (i + 2) as u16;
3854            match *account_type {
3855                "meta" => {
3856                    meta_account_idx = idx;
3857                    tx = tx.add_rw_account(*account);
3858                }
3859                "program" => {
3860                    program_account_idx = idx;
3861                    tx = tx.add_rw_account(*account);
3862                }
3863                _ => unreachable!(),
3864            }
3865        }
3866
3867        let instruction_data =
3868            build_manager_set_pause_instruction(meta_account_idx, program_account_idx, is_paused)?;
3869
3870        tx = tx.with_instructions(instruction_data);
3871        Ok(tx)
3872    }
3873
3874    /// Build manager program simple transactions (DESTROY, FINALIZE, CLAIM_AUTHORITY)
3875    pub fn build_manager_simple(
3876        fee_payer: TnPubkey,
3877        manager_program: TnPubkey,
3878        meta_account: TnPubkey,
3879        program_account: TnPubkey,
3880        instruction_type: u8,
3881        fee: u64,
3882        nonce: u64,
3883        start_slot: u64,
3884    ) -> Result<Transaction> {
3885        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3886            .with_start_slot(start_slot)
3887            .with_expiry_after(10000)
3888            .with_compute_units(100_000_000)
3889            .with_memory_units(5000)
3890            .with_state_units(0);
3891
3892        // Add accounts in sorted order
3893        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3894        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3895
3896        let mut meta_account_idx = 0u16;
3897        let mut program_account_idx = 0u16;
3898
3899        for (i, (account, account_type)) in accounts.iter().enumerate() {
3900            let idx = (i + 2) as u16;
3901            match *account_type {
3902                "meta" => {
3903                    meta_account_idx = idx;
3904                    tx = tx.add_rw_account(*account);
3905                }
3906                "program" => {
3907                    program_account_idx = idx;
3908                    tx = tx.add_rw_account(*account);
3909                }
3910                _ => unreachable!(),
3911            }
3912        }
3913
3914        let instruction_data = build_manager_header_instruction(
3915            instruction_type,
3916            meta_account_idx,
3917            program_account_idx,
3918        )?;
3919
3920        tx = tx.with_instructions(instruction_data);
3921        Ok(tx)
3922    }
3923
3924    /// Build manager program SET_AUTHORITY transaction
3925    pub fn build_manager_set_authority(
3926        fee_payer: TnPubkey,
3927        manager_program: TnPubkey,
3928        meta_account: TnPubkey,
3929        program_account: TnPubkey,
3930        authority_candidate: [u8; 32],
3931        fee: u64,
3932        nonce: u64,
3933        start_slot: u64,
3934    ) -> Result<Transaction> {
3935        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3936            .with_start_slot(start_slot)
3937            .with_expiry_after(10000)
3938            .with_compute_units(100_000_000)
3939            .with_memory_units(5000)
3940            .with_state_units(0);
3941
3942        // Add accounts in sorted order
3943        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3944        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3945
3946        let mut meta_account_idx = 0u16;
3947        let mut program_account_idx = 0u16;
3948
3949        for (i, (account, account_type)) in accounts.iter().enumerate() {
3950            let idx = (i + 2) as u16;
3951            match *account_type {
3952                "meta" => {
3953                    meta_account_idx = idx;
3954                    tx = tx.add_rw_account(*account);
3955                }
3956                "program" => {
3957                    program_account_idx = idx;
3958                    tx = tx.add_rw_account(*account);
3959                }
3960                _ => unreachable!(),
3961            }
3962        }
3963
3964        let instruction_data = build_manager_set_authority_instruction(
3965            meta_account_idx,
3966            program_account_idx,
3967            authority_candidate,
3968        )?;
3969
3970        tx = tx.with_instructions(instruction_data);
3971        Ok(tx)
3972    }
3973
3974    /// Build test uploader program CREATE transaction
3975    pub fn build_test_uploader_create(
3976        fee_payer: TnPubkey,
3977        test_uploader_program: TnPubkey,
3978        target_account: TnPubkey,
3979        account_sz: u32,
3980        seed: &[u8],
3981        is_ephemeral: bool,
3982        state_proof: Option<&[u8]>,
3983        fee: u64,
3984        nonce: u64,
3985        start_slot: u64,
3986    ) -> Result<Transaction> {
3987        // Account layout: [0: fee_payer, 1: test_uploader_program, 2: target_account]
3988        let target_account_idx = 2u16;
3989
3990        let tx = Transaction::new(fee_payer, test_uploader_program, fee, nonce)
3991            .with_start_slot(start_slot)
3992            .with_expiry_after(100)
3993            .with_compute_units(100_000 + account_sz)
3994            .with_memory_units(10_000)
3995            .with_state_units(account_state_units(account_sz as u64)?)
3996            .add_rw_account(target_account);
3997
3998        let instruction_data = build_test_uploader_create_instruction(
3999            target_account_idx,
4000            account_sz,
4001            seed,
4002            is_ephemeral,
4003            state_proof,
4004        )?;
4005
4006        let tx = tx.with_instructions(instruction_data);
4007        Ok(tx)
4008    }
4009
4010    /// Build test uploader program WRITE transaction
4011    pub fn build_test_uploader_write(
4012        fee_payer: TnPubkey,
4013        test_uploader_program: TnPubkey,
4014        target_account: TnPubkey,
4015        offset: u32,
4016        data: &[u8],
4017        fee: u64,
4018        nonce: u64,
4019        start_slot: u64,
4020    ) -> Result<Transaction> {
4021        // Account layout: [0: fee_payer, 1: test_uploader_program, 2: target_account]
4022        let target_account_idx = 2u16;
4023
4024        let tx = Transaction::new(fee_payer, test_uploader_program, fee, nonce)
4025            .with_start_slot(start_slot)
4026            .with_expiry_after(10_000)
4027            .with_compute_units(100_000 + 18 * data.len() as u32)
4028            .with_memory_units(10_000)
4029            .with_state_units(0)
4030            .add_rw_account(target_account);
4031
4032        let instruction_data =
4033            build_test_uploader_write_instruction(target_account_idx, offset, data)?;
4034
4035        let tx = tx.with_instructions(instruction_data);
4036        Ok(tx)
4037    }
4038
4039    /// Build legacy system-test DECOMPRESS2 (separate metadata/data accounts).
4040    /// This instruction format is not compatible with the managed compression program.
4041    pub fn build_decompress2(
4042        fee_payer: TnPubkey,
4043        program: TnPubkey,
4044        target_account: TnPubkey,
4045        meta_account: TnPubkey,
4046        data_account: TnPubkey,
4047        data_offset: u32,
4048        state_proof: &[u8],
4049        fee: u64,
4050        nonce: u64,
4051        start_slot: u64,
4052        data_sz: u32,
4053    ) -> Result<Transaction> {
4054        // Account layout: [0: fee_payer, 1: program, 2: target_account, 3+: meta/data accounts]
4055        let mut tx = Transaction::new(fee_payer, program, fee, nonce)
4056            .with_start_slot(start_slot)
4057            .with_expiry_after(100)
4058            .with_compute_units(10_000 + 2 * data_sz)
4059            .with_memory_units(10_000)
4060            .with_state_units(account_state_units(data_sz as u64)?);
4061
4062        // Add target account (read-write)
4063        let target_account_idx = 2u16;
4064        tx = tx.add_rw_account(target_account);
4065
4066        let mut meta_account_idx = 0u16;
4067        let mut data_account_idx = 0u16;
4068
4069        // Handle meta and data accounts - if they're the same, add only once; if different, add both and sort
4070        if meta_account == data_account {
4071            // Same account for both meta and data
4072            let account_idx = 3u16;
4073            meta_account_idx = account_idx;
4074            data_account_idx = account_idx;
4075            tx = tx.add_r_account(meta_account);
4076        } else {
4077            // Different accounts - add both and sort by pubkey
4078            let mut read_accounts = vec![(meta_account, "meta"), (data_account, "data")];
4079            read_accounts.sort_by(|a, b| a.0.cmp(&b.0));
4080
4081            for (i, (account, account_type)) in read_accounts.iter().enumerate() {
4082                let idx = (3 + i) as u16; // Start from index 3
4083                match *account_type {
4084                    "meta" => {
4085                        meta_account_idx = idx;
4086                        tx = tx.add_r_account(*account);
4087                    }
4088                    "data" => {
4089                        data_account_idx = idx;
4090                        tx = tx.add_r_account(*account);
4091                    }
4092                    _ => unreachable!(),
4093                }
4094            }
4095        }
4096
4097        let instruction_data = build_decompress2_instruction(
4098            target_account_idx,
4099            meta_account_idx,
4100            data_account_idx,
4101            data_offset,
4102            state_proof,
4103        )?;
4104
4105        tx = tx.with_instructions(instruction_data);
4106        Ok(tx)
4107    }
4108}
4109
4110/// Build uploader CREATE instruction data
4111fn build_uploader_create_instruction(
4112    buffer_account_idx: u16,
4113    meta_account_idx: u16,
4114    authority_account_idx: u16,
4115    buffer_size: u32,
4116    expected_hash: [u8; 32],
4117    seed: &[u8],
4118) -> Result<Vec<u8>> {
4119    let mut instruction = Vec::new();
4120
4121    // Discriminant (4 bytes, little-endian)
4122    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_CREATE.to_le_bytes());
4123
4124    // Create args struct
4125    let args = UploaderCreateArgs {
4126        buffer_account_idx,
4127        meta_account_idx,
4128        authority_account_idx,
4129        buffer_account_sz: buffer_size,
4130        expected_account_hash: expected_hash,
4131        seed_len: seed.len() as u32,
4132    };
4133
4134    // Serialize args (unsafe due to packed struct)
4135    let args_bytes = unsafe {
4136        std::slice::from_raw_parts(
4137            &args as *const _ as *const u8,
4138            std::mem::size_of::<UploaderCreateArgs>(),
4139        )
4140    };
4141    instruction.extend_from_slice(args_bytes);
4142
4143    // Append seed bytes
4144    instruction.extend_from_slice(seed);
4145
4146    Ok(instruction)
4147}
4148
4149/// Build uploader WRITE instruction data
4150fn build_uploader_write_instruction(
4151    buffer_account_idx: u16,
4152    meta_account_idx: u16,
4153    data: &[u8],
4154    offset: u32,
4155) -> Result<Vec<u8>> {
4156    let mut instruction = Vec::new();
4157
4158    // Discriminant (4 bytes, little-endian)
4159    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_WRITE.to_le_bytes());
4160
4161    // Write args
4162    let args = UploaderWriteArgs {
4163        buffer_account_idx,
4164        meta_account_idx,
4165        data_len: data.len() as u32,
4166        data_offset: offset,
4167    };
4168
4169    // Serialize args
4170    let args_bytes = unsafe {
4171        std::slice::from_raw_parts(
4172            &args as *const _ as *const u8,
4173            std::mem::size_of::<UploaderWriteArgs>(),
4174        )
4175    };
4176    instruction.extend_from_slice(args_bytes);
4177
4178    // Append data
4179    instruction.extend_from_slice(data);
4180
4181    Ok(instruction)
4182}
4183
4184/// Build uploader FINALIZE instruction data
4185fn build_uploader_finalize_instruction(
4186    buffer_account_idx: u16,
4187    meta_account_idx: u16,
4188    expected_hash: [u8; 32],
4189) -> Result<Vec<u8>> {
4190    let mut instruction = Vec::new();
4191
4192    // Discriminant (4 bytes, little-endian)
4193    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_FINALIZE.to_le_bytes());
4194
4195    // Finalize args
4196    let args = UploaderFinalizeArgs {
4197        buffer_account_idx,
4198        meta_account_idx,
4199        expected_account_hash: expected_hash,
4200    };
4201
4202    // Serialize args
4203    let args_bytes = unsafe {
4204        std::slice::from_raw_parts(
4205            &args as *const _ as *const u8,
4206            std::mem::size_of::<UploaderFinalizeArgs>(),
4207        )
4208    };
4209    instruction.extend_from_slice(args_bytes);
4210
4211    Ok(instruction)
4212}
4213
4214/// Build uploader DESTROY instruction data
4215fn build_uploader_destroy_instruction(
4216    buffer_account_idx: u16,
4217    meta_account_idx: u16,
4218) -> Result<Vec<u8>> {
4219    let mut instruction = Vec::new();
4220
4221    // Discriminant (4 bytes, little-endian)
4222    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_DESTROY.to_le_bytes());
4223
4224    // Destroy args
4225    let args = UploaderDestroyArgs {
4226        buffer_account_idx,
4227        meta_account_idx,
4228    };
4229
4230    // Serialize args
4231    let args_bytes = unsafe {
4232        std::slice::from_raw_parts(
4233            &args as *const _ as *const u8,
4234            std::mem::size_of::<UploaderDestroyArgs>(),
4235        )
4236    };
4237    instruction.extend_from_slice(args_bytes);
4238
4239    Ok(instruction)
4240}
4241
4242/// Build manager CREATE instruction data
4243pub fn build_manager_create_instruction(
4244    discriminant: u8,
4245    meta_account_idx: u16,
4246    program_account_idx: u16,
4247    srcbuf_account_idx: u16,
4248    authority_account_idx: u16,
4249    srcbuf_offset: u32,
4250    srcbuf_size: u32,
4251    srcbuf_sha256: [u8; 32],
4252    seed: &[u8],
4253    proof: Option<&[u8]>,
4254) -> Result<Vec<u8>> {
4255    let mut instruction = Vec::new();
4256
4257    // Create args
4258    let args = ManagerCreateArgs {
4259        discriminant,
4260        meta_account_idx,
4261        program_account_idx,
4262        srcbuf_account_idx,
4263        srcbuf_offset,
4264        srcbuf_size,
4265        srcbuf_sha256,
4266        authority_account_idx,
4267        seed_len: seed.len() as u32,
4268    };
4269
4270    // Serialize args
4271    let args_bytes = unsafe {
4272        std::slice::from_raw_parts(
4273            &args as *const ManagerCreateArgs as *const u8,
4274            std::mem::size_of::<ManagerCreateArgs>(),
4275        )
4276    };
4277    instruction.extend_from_slice(args_bytes);
4278
4279    // Add seed bytes
4280    instruction.extend_from_slice(seed);
4281
4282    // Add proof bytes (only for permanent accounts)
4283    if let Some(proof_bytes) = proof {
4284        instruction.extend_from_slice(proof_bytes);
4285    }
4286
4287    Ok(instruction)
4288}
4289
4290/// Build ABI manager CREATE META (official) instruction data
4291pub fn build_abi_manager_create_meta_official_instruction(
4292    discriminant: u8,
4293    abi_meta_account_idx: u16,
4294    program_meta_account_idx: u16,
4295    authority_account_idx: u16,
4296    proof: Option<&[u8]>,
4297) -> Result<Vec<u8>> {
4298    let mut instruction = Vec::new();
4299    instruction.push(discriminant);
4300
4301    let args = AbiManagerCreateMetaOfficialArgs {
4302        abi_meta_account_idx,
4303        program_meta_account_idx,
4304        authority_account_idx,
4305    };
4306
4307    let args_bytes = unsafe {
4308        std::slice::from_raw_parts(
4309            &args as *const AbiManagerCreateMetaOfficialArgs as *const u8,
4310            std::mem::size_of::<AbiManagerCreateMetaOfficialArgs>(),
4311        )
4312    };
4313
4314    instruction.extend_from_slice(args_bytes);
4315    if let Some(proof_bytes) = proof {
4316        instruction.extend_from_slice(proof_bytes);
4317    }
4318
4319    Ok(instruction)
4320}
4321
4322/// Build ABI manager CREATE META (external) instruction data
4323fn build_abi_manager_create_meta_external_instruction(
4324    discriminant: u8,
4325    abi_meta_account_idx: u16,
4326    authority_account_idx: u16,
4327    target_program: TnPubkey,
4328    seed: [u8; 32],
4329    proof: Option<&[u8]>,
4330) -> Result<Vec<u8>> {
4331    let mut instruction = Vec::new();
4332    instruction.push(discriminant);
4333
4334    let args = AbiManagerCreateMetaExternalArgs {
4335        abi_meta_account_idx,
4336        authority_account_idx,
4337        target_program,
4338        seed,
4339    };
4340
4341    let args_bytes = unsafe {
4342        std::slice::from_raw_parts(
4343            &args as *const AbiManagerCreateMetaExternalArgs as *const u8,
4344            std::mem::size_of::<AbiManagerCreateMetaExternalArgs>(),
4345        )
4346    };
4347
4348    instruction.extend_from_slice(args_bytes);
4349    if let Some(proof_bytes) = proof {
4350        instruction.extend_from_slice(proof_bytes);
4351    }
4352
4353    Ok(instruction)
4354}
4355
4356/// Build ABI manager CREATE ABI (official) instruction data
4357pub fn build_abi_manager_create_abi_official_instruction(
4358    discriminant: u8,
4359    abi_meta_account_idx: u16,
4360    program_meta_account_idx: u16,
4361    abi_account_idx: u16,
4362    srcbuf_account_idx: u16,
4363    srcbuf_offset: u32,
4364    srcbuf_size: u32,
4365    srcbuf_sha256: [u8; 32],
4366    authority_account_idx: u16,
4367    proof: Option<&[u8]>,
4368) -> Result<Vec<u8>> {
4369    let mut instruction = Vec::new();
4370    instruction.push(discriminant);
4371
4372    let args = AbiManagerCreateAbiOfficialArgs {
4373        abi_meta_account_idx,
4374        program_meta_account_idx,
4375        abi_account_idx,
4376        srcbuf_account_idx,
4377        srcbuf_offset,
4378        srcbuf_size,
4379        srcbuf_sha256,
4380        authority_account_idx,
4381    };
4382
4383    let args_bytes = unsafe {
4384        std::slice::from_raw_parts(
4385            &args as *const AbiManagerCreateAbiOfficialArgs as *const u8,
4386            std::mem::size_of::<AbiManagerCreateAbiOfficialArgs>(),
4387        )
4388    };
4389
4390    instruction.extend_from_slice(args_bytes);
4391    if let Some(proof_bytes) = proof {
4392        instruction.extend_from_slice(proof_bytes);
4393    }
4394
4395    Ok(instruction)
4396}
4397
4398/// Build ABI manager CREATE ABI (external) instruction data
4399fn build_abi_manager_create_abi_external_instruction(
4400    discriminant: u8,
4401    abi_meta_account_idx: u16,
4402    abi_account_idx: u16,
4403    srcbuf_account_idx: u16,
4404    srcbuf_offset: u32,
4405    srcbuf_size: u32,
4406    srcbuf_sha256: [u8; 32],
4407    authority_account_idx: u16,
4408    proof: Option<&[u8]>,
4409) -> Result<Vec<u8>> {
4410    let mut instruction = Vec::new();
4411    instruction.push(discriminant);
4412
4413    let args = AbiManagerCreateAbiExternalArgs {
4414        abi_meta_account_idx,
4415        abi_account_idx,
4416        srcbuf_account_idx,
4417        srcbuf_offset,
4418        srcbuf_size,
4419        srcbuf_sha256,
4420        authority_account_idx,
4421    };
4422
4423    let args_bytes = unsafe {
4424        std::slice::from_raw_parts(
4425            &args as *const AbiManagerCreateAbiExternalArgs as *const u8,
4426            std::mem::size_of::<AbiManagerCreateAbiExternalArgs>(),
4427        )
4428    };
4429
4430    instruction.extend_from_slice(args_bytes);
4431    if let Some(proof_bytes) = proof {
4432        instruction.extend_from_slice(proof_bytes);
4433    }
4434
4435    Ok(instruction)
4436}
4437
4438pub fn build_abi_manager_upgrade_abi_official_instruction(
4439    abi_meta_account_idx: u16,
4440    program_meta_account_idx: u16,
4441    abi_account_idx: u16,
4442    srcbuf_account_idx: u16,
4443    srcbuf_offset: u32,
4444    srcbuf_size: u32,
4445    srcbuf_sha256: [u8; 32],
4446    authority_account_idx: u16,
4447) -> Result<Vec<u8>> {
4448    let mut instruction = Vec::new();
4449    instruction.push(ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_OFFICIAL);
4450
4451    let args = AbiManagerUpgradeAbiOfficialArgs {
4452        abi_meta_account_idx,
4453        program_meta_account_idx,
4454        abi_account_idx,
4455        srcbuf_account_idx,
4456        srcbuf_offset,
4457        srcbuf_size,
4458        srcbuf_sha256,
4459        authority_account_idx,
4460    };
4461
4462    let args_bytes = unsafe {
4463        std::slice::from_raw_parts(
4464            &args as *const AbiManagerUpgradeAbiOfficialArgs as *const u8,
4465            std::mem::size_of::<AbiManagerUpgradeAbiOfficialArgs>(),
4466        )
4467    };
4468
4469    instruction.extend_from_slice(args_bytes);
4470    Ok(instruction)
4471}
4472
4473fn build_abi_manager_upgrade_abi_external_instruction(
4474    abi_meta_account_idx: u16,
4475    abi_account_idx: u16,
4476    srcbuf_account_idx: u16,
4477    srcbuf_offset: u32,
4478    srcbuf_size: u32,
4479    srcbuf_sha256: [u8; 32],
4480    authority_account_idx: u16,
4481) -> Result<Vec<u8>> {
4482    let mut instruction = Vec::new();
4483    instruction.push(ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_EXTERNAL);
4484
4485    let args = AbiManagerUpgradeAbiExternalArgs {
4486        abi_meta_account_idx,
4487        abi_account_idx,
4488        srcbuf_account_idx,
4489        srcbuf_offset,
4490        srcbuf_size,
4491        srcbuf_sha256,
4492        authority_account_idx,
4493    };
4494
4495    let args_bytes = unsafe {
4496        std::slice::from_raw_parts(
4497            &args as *const AbiManagerUpgradeAbiExternalArgs as *const u8,
4498            std::mem::size_of::<AbiManagerUpgradeAbiExternalArgs>(),
4499        )
4500    };
4501
4502    instruction.extend_from_slice(args_bytes);
4503    Ok(instruction)
4504}
4505
4506fn build_abi_manager_finalize_abi_official_instruction(
4507    abi_meta_account_idx: u16,
4508    program_meta_account_idx: u16,
4509    abi_account_idx: u16,
4510    authority_account_idx: u16,
4511) -> Result<Vec<u8>> {
4512    let mut instruction = Vec::new();
4513    instruction.push(ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_OFFICIAL);
4514
4515    let args = AbiManagerFinalizeAbiOfficialArgs {
4516        abi_meta_account_idx,
4517        program_meta_account_idx,
4518        abi_account_idx,
4519        authority_account_idx,
4520    };
4521
4522    let args_bytes = unsafe {
4523        std::slice::from_raw_parts(
4524            &args as *const AbiManagerFinalizeAbiOfficialArgs as *const u8,
4525            std::mem::size_of::<AbiManagerFinalizeAbiOfficialArgs>(),
4526        )
4527    };
4528
4529    instruction.extend_from_slice(args_bytes);
4530    Ok(instruction)
4531}
4532
4533fn build_abi_manager_finalize_abi_external_instruction(
4534    abi_meta_account_idx: u16,
4535    abi_account_idx: u16,
4536    authority_account_idx: u16,
4537) -> Result<Vec<u8>> {
4538    let mut instruction = Vec::new();
4539    instruction.push(ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_EXTERNAL);
4540
4541    let args = AbiManagerFinalizeAbiExternalArgs {
4542        abi_meta_account_idx,
4543        abi_account_idx,
4544        authority_account_idx,
4545    };
4546
4547    let args_bytes = unsafe {
4548        std::slice::from_raw_parts(
4549            &args as *const AbiManagerFinalizeAbiExternalArgs as *const u8,
4550            std::mem::size_of::<AbiManagerFinalizeAbiExternalArgs>(),
4551        )
4552    };
4553
4554    instruction.extend_from_slice(args_bytes);
4555    Ok(instruction)
4556}
4557
4558fn build_abi_manager_close_abi_official_instruction(
4559    abi_meta_account_idx: u16,
4560    program_meta_account_idx: u16,
4561    abi_account_idx: u16,
4562    authority_account_idx: u16,
4563) -> Result<Vec<u8>> {
4564    let mut instruction = Vec::new();
4565    instruction.push(ABI_MANAGER_INSTRUCTION_CLOSE_ABI_OFFICIAL);
4566
4567    let args = AbiManagerCloseAbiOfficialArgs {
4568        abi_meta_account_idx,
4569        program_meta_account_idx,
4570        abi_account_idx,
4571        authority_account_idx,
4572    };
4573
4574    let args_bytes = unsafe {
4575        std::slice::from_raw_parts(
4576            &args as *const AbiManagerCloseAbiOfficialArgs as *const u8,
4577            std::mem::size_of::<AbiManagerCloseAbiOfficialArgs>(),
4578        )
4579    };
4580
4581    instruction.extend_from_slice(args_bytes);
4582    Ok(instruction)
4583}
4584
4585fn build_abi_manager_close_abi_external_instruction(
4586    abi_meta_account_idx: u16,
4587    abi_account_idx: u16,
4588    authority_account_idx: u16,
4589) -> Result<Vec<u8>> {
4590    let mut instruction = Vec::new();
4591    instruction.push(ABI_MANAGER_INSTRUCTION_CLOSE_ABI_EXTERNAL);
4592
4593    let args = AbiManagerCloseAbiExternalArgs {
4594        abi_meta_account_idx,
4595        abi_account_idx,
4596        authority_account_idx,
4597    };
4598
4599    let args_bytes = unsafe {
4600        std::slice::from_raw_parts(
4601            &args as *const AbiManagerCloseAbiExternalArgs as *const u8,
4602            std::mem::size_of::<AbiManagerCloseAbiExternalArgs>(),
4603        )
4604    };
4605
4606    instruction.extend_from_slice(args_bytes);
4607    Ok(instruction)
4608}
4609
4610/// Build manager UPGRADE instruction data
4611/// Build manager UPGRADE instruction data. `srcbuf_sha256` is the SHA-256 of
4612/// exactly `srcbuf[srcbuf_offset, srcbuf_offset + srcbuf_size)`.
4613pub fn build_manager_upgrade_instruction(
4614    meta_account_idx: u16,
4615    program_account_idx: u16,
4616    srcbuf_account_idx: u16,
4617    srcbuf_offset: u32,
4618    srcbuf_size: u32,
4619    srcbuf_sha256: [u8; 32],
4620) -> Result<Vec<u8>> {
4621    let mut instruction = Vec::new();
4622
4623    let args = ManagerUpgradeArgs {
4624        discriminant: MANAGER_INSTRUCTION_UPGRADE,
4625        meta_account_idx,
4626        program_account_idx,
4627        srcbuf_account_idx,
4628        srcbuf_offset,
4629        srcbuf_size,
4630        srcbuf_sha256,
4631    };
4632
4633    let args_bytes = unsafe {
4634        std::slice::from_raw_parts(
4635            &args as *const ManagerUpgradeArgs as *const u8,
4636            std::mem::size_of::<ManagerUpgradeArgs>(),
4637        )
4638    };
4639    instruction.extend_from_slice(args_bytes);
4640
4641    Ok(instruction)
4642}
4643
4644/// Build manager SET_PAUSE instruction data
4645pub fn build_manager_set_pause_instruction(
4646    meta_account_idx: u16,
4647    program_account_idx: u16,
4648    is_paused: bool,
4649) -> Result<Vec<u8>> {
4650    let mut instruction = Vec::new();
4651
4652    let args = ManagerSetPauseArgs {
4653        discriminant: MANAGER_INSTRUCTION_SET_PAUSE,
4654        meta_account_idx,
4655        program_account_idx,
4656        is_paused: if is_paused { 1 } else { 0 },
4657    };
4658
4659    let args_bytes = unsafe {
4660        std::slice::from_raw_parts(
4661            &args as *const ManagerSetPauseArgs as *const u8,
4662            std::mem::size_of::<ManagerSetPauseArgs>(),
4663        )
4664    };
4665    instruction.extend_from_slice(args_bytes);
4666
4667    Ok(instruction)
4668}
4669
4670/// Build manager header-only instruction data (DESTROY, FINALIZE, CLAIM_AUTHORITY)
4671pub fn build_manager_header_instruction(
4672    discriminant: u8,
4673    meta_account_idx: u16,
4674    program_account_idx: u16,
4675) -> Result<Vec<u8>> {
4676    let mut instruction = Vec::new();
4677
4678    let args = ManagerHeaderArgs {
4679        discriminant,
4680        meta_account_idx,
4681        program_account_idx,
4682    };
4683
4684    let args_bytes = unsafe {
4685        std::slice::from_raw_parts(
4686            &args as *const ManagerHeaderArgs as *const u8,
4687            std::mem::size_of::<ManagerHeaderArgs>(),
4688        )
4689    };
4690    instruction.extend_from_slice(args_bytes);
4691
4692    Ok(instruction)
4693}
4694
4695/// Build manager SET_AUTHORITY instruction data
4696pub fn build_manager_set_authority_instruction(
4697    meta_account_idx: u16,
4698    program_account_idx: u16,
4699    authority_candidate: [u8; 32],
4700) -> Result<Vec<u8>> {
4701    let mut instruction = Vec::new();
4702
4703    let args = ManagerSetAuthorityArgs {
4704        discriminant: MANAGER_INSTRUCTION_SET_AUTHORITY,
4705        meta_account_idx,
4706        program_account_idx,
4707        authority_candidate,
4708    };
4709
4710    let args_bytes = unsafe {
4711        std::slice::from_raw_parts(
4712            &args as *const ManagerSetAuthorityArgs as *const u8,
4713            std::mem::size_of::<ManagerSetAuthorityArgs>(),
4714        )
4715    };
4716    instruction.extend_from_slice(args_bytes);
4717
4718    Ok(instruction)
4719}
4720
4721/// Build test uploader CREATE instruction data
4722fn build_test_uploader_create_instruction(
4723    account_idx: u16,
4724    account_sz: u32,
4725    seed: &[u8],
4726    is_ephemeral: bool,
4727    state_proof: Option<&[u8]>,
4728) -> Result<Vec<u8>> {
4729    let mut instruction = Vec::new();
4730
4731    // Discriminant (1 byte)
4732    instruction.push(TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_CREATE);
4733
4734    // Create args struct
4735    let args = TestUploaderCreateArgs {
4736        account_idx,
4737        is_ephemeral: if is_ephemeral { 1u8 } else { 0u8 },
4738        account_sz,
4739        seed_len: seed.len() as u32,
4740    };
4741
4742    // Serialize args (unsafe due to packed struct)
4743    let args_bytes = unsafe {
4744        std::slice::from_raw_parts(
4745            &args as *const _ as *const u8,
4746            std::mem::size_of::<TestUploaderCreateArgs>(),
4747        )
4748    };
4749    instruction.extend_from_slice(args_bytes);
4750
4751    // Append seed bytes
4752    instruction.extend_from_slice(seed);
4753
4754    // Append state proof if provided (for non-ephemeral accounts)
4755    if let Some(proof) = state_proof {
4756        instruction.extend_from_slice(proof);
4757    }
4758
4759    Ok(instruction)
4760}
4761
4762/// Build test uploader WRITE instruction data
4763fn build_test_uploader_write_instruction(
4764    target_account_idx: u16,
4765    target_offset: u32,
4766    data: &[u8],
4767) -> Result<Vec<u8>> {
4768    let mut instruction = Vec::new();
4769
4770    // Discriminant (1 byte)
4771    instruction.push(TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_WRITE);
4772
4773    // Write args
4774    let args = TestUploaderWriteArgs {
4775        target_account_idx,
4776        target_offset,
4777        data_len: data.len() as u32,
4778    };
4779
4780    // Serialize args
4781    let args_bytes = unsafe {
4782        std::slice::from_raw_parts(
4783            &args as *const _ as *const u8,
4784            std::mem::size_of::<TestUploaderWriteArgs>(),
4785        )
4786    };
4787    instruction.extend_from_slice(args_bytes);
4788
4789    // Append data
4790    instruction.extend_from_slice(data);
4791
4792    Ok(instruction)
4793}
4794
4795/// Build system program DECOMPRESS2 instruction data
4796pub fn build_decompress2_instruction(
4797    target_account_idx: u16,
4798    meta_account_idx: u16,
4799    data_account_idx: u16,
4800    data_offset: u32,
4801    state_proof: &[u8],
4802) -> Result<Vec<u8>> {
4803    let mut instruction = Vec::new();
4804
4805    // Discriminant (1 byte) - TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_DECOMPRESS2 = 0x08
4806    instruction.push(0x08);
4807
4808    // DECOMPRESS2 args
4809    let args = SystemProgramDecompress2Args {
4810        target_account_idx,
4811        meta_account_idx,
4812        data_account_idx,
4813        data_offset,
4814    };
4815
4816    // Serialize args
4817    let args_bytes = unsafe {
4818        std::slice::from_raw_parts(
4819            &args as *const _ as *const u8,
4820            std::mem::size_of::<SystemProgramDecompress2Args>(),
4821        )
4822    };
4823    instruction.extend_from_slice(args_bytes);
4824
4825    // Append state proof bytes
4826    instruction.extend_from_slice(state_proof);
4827
4828    Ok(instruction)
4829}
4830
4831/// Token program instruction discriminants
4832pub const TOKEN_INSTRUCTION_INITIALIZE_MINT: u8 = 0x00;
4833pub const TOKEN_INSTRUCTION_INITIALIZE_ACCOUNT: u8 = 0x01;
4834pub const TOKEN_INSTRUCTION_TRANSFER: u8 = 0x02;
4835pub const TOKEN_INSTRUCTION_MINT_TO: u8 = 0x03;
4836pub const TOKEN_INSTRUCTION_BURN: u8 = 0x04;
4837pub const TOKEN_INSTRUCTION_CLOSE_ACCOUNT: u8 = 0x05;
4838pub const TOKEN_INSTRUCTION_FREEZE_ACCOUNT: u8 = 0x06;
4839pub const TOKEN_INSTRUCTION_THAW_ACCOUNT: u8 = 0x07;
4840pub const TOKEN_INSTRUCTION_TRANSFER_CHECKED: u8 = 0x08;
4841
4842/// Longest ticker a token mint stores, in bytes.
4843pub const TOKEN_TICKER_MAX_LEN: usize = 8;
4844
4845/* WTHRU instruction discriminants */
4846pub const TN_WTHRU_INSTRUCTION_INITIALIZE_MINT: u32 = 0;
4847pub const TN_WTHRU_INSTRUCTION_DEPOSIT: u32 = 1;
4848pub const TN_WTHRU_INSTRUCTION_WITHDRAW: u32 = 2;
4849
4850/// Compute budget for an atomic WTHRU deposit: the standalone deposit
4851/// requests 400,000 and the EOA transfer 10,000; the rest covers Multicall
4852/// and its two invokes.
4853pub const WTHRU_DEPOSIT_WITH_TRANSFER_COMPUTE_UNITS: u32 = 500_000;
4854// lease, resolve (lil library), show lease info,
4855// cost to lease, renew, record management, listing records for domain,
4856// subdomain management
4857
4858/* Name service instruction discriminants */
4859pub const TN_NAME_SERVICE_INSTRUCTION_INITIALIZE_ROOT: u32 = 0;
4860pub const TN_NAME_SERVICE_INSTRUCTION_REGISTER_SUBDOMAIN: u32 = 1;
4861pub const TN_NAME_SERVICE_INSTRUCTION_APPEND_RECORD: u32 = 2;
4862pub const TN_NAME_SERVICE_INSTRUCTION_DELETE_RECORD: u32 = 3;
4863pub const TN_NAME_SERVICE_INSTRUCTION_UNREGISTER: u32 = 4;
4864
4865/* Name service proof discriminants */
4866pub const TN_NAME_SERVICE_PROOF_INLINE: u32 = 0;
4867
4868/* Name service limits */
4869pub const TN_NAME_SERVICE_MAX_DOMAIN_LENGTH: usize = 64;
4870pub const TN_NAME_SERVICE_MAX_KEY_LENGTH: usize = 32;
4871pub const TN_NAME_SERVICE_MAX_VALUE_LENGTH: usize = 256;
4872
4873// Thru registrar instruction types (u32 discriminants)
4874pub const TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY: u32 = 0;
4875pub const TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN: u32 = 1;
4876pub const TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE: u32 = 2;
4877pub const TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN: u32 = 3;
4878
4879/* Block-producer (BP) bond program instruction discriminants (u32).
4880Mirrors programs/c/examples/tn_block_producer_program.h.  Contiguous 0..7
4881(UNTO-1293 removed ClaimFees and closed the discriminant gaps). */
4882pub const TN_BP_INSTRUCTION_CREATE_ACCOUNT: u32 = 0;
4883pub const TN_BP_INSTRUCTION_SET_BOND_AUTHORITY: u32 = 1;
4884pub const TN_BP_INSTRUCTION_DEPOSIT: u32 = 2;
4885pub const TN_BP_INSTRUCTION_WITHDRAWAL: u32 = 3;
4886pub const TN_BP_INSTRUCTION_UPDATE_BOND: u32 = 4;
4887pub const TN_BP_INSTRUCTION_DELETE_ACCOUNT: u32 = 5;
4888pub const TN_BP_INSTRUCTION_SWEEP: u32 = 6;
4889pub const TN_BP_INSTRUCTION_PAY_OUT_BLOCK: u32 = 7;
4890
4891/* BP bond derivation — single source of truth is
4892programs/c/examples/tn_block_producer_derivation.h.  These mirror it byte
4893for byte (asserted by test_bp_bond_derivation_matches_c). */
4894
4895/// SHA256( prefix || signer ) — the bond / bond-TA seed.
4896fn bp_seed_with_prefix(prefix: &[u8], signer: &[u8; 32]) -> [u8; 32] {
4897    use sha2::{Digest, Sha256};
4898    let mut hasher = Sha256::new();
4899    hasher.update(prefix);
4900    hasher.update(signer);
4901    let hash = hasher.finalize();
4902    let mut out = [0u8; 32];
4903    out.copy_from_slice(&hash[..32]);
4904    out
4905}
4906
4907/// bond = PDA( SHA256("bp_bond" || signer), bp_program ).
4908pub fn bp_bond_account_address(bp_program: &[u8; 32], signer: &[u8; 32]) -> [u8; 32] {
4909    let seed = bp_seed_with_prefix(b"bp_bond", signer);
4910    crate::tn_public_address::create_program_defined_account_address(bp_program, false, &seed)
4911}
4912
4913/// bond_ta = PDA( SHA256(bp_program || wthru_mint || SHA256("bp_bond_ta" ||
4914/// signer)), token_program ).
4915pub fn bp_bond_ta_address(
4916    token_program: &[u8; 32],
4917    bp_program: &[u8; 32],
4918    wthru_mint: &[u8; 32],
4919    signer: &[u8; 32],
4920) -> [u8; 32] {
4921    use sha2::{Digest, Sha256};
4922    let ta_seed = bp_seed_with_prefix(b"bp_bond_ta", signer);
4923    let mut hasher = Sha256::new();
4924    hasher.update(bp_program);
4925    hasher.update(wthru_mint);
4926    hasher.update(&ta_seed);
4927    let hash = hasher.finalize();
4928    let mut token_seed = [0u8; 32];
4929    token_seed.copy_from_slice(&hash[..32]);
4930    crate::tn_public_address::create_program_defined_account_address(
4931        token_program,
4932        false,
4933        &token_seed,
4934    )
4935}
4936
4937/// Ed25519 (RFC 8032, strict) signature over the canonical EOA-create
4938/// authorization message [`build_eoa_create_message`]:
4939/// `"tn_eoa_create_v1" || chain_id LE || fee_payer || signer` (82 bytes),
4940/// proving control of `signer_private_key`.  This is exactly what
4941/// `tsys_account_create_eoa` verifies (`tn_vm_syscall_account_create_eoa`)
4942/// and what the BP CreateAccount Mode 2 path requires as
4943/// `signer_eoa_signature`.  The message binds the chain id and the paying fee
4944/// payer, so a signature is valid for one (chain, fee payer, signer) triple.
4945pub fn bp_sign_eoa_creation(
4946    signer_private_key: &[u8; 32],
4947    chain_id: u16,
4948    fee_payer: &TnPubkey,
4949    signer_pubkey: &TnPubkey,
4950) -> [u8; 64] {
4951    use ed25519_dalek::{Signer, SigningKey};
4952    let signing_key = SigningKey::from_bytes(signer_private_key);
4953    let msg = build_eoa_create_message(chain_id, fee_payer, signer_pubkey);
4954    signing_key.sign(&msg).to_bytes()
4955}
4956
4957/// Helper function to add sorted accounts and return their indices
4958fn add_sorted_accounts(tx: Transaction, accounts: &[(TnPubkey, bool)]) -> (Transaction, Vec<u16>) {
4959    // Separate RW and RO accounts, sort each group separately
4960    let mut rw_accounts: Vec<_> = accounts
4961        .iter()
4962        .enumerate()
4963        .filter(|(_, (_, writable))| *writable)
4964        .collect();
4965    let mut ro_accounts: Vec<_> = accounts
4966        .iter()
4967        .enumerate()
4968        .filter(|(_, (_, writable))| !*writable)
4969        .collect();
4970
4971    // Sort each group by pubkey
4972    rw_accounts.sort_by(|a, b| a.1 .0.cmp(&b.1 .0));
4973    ro_accounts.sort_by(|a, b| a.1 .0.cmp(&b.1 .0));
4974
4975    let mut updated_tx = tx;
4976    let mut indices = vec![0u16; accounts.len()];
4977    let mut seen: HashMap<TnPubkey, u16> = HashMap::new();
4978    seen.insert(updated_tx.fee_payer, 0u16);
4979    seen.insert(updated_tx.program, 1u16);
4980
4981    let mut next_idx = 2u16;
4982
4983    // Process RW accounts first (in sorted order)
4984    for (i, (account, _)) in rw_accounts.iter() {
4985        if let Some(idx) = seen.get(account) {
4986            indices[*i] = *idx;
4987            continue;
4988        }
4989
4990        let account_idx = next_idx;
4991        next_idx = next_idx.saturating_add(1);
4992        seen.insert(*account, account_idx);
4993        indices[*i] = account_idx;
4994
4995        updated_tx = updated_tx.add_rw_account(*account);
4996    }
4997
4998    // Then process RO accounts (in sorted order)
4999    for (i, (account, _)) in ro_accounts.iter() {
5000        if let Some(idx) = seen.get(account) {
5001            indices[*i] = *idx;
5002            continue;
5003        }
5004
5005        let account_idx = next_idx;
5006        next_idx = next_idx.saturating_add(1);
5007        seen.insert(*account, account_idx);
5008        indices[*i] = account_idx;
5009
5010        updated_tx = updated_tx.add_r_account(*account);
5011    }
5012
5013    (updated_tx, indices)
5014}
5015
5016/// Helper function to get authority index (0 if fee_payer, else add as readonly)
5017fn add_sorted_rw_accounts(mut tx: Transaction, accounts: &[TnPubkey]) -> (Transaction, Vec<u16>) {
5018    if accounts.is_empty() {
5019        return (tx, Vec::new());
5020    }
5021
5022    let mut sorted: Vec<(usize, TnPubkey)> = accounts.iter().cloned().enumerate().collect();
5023    sorted.sort_by(|a, b| a.1.cmp(&b.1));
5024
5025    let mut indices = vec![0u16; accounts.len()];
5026    for (pos, (orig_idx, account)) in sorted.into_iter().enumerate() {
5027        let idx = (2 + pos) as u16;
5028        indices[orig_idx] = idx;
5029        tx = tx.add_rw_account(account);
5030    }
5031
5032    (tx, indices)
5033}
5034
5035fn add_sorted_ro_accounts(
5036    mut tx: Transaction,
5037    base_idx: u16,
5038    accounts: &[TnPubkey],
5039) -> (Transaction, Vec<u16>) {
5040    if accounts.is_empty() {
5041        return (tx, Vec::new());
5042    }
5043
5044    let mut sorted: Vec<(usize, TnPubkey)> = accounts.iter().cloned().enumerate().collect();
5045    sorted.sort_by(|a, b| a.1.cmp(&b.1));
5046
5047    let mut indices = vec![0u16; accounts.len()];
5048    for (pos, (orig_idx, account)) in sorted.into_iter().enumerate() {
5049        let idx = base_idx + pos as u16;
5050        indices[orig_idx] = idx;
5051        tx = tx.add_r_account(account);
5052    }
5053
5054    (tx, indices)
5055}
5056
5057impl TransactionBuilder {
5058    /// Build token program InitializeMint transaction
5059    pub fn build_token_initialize_mint(
5060        fee_payer: TnPubkey,
5061        token_program: TnPubkey,
5062        mint_account: TnPubkey,
5063        creator: TnPubkey,
5064        mint_authority: TnPubkey,
5065        freeze_authority: Option<TnPubkey>,
5066        decimals: u8,
5067        ticker: &str,
5068        seed: [u8; 32],
5069        state_proof: Vec<u8>,
5070        fee: u64,
5071        nonce: u64,
5072        start_slot: u64,
5073    ) -> Result<Transaction> {
5074        let base_tx =
5075            Transaction::new(fee_payer, token_program, fee, nonce).with_start_slot(start_slot);
5076        let (tx, indices) = add_sorted_rw_accounts(base_tx, &[mint_account]);
5077        let mint_account_idx = indices[0];
5078
5079        let instruction_data = build_token_initialize_mint_instruction(
5080            mint_account_idx,
5081            decimals,
5082            creator,
5083            mint_authority,
5084            freeze_authority,
5085            ticker,
5086            seed,
5087            state_proof,
5088        )?;
5089
5090        let tx = tx
5091            .with_instructions(instruction_data)
5092            .with_expiry_after(100)
5093            .with_compute_units(300_000)
5094            .with_state_units(1)
5095            .with_memory_units(10_000);
5096
5097        Ok(tx)
5098    }
5099
5100    /// Build token program InitializeAccount transaction
5101    pub fn build_token_initialize_account(
5102        fee_payer: TnPubkey,
5103        token_program: TnPubkey,
5104        token_account: TnPubkey,
5105        mint_account: TnPubkey,
5106        owner: TnPubkey,
5107        seed: [u8; 32],
5108        state_proof: Vec<u8>,
5109        fee: u64,
5110        nonce: u64,
5111        start_slot: u64,
5112    ) -> Result<Transaction> {
5113        let owner_is_fee_payer = owner == fee_payer;
5114
5115        let mut rw_accounts = vec![token_account];
5116        rw_accounts.sort();
5117
5118        let mut ro_accounts = vec![mint_account];
5119        if !owner_is_fee_payer {
5120            ro_accounts.push(owner);
5121            ro_accounts.sort();
5122        }
5123
5124        let mut tx =
5125            Transaction::new(fee_payer, token_program, fee, nonce).with_start_slot(start_slot);
5126
5127        let mut token_account_idx = 0u16;
5128        for (i, account) in rw_accounts.iter().enumerate() {
5129            let idx = (2 + i) as u16;
5130            if *account == token_account {
5131                token_account_idx = idx;
5132            }
5133            tx = tx.add_rw_account(*account);
5134        }
5135
5136        let base_ro_idx = 2 + rw_accounts.len() as u16;
5137        let mut mint_account_idx = 0u16;
5138        let mut owner_account_idx = if owner_is_fee_payer { 0u16 } else { 0u16 };
5139        for (i, account) in ro_accounts.iter().enumerate() {
5140            let idx = base_ro_idx + i as u16;
5141            if *account == mint_account {
5142                mint_account_idx = idx;
5143            } else if !owner_is_fee_payer && *account == owner {
5144                owner_account_idx = idx;
5145            }
5146            tx = tx.add_r_account(*account);
5147        }
5148
5149        let instruction_data = build_token_initialize_account_instruction(
5150            token_account_idx,
5151            mint_account_idx,
5152            owner_account_idx,
5153            seed,
5154            state_proof,
5155        )?;
5156
5157        let tx = tx
5158            .with_instructions(instruction_data)
5159            .with_expiry_after(100)
5160            .with_compute_units(300_000)
5161            .with_state_units(1)
5162            .with_memory_units(10_000);
5163
5164        Ok(tx)
5165    }
5166
5167    /// Build token program Transfer transaction
5168    pub fn build_token_transfer(
5169        fee_payer: TnPubkey,
5170        token_program: TnPubkey,
5171        source_account: TnPubkey,
5172        dest_account: TnPubkey,
5173        _authority: TnPubkey,
5174        amount: u64,
5175        fee: u64,
5176        nonce: u64,
5177        start_slot: u64,
5178    ) -> Result<Transaction> {
5179        let mut tx = Transaction::new(fee_payer, token_program, fee, nonce)
5180            .with_start_slot(start_slot)
5181            .with_expiry_after(100)
5182            .with_compute_units(300_000)
5183            .with_state_units(0)
5184            .with_memory_units(10_000);
5185
5186        let is_self_transfer = source_account == dest_account;
5187        let (source_account_idx, dest_account_idx) = if is_self_transfer {
5188            // For self-transfers, add the account only once and use same index
5189            tx = tx.add_rw_account(source_account);
5190            (2u16, 2u16)
5191        } else {
5192            // Add source and dest accounts in sorted order
5193            let accounts = &[(source_account, true), (dest_account, true)];
5194            let (updated_tx, indices) = add_sorted_accounts(tx, accounts);
5195            tx = updated_tx;
5196            (indices[0], indices[1])
5197        };
5198
5199        // Note: For transfers, the authority (source account owner) must sign the transaction
5200        // The token program will verify the signature matches the source account owner
5201
5202        let instruction_data =
5203            build_token_transfer_instruction(source_account_idx, dest_account_idx, amount)?;
5204
5205        Ok(tx.with_instructions(instruction_data))
5206    }
5207
5208    /// Build token program TransferChecked transaction.
5209    ///
5210    /// Like [`Self::build_token_transfer`], but the instruction also names the
5211    /// mint account (read-only) and carries the mint's decimals and ticker.
5212    /// The token program reverts unless they equal the values stored in the
5213    /// mint account. `ticker` is the stored ticker: the first `ticker_len`
5214    /// bytes of the mint's ticker field, at most [`TOKEN_TICKER_MAX_LEN`].
5215    #[allow(clippy::too_many_arguments)]
5216    pub fn build_token_transfer_checked(
5217        fee_payer: TnPubkey,
5218        token_program: TnPubkey,
5219        source_account: TnPubkey,
5220        dest_account: TnPubkey,
5221        mint_account: TnPubkey,
5222        amount: u64,
5223        decimals: u8,
5224        ticker: &[u8],
5225        fee: u64,
5226        nonce: u64,
5227        start_slot: u64,
5228    ) -> Result<Transaction> {
5229        let tx = Transaction::new(fee_payer, token_program, fee, nonce)
5230            .with_start_slot(start_slot)
5231            .with_expiry_after(100)
5232            .with_compute_units(300_000)
5233            .with_state_units(0)
5234            .with_memory_units(10_000);
5235
5236        // Source and dest are read-write, the mint is read-only. A repeated
5237        // account (source == dest) reuses its index.
5238        let accounts = &[
5239            (source_account, true),
5240            (dest_account, true),
5241            (mint_account, false),
5242        ];
5243        let (tx, indices) = add_sorted_accounts(tx, accounts);
5244
5245        let instruction_data = build_token_transfer_checked_instruction(
5246            indices[0], indices[1], indices[2], amount, decimals, ticker,
5247        )?;
5248
5249        Ok(tx.with_instructions(instruction_data))
5250    }
5251
5252    /// Build token program MintTo transaction
5253    pub fn build_token_mint_to(
5254        fee_payer: TnPubkey,
5255        token_program: TnPubkey,
5256        mint_account: TnPubkey,
5257        dest_account: TnPubkey,
5258        authority: TnPubkey,
5259        amount: u64,
5260        fee: u64,
5261        nonce: u64,
5262        start_slot: u64,
5263    ) -> Result<Transaction> {
5264        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
5265            .with_start_slot(start_slot)
5266            .with_expiry_after(100)
5267            .with_compute_units(300_000)
5268            .with_state_units(0)
5269            .with_memory_units(10_000);
5270
5271        let (tx_after_rw, rw_indices) =
5272            add_sorted_rw_accounts(base_tx, &[mint_account, dest_account]);
5273        let mint_account_idx = rw_indices[0];
5274        let dest_account_idx = rw_indices[1];
5275
5276        let mut tx = tx_after_rw;
5277        let authority_account_idx = if authority == fee_payer {
5278            0u16
5279        } else {
5280            let base_ro_idx = 2 + rw_indices.len() as u16;
5281            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5282            tx = tx_after_ro;
5283            ro_indices[0]
5284        };
5285
5286        let instruction_data = build_token_mint_to_instruction(
5287            mint_account_idx,
5288            dest_account_idx,
5289            authority_account_idx,
5290            amount,
5291        )?;
5292
5293        Ok(tx.with_instructions(instruction_data))
5294    }
5295
5296    /// Build token program Burn transaction
5297    pub fn build_token_burn(
5298        fee_payer: TnPubkey,
5299        token_program: TnPubkey,
5300        token_account: TnPubkey,
5301        mint_account: TnPubkey,
5302        authority: TnPubkey,
5303        amount: u64,
5304        fee: u64,
5305        nonce: u64,
5306        start_slot: u64,
5307    ) -> Result<Transaction> {
5308        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
5309            .with_start_slot(start_slot)
5310            .with_expiry_after(100)
5311            .with_compute_units(300_000)
5312            .with_state_units(0)
5313            .with_memory_units(10_000);
5314
5315        let (tx_after_rw, rw_indices) =
5316            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
5317        let token_account_idx = rw_indices[0];
5318        let mint_account_idx = rw_indices[1];
5319
5320        let mut tx = tx_after_rw;
5321        let authority_account_idx = if authority == fee_payer {
5322            0u16
5323        } else {
5324            let base_ro_idx = 2 + rw_indices.len() as u16;
5325            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5326            tx = tx_after_ro;
5327            ro_indices[0]
5328        };
5329
5330        let instruction_data = build_token_burn_instruction(
5331            token_account_idx,
5332            mint_account_idx,
5333            authority_account_idx,
5334            amount,
5335        )?;
5336
5337        Ok(tx.with_instructions(instruction_data))
5338    }
5339
5340    /// Build token program FreezeAccount transaction
5341    pub fn build_token_freeze_account(
5342        fee_payer: TnPubkey,
5343        token_program: TnPubkey,
5344        token_account: TnPubkey,
5345        mint_account: TnPubkey,
5346        authority: TnPubkey,
5347        fee: u64,
5348        nonce: u64,
5349        start_slot: u64,
5350    ) -> Result<Transaction> {
5351        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
5352            .with_start_slot(start_slot)
5353            .with_expiry_after(100)
5354            .with_compute_units(300_000)
5355            .with_state_units(0)
5356            .with_memory_units(10_000);
5357
5358        let (tx_after_rw, rw_indices) =
5359            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
5360        let token_account_idx = rw_indices[0];
5361        let mint_account_idx = rw_indices[1];
5362
5363        let mut tx = tx_after_rw;
5364        let authority_account_idx = if authority == fee_payer {
5365            0u16
5366        } else {
5367            let base_ro_idx = 2 + rw_indices.len() as u16;
5368            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5369            tx = tx_after_ro;
5370            ro_indices[0]
5371        };
5372
5373        let instruction_data = build_token_freeze_account_instruction(
5374            token_account_idx,
5375            mint_account_idx,
5376            authority_account_idx,
5377        )?;
5378
5379        Ok(tx.with_instructions(instruction_data))
5380    }
5381
5382    /// Build token program ThawAccount transaction
5383    pub fn build_token_thaw_account(
5384        fee_payer: TnPubkey,
5385        token_program: TnPubkey,
5386        token_account: TnPubkey,
5387        mint_account: TnPubkey,
5388        authority: TnPubkey,
5389        fee: u64,
5390        nonce: u64,
5391        start_slot: u64,
5392    ) -> Result<Transaction> {
5393        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
5394            .with_start_slot(start_slot)
5395            .with_expiry_after(100)
5396            .with_compute_units(300_000)
5397            .with_state_units(0)
5398            .with_memory_units(10_000);
5399
5400        let (tx_after_rw, rw_indices) =
5401            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
5402        let token_account_idx = rw_indices[0];
5403        let mint_account_idx = rw_indices[1];
5404
5405        let mut tx = tx_after_rw;
5406        let authority_account_idx = if authority == fee_payer {
5407            0u16
5408        } else {
5409            let base_ro_idx = 2 + rw_indices.len() as u16;
5410            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5411            tx = tx_after_ro;
5412            ro_indices[0]
5413        };
5414
5415        let instruction_data = build_token_thaw_account_instruction(
5416            token_account_idx,
5417            mint_account_idx,
5418            authority_account_idx,
5419        )?;
5420
5421        Ok(tx.with_instructions(instruction_data))
5422    }
5423
5424    /// Build token program CloseAccount transaction
5425    pub fn build_token_close_account(
5426        fee_payer: TnPubkey,
5427        token_program: TnPubkey,
5428        token_account: TnPubkey,
5429        destination: TnPubkey,
5430        authority: TnPubkey,
5431        fee: u64,
5432        nonce: u64,
5433        start_slot: u64,
5434    ) -> Result<Transaction> {
5435        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
5436            .with_start_slot(start_slot)
5437            .with_expiry_after(100)
5438            .with_compute_units(300_000)
5439            .with_state_units(0)
5440            .with_memory_units(10_000);
5441
5442        let mut rw_accounts = vec![token_account];
5443        let destination_in_accounts = destination != fee_payer;
5444        if destination_in_accounts {
5445            rw_accounts.push(destination);
5446        }
5447
5448        let (tx_after_rw, rw_indices) = add_sorted_rw_accounts(base_tx, &rw_accounts);
5449        let token_account_idx = rw_indices[0];
5450        let destination_idx = if destination_in_accounts {
5451            rw_indices[1]
5452        } else {
5453            0u16
5454        };
5455
5456        let mut tx = tx_after_rw;
5457        let authority_account_idx = if authority == fee_payer {
5458            0u16
5459        } else {
5460            let base_ro_idx = 2 + rw_indices.len() as u16;
5461            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5462            tx = tx_after_ro;
5463            ro_indices[0]
5464        };
5465
5466        let instruction_data = build_token_close_account_instruction(
5467            token_account_idx,
5468            destination_idx,
5469            authority_account_idx,
5470        )?;
5471
5472        Ok(tx.with_instructions(instruction_data))
5473    }
5474
5475    /// Build WTHRU initialize transaction
5476    pub fn build_wthru_initialize_mint(
5477        fee_payer: TnPubkey,
5478        wthru_program: TnPubkey,
5479        token_program: TnPubkey,
5480        mint_account: TnPubkey,
5481        vault_account: TnPubkey,
5482        decimals: u8,
5483        mint_seed: [u8; 32],
5484        mint_proof: Vec<u8>,
5485        vault_proof: Vec<u8>,
5486        fee: u64,
5487        nonce: u64,
5488        start_slot: u64,
5489    ) -> Result<Transaction> {
5490        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5491            .with_start_slot(start_slot)
5492            .with_expiry_after(100)
5493            .with_compute_units(500_000)
5494            .with_state_units(2) // New mint and vault.
5495            .with_memory_units(10_000);
5496
5497        let accounts = [
5498            (mint_account, true),
5499            (vault_account, true),
5500            (token_program, false),
5501        ];
5502
5503        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5504        tx = tx_with_accounts;
5505
5506        let mint_account_idx = indices[0];
5507        let vault_account_idx = indices[1];
5508        let token_program_idx = indices[2];
5509
5510        let instruction_data = build_wthru_initialize_mint_instruction(
5511            token_program_idx,
5512            mint_account_idx,
5513            vault_account_idx,
5514            decimals,
5515            mint_seed,
5516            mint_proof,
5517            vault_proof,
5518        )?;
5519
5520        Ok(tx.with_instructions(instruction_data))
5521    }
5522
5523    /// Build WTHRU deposit transaction
5524    ///
5525    /// The deposit instruction mints the vault's unaccounted native balance
5526    /// delta to `dest_token_account` and does not transfer any native THRU
5527    /// itself. The transfer into the vault must therefore be in the same
5528    /// transaction as this instruction (e.g. batched via the multicall
5529    /// program); if the two are submitted separately, the delta sits
5530    /// unattributed on-chain and any caller can be credited it instead.
5531    /// [`Self::build_wthru_deposit_with_transfer`] builds that batched
5532    /// transaction. Use this builder on its own only to settle a delta that is
5533    /// already pending in the vault.
5534    pub fn build_wthru_deposit(
5535        fee_payer: TnPubkey,
5536        wthru_program: TnPubkey,
5537        token_program: TnPubkey,
5538        mint_account: TnPubkey,
5539        vault_account: TnPubkey,
5540        dest_token_account: TnPubkey,
5541        fee: u64,
5542        nonce: u64,
5543        start_slot: u64,
5544    ) -> Result<Transaction> {
5545        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5546            .with_start_slot(start_slot)
5547            .with_expiry_after(100)
5548            .with_compute_units(400_000)
5549            .with_state_units(0)
5550            .with_memory_units(10_000);
5551
5552        let accounts = [
5553            (mint_account, true),
5554            (vault_account, true),
5555            (dest_token_account, true),
5556            (token_program, false),
5557        ];
5558
5559        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5560        tx = tx_with_accounts;
5561
5562        let mint_account_idx = indices[0];
5563        let vault_account_idx = indices[1];
5564        let dest_account_idx = indices[2];
5565        let token_program_idx = indices[3];
5566
5567        let instruction_data = build_wthru_deposit_instruction(
5568            token_program_idx,
5569            vault_account_idx,
5570            mint_account_idx,
5571            dest_account_idx,
5572        )?;
5573
5574        Ok(tx.with_instructions(instruction_data))
5575    }
5576
5577    /// Build an atomic WTHRU deposit: fund the vault and mint in one transaction.
5578    ///
5579    /// The top-level program is `multicall_program`, which invokes, in order:
5580    ///
5581    /// 1. `eoa_program` `Transfer` of `amount` from the fee payer (index 0)
5582    ///    to `vault_account`;
5583    /// 2. `wthru_program` `Deposit`, which mints the vault's unaccounted
5584    ///    balance delta to `dest_token_account`.
5585    ///
5586    /// Both callees revert the whole transaction on failure, so the transfer
5587    /// and the mint land together or not at all, and no other caller can claim
5588    /// the transferred amount in between (see [`Self::build_wthru_deposit`]).
5589    /// The deposit mints the whole pending delta, so any delta already in the
5590    /// vault when this transaction executes is minted to `dest_token_account`
5591    /// as well.
5592    ///
5593    /// Account layout: `[0] fee_payer`, `[1] multicall_program`, then the
5594    /// read-write accounts `{mint, vault, dest_token_account}` sorted by
5595    /// pubkey, then the read-only programs `{token, wthru, eoa}` sorted by
5596    /// pubkey.
5597    #[allow(clippy::too_many_arguments)]
5598    pub fn build_wthru_deposit_with_transfer(
5599        fee_payer: TnPubkey,
5600        multicall_program: TnPubkey,
5601        eoa_program: TnPubkey,
5602        wthru_program: TnPubkey,
5603        token_program: TnPubkey,
5604        mint_account: TnPubkey,
5605        vault_account: TnPubkey,
5606        dest_token_account: TnPubkey,
5607        amount: u64,
5608        fee: u64,
5609        nonce: u64,
5610        start_slot: u64,
5611    ) -> Result<Transaction> {
5612        let tx = Transaction::new(fee_payer, multicall_program, fee, nonce)
5613            .with_start_slot(start_slot)
5614            .with_expiry_after(100)
5615            .with_compute_units(WTHRU_DEPOSIT_WITH_TRANSFER_COMPUTE_UNITS)
5616            .with_state_units(0)
5617            .with_memory_units(10_000);
5618
5619        let accounts = [
5620            (mint_account, true),
5621            (vault_account, true),
5622            (dest_token_account, true),
5623            (token_program, false),
5624            (wthru_program, false),
5625            (eoa_program, false),
5626        ];
5627
5628        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5629
5630        let mint_account_idx = indices[0];
5631        let vault_account_idx = indices[1];
5632        let dest_account_idx = indices[2];
5633        let token_program_idx = indices[3];
5634        let wthru_program_idx = indices[4];
5635        let eoa_program_idx = indices[5];
5636
5637        // The fee payer (index 0) funds the vault. It signed the transaction,
5638        // so the EOA program sees it as authorized inside the Multicall invoke.
5639        let transfer = build_transfer_instruction(0, vault_account_idx, amount)?;
5640        let deposit = build_wthru_deposit_instruction(
5641            token_program_idx,
5642            vault_account_idx,
5643            mint_account_idx,
5644            dest_account_idx,
5645        )?;
5646
5647        let instruction_data = crate::program_abi::build_multicall_instruction(&[
5648            (eoa_program_idx, transfer),
5649            (wthru_program_idx, deposit),
5650        ])?;
5651
5652        Ok(tx.with_instructions(instruction_data))
5653    }
5654
5655    /// Build WTHRU withdraw transaction
5656    pub fn build_wthru_withdraw(
5657        fee_payer: TnPubkey,
5658        wthru_program: TnPubkey,
5659        token_program: TnPubkey,
5660        mint_account: TnPubkey,
5661        vault_account: TnPubkey,
5662        wthru_token_account: TnPubkey,
5663        recipient_account: TnPubkey,
5664        amount: u64,
5665        fee: u64,
5666        nonce: u64,
5667        start_slot: u64,
5668    ) -> Result<Transaction> {
5669        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5670            .with_start_slot(start_slot)
5671            .with_expiry_after(100)
5672            .with_compute_units(400_000)
5673            .with_state_units(0)
5674            .with_memory_units(10_000);
5675
5676        let accounts = [
5677            (mint_account, true),
5678            (vault_account, true),
5679            (wthru_token_account, true),
5680            (recipient_account, true),
5681            (token_program, false),
5682        ];
5683
5684        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5685        tx = tx_with_accounts;
5686
5687        let mint_account_idx = indices[0];
5688        let vault_account_idx = indices[1];
5689        let token_account_idx = indices[2];
5690        let recipient_account_idx = indices[3];
5691        let token_program_idx = indices[4];
5692
5693        let owner_account_idx = 0u16; // fee payer/owner
5694
5695        let instruction_data = build_wthru_withdraw_instruction(
5696            token_program_idx,
5697            vault_account_idx,
5698            mint_account_idx,
5699            token_account_idx,
5700            owner_account_idx,
5701            recipient_account_idx,
5702            amount,
5703        )?;
5704
5705        Ok(tx.with_instructions(instruction_data))
5706    }
5707
5708    /// Build a block-producer (BP) bond CreateAccount transaction (disc 0).
5709    ///
5710    /// Two modes (see tn_block_producer_program.h:124-145):
5711    /// * Mode 1 (`create_signer_eoa == false`): the signer IS the fee payer; the
5712    ///   runtime-verified txn signature proves control.  `eoa_proof` must be
5713    ///   empty and `signer_eoa_signature` is ignored (pass zeros).
5714    /// * Mode 2 (`create_signer_eoa == true`): a third party pays.  The program
5715    ///   creates the signer's EOA via `account_create_eoa`, which requires
5716    ///   `signer_eoa_signature` = Ed25519 by the signer's key over the canonical
5717    ///   EOA-create authorization (chain id, fee payer, signer; see
5718    ///   [`bp_sign_eoa_creation`]) and the signer-EOA CREATION `eoa_proof`.
5719    ///
5720    /// Account writability: bond=rw, bond_ta=rw, mint=ro, token_program=ro, and
5721    /// in Mode 2 the signer EOA (== signer_pubkey) = rw (it is created here).
5722    #[allow(clippy::too_many_arguments)]
5723    pub fn build_bp_create_account(
5724        fee_payer: TnPubkey,
5725        bp_program: TnPubkey,
5726        token_program: TnPubkey,
5727        bond_account: TnPubkey,
5728        bond_ta: TnPubkey,
5729        mint_account: TnPubkey,
5730        signer_pubkey: TnPubkey,
5731        bond_authority: TnPubkey,
5732        create_signer_eoa: bool,
5733        signer_eoa_signature: [u8; 64],
5734        bond_proof: Vec<u8>,
5735        ta_proof: Vec<u8>,
5736        eoa_proof: Vec<u8>,
5737        fee: u64,
5738        nonce: u64,
5739        start_slot: u64,
5740    ) -> Result<Transaction> {
5741        let tx = Transaction::new(fee_payer, bp_program, fee, nonce)
5742            .with_start_slot(start_slot)
5743            .with_expiry_after(100)
5744            .with_compute_units(50_000_000)
5745            .with_state_units(2 + u16::from(create_signer_eoa)) // Bond, token account, optional EOA.
5746            .with_memory_units(10_000);
5747
5748        let mut accounts: Vec<(TnPubkey, bool)> = vec![
5749            (bond_account, true),
5750            (bond_ta, true),
5751            (mint_account, false),
5752            (token_program, false),
5753        ];
5754        if create_signer_eoa {
5755            /* The signer EOA is created by account_create_eoa, so it must be a
5756            writable creating account (mirrors the C Mode 2 test). */
5757            accounts.push((signer_pubkey, true));
5758        }
5759
5760        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5761        let bond_account_idx = indices[0];
5762        let bond_ta_idx = indices[1];
5763        let mint_account_idx = indices[2];
5764        let token_program_idx = indices[3];
5765        let signer_eoa_idx = if create_signer_eoa { indices[4] } else { 0u16 };
5766
5767        let instruction_data = build_bp_create_account_instruction(
5768            token_program_idx,
5769            bond_account_idx,
5770            bond_ta_idx,
5771            mint_account_idx,
5772            signer_eoa_idx,
5773            create_signer_eoa,
5774            &signer_pubkey,
5775            &bond_authority,
5776            &signer_eoa_signature,
5777            &bond_proof,
5778            &ta_proof,
5779            &eoa_proof,
5780        )?;
5781
5782        Ok(tx.with_instructions(instruction_data))
5783    }
5784
5785    /// Build a BP SetBondAuthority transaction (disc 2).  The current bond
5786    /// authority signs by being the fee payer.
5787    pub fn build_bp_set_authority(
5788        fee_payer: TnPubkey,
5789        bp_program: TnPubkey,
5790        bond_account: TnPubkey,
5791        new_bond_authority: TnPubkey,
5792        fee: u64,
5793        nonce: u64,
5794        start_slot: u64,
5795    ) -> Result<Transaction> {
5796        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5797        let (tx, indices) = add_sorted_accounts(tx, &[(bond_account, true)]);
5798        let bond_account_idx = indices[0];
5799
5800        let mut instruction_data = Vec::new();
5801        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_SET_BOND_AUTHORITY.to_le_bytes());
5802        instruction_data.extend_from_slice(&bond_account_idx.to_le_bytes());
5803        instruction_data.extend_from_slice(&new_bond_authority);
5804
5805        Ok(tx.with_instructions(instruction_data))
5806    }
5807
5808    /// Build a BP Deposit transaction (disc 3).  Stages `amount` from the
5809    /// operator's `source_ta` into the bond TA.  The bond authority and the
5810    /// source-TA owner are both the fee payer.
5811    #[allow(clippy::too_many_arguments)]
5812    pub fn build_bp_deposit(
5813        fee_payer: TnPubkey,
5814        bp_program: TnPubkey,
5815        token_program: TnPubkey,
5816        bond_account: TnPubkey,
5817        bond_ta: TnPubkey,
5818        source_ta: TnPubkey,
5819        amount: u64,
5820        fee: u64,
5821        nonce: u64,
5822        start_slot: u64,
5823    ) -> Result<Transaction> {
5824        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5825        let accounts = [
5826            (bond_account, true),
5827            (bond_ta, true),
5828            (source_ta, true),
5829            (token_program, false),
5830        ];
5831        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5832
5833        let mut instruction_data = Vec::new();
5834        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_DEPOSIT.to_le_bytes());
5835        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // token_program_idx
5836        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5837        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5838        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // source_ta_idx
5839        instruction_data.extend_from_slice(&amount.to_le_bytes());
5840
5841        Ok(tx.with_instructions(instruction_data))
5842    }
5843
5844    /// Build a BP Withdrawal transaction (disc 4).  `from_active` selects the
5845    /// staged (immediate) or active (lockout-gated) path.
5846    #[allow(clippy::too_many_arguments)]
5847    pub fn build_bp_withdrawal(
5848        fee_payer: TnPubkey,
5849        bp_program: TnPubkey,
5850        token_program: TnPubkey,
5851        bond_account: TnPubkey,
5852        bond_ta: TnPubkey,
5853        dest_ta: TnPubkey,
5854        attestor_table: TnPubkey,
5855        from_active: bool,
5856        amount: u64,
5857        fee: u64,
5858        nonce: u64,
5859        start_slot: u64,
5860    ) -> Result<Transaction> {
5861        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5862        let accounts = [
5863            (bond_account, true),
5864            (bond_ta, true),
5865            (dest_ta, true),
5866            (attestor_table, false),
5867            (token_program, false),
5868        ];
5869        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5870
5871        let mut instruction_data = Vec::new();
5872        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_WITHDRAWAL.to_le_bytes());
5873        instruction_data.extend_from_slice(&indices[4].to_le_bytes()); // token_program_idx
5874        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5875        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5876        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // dest_ta_idx
5877        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // attestor_table_idx
5878        instruction_data.push(if from_active { 1u8 } else { 0u8 });
5879        instruction_data.extend_from_slice(&amount.to_le_bytes());
5880
5881        Ok(tx.with_instructions(instruction_data))
5882    }
5883
5884    /// Build a BP UpdateBond transaction (disc 5).  Moves funds between staged
5885    /// and active to reach `new_active`, raising `unlock_slot`.
5886    #[allow(clippy::too_many_arguments)]
5887    pub fn build_bp_update_bond(
5888        fee_payer: TnPubkey,
5889        bp_program: TnPubkey,
5890        bond_account: TnPubkey,
5891        attestor_table: TnPubkey,
5892        new_unlock_slot: u64,
5893        new_active: u64,
5894        fee: u64,
5895        nonce: u64,
5896        start_slot: u64,
5897    ) -> Result<Transaction> {
5898        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5899        let accounts = [(bond_account, true), (attestor_table, false)];
5900        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5901
5902        let mut instruction_data = Vec::new();
5903        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_UPDATE_BOND.to_le_bytes());
5904        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5905        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // attestor_table_idx
5906        instruction_data.extend_from_slice(&new_unlock_slot.to_le_bytes());
5907        instruction_data.extend_from_slice(&new_active.to_le_bytes());
5908
5909        Ok(tx.with_instructions(instruction_data))
5910    }
5911
5912    /// Build a BP DeleteAccount transaction (disc 6).  Returns native lamports
5913    /// to `dest`; requires active==0 && staged==0 && slot>=unlock_slot.  `dest`
5914    /// may equal the fee payer (collapses to index 0 via add_sorted_accounts).
5915    pub fn build_bp_delete_account(
5916        fee_payer: TnPubkey,
5917        bp_program: TnPubkey,
5918        bond_account: TnPubkey,
5919        dest: TnPubkey,
5920        fee: u64,
5921        nonce: u64,
5922        start_slot: u64,
5923    ) -> Result<Transaction> {
5924        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5925        let accounts = [(bond_account, true), (dest, true)];
5926        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5927
5928        let mut instruction_data = Vec::new();
5929        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_DELETE_ACCOUNT.to_le_bytes());
5930        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5931        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // dest_idx
5932
5933        Ok(tx.with_instructions(instruction_data))
5934    }
5935
5936    /// Build a BP Sweep transaction (disc 7).  Reclaims stray inbound transfers
5937    /// (bond_TA.balance - active - staged) to `dest_ta`.
5938    #[allow(clippy::too_many_arguments)]
5939    pub fn build_bp_sweep(
5940        fee_payer: TnPubkey,
5941        bp_program: TnPubkey,
5942        token_program: TnPubkey,
5943        bond_account: TnPubkey,
5944        bond_ta: TnPubkey,
5945        dest_ta: TnPubkey,
5946        fee: u64,
5947        nonce: u64,
5948        start_slot: u64,
5949    ) -> Result<Transaction> {
5950        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5951        let accounts = [
5952            (bond_account, true),
5953            (bond_ta, true),
5954            (dest_ta, true),
5955            (token_program, false),
5956        ];
5957        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5958
5959        let mut instruction_data = Vec::new();
5960        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_SWEEP.to_le_bytes());
5961        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // token_program_idx
5962        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5963        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5964        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // dest_ta_idx
5965
5966        Ok(tx.with_instructions(instruction_data))
5967    }
5968
5969    /// Build faucet program Deposit transaction
5970    /// The faucet program will invoke the EOA program to transfer from depositor to faucet account
5971    pub fn build_faucet_deposit(
5972        fee_payer: TnPubkey,
5973        faucet_program: TnPubkey,
5974        faucet_account: TnPubkey,
5975        depositor_account: TnPubkey,
5976        eoa_program: TnPubkey,
5977        amount: u64,
5978        fee: u64,
5979        nonce: u64,
5980        start_slot: u64,
5981    ) -> Result<Transaction> {
5982        let tx = Transaction::new(fee_payer, faucet_program, fee, nonce)
5983            .with_start_slot(start_slot)
5984            .with_expiry_after(100)
5985            .with_compute_units(300_000)
5986            .with_state_units(0)
5987            .with_memory_units(10_000);
5988
5989        let (tx, depositor_account_idx) = Self::ensure_rw_account(tx, depositor_account);
5990        let (tx, faucet_account_idx) = Self::ensure_rw_account(tx, faucet_account);
5991        let (tx, eoa_program_idx) = Self::ensure_ro_account(tx, eoa_program);
5992
5993        let instruction_data = build_faucet_deposit_instruction(
5994            faucet_account_idx,
5995            depositor_account_idx,
5996            eoa_program_idx,
5997            amount,
5998        )?;
5999
6000        Ok(tx.with_instructions(instruction_data))
6001    }
6002
6003    fn resolve_account_index(tx: &Transaction, target: &TnPubkey) -> Option<u16> {
6004        if *target == tx.fee_payer {
6005            return Some(0u16);
6006        }
6007
6008        if *target == tx.program {
6009            return Some(1u16);
6010        }
6011
6012        if let Some(ref rw) = tx.rw_accs {
6013            if let Some(pos) = rw.iter().position(|acc| acc == target) {
6014                return Some(2u16 + pos as u16);
6015            }
6016        }
6017
6018        if let Some(ref ro) = tx.r_accs {
6019            let base = 2u16 + tx.rw_accs.as_ref().map_or(0u16, |v| v.len() as u16);
6020            if let Some(pos) = ro.iter().position(|acc| acc == target) {
6021                return Some(base + pos as u16);
6022            }
6023        }
6024
6025        None
6026    }
6027
6028    fn ensure_rw_account(mut tx: Transaction, account: TnPubkey) -> (Transaction, u16) {
6029        if let Some(idx) = Self::resolve_account_index(&tx, &account) {
6030            return (tx, idx);
6031        }
6032
6033        tx = tx.add_rw_account(account);
6034        let idx = Self::resolve_account_index(&tx, &account)
6035            .expect("read-write account index should exist after insertion");
6036
6037        (tx, idx)
6038    }
6039
6040    fn ensure_ro_account(mut tx: Transaction, account: TnPubkey) -> (Transaction, u16) {
6041        if let Some(idx) = Self::resolve_account_index(&tx, &account) {
6042            return (tx, idx);
6043        }
6044
6045        tx = tx.add_r_account(account);
6046        let idx = Self::resolve_account_index(&tx, &account)
6047            .expect("read-only account index should exist after insertion");
6048
6049        (tx, idx)
6050    }
6051
6052    /// Build faucet program Withdraw transaction
6053    pub fn build_faucet_withdraw(
6054        fee_payer: TnPubkey,
6055        faucet_program: TnPubkey,
6056        faucet_account: TnPubkey,
6057        recipient_account: TnPubkey,
6058        amount: u64,
6059        fee: u64,
6060        nonce: u64,
6061        start_slot: u64,
6062    ) -> Result<Transaction> {
6063        let mut tx = Transaction::new(fee_payer, faucet_program, fee, nonce)
6064            .with_start_slot(start_slot)
6065            .with_expiry_after(100)
6066            .with_compute_units(300_000)
6067            .with_state_units(0)
6068            .with_memory_units(10_000);
6069
6070        // Determine account indices, handling duplicates with fee_payer and between accounts
6071        // Check for duplicates first
6072        let faucet_is_fee_payer = faucet_account == fee_payer;
6073        let recipient_is_fee_payer = recipient_account == fee_payer;
6074        let recipient_is_faucet = recipient_account == faucet_account;
6075
6076        let (faucet_account_idx, recipient_account_idx) =
6077            if faucet_is_fee_payer && recipient_is_fee_payer {
6078                // Both are fee_payer (same account)
6079                (0u16, 0u16)
6080            } else if faucet_is_fee_payer {
6081                // Faucet is fee_payer, recipient is different
6082                tx = tx.add_rw_account(recipient_account);
6083                (0u16, 2u16)
6084            } else if recipient_is_fee_payer {
6085                // Recipient is fee_payer, faucet is different
6086                tx = tx.add_rw_account(faucet_account);
6087                (2u16, 0u16)
6088            } else if recipient_is_faucet {
6089                // Both are same account (but not fee_payer)
6090                tx = tx.add_rw_account(faucet_account);
6091                (2u16, 2u16)
6092            } else {
6093                // Both are different accounts, add in sorted order
6094                if faucet_account < recipient_account {
6095                    tx = tx.add_rw_account(faucet_account);
6096                    tx = tx.add_rw_account(recipient_account);
6097                    (2u16, 3u16)
6098                } else {
6099                    tx = tx.add_rw_account(recipient_account);
6100                    tx = tx.add_rw_account(faucet_account);
6101                    (3u16, 2u16)
6102                }
6103            };
6104
6105        let instruction_data =
6106            build_faucet_withdraw_instruction(faucet_account_idx, recipient_account_idx, amount)?;
6107
6108        Ok(tx.with_instructions(instruction_data))
6109    }
6110
6111    /// Build consensus validator program ACTIVATE transaction.
6112    ///
6113    /// This creates a transaction that activates a validator in the consensus system.
6114    /// The validator must have tokens in their source_token_account which will be
6115    /// transferred to the converted_vault.
6116    ///
6117    /// # Arguments
6118    /// * `fee_payer` - The validator identity (also the signer)
6119    /// * `source_token_account` - The validator's WTHRU token account holding the stake
6120    /// * `bls_pk` - BLS public key for the validator as tn_bls_pubkey_t bytes
6121    /// * `bls_pop` - Proof over compressed `bls_pk` followed by `fee_payer`,
6122    ///   under the PoP tag, as tn_bls_signature_t bytes
6123    /// * `claim_authority` - Pubkey that can claim rewards for this validator
6124    /// * `token_amount` - WTHRU base units to stake (a whole, nonzero multiple of the table's min_stake, the stake increment)
6125    /// * `fee` - Transaction fee
6126    /// * `nonce` - Account nonce
6127    /// * `start_slot` - Starting slot for transaction validity
6128    pub fn build_activate(
6129        fee_payer: TnPubkey,
6130        source_token_account: TnPubkey,
6131        bls_pk: [u8; 96],
6132        bls_pop: [u8; 192],
6133        claim_authority: TnPubkey,
6134        token_amount: u64,
6135        fee: u64,
6136        nonce: u64,
6137        start_slot: u64,
6138    ) -> Result<Transaction> {
6139        Self::build_activate_with_accounts(
6140            fee_payer,
6141            ConsensusValidatorAccounts::default(),
6142            source_token_account,
6143            bls_pk,
6144            bls_pop,
6145            claim_authority,
6146            token_amount,
6147            fee,
6148            nonce,
6149            start_slot,
6150        )
6151    }
6152
6153    /// Build consensus validator program ACTIVATE transaction using custom fixed
6154    /// account addresses.
6155    pub fn build_activate_with_accounts(
6156        fee_payer: TnPubkey,
6157        accounts: ConsensusValidatorAccounts,
6158        source_token_account: TnPubkey,
6159        bls_pk: [u8; 96],
6160        bls_pop: [u8; 192],
6161        claim_authority: TnPubkey,
6162        token_amount: u64,
6163        fee: u64,
6164        nonce: u64,
6165        start_slot: u64,
6166    ) -> Result<Transaction> {
6167        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot)
6168            .with_compute_units(CONSENSUS_VALIDATOR_PROOF_COMPUTE_UNITS);
6169
6170        /* Add accounts - must be sorted by pubkey within RW and RO groups:
6171        RW: attestor_table, source_token_account, converted_vault
6172        RO: token_program
6173        identity/fee_payer is already index 0 */
6174        let accounts = [
6175            (accounts.attestor_table, true),  /* RW */
6176            (source_token_account, true),     /* RW */
6177            (accounts.converted_vault, true), /* RW */
6178            (accounts.token_program, false),  /* RO */
6179        ];
6180        let (tx, indices) = add_sorted_accounts(tx, &accounts);
6181        let attestor_table_idx = indices[0];
6182        let source_token_account_idx = indices[1];
6183        let converted_vault_idx = indices[2];
6184        let token_program_idx = indices[3];
6185
6186        /* fee_payer is always index 0 */
6187        let identity_idx = 0u16;
6188
6189        let instruction_data = build_activate_instruction(
6190            attestor_table_idx as u64,
6191            token_program_idx,
6192            source_token_account_idx,
6193            converted_vault_idx,
6194            identity_idx,
6195            bls_pk,
6196            bls_pop,
6197            claim_authority,
6198            token_amount,
6199        )?;
6200
6201        Ok(tx.with_instructions(instruction_data))
6202    }
6203
6204    /// Build consensus validator program DEACTIVATE transaction.
6205    pub fn build_deactivate(
6206        fee_payer: TnPubkey,
6207        dest_token_account: TnPubkey,
6208        fee: u64,
6209        nonce: u64,
6210        start_slot: u64,
6211    ) -> Result<Transaction> {
6212        Self::build_deactivate_with_accounts(
6213            fee_payer,
6214            ConsensusValidatorAccounts::default(),
6215            dest_token_account,
6216            fee,
6217            nonce,
6218            start_slot,
6219        )
6220    }
6221
6222    /// Build consensus validator program DEACTIVATE transaction using custom
6223    /// fixed account addresses.
6224    pub fn build_deactivate_with_accounts(
6225        fee_payer: TnPubkey,
6226        accounts: ConsensusValidatorAccounts,
6227        dest_token_account: TnPubkey,
6228        fee: u64,
6229        nonce: u64,
6230        start_slot: u64,
6231    ) -> Result<Transaction> {
6232        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
6233
6234        let tx_accounts = [
6235            (accounts.attestor_table, true),
6236            (accounts.unclaimed_vault, true),
6237            (dest_token_account, true),
6238            (accounts.token_program, false),
6239        ];
6240        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
6241        let attestor_table_idx = indices[0];
6242        let unclaimed_vault_idx = indices[1];
6243        let dest_token_account_idx = indices[2];
6244        let token_program_idx = indices[3];
6245
6246        let instruction_data = build_deactivate_instruction(
6247            attestor_table_idx as u64,
6248            token_program_idx,
6249            unclaimed_vault_idx,
6250            dest_token_account_idx,
6251            0u16,
6252        )?;
6253
6254        Ok(tx.with_instructions(instruction_data))
6255    }
6256
6257    /// Build consensus validator program CONVERT_TOKENS transaction.
6258    /// `token_amount` is WTHRU base units: a whole, nonzero multiple of the
6259    /// table's min_stake (the stake increment); it adds
6260    /// `token_amount / stake_units_per_weight` power.
6261    pub fn build_convert_tokens(
6262        fee_payer: TnPubkey,
6263        source_token_account: TnPubkey,
6264        token_amount: u64,
6265        fee: u64,
6266        nonce: u64,
6267        start_slot: u64,
6268    ) -> Result<Transaction> {
6269        Self::build_convert_tokens_with_accounts(
6270            fee_payer,
6271            ConsensusValidatorAccounts::default(),
6272            source_token_account,
6273            token_amount,
6274            fee,
6275            nonce,
6276            start_slot,
6277        )
6278    }
6279
6280    /// Build consensus validator program CONVERT_TOKENS transaction using
6281    /// custom fixed account addresses.
6282    pub fn build_convert_tokens_with_accounts(
6283        fee_payer: TnPubkey,
6284        accounts: ConsensusValidatorAccounts,
6285        source_token_account: TnPubkey,
6286        token_amount: u64,
6287        fee: u64,
6288        nonce: u64,
6289        start_slot: u64,
6290    ) -> Result<Transaction> {
6291        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
6292
6293        let tx_accounts = [
6294            (accounts.attestor_table, true),
6295            (source_token_account, true),
6296            (accounts.converted_vault, true),
6297            (accounts.token_program, false),
6298        ];
6299        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
6300        let attestor_table_idx = indices[0];
6301        let source_token_account_idx = indices[1];
6302        let converted_vault_idx = indices[2];
6303        let token_program_idx = indices[3];
6304
6305        let instruction_data = build_convert_tokens_instruction(
6306            attestor_table_idx as u64,
6307            token_program_idx,
6308            source_token_account_idx,
6309            converted_vault_idx,
6310            0u16,
6311            token_amount,
6312        )?;
6313
6314        Ok(tx.with_instructions(instruction_data))
6315    }
6316
6317    /// Build consensus validator program CLAIM transaction.
6318    pub fn build_claim(
6319        fee_payer: TnPubkey,
6320        subject_attestor: TnPubkey,
6321        dest_token_account: TnPubkey,
6322        fee: u64,
6323        nonce: u64,
6324        start_slot: u64,
6325    ) -> Result<Transaction> {
6326        Self::build_claim_with_accounts(
6327            fee_payer,
6328            ConsensusValidatorAccounts::default(),
6329            subject_attestor,
6330            dest_token_account,
6331            fee,
6332            nonce,
6333            start_slot,
6334        )
6335    }
6336
6337    /// Build consensus validator program CLAIM transaction using custom fixed
6338    /// account addresses.
6339    pub fn build_claim_with_accounts(
6340        fee_payer: TnPubkey,
6341        accounts: ConsensusValidatorAccounts,
6342        subject_attestor: TnPubkey,
6343        dest_token_account: TnPubkey,
6344        fee: u64,
6345        nonce: u64,
6346        start_slot: u64,
6347    ) -> Result<Transaction> {
6348        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
6349
6350        let tx_accounts = [
6351            (accounts.attestor_table, true),
6352            (accounts.unclaimed_vault, true),
6353            (dest_token_account, true),
6354            (accounts.token_program, false),
6355        ];
6356        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
6357        let attestor_table_idx = indices[0];
6358        let unclaimed_vault_idx = indices[1];
6359        let dest_token_account_idx = indices[2];
6360        let token_program_idx = indices[3];
6361
6362        let instruction_data = build_claim_instruction(
6363            attestor_table_idx as u64,
6364            token_program_idx,
6365            unclaimed_vault_idx,
6366            dest_token_account_idx,
6367            0u16,
6368            subject_attestor,
6369        )?;
6370
6371        Ok(tx.with_instructions(instruction_data))
6372    }
6373
6374    /// Build consensus validator program SET_CLAIM_AUTH transaction.
6375    pub fn build_set_claim_authority(
6376        fee_payer: TnPubkey,
6377        subject_attestor: TnPubkey,
6378        new_claim_authority: TnPubkey,
6379        fee: u64,
6380        nonce: u64,
6381        start_slot: u64,
6382    ) -> Result<Transaction> {
6383        Self::build_set_claim_authority_with_accounts(
6384            fee_payer,
6385            ConsensusValidatorAccounts::default(),
6386            subject_attestor,
6387            new_claim_authority,
6388            fee,
6389            nonce,
6390            start_slot,
6391        )
6392    }
6393
6394    /// Build consensus validator program SET_CLAIM_AUTH transaction using
6395    /// custom fixed account addresses.
6396    pub fn build_set_claim_authority_with_accounts(
6397        fee_payer: TnPubkey,
6398        accounts: ConsensusValidatorAccounts,
6399        subject_attestor: TnPubkey,
6400        new_claim_authority: TnPubkey,
6401        fee: u64,
6402        nonce: u64,
6403        start_slot: u64,
6404    ) -> Result<Transaction> {
6405        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
6406
6407        let tx_accounts = [(accounts.attestor_table, true)];
6408        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
6409        let attestor_table_idx = indices[0];
6410
6411        let instruction_data = build_set_claim_authority_instruction(
6412            attestor_table_idx as u64,
6413            0u16,
6414            subject_attestor,
6415            new_claim_authority,
6416        )?;
6417
6418        Ok(tx.with_instructions(instruction_data))
6419    }
6420
6421    /// Build name service InitializeRoot transaction
6422    pub fn build_name_service_initialize_root(
6423        fee_payer: TnPubkey,
6424        name_service_program: TnPubkey,
6425        registrar_account: TnPubkey,
6426        authority_account: TnPubkey,
6427        root_name: &str,
6428        state_proof: Vec<u8>,
6429        fee: u64,
6430        nonce: u64,
6431        start_slot: u64,
6432    ) -> Result<Transaction> {
6433        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6434            .with_start_slot(start_slot)
6435            .with_expiry_after(100)
6436            .with_compute_units(500_000)
6437            .with_state_units(1)
6438            .with_memory_units(10_000);
6439
6440        let accounts = [(registrar_account, true), (authority_account, false)];
6441        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6442        tx = tx_with_accounts;
6443
6444        let registrar_account_idx = indices[0];
6445        let authority_account_idx = indices[1];
6446
6447        let instruction_data = build_name_service_initialize_root_instruction(
6448            registrar_account_idx,
6449            authority_account_idx,
6450            root_name,
6451            state_proof,
6452        )?;
6453
6454        Ok(tx.with_instructions(instruction_data))
6455    }
6456
6457    /// Build name service RegisterSubdomain transaction
6458    pub fn build_name_service_register_subdomain(
6459        fee_payer: TnPubkey,
6460        name_service_program: TnPubkey,
6461        domain_account: TnPubkey,
6462        parent_account: TnPubkey,
6463        owner_account: TnPubkey,
6464        authority_account: TnPubkey,
6465        domain_name: &str,
6466        state_proof: Vec<u8>,
6467        fee: u64,
6468        nonce: u64,
6469        start_slot: u64,
6470    ) -> Result<Transaction> {
6471        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6472            .with_start_slot(start_slot)
6473            .with_expiry_after(100)
6474            .with_compute_units(500_000)
6475            .with_state_units(1)
6476            .with_memory_units(10_000);
6477
6478        let accounts = [
6479            (domain_account, true),
6480            (parent_account, true),
6481            (owner_account, false),
6482            (authority_account, false),
6483        ];
6484        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6485        tx = tx_with_accounts;
6486
6487        let domain_account_idx = indices[0];
6488        let parent_account_idx = indices[1];
6489        let owner_account_idx = indices[2];
6490        let authority_account_idx = indices[3];
6491
6492        let instruction_data = build_name_service_register_subdomain_instruction(
6493            domain_account_idx,
6494            parent_account_idx,
6495            owner_account_idx,
6496            authority_account_idx,
6497            domain_name,
6498            state_proof,
6499        )?;
6500
6501        Ok(tx.with_instructions(instruction_data))
6502    }
6503
6504    /// Build name service AppendRecord transaction
6505    pub fn build_name_service_append_record(
6506        fee_payer: TnPubkey,
6507        name_service_program: TnPubkey,
6508        domain_account: TnPubkey,
6509        owner_account: TnPubkey,
6510        key: &[u8],
6511        value: &[u8],
6512        fee: u64,
6513        nonce: u64,
6514        start_slot: u64,
6515    ) -> Result<Transaction> {
6516        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6517            .with_start_slot(start_slot)
6518            .with_expiry_after(100)
6519            .with_compute_units(250_000)
6520            .with_state_units(1)
6521            .with_memory_units(10_000);
6522
6523        let accounts = [(domain_account, true), (owner_account, false)];
6524        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6525        tx = tx_with_accounts;
6526
6527        let domain_account_idx = indices[0];
6528        let owner_account_idx = indices[1];
6529
6530        let instruction_data = build_name_service_append_record_instruction(
6531            domain_account_idx,
6532            owner_account_idx,
6533            key,
6534            value,
6535        )?;
6536
6537        Ok(tx.with_instructions(instruction_data))
6538    }
6539
6540    /// Build name service DeleteRecord transaction
6541    pub fn build_name_service_delete_record(
6542        fee_payer: TnPubkey,
6543        name_service_program: TnPubkey,
6544        domain_account: TnPubkey,
6545        owner_account: TnPubkey,
6546        key: &[u8],
6547        fee: u64,
6548        nonce: u64,
6549        start_slot: u64,
6550    ) -> Result<Transaction> {
6551        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6552            .with_start_slot(start_slot)
6553            .with_expiry_after(100)
6554            .with_compute_units(200_000)
6555            .with_state_units(0)
6556            .with_memory_units(10_000);
6557
6558        let accounts = [(domain_account, true), (owner_account, false)];
6559        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6560        tx = tx_with_accounts;
6561
6562        let domain_account_idx = indices[0];
6563        let owner_account_idx = indices[1];
6564
6565        let instruction_data = build_name_service_delete_record_instruction(
6566            domain_account_idx,
6567            owner_account_idx,
6568            key,
6569        )?;
6570
6571        Ok(tx.with_instructions(instruction_data))
6572    }
6573
6574    /// Build name service UnregisterSubdomain transaction
6575    pub fn build_name_service_unregister_subdomain(
6576        fee_payer: TnPubkey,
6577        name_service_program: TnPubkey,
6578        domain_account: TnPubkey,
6579        owner_account: TnPubkey,
6580        fee: u64,
6581        nonce: u64,
6582        start_slot: u64,
6583    ) -> Result<Transaction> {
6584        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6585            .with_start_slot(start_slot)
6586            .with_expiry_after(100)
6587            .with_compute_units(200_000)
6588            .with_state_units(0)
6589            .with_memory_units(10_000);
6590
6591        let accounts = [(domain_account, true), (owner_account, false)];
6592        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6593        tx = tx_with_accounts;
6594
6595        let domain_account_idx = indices[0];
6596        let owner_account_idx = indices[1];
6597
6598        let instruction_data = build_name_service_unregister_subdomain_instruction(
6599            domain_account_idx,
6600            owner_account_idx,
6601        )?;
6602
6603        Ok(tx.with_instructions(instruction_data))
6604    }
6605
6606    /// Build thru registrar InitializeRegistry transaction
6607    pub fn build_thru_registrar_initialize_registry(
6608        fee_payer: TnPubkey,
6609        thru_registrar_program: TnPubkey,
6610        config_account: TnPubkey,
6611        name_service_program: TnPubkey,
6612        root_registrar_account: TnPubkey,
6613        treasurer_account: TnPubkey,
6614        token_mint_account: TnPubkey,
6615        token_program: TnPubkey,
6616        root_domain_name: &str,
6617        price_per_year: u64,
6618        config_proof: Vec<u8>,
6619        registrar_proof: Vec<u8>,
6620        fee: u64,
6621        nonce: u64,
6622        start_slot: u64,
6623    ) -> Result<Transaction> {
6624        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6625            .with_start_slot(start_slot)
6626            .with_expiry_after(100)
6627            .with_compute_units(500_000)
6628            .with_state_units(2) // New configuration and root.
6629            .with_memory_units(10_000);
6630
6631        // Add accounts in sorted order (read-write first, then read-only)
6632        // Registrar must be writable because the base name service CPI creates/resizes it.
6633        let mut rw_accounts = vec![config_account, root_registrar_account];
6634        rw_accounts.sort();
6635
6636        let mut ro_accounts = vec![
6637            name_service_program,
6638            treasurer_account,
6639            token_mint_account,
6640            token_program,
6641        ];
6642        ro_accounts.sort();
6643
6644        // Add RW accounts
6645        let mut config_account_idx = 0u16;
6646        let mut root_registrar_account_idx = 0u16;
6647        for (i, account) in rw_accounts.iter().enumerate() {
6648            let idx = (2 + i) as u16;
6649            if *account == config_account {
6650                config_account_idx = idx;
6651            } else if *account == root_registrar_account {
6652                root_registrar_account_idx = idx;
6653            }
6654            tx = tx.add_rw_account(*account);
6655        }
6656
6657        // Add RO accounts
6658        let base_ro_idx = 2 + rw_accounts.len() as u16;
6659        let mut name_service_program_idx = 0u16;
6660        let mut treasurer_account_idx = 0u16;
6661        let mut token_mint_account_idx = 0u16;
6662        let mut token_program_idx = 0u16;
6663
6664        for (i, account) in ro_accounts.iter().enumerate() {
6665            let idx = base_ro_idx + i as u16;
6666            if *account == name_service_program {
6667                name_service_program_idx = idx;
6668            } else if *account == root_registrar_account {
6669                root_registrar_account_idx = idx;
6670            } else if *account == treasurer_account {
6671                treasurer_account_idx = idx;
6672            } else if *account == token_mint_account {
6673                token_mint_account_idx = idx;
6674            } else if *account == token_program {
6675                token_program_idx = idx;
6676            }
6677            tx = tx.add_r_account(*account);
6678        }
6679
6680        let instruction_data = build_thru_registrar_initialize_registry_instruction(
6681            config_account_idx,
6682            name_service_program_idx,
6683            root_registrar_account_idx,
6684            treasurer_account_idx,
6685            token_mint_account_idx,
6686            token_program_idx,
6687            root_domain_name,
6688            price_per_year,
6689            config_proof,
6690            registrar_proof,
6691        )?;
6692
6693        Ok(tx.with_instructions(instruction_data))
6694    }
6695
6696    /// Build thru registrar PurchaseDomain transaction
6697    pub fn build_thru_registrar_purchase_domain(
6698        fee_payer: TnPubkey,
6699        thru_registrar_program: TnPubkey,
6700        config_account: TnPubkey,
6701        lease_account: TnPubkey,
6702        domain_account: TnPubkey,
6703        name_service_program: TnPubkey,
6704        root_registrar_account: TnPubkey,
6705        treasurer_account: TnPubkey,
6706        payer_token_account: TnPubkey,
6707        token_mint_account: TnPubkey,
6708        token_program: TnPubkey,
6709        domain_name: &str,
6710        years: u8,
6711        lease_proof: Vec<u8>,
6712        domain_proof: Vec<u8>,
6713        fee: u64,
6714        nonce: u64,
6715        start_slot: u64,
6716    ) -> Result<Transaction> {
6717        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6718            .with_start_slot(start_slot)
6719            .with_expiry_after(100)
6720            .with_compute_units(500_000)
6721            .with_state_units(2) // New lease and domain.
6722            .with_memory_units(10_000);
6723
6724        // Add accounts in sorted order
6725        // Token accounts must be writable for transfer; lease/domain are created; root registrar and config are updated via CPI.
6726        let mut rw_accounts = vec![
6727            config_account,
6728            lease_account,
6729            domain_account,
6730            treasurer_account,
6731            payer_token_account,
6732            root_registrar_account,
6733        ];
6734        rw_accounts.sort();
6735
6736        let mut ro_accounts = vec![name_service_program, token_mint_account, token_program];
6737        ro_accounts.sort();
6738
6739        // Add RW accounts
6740        let mut config_account_idx = 0u16;
6741        let mut lease_account_idx = 0u16;
6742        let mut domain_account_idx = 0u16;
6743        let mut treasurer_account_idx = 0u16;
6744        let mut payer_token_account_idx = 0u16;
6745        let mut root_registrar_account_idx = 0u16;
6746        for (i, account) in rw_accounts.iter().enumerate() {
6747            let idx = (2 + i) as u16;
6748            if *account == config_account {
6749                config_account_idx = idx;
6750            } else if *account == lease_account {
6751                lease_account_idx = idx;
6752            } else if *account == domain_account {
6753                domain_account_idx = idx;
6754            } else if *account == treasurer_account {
6755                treasurer_account_idx = idx;
6756            } else if *account == payer_token_account {
6757                payer_token_account_idx = idx;
6758            } else if *account == root_registrar_account {
6759                root_registrar_account_idx = idx;
6760            }
6761            tx = tx.add_rw_account(*account);
6762        }
6763
6764        // Add RO accounts
6765        let base_ro_idx = 2 + rw_accounts.len() as u16;
6766        let mut name_service_program_idx = 0u16;
6767        let mut token_mint_account_idx = 0u16;
6768        let mut token_program_idx = 0u16;
6769
6770        for (i, account) in ro_accounts.iter().enumerate() {
6771            let idx = base_ro_idx + i as u16;
6772            if *account == config_account {
6773                config_account_idx = idx; // Should remain zero; config moved to RW set
6774            } else if *account == name_service_program {
6775                name_service_program_idx = idx;
6776            } else if *account == root_registrar_account {
6777                root_registrar_account_idx = idx;
6778            } else if *account == treasurer_account {
6779                treasurer_account_idx = idx;
6780            } else if *account == payer_token_account {
6781                payer_token_account_idx = idx;
6782            } else if *account == token_mint_account {
6783                token_mint_account_idx = idx;
6784            } else if *account == token_program {
6785                token_program_idx = idx;
6786            }
6787            tx = tx.add_r_account(*account);
6788        }
6789
6790        let instruction_data = build_thru_registrar_purchase_domain_instruction(
6791            config_account_idx,
6792            lease_account_idx,
6793            domain_account_idx,
6794            name_service_program_idx,
6795            root_registrar_account_idx,
6796            treasurer_account_idx,
6797            payer_token_account_idx,
6798            token_mint_account_idx,
6799            token_program_idx,
6800            domain_name,
6801            years,
6802            lease_proof,
6803            domain_proof,
6804        )?;
6805
6806        Ok(tx.with_instructions(instruction_data))
6807    }
6808
6809    /// Build thru registrar RenewLease transaction
6810    pub fn build_thru_registrar_renew_lease(
6811        fee_payer: TnPubkey,
6812        thru_registrar_program: TnPubkey,
6813        config_account: TnPubkey,
6814        lease_account: TnPubkey,
6815        treasurer_account: TnPubkey,
6816        payer_token_account: TnPubkey,
6817        token_mint_account: TnPubkey,
6818        token_program: TnPubkey,
6819        years: u8,
6820        fee: u64,
6821        nonce: u64,
6822        start_slot: u64,
6823    ) -> Result<Transaction> {
6824        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6825            .with_start_slot(start_slot)
6826            .with_expiry_after(100)
6827            .with_compute_units(300_000)
6828            .with_state_units(0)
6829            .with_memory_units(10_000);
6830
6831        // Add accounts in sorted order
6832        // Token accounts must be writable for transfer.
6833        let mut rw_accounts = vec![lease_account, treasurer_account, payer_token_account];
6834        rw_accounts.sort();
6835
6836        let mut ro_accounts = vec![config_account, token_mint_account, token_program];
6837        ro_accounts.sort();
6838
6839        // Add RW accounts
6840        let mut lease_account_idx = 0u16;
6841        let mut treasurer_account_idx = 0u16;
6842        let mut payer_token_account_idx = 0u16;
6843        for (i, account) in rw_accounts.iter().enumerate() {
6844            let idx = (2 + i) as u16;
6845            if *account == lease_account {
6846                lease_account_idx = idx;
6847            } else if *account == treasurer_account {
6848                treasurer_account_idx = idx;
6849            } else if *account == payer_token_account {
6850                payer_token_account_idx = idx;
6851            }
6852            tx = tx.add_rw_account(*account);
6853        }
6854
6855        // Add RO accounts
6856        let base_ro_idx = 2 + rw_accounts.len() as u16;
6857        let mut config_account_idx = 0u16;
6858        let mut token_mint_account_idx = 0u16;
6859        let mut token_program_idx = 0u16;
6860
6861        for (i, account) in ro_accounts.iter().enumerate() {
6862            let idx = base_ro_idx + i as u16;
6863            if *account == config_account {
6864                config_account_idx = idx;
6865            } else if *account == token_mint_account {
6866                token_mint_account_idx = idx;
6867            } else if *account == token_program {
6868                token_program_idx = idx;
6869            }
6870            tx = tx.add_r_account(*account);
6871        }
6872
6873        let instruction_data = build_thru_registrar_renew_lease_instruction(
6874            config_account_idx,
6875            lease_account_idx,
6876            treasurer_account_idx,
6877            payer_token_account_idx,
6878            token_mint_account_idx,
6879            token_program_idx,
6880            years,
6881        )?;
6882
6883        Ok(tx.with_instructions(instruction_data))
6884    }
6885
6886    /// Build thru registrar ClaimExpiredDomain transaction
6887    pub fn build_thru_registrar_claim_expired_domain(
6888        fee_payer: TnPubkey,
6889        thru_registrar_program: TnPubkey,
6890        config_account: TnPubkey,
6891        lease_account: TnPubkey,
6892        treasurer_account: TnPubkey,
6893        payer_token_account: TnPubkey,
6894        token_mint_account: TnPubkey,
6895        token_program: TnPubkey,
6896        years: u8,
6897        fee: u64,
6898        nonce: u64,
6899        start_slot: u64,
6900    ) -> Result<Transaction> {
6901        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6902            .with_start_slot(start_slot)
6903            .with_expiry_after(100)
6904            .with_compute_units(300_000)
6905            .with_state_units(0)
6906            .with_memory_units(10_000);
6907
6908        // Add accounts in sorted order
6909        // Token accounts must be writable for transfer.
6910        let mut rw_accounts = vec![lease_account, treasurer_account, payer_token_account];
6911        rw_accounts.sort();
6912
6913        let mut ro_accounts = vec![config_account, token_mint_account, token_program];
6914        ro_accounts.sort();
6915
6916        // Add RW accounts
6917        let mut lease_account_idx = 0u16;
6918        let mut treasurer_account_idx = 0u16;
6919        let mut payer_token_account_idx = 0u16;
6920        for (i, account) in rw_accounts.iter().enumerate() {
6921            let idx = (2 + i) as u16;
6922            if *account == lease_account {
6923                lease_account_idx = idx;
6924            } else if *account == treasurer_account {
6925                treasurer_account_idx = idx;
6926            } else if *account == payer_token_account {
6927                payer_token_account_idx = idx;
6928            }
6929            tx = tx.add_rw_account(*account);
6930        }
6931
6932        // Add RO accounts
6933        let base_ro_idx = 2 + rw_accounts.len() as u16;
6934        let mut config_account_idx = 0u16;
6935        let mut token_mint_account_idx = 0u16;
6936        let mut token_program_idx = 0u16;
6937
6938        for (i, account) in ro_accounts.iter().enumerate() {
6939            let idx = base_ro_idx + i as u16;
6940            if *account == config_account {
6941                config_account_idx = idx;
6942            } else if *account == token_mint_account {
6943                token_mint_account_idx = idx;
6944            } else if *account == token_program {
6945                token_program_idx = idx;
6946            }
6947            tx = tx.add_r_account(*account);
6948        }
6949
6950        let instruction_data = build_thru_registrar_claim_expired_domain_instruction(
6951            config_account_idx,
6952            lease_account_idx,
6953            treasurer_account_idx,
6954            payer_token_account_idx,
6955            token_mint_account_idx,
6956            token_program_idx,
6957            years,
6958        )?;
6959
6960        Ok(tx.with_instructions(instruction_data))
6961    }
6962}
6963
6964/// Build token InitializeMint instruction data
6965fn build_token_initialize_mint_instruction(
6966    mint_account_idx: u16,
6967    decimals: u8,
6968    creator: TnPubkey,
6969    mint_authority: TnPubkey,
6970    freeze_authority: Option<TnPubkey>,
6971    ticker: &str,
6972    seed: [u8; 32],
6973    state_proof: Vec<u8>,
6974) -> Result<Vec<u8>> {
6975    let mut instruction_data = Vec::new();
6976
6977    // Instruction tag
6978    instruction_data.push(TOKEN_INSTRUCTION_INITIALIZE_MINT);
6979
6980    // mint_account_index (u16)
6981    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6982
6983    // decimals (u8)
6984    instruction_data.push(decimals);
6985
6986    // creator (32 bytes)
6987    instruction_data.extend_from_slice(&creator);
6988
6989    // mint_authority (32 bytes)
6990    instruction_data.extend_from_slice(&mint_authority);
6991
6992    // freeze_authority (32 bytes) and has_freeze_authority flag
6993    let (freeze_auth, has_freeze_auth) = match freeze_authority {
6994        Some(auth) => (auth, 1u8),
6995        None => ([0u8; 32], 0u8),
6996    };
6997    instruction_data.extend_from_slice(&freeze_auth);
6998    instruction_data.push(has_freeze_auth);
6999
7000    // ticker_len and ticker_bytes (max 8 bytes)
7001    let ticker_bytes = ticker.as_bytes();
7002    if ticker_bytes.len() > 8 {
7003        return Err(anyhow::anyhow!("Ticker must be 8 characters or less"));
7004    }
7005
7006    instruction_data.push(ticker_bytes.len() as u8);
7007    let mut ticker_padded = [0u8; 8];
7008    ticker_padded[..ticker_bytes.len()].copy_from_slice(ticker_bytes);
7009    instruction_data.extend_from_slice(&ticker_padded);
7010
7011    // seed (32 bytes)
7012    instruction_data.extend_from_slice(&seed);
7013
7014    // state proof (variable length)
7015    instruction_data.extend_from_slice(&state_proof);
7016
7017    Ok(instruction_data)
7018}
7019
7020/// Build token InitializeAccount instruction data
7021fn build_token_initialize_account_instruction(
7022    token_account_idx: u16,
7023    mint_account_idx: u16,
7024    owner_account_idx: u16,
7025    seed: [u8; 32],
7026    state_proof: Vec<u8>,
7027) -> Result<Vec<u8>> {
7028    let mut instruction_data = Vec::new();
7029
7030    // Instruction tag
7031    instruction_data.push(TOKEN_INSTRUCTION_INITIALIZE_ACCOUNT);
7032
7033    // token_account_index (u16)
7034    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
7035
7036    // mint_account_index (u16)
7037    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7038
7039    // owner_account_index (u16)
7040    instruction_data.extend_from_slice(&owner_account_idx.to_le_bytes());
7041
7042    // seed (32 bytes)
7043    instruction_data.extend_from_slice(&seed);
7044
7045    // state proof (variable length)
7046    instruction_data.extend_from_slice(&state_proof);
7047
7048    Ok(instruction_data)
7049}
7050
7051/// Build token Transfer instruction data
7052pub fn build_token_transfer_instruction(
7053    source_account_idx: u16,
7054    dest_account_idx: u16,
7055    amount: u64,
7056) -> Result<Vec<u8>> {
7057    let mut instruction_data = Vec::new();
7058
7059    // Instruction tag
7060    instruction_data.push(TOKEN_INSTRUCTION_TRANSFER);
7061
7062    // source_account_index (u16)
7063    instruction_data.extend_from_slice(&source_account_idx.to_le_bytes());
7064
7065    // dest_account_index (u16)
7066    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
7067
7068    // amount (u64)
7069    instruction_data.extend_from_slice(&amount.to_le_bytes());
7070
7071    Ok(instruction_data)
7072}
7073
7074/// Build token TransferChecked instruction data
7075pub fn build_token_transfer_checked_instruction(
7076    source_account_idx: u16,
7077    dest_account_idx: u16,
7078    mint_account_idx: u16,
7079    amount: u64,
7080    decimals: u8,
7081    ticker: &[u8],
7082) -> Result<Vec<u8>> {
7083    if ticker.len() > TOKEN_TICKER_MAX_LEN {
7084        return Err(anyhow::anyhow!("Ticker must be 8 bytes or less"));
7085    }
7086
7087    // 17 fixed bytes, then the ticker bytes
7088    let mut instruction_data = Vec::with_capacity(17 + TOKEN_TICKER_MAX_LEN);
7089
7090    // Instruction tag
7091    instruction_data.push(TOKEN_INSTRUCTION_TRANSFER_CHECKED);
7092
7093    // source_account_index (u16)
7094    instruction_data.extend_from_slice(&source_account_idx.to_le_bytes());
7095
7096    // dest_account_index (u16)
7097    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
7098
7099    // mint_account_index (u16)
7100    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7101
7102    // amount (u64)
7103    instruction_data.extend_from_slice(&amount.to_le_bytes());
7104
7105    // decimals (u8)
7106    instruction_data.push(decimals);
7107
7108    // ticker_len (u8)
7109    instruction_data.push(ticker.len() as u8);
7110
7111    // ticker_bytes (8 bytes, zero padded)
7112    let mut ticker_bytes = [0u8; TOKEN_TICKER_MAX_LEN];
7113    ticker_bytes[..ticker.len()].copy_from_slice(ticker);
7114    instruction_data.extend_from_slice(&ticker_bytes);
7115
7116    Ok(instruction_data)
7117}
7118
7119/// Build token MintTo instruction data
7120pub fn build_token_mint_to_instruction(
7121    mint_account_idx: u16,
7122    dest_account_idx: u16,
7123    authority_idx: u16,
7124    amount: u64,
7125) -> Result<Vec<u8>> {
7126    let mut instruction_data = Vec::new();
7127
7128    // Instruction tag
7129    instruction_data.push(TOKEN_INSTRUCTION_MINT_TO);
7130
7131    // mint_account_index (u16)
7132    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7133
7134    // dest_account_index (u16)
7135    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
7136
7137    // authority_index (u16)
7138    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
7139
7140    // amount (u64)
7141    instruction_data.extend_from_slice(&amount.to_le_bytes());
7142
7143    Ok(instruction_data)
7144}
7145
7146/// Build token Burn instruction data
7147pub fn build_token_burn_instruction(
7148    token_account_idx: u16,
7149    mint_account_idx: u16,
7150    authority_idx: u16,
7151    amount: u64,
7152) -> Result<Vec<u8>> {
7153    let mut instruction_data = Vec::new();
7154
7155    // Instruction tag
7156    instruction_data.push(TOKEN_INSTRUCTION_BURN);
7157
7158    // token_account_index (u16)
7159    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
7160
7161    // mint_account_index (u16)
7162    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7163
7164    // authority_index (u16)
7165    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
7166
7167    // amount (u64)
7168    instruction_data.extend_from_slice(&amount.to_le_bytes());
7169
7170    Ok(instruction_data)
7171}
7172
7173/// Build token FreezeAccount instruction data
7174pub fn build_token_freeze_account_instruction(
7175    token_account_idx: u16,
7176    mint_account_idx: u16,
7177    authority_idx: u16,
7178) -> Result<Vec<u8>> {
7179    let mut instruction_data = Vec::new();
7180
7181    // Instruction tag
7182    instruction_data.push(TOKEN_INSTRUCTION_FREEZE_ACCOUNT);
7183
7184    // token_account_index (u16)
7185    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
7186
7187    // mint_account_index (u16)
7188    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7189
7190    // authority_index (u16)
7191    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
7192
7193    Ok(instruction_data)
7194}
7195
7196/// Build token ThawAccount instruction data
7197pub fn build_token_thaw_account_instruction(
7198    token_account_idx: u16,
7199    mint_account_idx: u16,
7200    authority_idx: u16,
7201) -> Result<Vec<u8>> {
7202    let mut instruction_data = Vec::new();
7203
7204    // Instruction tag
7205    instruction_data.push(TOKEN_INSTRUCTION_THAW_ACCOUNT);
7206
7207    // token_account_index (u16)
7208    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
7209
7210    // mint_account_index (u16)
7211    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7212
7213    // authority_index (u16)
7214    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
7215
7216    Ok(instruction_data)
7217}
7218
7219/// Build token CloseAccount instruction data
7220pub fn build_token_close_account_instruction(
7221    token_account_idx: u16,
7222    destination_idx: u16,
7223    authority_idx: u16,
7224) -> Result<Vec<u8>> {
7225    let mut instruction_data = Vec::new();
7226
7227    // Instruction tag
7228    instruction_data.push(TOKEN_INSTRUCTION_CLOSE_ACCOUNT);
7229
7230    // token_account_index (u16)
7231    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
7232
7233    // destination_index (u16)
7234    instruction_data.extend_from_slice(&destination_idx.to_le_bytes());
7235
7236    // authority_index (u16)
7237    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
7238
7239    Ok(instruction_data)
7240}
7241
7242fn build_wthru_initialize_mint_instruction(
7243    token_program_idx: u16,
7244    mint_account_idx: u16,
7245    vault_account_idx: u16,
7246    decimals: u8,
7247    mint_seed: [u8; 32],
7248    mint_proof: Vec<u8>,
7249    vault_proof: Vec<u8>,
7250) -> Result<Vec<u8>> {
7251    let mint_proof_len =
7252        u64::try_from(mint_proof.len()).map_err(|_| anyhow::anyhow!("mint proof too large"))?;
7253    let vault_proof_len =
7254        u64::try_from(vault_proof.len()).map_err(|_| anyhow::anyhow!("vault proof too large"))?;
7255
7256    let mut instruction_data = Vec::new();
7257    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_INITIALIZE_MINT.to_le_bytes());
7258    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7259    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7260    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
7261    instruction_data.push(decimals);
7262    instruction_data.extend_from_slice(&mint_seed);
7263    instruction_data.extend_from_slice(&mint_proof_len.to_le_bytes());
7264    instruction_data.extend_from_slice(&vault_proof_len.to_le_bytes());
7265    instruction_data.extend_from_slice(&mint_proof);
7266    instruction_data.extend_from_slice(&vault_proof);
7267
7268    Ok(instruction_data)
7269}
7270
7271fn build_wthru_deposit_instruction(
7272    token_program_idx: u16,
7273    vault_account_idx: u16,
7274    mint_account_idx: u16,
7275    dest_account_idx: u16,
7276) -> Result<Vec<u8>> {
7277    let mut instruction_data = Vec::new();
7278    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_DEPOSIT.to_le_bytes());
7279    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7280    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
7281    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7282    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
7283
7284    Ok(instruction_data)
7285}
7286
7287fn build_wthru_withdraw_instruction(
7288    token_program_idx: u16,
7289    vault_account_idx: u16,
7290    mint_account_idx: u16,
7291    wthru_token_account_idx: u16,
7292    owner_account_idx: u16,
7293    recipient_account_idx: u16,
7294    amount: u64,
7295) -> Result<Vec<u8>> {
7296    let mut instruction_data = Vec::new();
7297    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_WITHDRAW.to_le_bytes());
7298    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7299    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
7300    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7301    instruction_data.extend_from_slice(&wthru_token_account_idx.to_le_bytes());
7302    instruction_data.extend_from_slice(&owner_account_idx.to_le_bytes());
7303    instruction_data.extend_from_slice(&recipient_account_idx.to_le_bytes());
7304    instruction_data.extend_from_slice(&amount.to_le_bytes());
7305
7306    Ok(instruction_data)
7307}
7308
7309/// Build BP CreateAccount (disc 0) instruction data.
7310///
7311/// Wire layout = u32 discriminant || tn_bp_create_account_args (packed, 164 B)
7312/// || bond_proof || ta_proof || eoa_proof.  The args struct field order mirrors
7313/// tn_block_producer_program.h:146-161 exactly.
7314#[allow(clippy::too_many_arguments)]
7315fn build_bp_create_account_instruction(
7316    token_program_idx: u16,
7317    bond_account_idx: u16,
7318    bond_ta_idx: u16,
7319    mint_account_idx: u16,
7320    signer_eoa_idx: u16,
7321    create_signer_eoa: bool,
7322    signer_pubkey: &[u8; 32],
7323    bond_authority: &[u8; 32],
7324    signer_eoa_signature: &[u8; 64],
7325    bond_proof: &[u8],
7326    ta_proof: &[u8],
7327    eoa_proof: &[u8],
7328) -> Result<Vec<u8>> {
7329    let bond_proof_size =
7330        u64::try_from(bond_proof.len()).map_err(|_| anyhow::anyhow!("bond proof too large"))?;
7331    let ta_proof_size =
7332        u64::try_from(ta_proof.len()).map_err(|_| anyhow::anyhow!("ta proof too large"))?;
7333    let eoa_proof_size =
7334        u64::try_from(eoa_proof.len()).map_err(|_| anyhow::anyhow!("eoa proof too large"))?;
7335
7336    let mut instruction_data = Vec::new();
7337    instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_CREATE_ACCOUNT.to_le_bytes());
7338    /* tn_bp_create_account_args (packed) */
7339    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7340    instruction_data.extend_from_slice(&bond_account_idx.to_le_bytes());
7341    instruction_data.extend_from_slice(&bond_ta_idx.to_le_bytes());
7342    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
7343    instruction_data.extend_from_slice(&signer_eoa_idx.to_le_bytes());
7344    instruction_data.push(if create_signer_eoa { 1u8 } else { 0u8 }); // create_signer_eoa
7345    instruction_data.push(0u8); // reserved (must be 0)
7346    instruction_data.extend_from_slice(signer_pubkey);
7347    instruction_data.extend_from_slice(bond_authority);
7348    instruction_data.extend_from_slice(signer_eoa_signature);
7349    instruction_data.extend_from_slice(&bond_proof_size.to_le_bytes());
7350    instruction_data.extend_from_slice(&ta_proof_size.to_le_bytes());
7351    instruction_data.extend_from_slice(&eoa_proof_size.to_le_bytes());
7352    /* trailing proofs */
7353    instruction_data.extend_from_slice(bond_proof);
7354    instruction_data.extend_from_slice(ta_proof);
7355    instruction_data.extend_from_slice(eoa_proof);
7356
7357    Ok(instruction_data)
7358}
7359
7360/// Build faucet Deposit instruction data
7361fn build_faucet_deposit_instruction(
7362    faucet_account_idx: u16,
7363    depositor_account_idx: u16,
7364    eoa_program_idx: u16,
7365    amount: u64,
7366) -> Result<Vec<u8>> {
7367    let mut instruction_data = Vec::new();
7368
7369    // Discriminant: TN_FAUCET_INSTRUCTION_DEPOSIT = 0 (u32, 4 bytes little-endian)
7370    instruction_data.extend_from_slice(&0u32.to_le_bytes());
7371
7372    // tn_faucet_deposit_args_t structure:
7373    // - faucet_account_idx (u16, 2 bytes little-endian)
7374    instruction_data.extend_from_slice(&faucet_account_idx.to_le_bytes());
7375
7376    // - depositor_account_idx (u16, 2 bytes little-endian)
7377    instruction_data.extend_from_slice(&depositor_account_idx.to_le_bytes());
7378
7379    // - eoa_program_idx (u16, 2 bytes little-endian)
7380    instruction_data.extend_from_slice(&eoa_program_idx.to_le_bytes());
7381
7382    // - amount (u64, 8 bytes little-endian)
7383    instruction_data.extend_from_slice(&amount.to_le_bytes());
7384
7385    Ok(instruction_data)
7386}
7387
7388/// Build faucet Withdraw instruction data
7389fn build_faucet_withdraw_instruction(
7390    faucet_account_idx: u16,
7391    recipient_account_idx: u16,
7392    amount: u64,
7393) -> Result<Vec<u8>> {
7394    let mut instruction_data = Vec::new();
7395
7396    // Discriminant: TN_FAUCET_INSTRUCTION_WITHDRAW = 1 (u32, 4 bytes little-endian)
7397    instruction_data.extend_from_slice(&1u32.to_le_bytes());
7398
7399    // tn_faucet_withdraw_args_t structure:
7400    // - faucet_account_idx (u16, 2 bytes little-endian)
7401    instruction_data.extend_from_slice(&faucet_account_idx.to_le_bytes());
7402
7403    // - recipient_account_idx (u16, 2 bytes little-endian)
7404    instruction_data.extend_from_slice(&recipient_account_idx.to_le_bytes());
7405
7406    // - amount (u64, 8 bytes little-endian)
7407    instruction_data.extend_from_slice(&amount.to_le_bytes());
7408
7409    Ok(instruction_data)
7410}
7411
7412/// Build consensus validator ACTIVATE instruction data.
7413/// Matches tn_consensus_validator_activate_args_t structure.
7414fn build_activate_instruction(
7415    attestor_table_idx: u64,
7416    token_program_idx: u16,
7417    source_token_account_idx: u16,
7418    converted_vault_idx: u16,
7419    identity_idx: u16,
7420    bls_pk: [u8; 96],
7421    bls_pop: [u8; 192],
7422    claim_authority: [u8; 32],
7423    token_amount: u64,
7424) -> Result<Vec<u8>> {
7425    let mut instruction_data = Vec::new();
7426
7427    /* Discriminant: TN_CONSENSUS_VALIDATOR_INSTRUCTION_ACTIVATE = 1 (u32, 4 bytes LE) */
7428    instruction_data.extend_from_slice(&1u32.to_le_bytes());
7429
7430    /* tn_consensus_validator_activate_args_t structure (packed): */
7431    /* - attestor_table_idx (u64, 8 bytes LE) */
7432    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7433
7434    /* - token_program_idx (u16, 2 bytes LE) */
7435    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7436
7437    /* - source_token_account_idx (u16, 2 bytes LE) */
7438    instruction_data.extend_from_slice(&source_token_account_idx.to_le_bytes());
7439
7440    /* - converted_vault_idx (u16, 2 bytes LE) */
7441    instruction_data.extend_from_slice(&converted_vault_idx.to_le_bytes());
7442
7443    /* - identity_idx (u16, 2 bytes LE) */
7444    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
7445
7446    /* - bls_pk (96 bytes, tn_bls_pubkey_t / blst_p1_affine) */
7447    instruction_data.extend_from_slice(&bls_pk);
7448
7449    /* - bls_pop (192 bytes, tn_bls_signature_t / blst_p2_affine) */
7450    instruction_data.extend_from_slice(&bls_pop);
7451
7452    /* - claim_authority (32 bytes, pubkey) */
7453    instruction_data.extend_from_slice(&claim_authority);
7454
7455    /* - token_amount (u64, 8 bytes LE) */
7456    instruction_data.extend_from_slice(&token_amount.to_le_bytes());
7457
7458    Ok(instruction_data)
7459}
7460
7461/// Build consensus validator DEACTIVATE instruction data.
7462/// Matches tn_consensus_validator_deactivate_args_t structure.
7463fn build_deactivate_instruction(
7464    attestor_table_idx: u64,
7465    token_program_idx: u16,
7466    unclaimed_vault_idx: u16,
7467    dest_token_account_idx: u16,
7468    identity_idx: u16,
7469) -> Result<Vec<u8>> {
7470    let mut instruction_data = Vec::new();
7471
7472    instruction_data.extend_from_slice(&2u32.to_le_bytes());
7473    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7474    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7475    instruction_data.extend_from_slice(&unclaimed_vault_idx.to_le_bytes());
7476    instruction_data.extend_from_slice(&dest_token_account_idx.to_le_bytes());
7477    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
7478
7479    Ok(instruction_data)
7480}
7481
7482/// Build consensus validator CONVERT_TOKENS instruction data.
7483/// Matches tn_consensus_validator_convert_args_t structure.
7484fn build_convert_tokens_instruction(
7485    attestor_table_idx: u64,
7486    token_program_idx: u16,
7487    source_token_account_idx: u16,
7488    converted_vault_idx: u16,
7489    identity_idx: u16,
7490    token_amount: u64,
7491) -> Result<Vec<u8>> {
7492    let mut instruction_data = Vec::new();
7493
7494    instruction_data.extend_from_slice(&3u32.to_le_bytes());
7495    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7496    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7497    instruction_data.extend_from_slice(&source_token_account_idx.to_le_bytes());
7498    instruction_data.extend_from_slice(&converted_vault_idx.to_le_bytes());
7499    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
7500    instruction_data.extend_from_slice(&token_amount.to_le_bytes());
7501
7502    Ok(instruction_data)
7503}
7504
7505/// Build consensus validator CLAIM instruction data.
7506/// Matches tn_consensus_validator_claim_args_t structure.
7507fn build_claim_instruction(
7508    attestor_table_idx: u64,
7509    token_program_idx: u16,
7510    unclaimed_vault_idx: u16,
7511    dest_token_account_idx: u16,
7512    claim_authority_idx: u16,
7513    subject_attestor: TnPubkey,
7514) -> Result<Vec<u8>> {
7515    let mut instruction_data = Vec::new();
7516
7517    instruction_data.extend_from_slice(&4u32.to_le_bytes());
7518    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7519    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7520    instruction_data.extend_from_slice(&unclaimed_vault_idx.to_le_bytes());
7521    instruction_data.extend_from_slice(&dest_token_account_idx.to_le_bytes());
7522    instruction_data.extend_from_slice(&claim_authority_idx.to_le_bytes());
7523    instruction_data.extend_from_slice(&subject_attestor);
7524
7525    Ok(instruction_data)
7526}
7527
7528/// Build consensus validator SET_CLAIM_AUTH instruction data.
7529/// Matches tn_consensus_validator_set_claim_auth_args_t structure.
7530fn build_set_claim_authority_instruction(
7531    attestor_table_idx: u64,
7532    current_claim_auth_idx: u16,
7533    subject_attestor: TnPubkey,
7534    new_claim_authority: TnPubkey,
7535) -> Result<Vec<u8>> {
7536    let mut instruction_data = Vec::new();
7537
7538    instruction_data.extend_from_slice(&5u32.to_le_bytes());
7539    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7540    instruction_data.extend_from_slice(&current_claim_auth_idx.to_le_bytes());
7541    instruction_data.extend_from_slice(&subject_attestor);
7542    instruction_data.extend_from_slice(&new_claim_authority);
7543
7544    Ok(instruction_data)
7545}
7546
7547/* ---------------- consensus validator manager ---------------- */
7548
7549/// Consensus validator manager instruction discriminants
7550/// (TN_CONSENSUS_VALIDATOR_INSTRUCTION_*; 7 is reserved for UPDATE_ID).
7551pub const CV_INSTRUCTION_INIT_VALIDATOR_MANAGER: u32 = 8;
7552pub const CV_INSTRUCTION_SET_VALIDATOR_MANAGER: u32 = 9;
7553pub const CV_INSTRUCTION_SET_SELF_SERVICE: u32 = 10;
7554pub const CV_INSTRUCTION_MANAGER_ACTIVATE: u32 = 11;
7555pub const CV_INSTRUCTION_MANAGER_DEACTIVATE: u32 = 12;
7556pub const CV_INSTRUCTION_SET_PARAMS: u32 = 13;
7557pub const CV_INSTRUCTION_MANAGER_SET_WEIGHT: u32 = 14;
7558
7559/// The attestor table's staking parameters, in SetParams order
7560/// (tn_consensus_validator_set_params_args_t after attestor_table_idx).
7561#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7562pub struct CvStakeParams {
7563    pub stake_units_per_weight: u64,
7564    pub min_stake: u64,
7565    pub max_decay_bps: u64,
7566    pub idle_gap_decay_bps: u64,
7567    pub max_idle_gap_decay_bps: u64,
7568    pub attestor_decay_fraction_bps: u64,
7569}
7570
7571fn cv_instruction(discriminant: u32, attestor_table_idx: u64, capacity: usize) -> Vec<u8> {
7572    let mut data = Vec::with_capacity(4 + 8 + capacity);
7573    data.extend_from_slice(&discriminant.to_le_bytes());
7574    data.extend_from_slice(&attestor_table_idx.to_le_bytes());
7575    data
7576}
7577
7578/// InitValidatorManager (tn_consensus_validator_init_manager_args_t): the
7579/// program's application authority installs the first validator manager.
7580pub fn build_cv_init_validator_manager_instruction(
7581    attestor_table_idx: u64,
7582    program_meta_idx: u16,
7583    validator_manager: TnPubkey,
7584) -> Vec<u8> {
7585    let mut data = cv_instruction(CV_INSTRUCTION_INIT_VALIDATOR_MANAGER, attestor_table_idx, 34);
7586    data.extend_from_slice(&program_meta_idx.to_le_bytes());
7587    data.extend_from_slice(&validator_manager);
7588    data
7589}
7590
7591/// SetValidatorManager (tn_consensus_validator_set_manager_args_t).
7592pub fn build_cv_set_validator_manager_instruction(attestor_table_idx: u64, validator_manager: TnPubkey) -> Vec<u8> {
7593    let mut data = cv_instruction(CV_INSTRUCTION_SET_VALIDATOR_MANAGER, attestor_table_idx, 32);
7594    data.extend_from_slice(&validator_manager);
7595    data
7596}
7597
7598/// SetSelfService (tn_consensus_validator_set_self_service_args_t).
7599pub fn build_cv_set_self_service_instruction(attestor_table_idx: u64, enabled: bool) -> Vec<u8> {
7600    let mut data = cv_instruction(CV_INSTRUCTION_SET_SELF_SERVICE, attestor_table_idx, 1);
7601    data.push(u8::from(enabled));
7602    data
7603}
7604
7605/// ManagerActivate (tn_consensus_validator_manager_activate_args_t). bls_pop
7606/// signs the compressed key followed by identity (bls_activation_key).
7607pub fn build_cv_manager_activate_instruction(
7608    attestor_table_idx: u64,
7609    identity: TnPubkey,
7610    bls_pk: [u8; 96],
7611    bls_pop: [u8; 192],
7612    claim_authority: TnPubkey,
7613    weight: u64,
7614) -> Vec<u8> {
7615    let mut data = cv_instruction(CV_INSTRUCTION_MANAGER_ACTIVATE, attestor_table_idx, 360);
7616    data.extend_from_slice(&identity);
7617    data.extend_from_slice(&bls_pk);
7618    data.extend_from_slice(&bls_pop);
7619    data.extend_from_slice(&claim_authority);
7620    data.extend_from_slice(&weight.to_le_bytes());
7621    data
7622}
7623
7624/// ManagerDeactivate (tn_consensus_validator_manager_deactivate_args_t).
7625pub fn build_cv_manager_deactivate_instruction(attestor_table_idx: u64, identity: TnPubkey) -> Vec<u8> {
7626    let mut data = cv_instruction(CV_INSTRUCTION_MANAGER_DEACTIVATE, attestor_table_idx, 32);
7627    data.extend_from_slice(&identity);
7628    data
7629}
7630
7631/// SetParams (tn_consensus_validator_set_params_args_t).
7632pub fn build_cv_set_params_instruction(attestor_table_idx: u64, params: &CvStakeParams) -> Vec<u8> {
7633    let mut data = cv_instruction(CV_INSTRUCTION_SET_PARAMS, attestor_table_idx, 48);
7634    for value in [
7635        params.stake_units_per_weight,
7636        params.min_stake,
7637        params.max_decay_bps,
7638        params.idle_gap_decay_bps,
7639        params.max_idle_gap_decay_bps,
7640        params.attestor_decay_fraction_bps,
7641    ] {
7642        data.extend_from_slice(&value.to_le_bytes());
7643    }
7644    data
7645}
7646
7647/// ManagerSetWeight (tn_consensus_validator_manager_set_weight_args_t).
7648pub fn build_cv_manager_set_weight_instruction(attestor_table_idx: u64, identity: TnPubkey, weight: u64) -> Vec<u8> {
7649    let mut data = cv_instruction(CV_INSTRUCTION_MANAGER_SET_WEIGHT, attestor_table_idx, 40);
7650    data.extend_from_slice(&identity);
7651    data.extend_from_slice(&weight.to_le_bytes());
7652    data
7653}
7654
7655impl TransactionBuilder {
7656    /// A consensus validator manager transaction: the attestor table
7657    /// (writable) and, for InitValidatorManager, the program's metadata
7658    /// account (read-only). `encode` gets the table's index and the
7659    /// metadata's. The fee payer is the authority (the manager, or the
7660    /// application authority for InitValidatorManager). `proof` raises the
7661    /// compute budget for an instruction that verifies a BLS proof of
7662    /// possession (ManagerActivate).
7663    #[allow(clippy::too_many_arguments)]
7664    pub fn build_cv_manager_with_accounts(
7665        fee_payer: TnPubkey,
7666        accounts: ConsensusValidatorAccounts,
7667        program_meta: Option<TnPubkey>,
7668        proof: bool,
7669        encode: impl FnOnce(u64, Option<u16>) -> Vec<u8>,
7670        fee: u64,
7671        nonce: u64,
7672        start_slot: u64,
7673    ) -> Result<Transaction> {
7674        let mut tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
7675        if proof {
7676            tx = tx.with_compute_units(CONSENSUS_VALIDATOR_PROOF_COMPUTE_UNITS);
7677        }
7678        let mut tx_accounts = vec![(accounts.attestor_table, true)];
7679        if let Some(meta) = program_meta {
7680            tx_accounts.push((meta, false));
7681        }
7682        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
7683        let data = encode(indices[0] as u64, program_meta.map(|_| indices[1]));
7684        Ok(tx.with_instructions(data))
7685    }
7686}
7687
7688#[cfg(test)]
7689mod cv_manager_instruction_tests {
7690    use super::*;
7691
7692    /* Sizes are 4 (discriminant) + sizeof the packed args struct in
7693       tn_consensus_validator_program.h. */
7694    #[test]
7695    fn manager_instructions_match_the_c_args() {
7696        let key = [7u8; 32];
7697        let init = build_cv_init_validator_manager_instruction(2, 3, key);
7698        assert_eq!(init.len(), 4 + 42);
7699        assert_eq!(&init[..4], &8u32.to_le_bytes());
7700        assert_eq!(&init[4..12], &2u64.to_le_bytes());
7701        assert_eq!(&init[12..14], &3u16.to_le_bytes());
7702        assert_eq!(&init[14..], &key);
7703        assert_eq!(build_cv_set_validator_manager_instruction(2, key).len(), 4 + 40);
7704        assert_eq!(
7705            build_cv_set_self_service_instruction(2, false),
7706            [&10u32.to_le_bytes()[..], &2u64.to_le_bytes()[..], &[0u8][..]].concat()
7707        );
7708        assert_eq!(build_cv_set_self_service_instruction(2, true)[12], 1);
7709        let activate = build_cv_manager_activate_instruction(2, key, [1; 96], [2; 192], [3; 32], 100);
7710        assert_eq!(activate.len(), 4 + 368);
7711        assert_eq!(&activate[activate.len() - 8..], &100u64.to_le_bytes());
7712        assert_eq!(build_cv_manager_deactivate_instruction(2, key).len(), 4 + 40);
7713        let params = CvStakeParams {
7714            stake_units_per_weight: 1,
7715            min_stake: 2,
7716            max_decay_bps: 3,
7717            idle_gap_decay_bps: 4,
7718            max_idle_gap_decay_bps: 5,
7719            attestor_decay_fraction_bps: 6,
7720        };
7721        let set_params = build_cv_set_params_instruction(2, &params);
7722        assert_eq!(set_params.len(), 4 + 56);
7723        for (i, value) in (1u64..=6).enumerate() {
7724            assert_eq!(&set_params[12 + 8 * i..20 + 8 * i], &value.to_le_bytes());
7725        }
7726        let set_weight = build_cv_manager_set_weight_instruction(2, key, 300);
7727        assert_eq!(set_weight.len(), 4 + 48);
7728        assert_eq!(&set_weight[..4], &14u32.to_le_bytes());
7729    }
7730
7731    #[test]
7732    fn manager_transaction_indexes_the_table_and_metadata() {
7733        let accounts = ConsensusValidatorAccounts::default();
7734        let meta = [9u8; 32];
7735        let mut seen = None;
7736        TransactionBuilder::build_cv_manager_with_accounts(
7737            [1u8; 32],
7738            accounts,
7739            Some(meta),
7740            false,
7741            |table, meta_idx| {
7742                seen = Some((table, meta_idx));
7743                build_cv_init_validator_manager_instruction(table, meta_idx.unwrap(), [5u8; 32])
7744            },
7745            0,
7746            0,
7747            0,
7748        )
7749        .unwrap();
7750        /* The table is the only writable account (2); the metadata is the
7751           only read-only one (3). */
7752        assert_eq!(seen, Some((2, Some(3))));
7753    }
7754}
7755
7756#[repr(C, packed)]
7757struct NameServiceInitializeRootArgs {
7758    registrar_account_idx: u16,
7759    authority_account_idx: u16,
7760    root_name: [u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7761    root_name_length: u32,
7762}
7763
7764#[repr(C, packed)]
7765struct NameServiceRegisterSubdomainArgs {
7766    domain_account_idx: u16,
7767    parent_account_idx: u16,
7768    owner_account_idx: u16,
7769    authority_account_idx: u16,
7770    name: [u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7771    name_length: u32,
7772}
7773
7774#[repr(C, packed)]
7775struct NameServiceAppendRecordArgs {
7776    domain_account_idx: u16,
7777    owner_account_idx: u16,
7778    key_length: u32,
7779    key: [u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7780    value_length: u32,
7781    value: [u8; TN_NAME_SERVICE_MAX_VALUE_LENGTH],
7782}
7783
7784#[repr(C, packed)]
7785struct NameServiceDeleteRecordArgs {
7786    domain_account_idx: u16,
7787    owner_account_idx: u16,
7788    key_length: u32,
7789    key: [u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7790}
7791
7792#[repr(C, packed)]
7793struct NameServiceUnregisterSubdomainArgs {
7794    domain_account_idx: u16,
7795    owner_account_idx: u16,
7796}
7797
7798/// Build name service InitializeRoot instruction data
7799fn build_name_service_initialize_root_instruction(
7800    registrar_account_idx: u16,
7801    authority_account_idx: u16,
7802    root_name: &str,
7803    state_proof: Vec<u8>,
7804) -> Result<Vec<u8>> {
7805    let root_name_bytes = root_name.as_bytes();
7806    if root_name_bytes.is_empty() || root_name_bytes.len() > TN_NAME_SERVICE_MAX_DOMAIN_LENGTH {
7807        return Err(anyhow::anyhow!(
7808            "Root name length must be between 1 and {}",
7809            TN_NAME_SERVICE_MAX_DOMAIN_LENGTH
7810        ));
7811    }
7812
7813    let mut args = NameServiceInitializeRootArgs {
7814        registrar_account_idx,
7815        authority_account_idx,
7816        root_name: [0u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7817        root_name_length: root_name_bytes.len() as u32,
7818    };
7819    args.root_name[..root_name_bytes.len()].copy_from_slice(root_name_bytes);
7820
7821    let mut instruction_data = Vec::new();
7822    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_INITIALIZE_ROOT.to_le_bytes());
7823
7824    let args_bytes = unsafe {
7825        std::slice::from_raw_parts(
7826            &args as *const _ as *const u8,
7827            std::mem::size_of::<NameServiceInitializeRootArgs>(),
7828        )
7829    };
7830    instruction_data.extend_from_slice(args_bytes);
7831
7832    instruction_data.extend_from_slice(&TN_NAME_SERVICE_PROOF_INLINE.to_le_bytes());
7833    instruction_data.extend_from_slice(&state_proof);
7834
7835    Ok(instruction_data)
7836}
7837
7838/// Build name service RegisterSubdomain instruction data
7839fn build_name_service_register_subdomain_instruction(
7840    domain_account_idx: u16,
7841    parent_account_idx: u16,
7842    owner_account_idx: u16,
7843    authority_account_idx: u16,
7844    domain_name: &str,
7845    state_proof: Vec<u8>,
7846) -> Result<Vec<u8>> {
7847    let domain_bytes = domain_name.as_bytes();
7848    if domain_bytes.is_empty() || domain_bytes.len() > TN_NAME_SERVICE_MAX_DOMAIN_LENGTH {
7849        return Err(anyhow::anyhow!(
7850            "Domain name length must be between 1 and {}",
7851            TN_NAME_SERVICE_MAX_DOMAIN_LENGTH
7852        ));
7853    }
7854
7855    let mut args = NameServiceRegisterSubdomainArgs {
7856        domain_account_idx,
7857        parent_account_idx,
7858        owner_account_idx,
7859        authority_account_idx,
7860        name: [0u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7861        name_length: domain_bytes.len() as u32,
7862    };
7863    args.name[..domain_bytes.len()].copy_from_slice(domain_bytes);
7864
7865    let mut instruction_data = Vec::new();
7866    instruction_data
7867        .extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_REGISTER_SUBDOMAIN.to_le_bytes());
7868
7869    let args_bytes = unsafe {
7870        std::slice::from_raw_parts(
7871            &args as *const _ as *const u8,
7872            std::mem::size_of::<NameServiceRegisterSubdomainArgs>(),
7873        )
7874    };
7875    instruction_data.extend_from_slice(args_bytes);
7876
7877    instruction_data.extend_from_slice(&TN_NAME_SERVICE_PROOF_INLINE.to_le_bytes());
7878    instruction_data.extend_from_slice(&state_proof);
7879
7880    Ok(instruction_data)
7881}
7882
7883/// Build name service AppendRecord instruction data
7884fn build_name_service_append_record_instruction(
7885    domain_account_idx: u16,
7886    owner_account_idx: u16,
7887    key: &[u8],
7888    value: &[u8],
7889) -> Result<Vec<u8>> {
7890    if key.is_empty() || key.len() > TN_NAME_SERVICE_MAX_KEY_LENGTH {
7891        return Err(anyhow::anyhow!(
7892            "Key length must be between 1 and {} bytes",
7893            TN_NAME_SERVICE_MAX_KEY_LENGTH
7894        ));
7895    }
7896    if value.len() > TN_NAME_SERVICE_MAX_VALUE_LENGTH {
7897        return Err(anyhow::anyhow!(
7898            "Value length must be <= {} bytes",
7899            TN_NAME_SERVICE_MAX_VALUE_LENGTH
7900        ));
7901    }
7902
7903    let mut args = NameServiceAppendRecordArgs {
7904        domain_account_idx,
7905        owner_account_idx,
7906        key_length: key.len() as u32,
7907        key: [0u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7908        value_length: value.len() as u32,
7909        value: [0u8; TN_NAME_SERVICE_MAX_VALUE_LENGTH],
7910    };
7911    args.key[..key.len()].copy_from_slice(key);
7912    args.value[..value.len()].copy_from_slice(value);
7913
7914    let mut instruction_data = Vec::new();
7915    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_APPEND_RECORD.to_le_bytes());
7916
7917    let args_bytes = unsafe {
7918        std::slice::from_raw_parts(
7919            &args as *const _ as *const u8,
7920            std::mem::size_of::<NameServiceAppendRecordArgs>(),
7921        )
7922    };
7923    instruction_data.extend_from_slice(args_bytes);
7924
7925    Ok(instruction_data)
7926}
7927
7928/// Build name service DeleteRecord instruction data
7929fn build_name_service_delete_record_instruction(
7930    domain_account_idx: u16,
7931    owner_account_idx: u16,
7932    key: &[u8],
7933) -> Result<Vec<u8>> {
7934    if key.is_empty() || key.len() > TN_NAME_SERVICE_MAX_KEY_LENGTH {
7935        return Err(anyhow::anyhow!(
7936            "Key length must be between 1 and {} bytes",
7937            TN_NAME_SERVICE_MAX_KEY_LENGTH
7938        ));
7939    }
7940
7941    let mut args = NameServiceDeleteRecordArgs {
7942        domain_account_idx,
7943        owner_account_idx,
7944        key_length: key.len() as u32,
7945        key: [0u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7946    };
7947    args.key[..key.len()].copy_from_slice(key);
7948
7949    let mut instruction_data = Vec::new();
7950    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_DELETE_RECORD.to_le_bytes());
7951
7952    let args_bytes = unsafe {
7953        std::slice::from_raw_parts(
7954            &args as *const _ as *const u8,
7955            std::mem::size_of::<NameServiceDeleteRecordArgs>(),
7956        )
7957    };
7958    instruction_data.extend_from_slice(args_bytes);
7959
7960    Ok(instruction_data)
7961}
7962
7963/// Build name service UnregisterSubdomain instruction data
7964fn build_name_service_unregister_subdomain_instruction(
7965    domain_account_idx: u16,
7966    owner_account_idx: u16,
7967) -> Result<Vec<u8>> {
7968    let args = NameServiceUnregisterSubdomainArgs {
7969        domain_account_idx,
7970        owner_account_idx,
7971    };
7972
7973    let mut instruction_data = Vec::new();
7974    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_UNREGISTER.to_le_bytes());
7975
7976    let args_bytes = unsafe {
7977        std::slice::from_raw_parts(
7978            &args as *const _ as *const u8,
7979            std::mem::size_of::<NameServiceUnregisterSubdomainArgs>(),
7980        )
7981    };
7982    instruction_data.extend_from_slice(args_bytes);
7983
7984    Ok(instruction_data)
7985}
7986
7987/// Build thru registrar InitializeRegistry instruction data
7988fn build_thru_registrar_initialize_registry_instruction(
7989    config_account_idx: u16,
7990    name_service_program_idx: u16,
7991    root_registrar_account_idx: u16,
7992    treasurer_account_idx: u16,
7993    token_mint_account_idx: u16,
7994    token_program_idx: u16,
7995    root_domain_name: &str,
7996    price_per_year: u64,
7997    config_proof: Vec<u8>,
7998    registrar_proof: Vec<u8>,
7999) -> Result<Vec<u8>> {
8000    let mut instruction_data = Vec::new();
8001
8002    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY = 0 (u32, 4 bytes little-endian)
8003    instruction_data
8004        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY.to_le_bytes());
8005
8006    // tn_thru_registrar_initialize_registry_args_t structure:
8007    // - config_account_idx (u16, 2 bytes little-endian)
8008    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
8009    // - name_service_program_account_idx (u16, 2 bytes little-endian)
8010    instruction_data.extend_from_slice(&name_service_program_idx.to_le_bytes());
8011    // - root_registrar_account_idx (u16, 2 bytes little-endian)
8012    instruction_data.extend_from_slice(&root_registrar_account_idx.to_le_bytes());
8013    // - treasurer_account_idx (u16, 2 bytes little-endian)
8014    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
8015    // - token_mint_account_idx (u16, 2 bytes little-endian)
8016    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
8017    // - token_program_account_idx (u16, 2 bytes little-endian)
8018    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
8019    // - root_domain_name (64 bytes, padded with zeros)
8020    let domain_bytes = root_domain_name.as_bytes();
8021    if domain_bytes.len() > 64 {
8022        return Err(anyhow::anyhow!(
8023            "Root domain name must be 64 characters or less"
8024        ));
8025    }
8026    let mut domain_padded = [0u8; 64];
8027    domain_padded[..domain_bytes.len()].copy_from_slice(domain_bytes);
8028    instruction_data.extend_from_slice(&domain_padded);
8029    // - root_domain_name_length (u32, 4 bytes little-endian)
8030    instruction_data.extend_from_slice(&(domain_bytes.len() as u32).to_le_bytes());
8031    // - price_per_year (u64, 8 bytes little-endian)
8032    instruction_data.extend_from_slice(&price_per_year.to_le_bytes());
8033
8034    // Variable-length proofs follow:
8035    // - config_proof (variable length)
8036    instruction_data.extend_from_slice(&config_proof);
8037    // - registrar_proof (variable length)
8038    instruction_data.extend_from_slice(&registrar_proof);
8039
8040    Ok(instruction_data)
8041}
8042
8043/// Build thru registrar PurchaseDomain instruction data
8044fn build_thru_registrar_purchase_domain_instruction(
8045    config_account_idx: u16,
8046    lease_account_idx: u16,
8047    domain_account_idx: u16,
8048    name_service_program_idx: u16,
8049    root_registrar_account_idx: u16,
8050    treasurer_account_idx: u16,
8051    payer_token_account_idx: u16,
8052    token_mint_account_idx: u16,
8053    token_program_idx: u16,
8054    domain_name: &str,
8055    years: u8,
8056    lease_proof: Vec<u8>,
8057    domain_proof: Vec<u8>,
8058) -> Result<Vec<u8>> {
8059    let mut instruction_data = Vec::new();
8060
8061    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN = 1 (u32, 4 bytes little-endian)
8062    instruction_data
8063        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN.to_le_bytes());
8064
8065    // tn_thru_registrar_purchase_domain_args_t structure:
8066    // - config_account_idx (u16, 2 bytes little-endian)
8067    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
8068    // - lease_account_idx (u16, 2 bytes little-endian)
8069    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
8070    // - domain_account_idx (u16, 2 bytes little-endian)
8071    instruction_data.extend_from_slice(&domain_account_idx.to_le_bytes());
8072    // - name_service_program_account_idx (u16, 2 bytes little-endian)
8073    instruction_data.extend_from_slice(&name_service_program_idx.to_le_bytes());
8074    // - root_registrar_account_idx (u16, 2 bytes little-endian)
8075    instruction_data.extend_from_slice(&root_registrar_account_idx.to_le_bytes());
8076    // - treasurer_account_idx (u16, 2 bytes little-endian)
8077    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
8078    // - payer_token_account_idx (u16, 2 bytes little-endian)
8079    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
8080    // - token_mint_account_idx (u16, 2 bytes little-endian)
8081    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
8082    // - token_program_account_idx (u16, 2 bytes little-endian)
8083    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
8084    // - domain_name (64 bytes, padded with zeros)
8085    let domain_bytes = domain_name.as_bytes();
8086    if domain_bytes.len() > 64 {
8087        return Err(anyhow::anyhow!("Domain name must be 64 characters or less"));
8088    }
8089    let mut domain_padded = [0u8; 64];
8090    domain_padded[..domain_bytes.len()].copy_from_slice(domain_bytes);
8091    instruction_data.extend_from_slice(&domain_padded);
8092    // - domain_name_length (u32, 4 bytes little-endian)
8093    instruction_data.extend_from_slice(&(domain_bytes.len() as u32).to_le_bytes());
8094    // - years (u8, 1 byte)
8095    instruction_data.push(years);
8096
8097    // Variable-length proofs follow:
8098    // - lease_proof (variable length)
8099    instruction_data.extend_from_slice(&lease_proof);
8100    // - domain_proof (variable length)
8101    instruction_data.extend_from_slice(&domain_proof);
8102
8103    Ok(instruction_data)
8104}
8105
8106/// Build thru registrar RenewLease instruction data
8107fn build_thru_registrar_renew_lease_instruction(
8108    config_account_idx: u16,
8109    lease_account_idx: u16,
8110    treasurer_account_idx: u16,
8111    payer_token_account_idx: u16,
8112    token_mint_account_idx: u16,
8113    token_program_idx: u16,
8114    years: u8,
8115) -> Result<Vec<u8>> {
8116    let mut instruction_data = Vec::new();
8117
8118    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE = 2 (u32, 4 bytes little-endian)
8119    instruction_data.extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE.to_le_bytes());
8120
8121    // tn_thru_registrar_renew_lease_args_t structure:
8122    // - config_account_idx (u16, 2 bytes little-endian)
8123    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
8124    // - lease_account_idx (u16, 2 bytes little-endian)
8125    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
8126    // - treasurer_account_idx (u16, 2 bytes little-endian)
8127    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
8128    // - payer_token_account_idx (u16, 2 bytes little-endian)
8129    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
8130    // - token_mint_account_idx (u16, 2 bytes little-endian)
8131    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
8132    // - token_program_account_idx (u16, 2 bytes little-endian)
8133    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
8134    // - years (u8, 1 byte)
8135    instruction_data.push(years);
8136
8137    Ok(instruction_data)
8138}
8139
8140/// Build thru registrar ClaimExpiredDomain instruction data
8141fn build_thru_registrar_claim_expired_domain_instruction(
8142    config_account_idx: u16,
8143    lease_account_idx: u16,
8144    treasurer_account_idx: u16,
8145    payer_token_account_idx: u16,
8146    token_mint_account_idx: u16,
8147    token_program_idx: u16,
8148    years: u8,
8149) -> Result<Vec<u8>> {
8150    let mut instruction_data = Vec::new();
8151
8152    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN = 3 (u32, 4 bytes little-endian)
8153    instruction_data
8154        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN.to_le_bytes());
8155
8156    // tn_thru_registrar_claim_expired_domain_args_t structure:
8157    // - config_account_idx (u16, 2 bytes little-endian)
8158    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
8159    // - lease_account_idx (u16, 2 bytes little-endian)
8160    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
8161    // - treasurer_account_idx (u16, 2 bytes little-endian)
8162    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
8163    // - payer_token_account_idx (u16, 2 bytes little-endian)
8164    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
8165    // - token_mint_account_idx (u16, 2 bytes little-endian)
8166    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
8167    // - token_program_account_idx (u16, 2 bytes little-endian)
8168    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
8169    // - years (u8, 1 byte)
8170    instruction_data.push(years);
8171
8172    Ok(instruction_data)
8173}
8174
8175#[cfg(test)]
8176mod srcbuf_digest_wire_tests {
8177    use super::*;
8178
8179    const DIGEST: [u8; 32] = [0xA5; 32];
8180
8181    #[test]
8182    fn manager_create_commits_digest_after_srcbuf_size() {
8183        let seed = b"seed";
8184        let d = build_manager_create_instruction(
8185            MANAGER_INSTRUCTION_CREATE_EPHEMERAL,
8186            2,
8187            3,
8188            4,
8189            0,
8190            0x0102_0304,
8191            0x1000,
8192            DIGEST,
8193            seed,
8194            None,
8195        )
8196        .unwrap();
8197        assert_eq!(std::mem::size_of::<ManagerCreateArgs>(), 53);
8198        assert_eq!(d.len(), 53 + seed.len());
8199        assert_eq!(&d[7..11], &0x0102_0304u32.to_le_bytes());
8200        assert_eq!(&d[11..15], &0x1000u32.to_le_bytes());
8201        assert_eq!(&d[15..47], &DIGEST);
8202        assert_eq!(&d[47..49], &0u16.to_le_bytes());
8203        assert_eq!(&d[49..53], &(seed.len() as u32).to_le_bytes());
8204        assert_eq!(&d[53..], seed);
8205    }
8206
8207    #[test]
8208    fn manager_upgrade_commits_digest() {
8209        let d = build_manager_upgrade_instruction(2, 3, 4, 8, 6664, DIGEST).unwrap();
8210        assert_eq!(d.len(), 47);
8211        assert_eq!(d[0], MANAGER_INSTRUCTION_UPGRADE);
8212        assert_eq!(&d[5..7], &4u16.to_le_bytes());
8213        assert_eq!(&d[11..15], &6664u32.to_le_bytes());
8214        assert_eq!(&d[15..47], &DIGEST);
8215    }
8216
8217    #[test]
8218    fn abi_official_create_and_upgrade_commit_digest() {
8219        let c = build_abi_manager_create_abi_official_instruction(
8220            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL,
8221            2,
8222            3,
8223            4,
8224            5,
8225            0,
8226            77,
8227            DIGEST,
8228            9,
8229            None,
8230        )
8231        .unwrap();
8232        let u = build_abi_manager_upgrade_abi_official_instruction(2, 3, 4, 5, 0, 77, DIGEST, 9)
8233            .unwrap();
8234        for d in [&c, &u] {
8235            assert_eq!(d.len(), 51);
8236            assert_eq!(&d[13..17], &77u32.to_le_bytes());
8237            assert_eq!(&d[17..49], &DIGEST);
8238            assert_eq!(&d[49..51], &9u16.to_le_bytes());
8239        }
8240        assert_eq!(c[0], ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL);
8241        assert_eq!(u[0], ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_OFFICIAL);
8242    }
8243
8244    #[test]
8245    fn abi_external_create_and_upgrade_commit_digest() {
8246        let c = build_abi_manager_create_abi_external_instruction(
8247            ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL,
8248            2,
8249            4,
8250            5,
8251            0,
8252            77,
8253            DIGEST,
8254            9,
8255            None,
8256        )
8257        .unwrap();
8258        let u =
8259            build_abi_manager_upgrade_abi_external_instruction(2, 4, 5, 0, 77, DIGEST, 9).unwrap();
8260        assert_eq!(std::mem::size_of::<AbiManagerCreateAbiExternalArgs>(), 48);
8261        assert_eq!(std::mem::size_of::<AbiManagerUpgradeAbiExternalArgs>(), 48);
8262        for d in [&c, &u] {
8263            assert_eq!(d.len(), 49);
8264            assert_eq!(&d[11..15], &77u32.to_le_bytes());
8265            assert_eq!(&d[15..47], &DIGEST);
8266            assert_eq!(&d[47..49], &9u16.to_le_bytes());
8267        }
8268        assert_eq!(c[0], ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL);
8269        assert_eq!(u[0], ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_EXTERNAL);
8270    }
8271}