Skip to main content

thru_base/
txn_tools.rs

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