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