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