Skip to main content

thru_base/
txn_tools.rs

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