Skip to main content

thru_base/
txn_tools.rs

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